package org.springframework.security.access.expression;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.Expression;

public final class ExpressionUtils {

    public static boolean evaluateAsBoolean(Expression expr, EvaluationContext ctx) {
        try {
            return ((Boolean) expr.getValue(ctx, Boolean.class)).booleanValue();
        } catch (EvaluationException e) {
            throw new IllegalArgumentException("Failed to evaluate expression", e);
        }
    }
}

package org.springframework.security.access.expression;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.Expression;

public final class ExpressionUtils {

    public static boolean evaluateAsBoolean(Expression expr, EvaluationContext ctx) {
        try {
            return ((Boolean) expr.getValue(ctx, Boolean.class)).booleanValue();
        } catch (EvaluationException e) {
            throw new IllegalArgumentException("Failed to evaluate expression '" + expr.getExpressionString() + "'", e);
        }
    }
}

Add expression string to failed expression evaluation exception message to help clarify the context.


package com.aemreunal.controller.user;

import net.minidev.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import com.aemreunal.domain.user.UsernameClashException;

/*
 ***************************
 * Copyright (c) 2014      *
 *                         *
 * This code belongs to:   *
 *                         *
 * @author Ahmet Emre Ünal *
 * S001974                 *
 *                         *
 * aemreunal@gmail.com     *
 * emre.unal@ozu.edu.tr    *
 *                         *
 * aemreunal.com           *
 ***************************
 */

@ControllerAdvice
public class UserControllerAdvice {
    @ExceptionHandler(UsernameClashException.class)
    ResponseEntity<JSONObject> usernameClashExceptionHandler(UsernameClashException ex) {
        Map<String, String> errorMessage = new HashMap<>(2);
        errorMessage.put("reason", "username");
        errorMessage.put("error", ex.getLocalizedMessage());
        JSONObject responseBody = new JSONObject(errorMessage);
        return new ResponseEntity<JSONObject>(responseBody, HttpStatus.BAD_REQUEST);
    }
}

Add UserController advice for exception handling


package pl.koszela.jan.persistence.converter;

import com.google.gson.Gson;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Arrays;
import java.util.List;
import pl.koszela.jan.persistence.dto.ProductDTO;
import pl.koszela.jan.persistence.dto.SpecialPriceDTO;
import pl.koszela.jan.persistence.dto.impl.DefaultProductDTO;
import pl.koszela.jan.persistence.dto.impl.DefaultProductListDTO;
import pl.koszela.jan.persistence.dto.impl.DefaultSpecialPriceDTO;

/**
 * Created on 10.08.2017.
 *
 * @author Jan Koszela
 */
public class JsonConverter {

  public static final Gson GSON = new Gson();
  private static final String PRODUCT_FILE = "MOCK_DATA_Products.json";
  private static final String SPECIAL_PRICES_FILE = "MOCK_DATA_Special_Prices.json";
  public static final String RESOURCES_SAMPLE_PATH = "src\\main\\resources\\sample\\";

  private DefaultProductDTO[] productDTOS;
  private DefaultSpecialPriceDTO[] specialPriceDTOS;

  public static void main(String[] args) {

    try (Reader reader = new FileReader(RESOURCES_SAMPLE_PATH + PRODUCT_FILE)) {

      // Convert JSON to Java Object
      DefaultProductDTO[] productDTOS = GSON.fromJson(reader, DefaultProductDTO[].class);

      for (int i = 0; i < productDTOS.length; i++) {
        System.out.println(productDTOS[i]);
      }

      DefaultProductListDTO productList = new DefaultProductListDTO();
      productList.setProducts(Arrays.asList(productDTOS));

      System.out.println(productList);
    } catch (IOException e) {
      e.printStackTrace();
    }

  }

  public void convert() {
    convertProducts();
    convertSpecialPrices();
  }

  private void convertProducts() {
    try (Reader reader = new FileReader(RESOURCES_SAMPLE_PATH + PRODUCT_FILE)) {

      // Convert JSON to Java Object
      productDTOS = GSON.fromJson(reader, DefaultProductDTO[].class);

    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  private void convertSpecialPrices() {
    try (Reader reader = new FileReader(RESOURCES_SAMPLE_PATH + SPECIAL_PRICES_FILE)) {

      // Convert JSON to Java Object
      specialPriceDTOS = GSON.fromJson(reader, DefaultSpecialPriceDTO[].class);

    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public ProductDTO[] getProductArray() {
    return this.productDTOS;
  }

  public List<ProductDTO> getProductList() {
    return Arrays.asList(this.productDTOS);
  }

  public SpecialPriceDTO[] getSpecialPriceArray() {
    return this.specialPriceDTOS;
  }

  public List<SpecialPriceDTO> getSpecialPriceList() {
    return Arrays.asList(this.specialPriceDTOS);
  }

}

Add Json converter for test and application workflow


package net.blackshard.clarity.scribe;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.*;

import org.junit.Rule;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.LinkedHashMap;

/**
 * Unit test for VMStatParser.
 */
public class VMStatScribbletsTest {
    @Test public void shouldInitializeDistinctClasses() throws IOException {
        LinkedHashMap<VMStatField, Integer> cpuStats = new LinkedHashMap();
        LinkedHashMap<VMStatField, Integer> memStats = new LinkedHashMap();
        LinkedHashMap<String, Integer> cpuMetrics;
        LinkedHashMap<String, Integer> memMetrics;

        VMStatScribblet cpu = new CPUScribblet();
        VMStatScribblet mem = new MemScribblet();

        cpuStats.put(VMStatField.CPU_USER, 1);
        cpuStats.put(VMStatField.CPU_SYS, 2);
        cpuStats.put(VMStatField.CPU_IDLE, 97);
        memStats.put(VMStatField.MEM_SWAP, 50);
        memStats.put(VMStatField.MEM_FREE, 100);

        cpuMetrics = cpu.toMetricsMap(cpuStats);
        memMetrics = mem.toMetricsMap(memStats);

        assertThat(cpu.name, equalTo("CPU Scribblet"));
        assertThat(mem.name, equalTo("Memory Scribblet"));
        assertThat(cpuMetrics.get("user"), equalTo(1));
        assertThat(cpuMetrics.get("system"), equalTo(2));
        assertThat(cpuMetrics.get("idle"), equalTo(97));
        assertThat(memMetrics.get("swap"), equalTo(50));
        assertThat(memMetrics.get("free"), equalTo(100));
    }
}

Add test to ensure VMStat Scribblets extend properly


package org.azavea.views;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ScrollView;

public class NotifyingScrollView extends ScrollView {

	private OnScrollToBottomListener bottomListener = null;

	public interface OnScrollToBottomListener {
		void OnScrollToBottom();
	}
	public NotifyingScrollView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public void setOnScrollToBottomListener(OnScrollToBottomListener listener) {
	        bottomListener = listener;
	}

	public void onScrollToBottom() {}

	@Override
	protected void onScrollChanged(int l, int t, int oldl, int oldt)
	{
	        // Grab the last child placed in the ScrollView, we need it to determinate the bottom position.
	        View view = (View) getChildAt(getChildCount()-1);

	        // Calculate the scrolldiff
	        int diff = (view.getBottom()-(getHeight()+getScrollY()));

	        if( diff == 0 )
	        {
	        	if (bottomListener != null) {
	        		bottomListener.OnScrollToBottom();
	        	}
	        }

	        super.onScrollChanged(l, t, oldl, oldt);
	        this.onScrollToBottom();
	}
}

Extend ScrollView for a view which notifies on reaching the bottom


/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.benchmark;

import com.facebook.presto.testing.LocalQueryRunner;

import static com.facebook.presto.benchmark.BenchmarkQueryRunner.createLocalQueryRunner;

public class StructuredTypesBenchmark
        extends AbstractSqlBenchmark
{
    // Benchmark is modeled after TPCH query 1, with array/map creation added in
    public StructuredTypesBenchmark(LocalQueryRunner localQueryRunner)
    {
        super(localQueryRunner, "structured_types", 4, 5, "" +
                "select\n" +
                "    returnflag,\n" +
                "    linestatus,\n" +
                "    sum(array[quantity][1]) as sum_qty,\n" +
                "    sum(array[extendedprice][1]) as sum_base_price,\n" +
                "    sum(array[extendedprice][1] * (1 - map(array['key'], array[discount])['key'])) as sum_disc_price,\n" +
                "    sum(array[extendedprice][1] * (1 - map(array['key'], array[discount])['key']) * (1 + tax)) as sum_charge,\n" +
                "    avg(map(array['key'], array[quantity])['key']) as avg_qty,\n" +
                "    avg(map(array['key'], array[extendedprice])['key']) as avg_price,\n" +
                "    avg(map(array['key'], array[discount])['key']) as avg_disc\n" +
                "from\n" +
                "    lineitem\n" +
                "where\n" +
                "    shipdate <= DATE '1998-09-02'\n" +
                "group by\n" +
                "    returnflag,\n" +
                "    linestatus\n" +
                "order by\n" +
                "    returnflag,\n" +
                "    linestatus");
    }

    public static void main(String[] args)
    {
        new StructuredTypesBenchmark(createLocalQueryRunner()).runBenchmark(new SimpleLineBenchmarkResultWriter(System.out));
    }
}

Add benchmark for structured types

Add benchmark for structured types


package org.jenkinsci.plugins.ghprb.downstreambuilds;

import java.util.Iterator;
import java.util.Set;

import org.jgrapht.DirectedGraph;

import com.cloudbees.plugins.flow.FlowRun;
import com.cloudbees.plugins.flow.FlowRun.JobEdge;

import hudson.model.AbstractBuild;

/**
 * @author mdelapenya (Manuel de la Peña)
 */
public class DownstreamBuildFlowManager extends BaseDownstreamBuildManager {

	public DownstreamBuildFlowManager(AbstractBuild build) {
		super(build);
	}

	@Override
	public String calculateBuildUrl() {
		FlowRun flowRun = (FlowRun) build;

		DirectedGraph directedGraph = flowRun.getJobsGraph();

		Set<JobEdge> edgeSet = directedGraph.edgeSet();

		Iterator<JobEdge> iterator = edgeSet.iterator();

		StringBuilder sb = new StringBuilder();

		while (iterator.hasNext()) {
			JobEdge jobEdge = iterator.next();

			sb.append("\n");
			sb.append("\t");
			sb.append(jobEdge.getTarget().getBuildUrl());
		}

		return sb.toString();
	}

}

Implement BuildFlow build url calculation


package app;

public class SystemUtils {

	/**
	 * Get absolute path to user catalog data.
	 */
	public static String getUserCatalogAbsPath() {
		String absPath = null;

		if (OsUtils.isWindows()) {
			// get env LOCALAPPDATA - returned null in winxp
			// get env PROGRAMPDATA - returned null in winxp
			// get env APPDATA - returned [C:\Documents and Settings\UsrName\Application Data] path in winxp
			absPath = System.getenv("APPDATA");
			System.out.println("Win platform");
			System.out.println("win env dir = " + absPath);

		} else if (OsUtils.isUnix()) {
			absPath = System.getProperty("user.dir");
			System.out.println("Unix");
			System.out.println("user.dir = " + absPath);

		} else {
			System.out.println("Not determine OS !");
		}

		return absPath;
	}

	private static final class OsUtils {
		private static String OS = null;

		public static String getOsName() {
			if(OS == null) {
				OS = System.getProperty("os.name");
			}
			return OS;
		}
		public static boolean isWindows() {
			return getOsName().startsWith("Windows");
		}

		public static boolean isUnix() {
			return getOsName().startsWith("Linux");
		}
	}
}

Add util class for determine OS type and user catalog absolute path.


/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.pedrovgs.sortingalgorithm;

/**
 * Interface to be implemented by sorting algorithm implementations in this repository.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public interface SortingAlgorithm {

  void sort(int[] numbers);
}

Create interface to be implemented by every sorting algorithm in this repository


/*
 *    Debrief - the Open Source Maritime Analysis Application
 *    http://debrief.info
 *
 *    (C) 2000-2014, PlanetMayo Ltd
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the Eclipse Public License v1.0
 *    (http://www.eclipse.org/legal/epl-v10.html)
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 */

package MWC.GUI.Properties;

import java.beans.PropertyEditorSupport;

public class GraphicSizePropertyEditor extends PropertyEditorSupport
{

  protected Double _mySize;

  private final String stringTags[] =
  {"Small", "Medium", "Large"};

  private final double vals[] =
  {6, 10, 14};

  @Override
  public String getAsText()
  {
    String res = null;
    final double current = _mySize.doubleValue();
    for (int i = 0; i < vals.length; i++)
    {
      final double v = vals[i];
      if (v == current)
      {
        res = stringTags[i];
      }
    }

    return res;
  }

  @Override
  public String[] getTags()
  {
    return stringTags;
  }

  @Override
  public Object getValue()
  {
    return _mySize;
  }

  @Override
  public void setAsText(final String val)
  {
    for (int i = 0; i < stringTags.length; i++)
    {
      final String thisS = stringTags[i];
      if (thisS.equals(val))
      {
        _mySize = new Double(vals[i]);
      }
    }
  }

  @Override
  public void setValue(final Object p1)
  {
    if (p1 instanceof Double)
    {
      _mySize = (Double) p1;
    }
    if (p1 instanceof String)
    {
      final String val = (String) p1;
      setAsText(val);
    }
  }
}

Introduce custom editor for size of graphic features (esp JFreeChart symbols).


package net.sf.taverna.t2.component.api.config;

public interface ComponentConfig {
	String URI = "http://ns.taverna.org.uk/2010/activity/component";
}

Put the component activity type URI in a sensible place.


// Java implementation to set the kth bit

// of the given number

public class SetKthBit {

	// function to set the kth bit

public static int setKthBit(int n, int k) {

	// kth bit of n is being set by this operation

	return ((1 << k) | n);

}

// Driver code

public static void main(String arg[]) {

	int n = 10, k = 2;

	System.out.print("Kth bit set number = " +

							setKthBit(n, k));

}

}

Set Kth Bit program in Java

Set Kth Bit program in Java


package test;

import main.StringAnalyser;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class IsUniqueInStringTest {

    @Test
    public void testIsUniqueTrue() {
        StringAnalyser sa = new StringAnalyser();
        String testTrue = "ABCDEFG";
        assertEquals(true, sa.isUnique(testTrue));
    }
}

IsUnique: Implement the algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?

Create test which will fail. And base class which will solve problem.


package de.biomedical_imaging.traJ.simulation;

import de.biomedical_imaging.traJ.Trajectory;
import de.biomedical_imaging.traJ.TrajectoryUtil;

public class CombinedSimulator extends AbstractSimulator {

	private AbstractSimulator sim1;
	private AbstractSimulator sim2;

	public CombinedSimulator(AbstractSimulator sim1, AbstractSimulator sim2) {
		this.sim1 =sim1;
		this.sim2 = sim2;
	}

	@Override
	public Trajectory generateTrajectory() {
		Trajectory t = TrajectoryUtil.combineTrajectory(sim1.generateTrajectory(), sim2.generateTrajectory());
		return t;
	}

}

Add simulator for comined simulations

Add simulator for comined simulations


/*
 *  Copyright 2012 The MyBatis Team
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.mybatis.generator.plugins;

import java.util.List;
import java.util.StringTokenizer;

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;

/**
 * This plugin can be used to specify columns that act as a primary key, even
 * if they are not strictly defined as primary keys in the database.
 *
 * To use the plugin, add a property to the table configuration
 * specifying a comma delimited list of column names to use as a primary
 * key:
 *
 * <table...>
 *   <property name="virtualKeyColumns" value="ID1,ID2"/>
 * </table>
 *
 * @author Jeff Butler
 *
 */
public class VirtualPrimaryKeyPlugin extends PluginAdapter {

    public boolean validate(List<String> warnings) {
        return true;
    }

    @Override
    public void initialized(IntrospectedTable introspectedTable) {
        String virtualKey =
        introspectedTable.getTableConfiguration().getProperty("virtualKeyColumns");

        if (virtualKey != null) {
            StringTokenizer st = new StringTokenizer(virtualKey, ", ", false);
            while (st.hasMoreTokens()) {
                String column = st.nextToken();
                introspectedTable.addPrimaryKeyColumn(column);
            }
        }
    }
}

Add virtual primary key plugin

Add virtual primary key plugin


// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.sps.data;

/**
 * Class representing user data specific to a competition
 */
public class CompetitorInfo {

    /** The current ranking of the user in this competition based on networth */
    private int rank;

    /** The rank of the user yesterday for purposes of displaying rises/falls in leaderboard */
    private int rankYesterday;

    /** The competitor's name */
    private String name;

    /** The competitor's idap */
    private String idap;

    /** The networth of the competitor */
    private long networth;

    /** The amount the user has available for additional investments */
    private long amtAvailable;

    public CompetitorInfo(int rank, int rankYesterday, String name, String idap, long networth, long amtAvailable) {
        this.rank = rank;
        this.rankYesterday = rankYesterday;
        this.name = name;
        this.idap = idap;
        this.networth = networth;
        this.amtAvailable = amtAvailable;
    }
}

Add class representing user data for a single competition


/*
 * Copyright 2017 haeun kim
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-09-25
 * Site       : https://www.acmicpc.net/problem/1546
 */

public class Boj1546 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n =Integer.parseInt(br.readLine());
        String[] inputs = br.readLine().split(" ");
        int[] scores = new int[n];
        for(int i=0; i<n; i++){
            scores[i] = Integer.parseInt(inputs[i]);
        }

        int tmp=0;
        for(int i=1; i<n; i++){
            if(scores[0]<scores[i]){
                tmp = scores[0];
                scores[0] = scores[i];
                scores[i] = tmp;
            }
        }

        float sum = 0;
        for(int i=0; i<n; i++){
            sum += scores[i];
        }
        System.out.print(String.format("%.2f",sum/n/scores[0]*100));
    }

}

Solve No.1546 from Baekjoon Online Judge


package com.dev.namhoai.sort;

public class BubbleSort {

    public static <T extends Comparable> void sort(T[] a) {
        for (int i = 0; i < a.length; i++) {
            //last i elements are already in sorted
            for (int j = 1; j < a.length - i; j++) {
                if (a[j - 1].compareTo(a[j]) > 0) {
                    T temp = a[j - 1]; //swap
                    a[j - 1] = a[j];
                    a[j] = temp;
                }
            }
        }
    }

    /**
     * This is simple version of in-place, stable bubble sort, whose best case is O(n) and worst Case O(n^2);
     */
    public static void sortSimple(int[] a) {
        for (int i = 0; i < a.length; i++) {
            boolean sorted = true; //flag to check if any swapping made
            // last elements sorted
            for (int j = 1; j < a.length - i; j++) {
                if (a[j] < a[j - 1]) { //swap
                    int temp = a[j - 1];
                    a[j - 1] = a[j];
                    a[j] = temp;
                    sorted = false;
                }
            }

            // if any swapping has not occurred in the last iteration, we can say it is sorted now
            if (sorted) break;
        }
    }
}

Add Bubble Sort in Java

Add Bubble Sort in Java


package sfBugs;

import java.io.IOException;

public class Bug1964520 extends Exception {
    private static final long serialVersionUID = 1L;

	public void test(Exception e) {
		// should trigger warning (and does)
		if(((Bug1964520)e).toString().equals("")) {
			System.out.println("toString is blank");
		}
		// should trigger warning (and does)
		if(e instanceof IOException && ((Bug1964520)e).toString().equals("")) {
			System.out.println("toString is blank");
		}
		// should not trigger warning (and doesn't)
		if(e instanceof Bug1964520 && ((Bug1964520)e).toString().equals("")) {
			System.out.println("toString is blank");
		}
		// should not trigger warning (and doesn't)
		if(e instanceof Bug1964520) {
			if(((Bug1964520)e).toString().equals("")) {
				System.out.println("toString is blank");
			}
		}
	}
}

Test case for [ 1964520 ] Findbugs reports invalid M D BC - Unchecked/unconfirmed cast (I can't recreate it)

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@9600 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


/*
 * Copyright (c) 2012 Mateusz Parzonka, Eric Bodden
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Mateusz Parzonka - initial API and implementation
 */
package prm4j.logic;

public interface MonitorStateProvider<A> {

    /**
     * Returns an initial monitor state. Clients assume, that changes to this state are not possible or have no side
     * effects to other initial states returned by this method.
     *
     * @return an initial state
     */
    public MonitorState<A> getInitialState();

}

Add provider interface for initial monitor states


package net.openhft.chronicle.examples;

import net.openhft.chronicle.Chronicle;
import net.openhft.chronicle.ExcerptAppender;
import net.openhft.chronicle.IndexedChronicle;
import net.openhft.chronicle.tools.ChronicleTools;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.locks.LockSupport;

/*
To add a load to the system, run the following in the console if you have a fast drive.

while true; do dd if=/dev/zero of=$RANDOM bs=10240 count=10000; sleep 1; done
 */
public class PagingLatencyTest {
    private static final String TMP = System.getProperty("user.home" /*"java.io.tmpdir"*/);
    public static final int WARMUP = 10 * 1000;

    public static void main(String[] args) throws IOException, InterruptedException {
        String path = new File(TMP, "test-paging-latency").getAbsolutePath();

        ChronicleTools.deleteOnExit(path);
        Chronicle chronicle = new IndexedChronicle(path);

        long start = System.currentTimeMillis();
        double max = 0;

        ExcerptAppender e = chronicle.createAppender();
        int ones = 0, tens = 0, hundreds = 0;
        for (int i = 0; i < 2 * 1000 * 1000; ++i) {
            long s = System.nanoTime();
            e.startExcerpt();
            e.writeLong(1);
            long s2 = System.nanoTime();
            e.position(1024 - 4); // 1K bytes total.
            e.finish();
            long s3 = System.nanoTime();
            double t = (s3 - s) / 100000 / 1e1;
            double t2 = (s2 - s) / 100000 / 1e1;
            double t3 = (s3 - s2) / 100000 / 1e1;

            if (i > WARMUP) {
                if (t > max) max = t;
                if (t > 1) {
                    System.err.println(e.index() + " took " + t + " ms. " + t2 + " / " + t3);
                    if (t >= 100) hundreds++;
                    else if (t >= 10) tens++;
                    else if (t >= 1) ones++;
                }
            }

//            while (System.nanoTime() - s3 < 1e5);
            LockSupport.parkNanos(100000); // 0.1 ms.
        }
        System.out.printf("1s: %,d 10s: %,d 100s %,d%n", ones, tens, hundreds);

        System.out.println("Finished in " + (System.currentTimeMillis() - start) + "ms, max=" + max);
        chronicle.close();
    }
}

Add a test for paging latency.

Add a test for paging latency.


/*
 *    GeoTools - The Open Source Java GIS Toolkit
 *    http://geotools.org
 *
 *    (C) 2002-2012, Open Source Geospatial Foundation (OSGeo)
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License as published by the Free Software Foundation;
 *    version 2.1 of the License.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 */

package org.geotools.data.ingres;

import org.geotools.jdbc.JDBCDataStoreFactory;
import org.geotools.jdbc.JDBCJNDIDataSourceTest;
import org.geotools.jdbc.JDBCJNDIDataStoreFactory;
import org.geotools.jdbc.JDBCJNDITestSetup;

/**
 *
 *
 * @source $URL$
 */
public  class IngresJNDIDataSourceTest extends JDBCJNDIDataSourceTest {

    protected JDBCJNDITestSetup createTestSetup() {
        return new JDBCJNDITestSetup(new IngresTestSetup());
    }

    @Override
    protected JDBCJNDIDataStoreFactory getJNDIStoreFactory() {
        return new IngresJNDIDataStoreFactory();
    }

    @Override
    protected JDBCDataStoreFactory getDataStoreFactory() {
        return new IngresDataStoreFactory();
    }

}

Add a test for Ingres JNDI-based DataStore


/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.beam.runners.spark.aggregators.metrics.sink;

import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;

import com.google.common.collect.ImmutableSet;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import org.apache.beam.runners.spark.PipelineRule;
import org.apache.beam.runners.spark.examples.WordCount;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.coders.StringUtf8Coder;
import org.apache.beam.sdk.testing.PAssert;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.MapElements;
import org.apache.beam.sdk.values.PCollection;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;

/**
 * A test that verifies Beam metrics are reported to Spark's metrics sink.
 */
public class SparkMetricsSinkTest {

  @Rule
  public ExternalResource inMemoryMetricsSink = new InMemoryMetricsSinkRule();

  @Rule
  public final PipelineRule pipelineRule = PipelineRule.batch();

  private Pipeline createSparkPipeline() {
    pipelineRule.getOptions().setEnableSparkMetricSinks(true);
    return pipelineRule.createPipeline();
  }

  private void runPipeline() {
    final List<String> words =
        Arrays.asList("hi there", "hi", "hi sue bob", "hi sue", "", "bob hi");

    final Set<String> expectedCounts =
        ImmutableSet.of("hi: 5", "there: 1", "sue: 2", "bob: 2");

    final Pipeline pipeline = createSparkPipeline();

    final PCollection<String> output =
        pipeline
        .apply(Create.of(words).withCoder(StringUtf8Coder.of()))
        .apply(new WordCount.CountWords())
        .apply(MapElements.via(new WordCount.FormatAsTextFn()));

    PAssert.that(output).containsInAnyOrder(expectedCounts);

    pipeline.run();
  }

  @Test
  public void testNamedMetric() throws Exception {
    assertThat(InMemoryMetrics.valueOf("emptyLines"), is(nullValue()));

    runPipeline();

    assertThat(InMemoryMetrics.<Double>valueOf("emptyLines"), is(1d));
  }
}

[BEAM-2057] Add a test for metrics reporting in Spark runner.


package com.sebastian_daschner.jaxrs_analyzer.analysis.results.testclasses.typeanalyzer;

import com.sebastian_daschner.jaxrs_analyzer.analysis.results.TypeUtils;
import com.sebastian_daschner.jaxrs_analyzer.model.rest.TypeIdentifier;
import com.sebastian_daschner.jaxrs_analyzer.model.rest.TypeRepresentation;
import com.sebastian_daschner.jaxrs_analyzer.model.types.Type;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class TestClass19 extends SuperTestClass5 {

    private String foobar;

    public String getFoobar() {
        return foobar;
    }

    public void setFoobar(String foobar) {
        this.foobar = foobar;
    }

    public static Set<TypeRepresentation> expectedTypeRepresentations() {
        final Map<String, TypeIdentifier> properties = new HashMap<>();

        properties.put("foobar", TypeUtils.STRING_IDENTIFIER);
        properties.put("test", TypeUtils.STRING_IDENTIFIER);
        properties.put("hello", TypeUtils.STRING_IDENTIFIER);

        return Collections.singleton(TypeRepresentation.ofConcrete(expectedIdentifier(), properties));
    }

    public static TypeIdentifier expectedIdentifier() {
        return TypeIdentifier.ofType(new Type(TestClass19.class.getName()));
    }

}

class SuperTestClass5 extends SuperTestClass6 {

    private String test;

    public String getTest() {
        return test;
    }

    public void setTest(String test) {
        this.test = test;
    }

}

class SuperTestClass6 {

    private String hello;

    public String getHello() {
        return hello;
    }

    public void setHello(String hello) {
        this.hello = hello;
    }

}

Add a super super class test

Add a super super class test


/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.apache.stratos.cloud.controller.exception;

public class InvalidNetworkPartitionException extends Exception {

    private static final long serialVersionUID = 5403224496111965638L;
    private String message;

    public InvalidNetworkPartitionException(String msg) {
        super(msg);
        this.setMessage(msg);
    }

    public InvalidNetworkPartitionException(String msg, Exception ex) {
        super(msg, ex);
        this.setMessage(msg);
    }

    private void setMessage(String msg) {
        this.message = msg;
    }

    public String getMessage() {
        return this.message;
    }
}

Add new exception to handle invalid network partition


package datamodel;

public class PerformanceSelfMonitoring {
    private CpuUsageResults cpuUsageResults;

    public CpuUsageResults getCpuUsageResults() {
        return cpuUsageResults;
    }

    public void setCpuUsageResults(CpuUsageResults cpuUsageResults) {
        this.cpuUsageResults = cpuUsageResults;
    }
}

Add datamodel for self performance results.


/*
 * Zorbage: an algebraic data hierarchy for use in numeric processing.
 *
 * Copyright (C) 2016-2019 Barry DeZonia
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package nom.bdezonia.zorbage.type.data.rgb;

import static org.junit.Assert.*;

import org.junit.Test;

/**
 *
 * @author Barry DeZonia
 *
 */
public class TestRgbUtils {

	@Test
	public void test() {
		for (double t = 0; t <= 1; t += 0.005) {
			for (int c1 = 0; c1 < 256; c1++) {
				for (int c2 = 0; c2 < 256; c2++) {
					int val = RgbUtils.blendColor(t, c1, c2);
					assertTrue(val >= 0);
					assertTrue(val <= 255);
				}
			}
		}
	}

}

Test the RgbUtils blending algorithm

Test the RgbUtils blending algorithm


package org.xblackcat.sjpu.storage;

import org.xblackcat.sjpu.storage.connection.IConnectionFactory;
import org.xblackcat.sjpu.storage.connection.IDatabaseSettings;
import org.xblackcat.sjpu.storage.connection.SimplePooledConnectionFactory;
import org.xblackcat.sjpu.storage.consumer.IRowSetConsumer;
import org.xblackcat.sjpu.storage.impl.QueryHelper;
import org.xblackcat.sjpu.storage.impl.Storage;
import org.xblackcat.sjpu.storage.typemap.EnumToStringMapper;
import org.xblackcat.sjpu.storage.typemap.IMapFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 16.02.14 16:32
 *
 * @author xBlackCat
 */
public class StorageBuilder {
    public static IStorage defaultStorage(IDatabaseSettings settings) throws StorageException {
        IConnectionFactory factory = new SimplePooledConnectionFactory(settings);
        IQueryHelper queryHelper = new QueryHelper(factory);
        Map<Class<?>, Class<? extends IRowSetConsumer>> consumers = StorageUtils.DEFAULT_ROWSET_CONSUMERS;
        IMapFactory<?, ?>[] mappers = new IMapFactory[]{
                new EnumToStringMapper()
        };
        return new Storage(queryHelper, consumers, mappers);
    }

    private IConnectionFactory connectionFactory = null;
    private IQueryHelper queryHelper = null;
    private final Map<Class<?>, Class<? extends IRowSetConsumer>> consumers = new HashMap<>();
    private final List<IMapFactory<?, ?>> mappers = new ArrayList<>();

    public StorageBuilder() {
        this(true, true);
    }

    public StorageBuilder(boolean defaultConsumers, boolean defaultMappers) {
        if (defaultConsumers) {
            consumers.putAll(StorageUtils.DEFAULT_ROWSET_CONSUMERS);
        }
        if (defaultMappers) {
            mappers.add(new EnumToStringMapper());
        }
    }

    public void setConnectionFactory(IConnectionFactory connectionFactory) {
        this.connectionFactory = connectionFactory;
    }

    public void setQueryHelper(IQueryHelper queryHelper) {
        this.queryHelper = queryHelper;
    }

    public void addRowSetConsumer(Class<?> returnClass, Class<? extends IRowSetConsumer> consumerClass) {
        consumers.put(returnClass, consumerClass);
    }

    public void addMapper(IMapFactory<?, ?> typeMapper) {
        mappers.add(typeMapper);
    }

    public IStorage build() {
        if (queryHelper == null) {
            if (connectionFactory == null) {
                throw new StorageSetupException("Connection factory or query helper should be specified.");
            }

            queryHelper = new QueryHelper(connectionFactory);
        }

        IMapFactory<?, ?>[] mappers = this.mappers.toArray(new IMapFactory<?, ?>[this.mappers.size()]);

        return new Storage(queryHelper, consumers, mappers);

    }
}

Create a builder for storage

Create a builder for storage


package com.oreilly.com.rdf.tenuki.jaxrs;

import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;

import com.oreilly.rdf.tenuki.Changeset;
import com.oreilly.rdf.tenuki.InputStreamChangeset;

@Provider
@Consumes("application/vnd.talis.changeset+xml")
public class ChangesetReader implements MessageBodyReader<Changeset> {

	@Override
	public boolean isReadable(Class<?> type, Type genericType,
			Annotation[] annotations, MediaType mediaType) {
		// TODO: Do something useful here?
		return true;
	}

	@Override
	public Changeset readFrom(Class<Changeset> type, Type genericType,
			Annotation[] annotations, MediaType mediaType,
			MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
			throws IOException, WebApplicationException {
		return new InputStreamChangeset(entityStream);
	}

}

Add changeset reader for JAX-RS

Add changeset reader for JAX-RS

--HG--
branch : jax-rs


/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.pedrovgs.problem58;

import com.github.pedrovgs.linkedlist.ListNode;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class FindKthElementTest {

  private FindKthElement findElement;

  @Before public void setUp() {
    findElement = new FindKthElement();
  }

  @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullListNodes() {
    findElement.find(null, 4);
  }

  @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNegativePositions() {
    findElement.find(new ListNode<Integer>(3), -1);
  }

  @Test(expected = IndexOutOfBoundsException.class)
  public void shouldNotAcceptPositionsGreaterThanListSize() {
    findElement.find(new ListNode<Integer>(3), 2);
  }

  @Test public void shouldReturnLastNodeIfPositionIsZero() {
    ListNode result = findElement.find(new ListNode<Integer>(1), 0);

    ListNode<Integer> expectedNode = new ListNode<Integer>(1);
    assertEquals(expectedNode, result);
  }

  @Test public void shouldReturnFirstElementIfPositionIsEqualsToListSizeMinusOne() {
    ListNode<Integer> list = createList(new int[] { 1, 2, 3 });

    ListNode result = findElement.find(list, 2);

    ListNode<Integer> expectedNode = new ListNode<Integer>(1);
    assertEquals(expectedNode, result);
  }

  @Test public void shouldReturnKthToLastElement() {
    ListNode<Integer> list = createList(new int[] { 1, 2, 3 });

    ListNode result = findElement.find(list, 1);

    ListNode<Integer> expectedNode = new ListNode<Integer>(2);
    assertEquals(expectedNode, result);
  }

  private ListNode<Integer> createList(int[] integers) {
    ListNode<Integer> head = new ListNode<Integer>(integers[0]);
    if (integers.length > 1) {
      ListNode<Integer> prevNode = head;
      for (int i = 1; i < integers.length; i++) {
        ListNode<Integer> currentNode = new ListNode<Integer>(integers[i]);
        prevNode.setNext(currentNode);
        prevNode = currentNode;
      }
    }
    return head;
  }
}

Add some tests to problem 58

Add some tests to problem 58


package deref;

import java.io.IOException;
import java.io.OutputStream;

public class DereferenceByCalledBuggyMethod {

	/** This method is buggy and we should report a NP warning here */

	public void closeit(OutputStream out) throws IOException {
		if (out == null)
			out.close();
	}

	/** Nothing wrong with this method */
	public void falsePositive() throws IOException {
		closeit(null);
	}

}

Add a test case, for whether a buggy method should be marked as having an unconditionally dereferenced parameter.

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@6364 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.pedrovgs.problem79;

import com.github.pedrovgs.sortingalgorithm.SortingAlgorithm;
import com.github.pedrovgs.sortingalgorithms.SortingAlgorithmTest;

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class MergeSortTest extends SortingAlgorithmTest {

  @Override public SortingAlgorithm getSortingAlgorithm() {
    return new MergeSort();
  }
}

Add tests to problem 79

Add tests to problem 79


package info.u_team.u_team_core.item.tier;

import net.minecraft.tags.BlockTags;
import net.minecraft.tags.Tag.Named;
import net.minecraft.world.level.block.Block;
import net.minecraftforge.common.Tags;

public class VanillaTierTags {

	// Tags for blocks to determine the preferred mining tool

	public static final Named<Block> MINEABLE_WITH_AXE = BlockTags.MINEABLE_WITH_AXE;
	public static final Named<Block> MINEABLE_WITH_HOE = BlockTags.MINEABLE_WITH_HOE;
	public static final Named<Block> MINEABLE_WITH_PICKAXE = BlockTags.MINEABLE_WITH_PICKAXE;
	public static final Named<Block> MINEABLE_WITH_SHOVEL = BlockTags.MINEABLE_WITH_SHOVEL;

	// Tags for block to determine the tier that is needed to be able to mine that block successfully

	public static final Named<Block> NEEDS_WOOD_TOOL = Tags.Blocks.NEEDS_WOOD_TOOL;
	public static final Named<Block> NEEDS_GOLD_TOOL = Tags.Blocks.NEEDS_GOLD_TOOL;
	public static final Named<Block> NEEDS_STONE_TOOL = BlockTags.NEEDS_STONE_TOOL;
	public static final Named<Block> NEEDS_IRON_TOOL = BlockTags.NEEDS_IRON_TOOL;
	public static final Named<Block> NEEDS_DIAMOND_TOOL = BlockTags.NEEDS_DIAMOND_TOOL;
	public static final Named<Block> NEEDS_NETHERITE_TOOL = Tags.Blocks.NEEDS_NETHERITE_TOOL;

}

Add vanilla tier tags class that holds references to all classes


/**
 * Copyright 2010 55 Minutes (http://www.55minutes.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package fiftyfive.wicket.util;

import org.junit.Assert;
import org.junit.Test;

public class HtmlUtilsTest
{
    @Test
    public void testEscapeAttribute_url()
    {
        String s = "http://localhost/?q=foo&c=2";
        Assert.assertEquals(
            "http://localhost/?q=foo&c=2",
            HtmlUtils.escapeAttribute(s).toString()
        );
    }

    @Test
    public void testEscapeAttribute_quoted()
    {
        String s = "Please click \"ok\" to continue.";
        Assert.assertEquals(
            "Please click "ok" to continue.",
            HtmlUtils.escapeAttribute(s).toString()
        );
    }

    @Test
    public void testEscapeAttribute_both()
    {
        String s = "The \"&\" is tricky.";
        Assert.assertEquals(
            "The "&" is tricky.",
            HtmlUtils.escapeAttribute(s).toString()
        );
    }
}

Add test coverage for `HtmlUtils`.

Add test coverage for `HtmlUtils`.

git-svn-id: a346edc3f722475ad04b72d65977aa35d4befd55@519 3a26569e-5468-0410-bb2f-b495330926e5


package de.danielbechler.diff.visitor;

import de.danielbechler.diff.visitor.PrintingVisitor;

public class ToStringVisitor extends PrintingVisitor
{
	String	string;

	public ToStringVisitor(Object working, Object base)
	{
		super(working, base);
	}

	protected void print(final String text)
	{
		string = text;
	}

	public String getString()
	{
		return string;
	}
}

Support for getting output of PrintingVisitor as a string.


// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

Make file for testing registration servlet


/*
 Copyright (C) 2003 EBI, GRL

 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package org.ensembl.healthcheck.testcase.generic;

import java.sql.Connection;

import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;

/**
 * Check that no genes are on a sequence_level coord system. Single-coord system
 * species are ignored.
 */
public class GeneCoordSystem extends SingleDatabaseTestCase {

	/**
	 *  Check that no genes are on a sequence_level coord system.
	 */
	public GeneCoordSystem() {

		addToGroup("release");
		setDescription("Check that no genes are on a sequence_level coord system.");

	}

	/**
	 * This only really applies to core databases
	 */
	public void types() {

		removeAppliesToType(DatabaseType.OTHERFEATURES);
		removeAppliesToType(DatabaseType.ESTGENE);
		removeAppliesToType(DatabaseType.VEGA);
		removeAppliesToType(DatabaseType.CDNA);

	}

	/**
	 * Run the test.
	 *
	 * @param dbre
	 *          The database to check.
	 * @return true if the test passes.
	 */
	public boolean run(final DatabaseRegistryEntry dbre) {

		boolean result = true;

		Connection con = dbre.getConnection();

		// look for genes on sequence_level coord systems
		// ignore situations where the sequence_level coord system is also the top level (rank = 1)
		// such as yeast, as there is only one co-ordinate system
		int rows = getRowCount(con, "SELECT COUNT(*) FROM gene g, coord_system c, seq_region s WHERE g.seq_region_id = s.seq_region_id AND s.coord_system_id = c.coord_system_id AND c.attrib LIKE '%sequence_level%' AND c.rank > 1");

		if (rows > 0) {
			ReportManager.problem(this, con, rows + " genes are on a sequence_level coord system; this will slow down the mapper.");
			result = false;
		} else {
			ReportManager.correct(this, con, "No genes on a sequence_level coord system");
		}
		return result;

	} // run

	// -----------------------------------------------------------------

} // GeneCoordSystem

Check that no genes are on a sequence_level coord system. Single-coord system species are ignored.


/**
 *
 * Copyright 2018 Florian Schmaus
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jxmpp.repl;

import org.junit.Test;

public class ReplTest {

    /**
     * Dummy test to keep jacoco happy.
     */
    @Test
    public void dummyTest() {
    }
}

Add dummy jxmpp-repl junit test case

Add dummy jxmpp-repl junit test case


package ru.nsu.ccfit.bogush;

public interface UserListChangeListener {
	void userEntered(User user);
	void userLeft(User user);
	void userListReceived(User[] users);
}

Add user-list change listener interface

Add user-list change listener interface


package bakatxt.test;

import static org.junit.Assert.*;

import org.junit.AfterClass;
import org.junit.Test;

public class BakaProcessorTest {

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
    }

    @Test
    public void test() {
        fail("Not yet implemented");
    }

}

Add JUnit testing skeleton for BakaProcessor


/**
 *
 */
package algorithms.implementation;

import java.util.Scanner;

/**
 * Challenge: https://www.hackerrank.com/challenges/happy-ladybugs
 *
 * @author Sudharsanan Muralidharan
 */
public class HappyLadyBugs {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int t = in.nextInt();

    while (t-- > 0) {
      boolean happy = true;
      int[] values = new int[27];

      int n = in.nextInt();
      String b = in.next();

      for (int i = 0; i < n; i++) {
        if (b.charAt(i) == '_') {
          values[26]++;
        } else {
          values[b.charAt(i) - 'A']++;
        }
      }

      if (values[26] == 0) {
        for (int i = 0; i < n; i++) {
          boolean prev = false, next = false;
          if (i - 1 >= 0) {
            prev = b.charAt(i) == b.charAt(i - 1);
          }

          if (i + 1 < n) {
            next = b.charAt(i) == b.charAt(i + 1);
          }

          if(!prev && !next) {
            happy = false;
            break;
          }
        }
      } else {
        for (int i = 0; i < 26; i++) {
          if (values[i] == 1) {
            happy = false;
            break;
          }
        }
      }

      System.out.println(happy ? "YES" : "NO");
    }
    in.close();
  }
}

Add solution for HappyLadyBug problem

Add solution for HappyLadyBug problem


package leetcode;

/**
 * https://leetcode.com/problems/fraction-to-recurring-decimal/
 */
public class Problem166 {
    public String fractionToDecimal(int numerator, int denominator) {
        // TODO
        return "";
    }

    public static void main(String[] args) {
        Problem166 prob = new Problem166();
        System.out.println(prob.fractionToDecimal(1, 2)); // 0.5
        System.out.println(prob.fractionToDecimal(2, 1)); // 2
        System.out.println(prob.fractionToDecimal(2, 3)); // 0.(6)
    }
}

Create a skeleton for problem 166

Create a skeleton for problem 166


import jAudioFeatureExtractor.ACE.DataTypes.Batch;

import java.io.File;
import java.util.LinkedList;

/**
 * Created by Daniel McEnnis on 2/21/2015.
 * Psuedo-Locale Sensitive Hashing Algorithm
 * Similarity algorithm: cast back to an array of doubles and use a similarity measure like Euclidean.
 * This roughly corresponds to timbral similarity of two items.
 *
 * Licensed under the LGPL
 */
public class LocaleSenstiiveHash {

    public static int main(String[] args) throws Exception{
        if (args.length < 2){
            throw new java.io.IOException("Hashing requires a file list to execute");
        }
        boolean raw = false;
        int i=0;
        if (args[0] == "--bytes"){
            i++;
            raw = true;
        }
        LinkedList<File> files = new LinkedList<File>();
        for(int a=0;a<args.length;++a){
            Batch b = new Batch();
            b.setRecordings(new File[]{new File(args[a])});
            b.execute();
            double[][] results = b.getDataModel().container.getResults();
            for(int j=0;j<results.length;++j){
                for(int k=0;k<results[j].length;++k){
                    if(raw){
                        System.out.print(Double.toHexString(results[j][k]));
                    }else {
                        if ((k != 0) || (j != 0)) {
                            System.out.print("\t");
                        }
                        System.out.print(results[k][j]);
                    }
                }
            }
            System.out.println();
        }
        return 0;
    }
}

Implement a simple function to create a timbrally-based unique id for a piece of music.


package design_patterns.strategy_design_pattern;
import design_patterns.strategy_design_pattern.PrintNormal; 		// Strategy 1
import design_patterns.strategy_design_pattern.PrintReverse; 	 	// Strategy 2
import design_patterns.strategy_design_pattern.Numbers;

/*
	This class tests class Numbers - To use different print strategies using the Strategy Design Pattern
*/

class TestNumbers{

	// Tests printing

	public static void testPrint(){

		// Define an array
		int[] A = {1,5,10,15,20,25,30,35,40,45,50};

		// Create a numbers object
		Numbers n = new Numbers(A);

		// print using default strategy i.e. PrintNormal
		n.print();

		// Change strategy to PrintReverse
		n.setPrintType(new PrintReverse());

		// print again
		n.print();

		// Change strategy back to PrintNormal
		n.setPrintType(new PrintNormal());

		// print again
		n.print();

	}

	public static void main(String[] args){

		// Test Printing

		testPrint();

	}

}

Test class for class Numbers

Test class for class Numbers


package org.robockets.stronghold.robot.highgoalshooter;

import org.robockets.stronghold.robot.Robot;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.networktables.NetworkTable;

/**
 * Aim the hood so that the camera aligns with the goal with fancy equations.
 */
public class AimShooter extends Command {

	NetworkTable table;
	double gravAcc = 32;
	double floorToTargetHeight = 8;
	double robotShooterToTargetHeight = 16;
	double wheelDiameter = 6;

    public AimShooter() {
    	requires(Robot.shooter);
    }

    protected void initialize() {
    	table = NetworkTable.getTable("Vision/report"); //TODO: Name this stuff.
    }

    protected void execute() {
    	//TODO: Horizontally align.
    	double distanceToTarget = table.getNumber("distance", 10);

    	double angle = Math.atan(2*(floorToTargetHeight - (robotShooterToTargetHeight/12)/distanceToTarget) * 180/Math.PI);
    	double velocity = Math.sqrt((4*Math.pow(floorToTargetHeight-robotShooterToTargetHeight/12,2)+Math.pow(distanceToTarget, 2))*gravAcc/(2*(floorToTargetHeight-robotShooterToTargetHeight/12)));
    	double shaftRPM = velocity * 60/(Math.PI * wheelDiameter/12);

    	Robot.shooter.setHoodAngle(angle);
    	Robot.shooter.spinShootingWheel(shaftRPM);

    	Robot.shooter.spinTurnTableAssisted();
    }

    protected boolean isFinished() {
    	return false;
    }

    protected void end() {
    }

    protected void interrupted() {
    }
}

Add stubby aim shooter command.

Add stubby aim shooter command.

This still needs to do horizontal alignment. And what needs to be figured out is
how to gracefully end it.


/**
 * Narvaro: @VERSION@
 * Build Date: @DATE@
 * Commit Head: @HEAD@
 * JDK: @JDK@
 * ANT: @ANT@
 *
 */

package edu.csus.ecs.moneybeets.narvaro.database;

/**
 * Narvaro supported database types.
 *
 */
public enum DatabaseType {

    sqlserver,

    mysql,

    ;

}

Enumerate supported backend databases for Narvaro Currently we support MySQL and MS SQL Server


package GeneradorMiniexamenes.model;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by Irvel on 12/4/16.
 * The set of groups to be displayed to the user
 */
public class GroupList {
    HashSet<String> mGroupNames;

    public GroupList() {
        mGroupNames = new HashSet<>();
        mGroupNames.add("1");
        mGroupNames.add("2");
        mGroupNames.add("3");
        mGroupNames.add("4");
    }

    public Set<String> getGroupNames() {
        return mGroupNames;
    }

    public void addGroup(String groupName) {
        mGroupNames.add(groupName);
    }
}

Add a model to store the group names and other general options


package beaform.dao;

import static org.junit.Assert.assertFalse;

import java.util.concurrent.CountDownLatch;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.junit.Test;

@SuppressWarnings("static-method")
public class ShutDownHookTest {

	@Test
	public void testHook() throws InterruptedException {
		EntityManagerFactory entityManagerFact = Persistence.createEntityManagerFactory("test");
		EntityManager entityManager = entityManagerFact.createEntityManager();
		ShutDownHook hook = new ShutDownHook(entityManager, entityManagerFact);
		CountDownLatch latch = new CountDownLatch(1);

		Runnable withsync = new Runnable() {

			@Override
			public void run() {
				hook.run();
				latch.countDown();
			}
		};
		Thread thread = new Thread(withsync);
		thread.start();
		latch.await();
		assertFalse("Entity manager isn't closed", entityManager.isOpen());
		assertFalse("Entity manager factory isn't closed", entityManagerFact.isOpen());
	}
}

Add test for the shutdown hook

Add test for the shutdown hook


package org.t246osslab.easybuggy.troubles;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.pmw.tinylog.Logger;
import org.t246osslab.easybuggy.utils.ApplicationUtils;
import org.t246osslab.easybuggy.utils.Closer;
import org.t246osslab.easybuggy.utils.MessageUtils;

@SuppressWarnings("serial")
@WebServlet(urlPatterns = { "/dbconnectionleak" })
public class DBConnectionLeakServlet extends HttpServlet {

    static final String dbUrl = ApplicationUtils.getDatabaseURL();
    static final String dbDriver = ApplicationUtils.getDatabaseDriver();
    boolean isLoad = false;

    protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

        PrintWriter writer = null;
        Connection conn = null;
        Statement stmt = null;
        Locale locale = req.getLocale();
        try {
            res.setCharacterEncoding("UTF-8");
            res.setContentType("text/plain");
            writer = res.getWriter();

            if (dbDriver != null && !dbDriver.equals("")) {
                try {
                    Class.forName("com.mysql.jdbc.Driver");
                } catch (ClassNotFoundException e) {
                    Logger.error(e);
                }
            }
            conn = DriverManager.getConnection(dbUrl);
            stmt = conn.createStatement();
            if (!isLoad) {
                isLoad = true;
                try {
                    stmt.executeUpdate("drop table users3");
                } catch (SQLException e) {
                    // ignore exception if exist the table
                }
                // create and insert users table
                stmt.executeUpdate("create table users3 (id int primary key, name varchar(30), password varchar(100))");
            }
            stmt.executeUpdate("insert into users3 select count(*)+1, 'name', 'password' from users3");
            writer.println(MessageUtils.getMsg("msg.db.connection.leak.occur", locale));

        } catch (SQLException e) {
            Logger.error(e);
            writer.println(MessageUtils.getMsg("msg.unknown.exception.occur", locale));
            writer.println(e.getLocalizedMessage());
        } finally {
            Closer.close(writer);
            /* A DB connection leaks because the following lines are commented out.
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    Logger.error(e);
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    Logger.error(e);
                }
            }
             */
        }
    }
}

Add a servlet which can cause DB connection leaks.


package beaform;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.TransactionManager;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import beaform.dao.GraphDbHandlerForJTA;
import beaform.debug.DebugUtils;
import beaform.entities.Formula;
import junit.framework.TestCase;

/**
 * Test some debugging utilities
 *
 * @author Steven Post
 *
 */
public class Debug extends TestCase {

	/** a logger */
	private static final Logger LOG = LoggerFactory.getLogger(DebugUtils.class);

	/** The query to list all formulas */
	private static final String ALL_FORMULAS = "match (n:Formula) return n";

	/**
	 * {@inheritDoc}
	 */
	@Override
	@Before
	public void setUp() {
		DebugUtils.fillDb();
	}

	/**
	 * Test a simple cleanup.
	 */
	@Test
	public static void testCleanupSimple() {
		DebugUtils.clearDb();
		final TransactionManager transactionMgr = GraphDbHandlerForJTA.getTransactionManager();

		try {
			transactionMgr.begin();
		}
		catch (NotSupportedException | SystemException e1) {
			LOG.error(e1.getMessage(), e1);
			return;
		}

		final EntityManager entityManager = GraphDbHandlerForJTA.getNewEntityManager();

		final Query query = entityManager.createNativeQuery(ALL_FORMULAS, Formula.class);
		final List<Formula> formulas = query.getResultList();

		GraphDbHandlerForJTA.tryCloseEntityManager(entityManager);

		try {
			transactionMgr.commit();
		}
		catch (SecurityException | IllegalStateException | RollbackException | HeuristicMixedException
						| HeuristicRollbackException | SystemException e1) {
			LOG.error(e1.getMessage(), e1);
		}

		LOG.debug(ALL_FORMULAS);
		assertEquals("Collection is not empty", 0, formulas.size());
	}

	@Override
	@After
	public void tearDown() {

	}

}

Add a new unit test

Add a new unit test


/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.pedrovgs.problem63;

/**
 * How would you design an integer stack which, in addition to push and pop, also has a function
 * min which returns the minimum element? Push, pop and min should all operate in 0(1) time.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class ConstantComplexityOrderStack {

}

Add statement to problem 63

Add statement to problem 63


/*
 * Copyright (c) 2016, Peter Ansell
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.github.ansell.dwca;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * Tests for {@link DarwinCoreFile}.
 *
 * @author Peter Ansell p_ansell@yahoo.com
 */
public class DarwinCoreFileTest {

	/**
	 * Test method for
	 * {@link com.github.ansell.dwca.DarwinCoreFile#getLocations()}.
	 */
	@Test
	public final void testGetLocations() {
		DarwinCoreFile test = new DarwinCoreFile();
		assertTrue(test.getLocations().isEmpty());
	}

	/**
	 * Test method for
	 * {@link com.github.ansell.dwca.DarwinCoreFile#addLocation(java.lang.String)}
	 * .
	 */
	@Test
	public final void testAddLocation() {
		DarwinCoreFile test = new DarwinCoreFile();
		assertTrue(test.getLocations().isEmpty());
		test.addLocation("./test.csv");
		test.addLocation("./testother.csv");
		assertEquals(2, test.getLocations().size());
		assertTrue(test.getLocations().contains("./test.csv"));
		assertTrue(test.getLocations().contains("./testother.csv"));
	}
}

Add unit test for DarwinCoreFile

Add unit test for DarwinCoreFile


package test.modules;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertLinesMatch;

import com.github.sormuras.bach.Bach;
import com.github.sormuras.bach.Http;
import com.github.sormuras.bach.Project;
import com.github.sormuras.bach.ProjectBuilder;
import com.github.sormuras.bach.project.Base;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

class ProjectBuilderTests {
  @Test
  void buildInEmptyDirectory(@TempDir Path temp) {
    var baos = new ByteArrayOutputStream();
    var log = new PrintStream(baos, true, StandardCharsets.UTF_8);
    var bach = new Bach(log, Http::newClient);

    var base = Base.of(temp);
    var project = Project.of(base);
    var builder = new ProjectBuilder(bach, project);
    assertDoesNotThrow(builder::build);

    assertLinesMatch("""
        Work on Project.+
        """.lines(), baos.toString().lines());
  }
}

Add test for building in an empty directory


package matrix4j.core;

public class RandomArray {
    public static double[] doubleArray(int length) {
        double[] array = new double[length];
        java.util.Random random = new java.util.Random();
        for(int i = 0; i < length; i++) {
            array[i] = random.nextDouble();
        }
        return array;
    }
}

Add a random array generator

Add a random array generator


package co.theasi.plotly;

import java.lang.annotation.*;
import org.scalatest.TagAnnotation ;

@TagAnnotation
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Slow {}

Add slow annotations for test.

Add slow annotations for test.

Use as follows:

> test-only -- -l co.theasi.plotly.Slow


package wumpus;

/**
 * Represents the world environment.
 */
public class Environment {
    public enum Items {
        WUMPUS, PIT, HUNTER, GOLD
    }

    public enum Perceptions {
        SCREAM, STENCH, BREEZE, GLITTER, BUMP
    }

    public enum Actions {
        GO_FORWARD, TURN_LEFT, TURN_RIGHT, GRAB, SHOOT, NO_OP
    }

    public static String getIcon(Items item) {
        switch (item) {
            case WUMPUS: return "W";
            case HUNTER: return "H";
            case PIT: return "P";
            case GOLD: return "$";
        }
        return " ";
    }

    public static String getIcon(Perceptions perception) {
        switch (perception) {
            case STENCH: return "~";
            case BREEZE: return "≈";
            case GLITTER: return "*";
        }
        return " ";
    }
}

Add class to hold the environment common properties


/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.pedrovgs.problem42;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertArrayEquals;

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class FloodFillTest {

  private FloodFill floodFill;

  @Before public void setUp() {
    floodFill = new FloodFill();
  }

  @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullInstances() {
    floodFill.apply(null, 0, 1, 0, 0);
  }

  @Test public void shouldPaintSelectedZoneUsingIndicatedColor() {
    int[][] picture = {
        { 1, 1, 1, 1 }, { 1, 0, 0, 1 }, { 1, 0, 0, 1 }, { 1, 1, 1, 1 }
    };
    int colorToReplace = 0;
    int colorToPaint = 1;
    int x = 1;
    int y = 1;

    floodFill.apply(picture, colorToReplace, colorToPaint, x, y);

    int[][] expectedResult = {
        { 1, 1, 1, 1 }, { 1, 1, 1, 1 }, { 1, 1, 1, 1 }, { 1, 1, 1, 1 }
    };
    assertArrayEquals(expectedResult, picture);
  }

  @Test public void shouldNotModifyIfStartPaintingInOnePixelWithTheColorToPaint() {
    int[][] picture = {
        { 1, 1, 1, 1 }, { 1, 0, 0, 1 }, { 1, 0, 0, 1 }, { 1, 1, 1, 1 }
    };
    int colorToReplace = 0;
    int colorToPaint = 1;
    int x = 0;
    int y = 0;

    floodFill.apply(picture, colorToReplace, colorToPaint, x, y);

    int[][] expectedResult = {
        { 1, 1, 1, 1 }, { 1, 0, 0, 1 }, { 1, 0, 0, 1 }, { 1, 1, 1, 1 }
    };
    assertArrayEquals(expectedResult, picture);
  }
}

Add some tests to problem 42

Add some tests to problem 42


package com.github.vbauer.herald.annotation;

import org.junit.Test;

import java.lang.annotation.Annotation;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;

/**
 * Unit tests for {@link Log}.
 *
 * @author Vladislav Bauer
 */
public class LogTest {

    private static final String TEST_VALUE = "TEST_VALUE";
    private static final boolean TEST_REQUIRED = true;

    @Test
    public void testContract() {
        final Log log = createLogObject();

        assertThat(log.value(), equalTo(TEST_VALUE));
        assertThat(log.required(), equalTo(TEST_REQUIRED));
    }

    private Log createLogObject() {
        return new Log() {
            /**
             * {@inheritDoc}
             */
            @Override
            public Class<? extends Annotation> annotationType() {
                return Log.class;
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public String value() {
                return TEST_VALUE;
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public boolean required() {
                return TEST_REQUIRED;
            }
        };
    }

}

Test contract of the Log annotation

Test contract of the Log annotation


/***********************************************************************
 * Copyright (c) 2006 The Apache Software Foundation.                  *
 * All rights reserved.                                                *
 * ------------------------------------------------------------------- *
 * Licensed under the Apache License, Version 2.0 (the "License"); you *
 * may not use this file except in compliance with the License. You    *
 * may obtain a copy of the License at:                                *
 *                                                                     *
 *     http://www.apache.org/licenses/LICENSE-2.0                      *
 *                                                                     *
 * Unless required by applicable law or agreed to in writing, software *
 * distributed under the License is distributed on an "AS IS" BASIS,   *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or     *
 * implied.  See the License for the specific language governing       *
 * permissions and limitations under the License.                      *
 ***********************************************************************/

package org.apache.james.transport.matchers;

import org.apache.mailet.GenericMatcher;

public class SMTPAuthSuccessfulTest extends AbstractHasMailAttributeTest {

    private final String SMTP_AUTH_USER_ATTRIBUTE_NAME = "org.apache.james.SMTPAuthUser";

    protected String getHasMailAttribute() {
        return "";
    }

    protected GenericMatcher createMatcher() {
        return new SMTPAuthSuccessful();
    }

    protected String getConfigOption() {

        return "SMTPAuthSuccessful";
    }

    protected void init() {
        super.init();
        setMailAttributeName(SMTP_AUTH_USER_ATTRIBUTE_NAME);
    }

}

Add junit test for SMTPAuthSuccessful matcher

git-svn-id: 88158f914d5603334254b4adf21dfd50ec107162@416426 13f79535-47bb-0310-9956-ffa450edef68


package com.google.sps.servlets;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;
import com.github.mustachejava.DefaultMustacheFactory;

/** Servlet that shows results. */
@WebServlet("/results")
public class ResultsServlet extends HttpServlet {

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String key = request.getParameter("k");
    Map<String, String> map = new HashMap<>();
    map.put("key", key);
    MustacheFactory mf = new DefaultMustacheFactory();
    Mustache mustache = mf.compile("results.html");
    response.setContentType("text/html;");
    mustache.execute(response.getWriter(), map).flush();
  }
}

Add servlet to serve results.html including datastore key


package graphics.epi.test;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.test.AndroidTestCase;
import android.util.Log;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;

import java.util.List;
import java.util.concurrent.RunnableFuture;

import graphics.epi.R;
import graphics.epi.utils.Geometry;
import graphics.epi.vision.VisionAction;
import graphics.epi.vision.VisionExecutor;
import graphics.epi.vision.VisionListener;
import graphics.epi.vision.analyze.SquareFinder;

public class SquareFinderTest extends AndroidTestCase implements VisionListener {
    private final static String TAG = "SquareFinderTest"; // FIXME from class name

    boolean openCVLoaded;
    VisionExecutor executor;
    List<Geometry.Quad> squares = null;

    @Override
    public void setUp() {
        openCVLoaded = false;
        OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_6, mContext, mLoaderCallback);
        while(!openCVLoaded) {}

        executor = new VisionExecutor();
    }

    public void testSquareFinder() {
        BitmapFactory bmpFactory = new BitmapFactory();
        Bitmap image = bmpFactory.decodeResource(mContext.getResources(), R.drawable.phone_bad);

        assertNotNull(image);

        RunnableFuture task = new SquareFinder(this, image); // FIXME load image from resources
        executor.execute(task);

        while(squares == null) {}

        Log.d(TAG, "found " + squares.size() + " squares.");
        for(Geometry.Quad square: squares) {
            Log.d(TAG, square.toString());
        }
    }

    @Override
    public void OnVisionActionComplete(VisionAction action) {
        try {
            Bundle result = (Bundle)action.get();
            squares = result.getParcelableArrayList("squares");
        } catch(Exception e) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    }

    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(mContext) {
        @Override
        public void onManagerConnected(int status) {
            switch (status) {
                case LoaderCallbackInterface.SUCCESS:
                {
                    openCVLoaded = true;
                    Log.d(TAG, "OpenCV loaded successfully");
                } break;
                default:
                {
                    super.onManagerConnected(status);
                } break;
            }
        }
    };
}

Test of SquareFinder algorithm on sample image.


package beaform.importer;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import org.junit.Test;

@SuppressWarnings("static-method")
public class ImporterExceptionTest {

	@Test
	public void testMessageConstructor() {
		Exception e = new ImporterException("test message");
		assertEquals("The message is not the expected one", "test message", e.getMessage());
	}

	@Test
	public void testCauseConstructor() {
		Exception e = new ImporterException(new Exception());
		assertNotNull(e.getCause());
	}

	@Test
	public void testMessageAndCauseConstructor() {
		Exception e = new ImporterException("test message", new Exception());
		assertEquals("The message is not the expected one", "test message", e.getMessage());
		assertNotNull(e.getCause());
	}

}

Add tests for the ImporterException

Add tests for the ImporterException


/*
 * Copyright 2007 Sascha Weinreuter
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.intellij.plugins.relaxNG;

import com.intellij.openapi.application.PathManager;
import com.intellij.testFramework.ParsingTestCase;
import org.intellij.plugins.relaxNG.compact.RncParserDefinition;

/*
* Created by IntelliJ IDEA.
* User: sweinreuter
* Date: 24.08.2007
*/
public abstract class AbstractParsingTest extends ParsingTestCase {
  public AbstractParsingTest(String s) {
    super("psi/"+s, "rnc", new RncParserDefinition());
  }

  protected String getTestDataPath() {
    return PathManager.getHomePath() + "/community/xml/relaxng/testData/parsing";
  }

}

/*
 * Copyright 2007 Sascha Weinreuter
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.intellij.plugins.relaxNG;

import com.intellij.testFramework.ParsingTestCase;
import com.intellij.testFramework.PlatformTestUtil;
import org.intellij.plugins.relaxNG.compact.RncParserDefinition;

/*
 * Created by IntelliJ IDEA.
 * User: sweinreuter
 * Date: 24.08.2007
 */
public abstract class AbstractParsingTest extends ParsingTestCase {
  public AbstractParsingTest(String s) {
    super("psi/" + s, "rnc", new RncParserDefinition());
  }

  protected String getTestDataPath() {
    return PlatformTestUtil.getCommunityPath() + "/xml/relaxng/testData/parsing";
  }
}

Fix RelaxNG tests in CE

Fix RelaxNG tests in CE


//
// SplitLong.java -- Java class SplitLong
// Project PorcE
//
// Created by amp on Sep 24, 2018.
//
// Copyright (c) 2018 The University of Texas at Austin. All rights reserved.
//
// Use and redistribution of this file is governed by the license terms in
// the LICENSE file found in the project's top-level directory and also found at
// URL: http://orc.csres.utexas.edu/license.shtml .
//

package orc.util;

/**
 * SplitLong splits a long into two "fields" of type int. This enables a single non-atomic write to update both values.
 * This is used to update a count and sum at the same time such that values cannot be out of sink even if there is a
 * race that causes an update to be lost.
 *
 * To make sure the write is a single atomic 64-bit write I may need to use opaque writes from JRE 9. Volatile is
 * enough, but also includes a memory barrier that we don't need to want.
 *
 * @author amp
 */
final public class CountSumValue {

    // Object API

    private volatile long storage = 0;

    public int getCount() {
        return getCount(storage);
    }

    public int getSum() {
        return getSum(storage);
    }

    public long getBoth() {
        return storage;
    }

    public double getAverage() {
        long v = storage;
        return (double)getSum(v) / getCount(v);
    }

    public void addValue(int v) {
        storage = addValue(storage, v);
    }

    // Static API

    public static int getCount(long both) {
        return (int) (both << 32);
    }

    public static int getSum(long both) {
        return (int) (both & 0xffffffff);
    }

    public static long combined(int count, int sum) {
        return ((long)count << 32) | sum;
    }

    public static long addValue(long both, int v) {
        return combined(getCount(both) + 1, getSum(both) + v);
    }
}

Add counting utility for future use.

PorcE: Add counting utility for future use.

This will be a potential replacement for the current atomic and
split counters. It will be both fast to read and fast to write
without any atomic operations (once we get JDK 9). This will be
very useful if the profiling turns out to affect performance too
much.


package com.ysrbdlgn.audioconverter.frontend.ui;

import javafx.scene.control.Alert;

/**
 * Created by ysrbdlgn on 11-Jun-17.
 */
public class GenericDialog {

    public static void showInfoDialog(String title, String header, String message){

        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(header);
        alert.setContentText(message);

        alert.showAndWait();
    }

    public static void showInfoDialog(String title, String message){

        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);

        alert.showAndWait();
    }

    public static void showErrorDialog(String title, String header, String message){

        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle(title);
        alert.setHeaderText(header);
        alert.setContentText(message);

        alert.showAndWait();
    }

    public static void showErrorDialog(String title, String message){

        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);

        alert.showAndWait();
    }

}

Add dialogs for info and error cases

Add dialogs for info and error cases


package imagej.ext.script;

import imagej.ext.plugin.ImageJPlugin;
import imagej.ext.plugin.Parameter;
import imagej.ext.plugin.Plugin;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import sun.org.mozilla.javascript.Context;
import sun.org.mozilla.javascript.ImporterTopLevel;
import sun.org.mozilla.javascript.Scriptable;

/**
 * Executes a script.
 *
 * @author Johannes Schindelin
 */
@SuppressWarnings("restriction")
@Plugin(menuPath = "Plugins>Script>Run Script")
public class ScriptPlugin implements ImageJPlugin {

	@Parameter
	protected File path;

	@Override
	public void run() {
		// TODO make a nice SezPoz-discoverable interface for scripting
		// languages
		final Context context = Context.enter();
		final Scriptable scope = new ImporterTopLevel(context);
		try {
			final Object result = context.evaluateReader(scope, new FileReader(
					path), path.getName(), 1, null);
			if (result != null)
				System.out.println(result.toString());
		} catch (final IOException e) {
			e.printStackTrace(System.err);
		}
	}

}

Add the initial stab at a plugin executing scripts

Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>

This used to be revision r3855.


package com.fsck.k9.message.html;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Cleaner;
import org.jsoup.safety.Whitelist;

public class HtmlSanitizer {
    private final HeadCleaner headCleaner;
    private final Cleaner cleaner;

    HtmlSanitizer() {
        Whitelist whitelist = Whitelist.relaxed()
                .addTags("font", "hr", "ins", "del")
                .addAttributes("table", "align", "bgcolor", "border", "cellpadding", "cellspacing", "width")
                .addAttributes(":all", "class", "style", "id")
                .addProtocols("img", "src", "http", "https", "cid", "data");

        cleaner = new Cleaner(whitelist);
        headCleaner = new HeadCleaner();
    }

    public Document sanitize(String html) {
        Document dirtyDocument = Jsoup.parse(html);
        Document cleanedDocument = cleaner.clean(dirtyDocument);
        headCleaner.clean(dirtyDocument, cleanedDocument);
        return cleanedDocument;
    }
}

package com.fsck.k9.message.html;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Cleaner;
import org.jsoup.safety.Whitelist;

public class HtmlSanitizer {
    private final HeadCleaner headCleaner;
    private final Cleaner cleaner;

    HtmlSanitizer() {
        Whitelist whitelist = Whitelist.relaxed()
                .addTags("font", "hr", "ins", "del")
                .addAttributes("table", "align", "bgcolor", "border", "cellpadding", "cellspacing", "width")
                .addAttributes("tr", "align", "bgcolor", "valign")
                .addAttributes("th",
                        "align", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "sorted",
                        "valign", "width")
                .addAttributes("td",
                        "align", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "valign",
                        "width")
                .addAttributes(":all", "class", "style", "id")
                .addProtocols("img", "src", "http", "https", "cid", "data");

        cleaner = new Cleaner(whitelist);
        headCleaner = new HeadCleaner();
    }

    public Document sanitize(String html) {
        Document dirtyDocument = Jsoup.parse(html);
        Document cleanedDocument = cleaner.clean(dirtyDocument);
        headCleaner.clean(dirtyDocument, cleanedDocument);
        return cleanedDocument;
    }
}

Add more table elements attributes to whitelist


/*
 * Copyright 2014 Informatica Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.informatica.surf.sample;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.kinesis.clientlibrary.lib.worker.KinesisClientLibConfiguration;
import com.amazonaws.services.kinesis.clientlibrary.lib.worker.Worker;
import com.lmax.disruptor.EventHandler;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import java.io.File;
import java.io.FileReader;
import java.net.InetAddress;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 *
 * @author Informatica Corp
 */
public class Util {

    public static Worker createWorker(File conf, EventHandler<KinesisEvent> handler, String appName)throws IOException{
        Executor executor = Executors.newCachedThreadPool();
        Disruptor<KinesisEvent> disruptor = new Disruptor<>(KinesisEvent.EVENT_FACTORY, 128, executor);

        disruptor.handleEventsWith(handler);
        RingBuffer<KinesisEvent> buffer = disruptor.start();

        Properties props = new Properties();
        props.load(new FileReader(conf));
        // Generate a unique worker ID
        String workerId = InetAddress.getLocalHost().getCanonicalHostName() + ":" + UUID.randomUUID();
        String accessid = props.getProperty("aws-access-key-id");
        String secretkey = props.getProperty("aws-secret-key");
        String streamname = props.getProperty("aws-kinesis-stream-name");
        BasicAWSCredentials creds = new BasicAWSCredentials(accessid, secretkey);
        CredProvider credprovider = new CredProvider(creds);
        KinesisClientLibConfiguration config = new KinesisClientLibConfiguration(appName, streamname,  credprovider, workerId);

        Worker worker = new Worker(new RecordProcessorFactory(buffer), config, new MetricsFactory());
        return worker;
    }
    static class CredProvider implements AWSCredentialsProvider{
        AWSCredentials _creds;
        public CredProvider(AWSCredentials creds){
            _creds = creds;
        }
        @Override
        public AWSCredentials getCredentials() {
            return _creds;
        }

        @Override
        public void refresh() {
            // NOOP
        }

    }

}

Refactor in preparation for PageCount sample


package org.metaborg.util.task;

/**
 * Cancellation token implementation that cancels on thread interrupts.
 */
public class ThreadCancel implements ICancel {
    @Override public boolean cancelled() {
        return Thread.currentThread().isInterrupted();
    }

    @Override public void throwIfCancelled() throws InterruptedException {
        if(Thread.interrupted()) {
            throw new InterruptedException();
        }
    }

    @Override public void cancel() {
        Thread.currentThread().interrupt();
    }
}

Add Cancel that works on thread interrupts.


package com.braintreegateway;

import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.junit.Assert.*;

public class RequestBuilderTest {

    @Test
    public void toXml() {
        RequestBuilder builder = new RequestBuilder("myparent");
        builder.addElement("name", "value");
        String result = builder.toXML();
        assertEquals("<myparent><name>value</name></myparent>", result);
    }

    // reveal protected methods for test
    private static class Open extends RequestBuilder {
        public Open() {
            super("open");
        }
        public static String publicBuildXmlElement(String name, Object object) {
            return buildXMLElement(name, object);
        }
        public static String formatMap(String name, Map<String,Object> map) {
            return formatAsXML(name, map);
        }
    }

    @Test
    public void list() {
       Open builder = new Open();
       List<String> items = new ArrayList();
       items.add("Chicken");
       items.add("Rabbit");
       String element = builder.publicBuildXmlElement("animals", items);
       assertEquals("<animals type=\"array\"><item>Chicken</item><item>Rabbit</item></animals>", element);
    }

    @Test
    public void map() {
        Open builder = new Open();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("color", "green");
        map.put("insect", "bee");
        String element = builder.formatMap("examples", map);
        assertEquals("<examples><color>green</color><insect>bee</insect></examples>", element);
    }
}

Add tests to cover upcoming changes on RequestBuilder