/* @(#)MoveFitness.java
 */
/**
 *  Class containing all of the business logic regarding whether a
 *  move is considered good or not.
 *
 * @author Geoff Shannon
 */

package wall_follower;

public class MoveFitness {

    // TODO: fix these values!!! Set arbitrarily for right now
    private static final float MIN_GOOD_DISTANCE = 0.1f;
    private static final float MAX_GOOD_DISTANCE = 1.0f;

    private int goodMoves;
    private int badMoves;

    /**
     *  Overall, the way that we score moves is this: there is a
     *  predefined "good" range.  If the move caused us to stay in
     *  that range, then it was good.  If we were outside the range,
     *  then if the move put us closer to that range it was good.
     *  Otherwise, it was a bad move.
     */
    public void scoreMove(SensorReading before, SensorReading after) {

        if (inGoodRange(before.distance)) {
            if (inGoodRange(after.distance)) {
                goodMoves++;
            } else {
                badMoves++;
            }
        } else {
            // If deltaDistance is positive then we moved away from
            // the wall, if it is negative then we moved closer.
            float deltaDistance = after.distance - before.distance;

            // If we were too close, and got farther away: good
            if (before.distance < MIN_GOOD_DISTANCE &&
                deltaDistance > 0) {
                goodMoves++;
            // Or if we were too far and got closer: good
            } else if (before.distance > MAX_GOOD_DISTANCE &&
                       deltaDistance < 0) {
                goodMoves++;

            } else {
                badMoves++;
            }
        }
    }

    public float getFitness() {
        return goodMoves / badMoves;
    }

    private static boolean inGoodRange(float distance) {
        return (distance >= MIN_GOOD_DISTANCE) &&
            (distance <= MAX_GOOD_DISTANCE);
    }
}

Add a simplistic move fitness evaluation


/*
 * Copyright (c) 2011-2019, PCJ Library, Marek Nowicki
 * All rights reserved.
 *
 * Licensed under New BSD License (3-clause license).
 *
 * See the file "LICENSE" for the full license governing this code.
 */
package org.pcj.test;

import org.pcj.PCJ;
import org.pcj.RegisterStorage;
import org.pcj.StartPoint;
import org.pcj.Storage;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Marek Nowicki (faramir@mat.umk.pl)
 */
@RegisterStorage(AbortTest.Vars.class)
public class AbortTest implements StartPoint {
    @Storage(AbortTest.class)
    enum Vars {wait}

    private boolean wait;

    public static void main(String[] args) {
        Level level = Level.INFO;
//        Level level = Level.CONFIG;
        Logger logger = Logger.getLogger("");
        Arrays.stream(logger.getHandlers()).forEach(handler -> handler.setLevel(level));
        logger.setLevel(level);

        String[] nodes = {
                "localhost:8091",
                "localhost:8002",
                "localhost:8003",
                "localhost:8004",
                "localhost:8091",
                "localhost:8002",
                "localhost:8003",
                "localhost:8004",
        };

        PCJ.executionBuilder(AbortTest.class)
                .addNodes(nodes)
                .deploy();
    }

    @Override
    public void main() throws Throwable {
        if (PCJ.myId() == 2) {
            Thread.sleep(1_000);
            throw new RuntimeException("Thread-" + PCJ.myId() + ": Abort");
        }
        PCJ.at(0, () -> {
            try {
                Thread.sleep(2_000);
            } catch (Exception e) {
                System.err.println("Thread-" + PCJ.myId() + " exception: " + e);
            }
            PCJ.waitFor(Vars.wait);
        });
        try {
            Thread.sleep(2_000);
        } catch (Exception e) {
            System.err.println("Thread-" + PCJ.myId() + " exception: " + e);
        }
        PCJ.waitFor(Vars.wait);
    }
}

Stop PCJ threads on error/abort.


package javaAnagrams;

import java.util.Scanner;

public class Solution {

	   static boolean isAnagram(String A, String B) {
		   if( A.length() != B.length() )
			   return false;
		   int arrayLength = 256;
	       int[] arrayOne = new int[arrayLength],
	    		 arrayTwo = new int[arrayLength];
	       for(int i = 0; i < A.length(); ++i) {
	    	   arrayOne[(A.charAt(i) - '0' - 1)] += 1;
	    	   arrayTwo[(B.charAt(i) - '0' - 1)] += 1;
	       }
	       for(int i = 0; i < arrayLength; ++i) {
	    	   if(arrayOne[i] != arrayTwo[i])
	    		  return false;
	       }
		   return true;
	   }
	    public static void main(String[] args) {
	        Scanner scanner = new Scanner(System.in);
	        String wordOne = scanner.next();
	        String wordTwo = scanner.next();
	        boolean decision = isAnagram(wordOne.toLowerCase(), wordTwo.toLowerCase());
	        if(decision)
	        	System.out.println("Anagrams");
	        else
	        	System.out.println("Not Anagrams");
	        scanner.close();
	    }
	}

Add problem Java Anagrams, HackerRank/Java/Strings/Java String


package org.jsmpp.util;

import static org.testng.Assert.*;
import org.jsmpp.bean.DeliveryReceipt;
import org.testng.annotations.Test;

/**
 * @author uudashr
 *
 */
public class DeliveryReceiptParserTest {
    private PDUDecomposer decomposer = new DefaultDecomposer();
    private static final String ORIGINAL_MESSAGE = "testing jsmpp bow";

    @Test
    public void parseTextWithLowerCase() {
        try {
            DeliveryReceipt delReceipt = decomposer.deliveryReceipt("id:0123456789 sub:001 dlvrd:001 submit date:200809011130 done date:200809011131 stat:DELIVRD err:000 text:" + ORIGINAL_MESSAGE);
            assertEquals(delReceipt.getText(), ORIGINAL_MESSAGE);
        } catch (InvalidDeliveryReceiptException e) {
            fail("Failed parsing delivery receipt:" + e.getMessage());
        }
    }

    @Test
    public void parsingTextWithUpperCase() {
        try {
            DeliveryReceipt delReceipt = decomposer.deliveryReceipt("id:0123456789 sub:001 dlvrd:001 submit date:200809011130 done date:200809011131 stat:DELIVRD err:000 Text:" + ORIGINAL_MESSAGE);
            assertEquals(delReceipt.getText(), ORIGINAL_MESSAGE);
        } catch (InvalidDeliveryReceiptException e) {
            fail("Failed parsing delivery receipt:" + e.getMessage());
        }
    }

    @Test
    public void parseWithNoTextAttribute() {
        try {
            DeliveryReceipt delReceipt = decomposer.deliveryReceipt("id:0123456789 sub:001 dlvrd:001 submit date:200809011130 done date:200809011131 stat:DELIVRD err:000 " + ORIGINAL_MESSAGE);
            assertEquals(delReceipt.getText(), null);
        } catch (InvalidDeliveryReceiptException e) {
            e.printStackTrace();
            fail("Failed parsing delivery receipt:" + e.getMessage());
        }
    }
}

Add delivery receipt test case


/*
 * 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-30
 * Site       : https://www.acmicpc.net/problem/8958
 */

public class Boj8958 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n =Integer.parseInt(br.readLine());
        for(int i=0; i<n; i++){
            char[] inputs = br.readLine().toCharArray();
            int result = 0;
            for(int j=0; j<inputs.length; ) {
                int count = 0;
                while(inputs[j] == 'O') {
                    count++;
                    j++;
                    if(j==inputs.length){
                        break;
                    }
                }
                result += count*(count+1)/2;
                j++;
            }
            System.out.println(result);
        }
    }

}

Solve No.8958 from Baekjoon Online Judge


package com.grayben.riskExtractor;

import java.io.File;

import com.grayben.riskExtractor.htmlScorer.HtmlScorer;
import com.grayben.riskExtractor.htmlScorer.ArrayListScoredText;
import com.grayben.riskExtractor.htmlScorer.TreeHtmlScorer;

public class RiskExtractor {

	public static void main(String[] args) {
		long startTime = System.currentTimeMillis();
		checkArgs(args);
		String fileName = args[0];
		File htmlFile = new File(fileName);
		String charsetName = args[1];
		HtmlScorer scorer = new TreeHtmlScorer();
		ArrayListScoredText scoredText = scorer.scoreHtml(htmlFile, charsetName);
		System.out.print(scoredText.toString());
		System.out.println();
		System.out.println("Program finished.");
		long endTime = System.currentTimeMillis();
		long secondsElapsed = (endTime - startTime)/1000;
		System.out.println("Time elapsed: " + secondsElapsed);

	}

	private static void checkArgs(String[] args){
		int argsLen = 2;
		if(args.length != argsLen){
			System.err.println("ERROR: must pass " + argsLen + " arguments.");
			System.exit(1);
		}
	}

}

Add driving class with main method


package org.opencompare;

import org.junit.Assert;
import org.junit.Test;
import org.opencompare.api.java.PCMElement;
import org.opencompare.api.java.PCMFactory;
import org.opencompare.api.java.Value;
import org.opencompare.api.java.util.PCMVisitor;
import org.opencompare.api.java.value.BooleanValue;
import org.opencompare.model.impl.BooleanValueImpl;

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

/**
 * @author Moussa Lydia
 */
public class TraitementPcmTest {

    @Test
    public void testWhenFileExistsGetPcmIsNotNull() throws IOException {
        // si le fichier pcm exist
        final File file = new File("pcms/Comparison_between_Argentine_provinces_and_countries_by_GDP_(PPP)_per_capita_0.pcm");
        // et que je crée le TraitementPcm
        final TraitementPcm traitementPcm = new TraitementPcm(file);
        // alors getPcm ne doit pas être null
        Assert.assertNotNull(traitementPcm.getPcm());
        Assert.assertEquals("Comparison_between_Argentine_provinces_and_countries_by_GDP_(PPP)_per_capita", traitementPcm.getPcm().getName());
    }
}

Test TraitementPcm getPcm is not null


package org.jsconf.core.test;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.jsconf.core.ConfigurationFactory;
import org.jsconf.core.sample.bean.ConfigBean;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.Repeat;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;

//Required to put ${java.io.tmpdir} on classpath
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class RealReloadingTest {
	private static final String TIC = "Tic";

	private static final String TAC = "Tac";

	private static File createTempFile;

	@Autowired
	private ConfigBean conf;

	@Autowired
	private ConfigurationFactory factory;

	@BeforeClass
	public static void init() throws IOException, InterruptedException {
		String prefix = Long.toString(System.nanoTime());
		createTempFile = File.createTempFile(prefix, "_app.conf");
		createTempFile.deleteOnExit();
		write(TIC);
	}

	@Test
	@Repeat
	public void test() throws IOException, InterruptedException {
		final Object ref = this.conf;
		Assert.assertNotNull(this.conf);
		Assert.assertEquals(TIC, this.conf.getUrl());

		write(TAC);

		Assert.assertTrue(ref == this.conf);
		Assert.assertEquals(TAC, this.conf.getUrl());
	}

	private static void write(String value) throws IOException, InterruptedException {
		createTempFile.delete();
		createTempFile.createNewFile();
		try (FileWriter fw = new FileWriter(createTempFile)) {
			fw.append("simpleConf : {  url : \"" + value + "\" }");
		}
		Thread.sleep(1000);
	}

	@Configuration
	static class ContextConfiguration {
		@Bean
		public ConfigurationFactory configurationFactory() {
			return new ConfigurationFactory().withResourceName(createTempFile.getName())//
					.withBean("simpleConf", ConfigBean.class, null, true);
		}
	}
}

Add new true reloading test


package eme;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

import eme.generator.EObjectGeneratorTest;
import eme.generator.EcoreMetamodelGeneratorTest;

@RunWith(Suite.class)

@SuiteClasses({
    EcoreMetamodelGeneratorTest.class,
    EObjectGeneratorTest.class
})

public class AllHeadlessTests {
}

Test suite for test that will be run as a normal JUnit test.


package SecureElection.Common;

/**
 * Created by kalas on 2015-11-20.
 */
public class Settings {
    public static final int CLA_PORT = 8988;
    public static final int CTF_PORT = 8989;
    public static final String KEYLOCATION = "./assets/";
}

Add settings class to common package


package leetcode.symmetric_tree;

import common.TreeNode;

public class Solution {
	public boolean isSymmetric(TreeNode root) {
		if(root == null) return true;
		return isSymmetric(root.left, root.right);
	}
	private static boolean isSymmetric(TreeNode left, TreeNode right) {
		if(left == null && right == null) return true;
		if(left != null && right == null) return false;
		if(left == null && right != null) return false;
		if(left.val != right.val) return false;
		return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
	}

}

Add java solution for 101. Symmetric Tree


/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.shell.command;

import alluxio.AlluxioURI;
import alluxio.client.block.AlluxioBlockStore;
import alluxio.client.file.FileSystem;
import alluxio.client.file.URIStatus;
import alluxio.exception.AlluxioException;

import org.apache.commons.cli.CommandLine;

import java.io.IOException;

import javax.annotation.concurrent.ThreadSafe;

/**
 * Displays the path's info.
 * If path is a directory it displays the directory's info.
 * If path is a file, it displays the file's all blocks info.
 */
@ThreadSafe
public final class StatCommand extends WithWildCardPathCommand {
  /**
   * @param fs the filesystem of Alluxio
   */
  public StatCommand(FileSystem fs) {
    super(fs);
  }

  @Override
  public String getCommandName() {
    return "stat";
  }

  @Override
  protected void runCommand(AlluxioURI path, CommandLine cl) throws AlluxioException, IOException {
    URIStatus status = mFileSystem.getStatus(path);
    if (status.isFolder()) {
      System.out.println(path + " is a directory path.");
      System.out.println(status);
    } else {
      System.out.println(path + " is a file path.");
      System.out.println(status);
      System.out.println("Containing the following blocks: ");
      AlluxioBlockStore blockStore = AlluxioBlockStore.create();
      for (long blockId : status.getBlockIds()) {
        System.out.println(blockStore.getInfo(blockId));
      }
    }
  }

  @Override
  public String getUsage() {
    return "stat <path>";
  }

  @Override
  public String getDescription() {
    return "Displays info for the specified path both file and directory.";
  }
}

Add stat command class file


package org.hisp.dhis.android.core.datavalue;

import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;

import org.hisp.dhis.android.core.common.State;
import org.hisp.dhis.android.core.data.database.DatabaseAdapter;
import org.hisp.dhis.android.core.utils.StoreUtils;

import java.util.ArrayList;
import java.util.Collection;

public class DataValueSetStore {

    private static final String QUERY_WITH_STATE = "SELECT " +
            DataValueModel.Columns.DATA_ELEMENT + "," +
            DataValueModel.Columns.PERIOD + "," +
            DataValueModel.Columns.ORGANISATION_UNIT + "," +
            DataValueModel.Columns.VALUE +
            " FROM " +
            DataValueModel.TABLE +
            " WHERE " +
            DataValueModel.Columns.STATE +
            " = ':state'";

    private static final String UPDATE_STATE = "UPDATE "
            + DataValueModel.TABLE +
            " SET " +
            DataValueModel.Columns.STATE + " = ? " +
            " WHERE " +
            DataValueModel.Columns.DATA_ELEMENT + " = ?;";

    private final DatabaseAdapter databaseAdapter;
    private final SQLiteStatement updateStateStatement;

    public DataValueSetStore(DatabaseAdapter databaseAdapter) {

        this.databaseAdapter = databaseAdapter;
        this.updateStateStatement = databaseAdapter.compileStatement(UPDATE_STATE);
    }

    public Collection<DataValue> getDataValuesWithState(State state) {
        return queryDataValuesWithState(state);
    }

    private Collection<DataValue> queryDataValuesWithState(State state) {

        String query = QUERY_WITH_STATE.replace(":state", state.name());

        Cursor cursor = databaseAdapter.query(query);

        return map(cursor);
    }

    private Collection<DataValue> map(Cursor cursor) {

        Collection<DataValue> dataValues = new ArrayList<>();

        cursor.moveToFirst();

        if (cursor.getCount() > 0) {

            do {

                DataValue dataValue = DataValue.create(
                        cursor.getString(0),
                        cursor.getString(1),
                        cursor.getString(2),
                        null,
                        null,
                        cursor.getString(3),
                        null,
                        null,
                        null,
                        null,
                        null,
                        null
                );

                dataValues.add(dataValue);

            } while(cursor.moveToNext());
        }

        return dataValues;
    }

    /**
     * @param dataElementUid UID from the DataElement related to the DataValue you want to set
     * @param newState The new state to be set for the DataValue
     *
     * @return True if any DataValue has been updated
     */
    @SuppressWarnings("PMD.UselessParentheses")
    public boolean setState(String dataElementUid, State newState) {

        StoreUtils.sqLiteBind(updateStateStatement, 1, newState.name());
        StoreUtils.sqLiteBind(updateStateStatement, 2, dataElementUid);

        int updatedRows = databaseAdapter.executeUpdateDelete(DataValueModel.TABLE, updateStateStatement);
        updateStateStatement.clearBindings();

        return (updatedRows > 0);
    }
}

Add DB store for DataValueSets


/**
 * The MIT License
 * Copyright (c) 2014 Ilkka Seppälä
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.iluwatar.hexagonal.domain;

/**
 *
 * Provides notifications for lottery events.
 *
 */
public interface LotteryNotifications {

  void notifyTicketSubmitted(PlayerDetails details);
  void notifyNoWin(PlayerDetails details);
  void notifyPrize(PlayerDetails details);

}

Add interface for lottery event notifications


package learn_to_code.java_api.io_and_nio.nio;

import learn_to_code.java_api.io_and_nio.io.FilesCreatorIO;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class DirectoryStreamExample {
    public static void main (String[] args) {

        /* This 2 calls will create directories for both nio and io files.
        * We will try to filter out only directory with 'nio' as part of the name*/
        FilesCreatorNIO.createFiles();
        FilesCreatorIO.createFiles();

        Path startPath = Paths.get(FilesCreatorNIO.getDirNIOFiles()).getParent();

        /* Only accept directories which contain NIO. DirectoryStream can be worked with using foreach cycle */
        try (DirectoryStream<Path> ds = Files.newDirectoryStream(startPath,
                e -> e.toString().toLowerCase().contains("nio"))) {
            for (Path path: ds) {
                System.out.println(path.toAbsolutePath());
            }

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

Add DirectoryStream example with filter


package com.deepak.Strings;

/**
 *
Problem Statement

 *
 Given a string of characters consisting of 0 or more spaces,
 * remove all the spaces from this given string.
 * Separation of spaces from other characters should be done in-place(without using extra space).
 * Expected time and space complexity is O(n).
 * For example, if the input string is "  Hi, How are you?  "
 * then the output returned should be "Hi,Howareyou?"

 *
 * @author Deepak
 */
public class RemoveSpaces {

	/**
	 * Method to start the flow of the program
	 * @param args
	 */
	public static void main(String[] args) {
		String strWithSpaces = "  Hey, How are you doing?? ";
		String strWithOutSpaces = removeSpaces(strWithSpaces);
		System.out.println("Actual String => " + strWithSpaces);
		System.out.println("String after removing spaces => " + strWithOutSpaces);
	}

	/**
	 * Method to remove spaces with O(n^2) complexity [Not recommended]
	 *
 Algorithm :
	 * 1. Convert the entire string to char Array
	 * 2. Loop through it and search for white space
	 * 3. If found, loop through the array on right side
	 * 4. Shift each element to left and decrease the array size by 1
	 * 5. Repeat step 2-4 until all the white spaces are removed

	 *
	 * @param strWithSpaces
	 * @return {@link String}
	 */
	private static String removeSpaces(String strWithSpaces) {
		char[] strToCharArray = strWithSpaces.toCharArray();
		int charArraySize = strToCharArray.length;
		for (int i = 0; i < charArraySize; i++) {
			if (strToCharArray[i] == ' ') {
				for (int j = i; j < charArraySize - 1; j++) {
					strToCharArray[j] = strToCharArray[j+1];
				}
				charArraySize--;
			}
		}
		return new String(strToCharArray);
	}

}

Remove Spaces - O(n^2) complexity [Not recommended]


/*
 * 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.geronimo.gshell;

/**
 * Thrown when a command execution fails.
 *
 * @version $Rev$ $Date$
 */
public class CommandExecutionFailied
    extends Exception
{
    public CommandExecutionFailied(final Throwable cause) {
        super(cause);
    }
}

Add new exception type when commands fail


package com.jshoresdevelopment.conversioncalculator;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class AllUnitListItem {
    private String value;
    private String unit;

    public AllUnitListItem(String value, String unit) {
        this.value = value;
        this.unit = unit;
    }
}

Add convert all list item class.


package leetcode.permutations;

import java.util.ArrayList;

public class Solution {
	public void dfs(ArrayList<ArrayList<Integer>> ans, ArrayList<Integer> cur, int[] num, int depth, boolean visit[]){
		if(depth == num.length){
			ans.add(new ArrayList<Integer>(cur));
		}else{
			for(int i = 0; i < num.length; i++){
				if(!visit[i]){
					visit[i] = true;
					cur.add(num[i]);
					dfs(ans, cur, num, depth + 1, visit);
					visit[i] = false;
					cur.remove(depth);
				}
			}
		}
	}
    public ArrayList<ArrayList<Integer>> permute(int[] num) {
    	ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
        if(num == null || num.length == 0) return ans;
        boolean[] visit = new boolean[num.length];
        dfs(ans, new ArrayList<Integer>(), num, 0, visit);
        return ans;
    }

    public static void main(String[] args){
    	for(ArrayList<Integer> ary : new Solution().permute(new int[]{2,3,4,5,6})){
    		for(int x : ary){
    			System.err.print(x + ", ");
    		}
    		System.err.println("");;
    	}
    }
}

Add java solution for 46. Permutations


package com.elmakers.mine.bukkit.world.block.builtin;

import java.util.Deque;
import java.util.Random;
import javax.annotation.Nonnull;

import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;

import com.elmakers.mine.bukkit.api.automata.Automaton;
import com.elmakers.mine.bukkit.utility.RandomUtils;
import com.elmakers.mine.bukkit.utility.WeightedPair;
import com.elmakers.mine.bukkit.world.BlockResult;
import com.elmakers.mine.bukkit.world.block.BlockRule;

public class AutomatonRule extends BlockRule {
    private Deque<WeightedPair<String>> automatonProbability;
    private ConfigurationSection parameters;

    @Override
    public boolean onLoad(ConfigurationSection parameters) {
        RandomUtils.populateStringProbabilityMap(automatonProbability, parameters, "automaton");
        this.parameters = parameters.getConfigurationSection("automaton_parameters");
        return !automatonProbability.isEmpty();
    }

    @Override
    @Nonnull
    public BlockResult onHandle(Block block, Random random, Player cause) {
        String automatonKey = RandomUtils.weightedRandom(automatonProbability);

        if (automatonKey.equalsIgnoreCase("none")) {
            return BlockResult.SKIP;
        }
        try {
            BlockResult result = BlockResult.valueOf(automatonKey.toUpperCase());
            return result;
        } catch (Exception ignore) {
        }

        Location location = block.getLocation();
        Automaton automaton = controller.addAutomaton(location, automatonKey, null, null, parameters);
        return automaton == null ? BlockResult.SKIP : BlockResult.REMOVE_DROPS;
    }
}

Add Automaton block replace rule


package io.quarkus.gradle;

import static org.assertj.core.api.Assertions.assertThat;

import java.io.File;

import org.junit.jupiter.api.Test;

public class JandexMultiModuleTest extends QuarkusGradleWrapperTestBase {

    @Test
    public void testBasicMultiModuleBuild() throws Exception {

        final File projectDir = getProjectDir("jandex-basic-multi-module-project");

        BuildResult build = runGradleWrapper(projectDir, "clean", ":application:quarkusBuild");
        assertThat(build.getTasks().get(":common:jandex")).isEqualTo(BuildResult.SUCCESS_OUTCOME);
        assertThat(build.getTasks().get(":application:quarkusBuild")).isEqualTo(BuildResult.SUCCESS_OUTCOME);
    }

}

Test that jandex plugin is ran on quarkusBuild task


package ru.stqa.pft.sandbox;

import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * Created by Alexander Gorny on 1/25/2017.
 */
public class DistanceTest {

  @Test
  public void testDistance(){

    Point p1 = new Point(0, 0);
    Point p2 = new Point(60, 80);

    Assert.assertEquals(p1.distance(p2), 100.0);

    p2.x = 30;
    p2.y = 40;
    Assert.assertEquals(p1.distance(p2), 50.0);

    p1.x = -2.3;
    p1.y = 4;
    p2.x = 8.5;
    p2.y = 0.7;
    Assert.assertEquals(p1.distance(p2), 11.292918134831227);

    p1.x = -25;
    p1.y = -1;
    p2.x = -25;
    p2.y = -1;
    Assert.assertEquals(p1.distance(p2), 0.0);

    p1.x = -25;
    p1.y = -1;
    p2.x = -25;
    p2.y = -1;
    Assert.assertEquals(p1.distance(p2), 0.0);

    p1.x = 67;
    p1.y = 13;
    p2.x = 67;
    p2.y = 1313;
    Assert.assertEquals(p1.distance(p2), 1300.0);

  }

}

Add tests for CalculateDistance class


package com.ushahidi.android.data.entity;

import com.ushahidi.android.BuildConfig;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;

import static com.google.common.truth.Truth.assertThat;

/**
 * @author Ushahidi Team <team@ushahidi.com>
 */
@RunWith(RobolectricGradleTestRunner.class)
@Config(sdk = 21, constants = BuildConfig.class)
public class FormAttributeEntityTest {

    @Test
    public void shouldSetFormAttributeEntityTest() {
        FormAttributeEntity formAttributeEntity = TestEntityFixtures.getFormAttributeEntity();
        assertThat(formAttributeEntity).isNotNull();
        assertThat(formAttributeEntity.getKey()).isEqualTo("test_varchar");
        assertThat(formAttributeEntity.getFormId())
                .isEqualTo(1l);
        assertThat(formAttributeEntity.getKey())
                .isEqualTo("test_varchar");
        assertThat(formAttributeEntity.getLabel())
                .isEqualTo("Test varchar");
        assertThat(formAttributeEntity.getRequired())
                .isFalse();
        assertThat(formAttributeEntity.getPriority())
                .isEqualTo(1);
        assertThat(formAttributeEntity.getCardinality())
                .isEqualTo(1);
        assertThat(formAttributeEntity.getOptions()).isNull();
    }
}

Add test for form attribute


package com.novoda.downloadmanager;

import android.os.StatFs;

import java.io.File;

public final class ByteBasedStorageRequirementRule implements StorageRequirementRule {

    private final StorageCapacityReader storageCapacityReader;
    private final long bytesRemainingAfterDownload;

    public static ByteBasedStorageRequirementRule withPercentageOfStorageRemaining(long bytesRemainingAfterDownload) {
        return new ByteBasedStorageRequirementRule(new StorageCapacityReader(), bytesRemainingAfterDownload);
    }

    private ByteBasedStorageRequirementRule(StorageCapacityReader storageCapacityReader, long bytesRemainingAfterDownload) {
        this.storageCapacityReader = storageCapacityReader;
        this.bytesRemainingAfterDownload = bytesRemainingAfterDownload;
    }

    @Override
    public boolean hasViolatedRule(File storageDirectory,
                                   FileSize downloadFileSize) {
        StatFs statFs = new StatFs(storageDirectory.getPath());
        long storageCapacityInBytes = storageCapacityReader.storageCapacityInBytes(statFs);
        long usableStorageInBytes = storageDirectory.getUsableSpace();
        long remainingStorageAfterDownloadInBytes = usableStorageInBytes - downloadFileSize.totalSize();

        Logger.v("Storage capacity in bytes: ", storageCapacityInBytes);
        Logger.v("Usable storage in bytes: ", usableStorageInBytes);
        Logger.v("Minimum required storage in bytes: ", bytesRemainingAfterDownload);
        return remainingStorageAfterDownloadInBytes < bytesRemainingAfterDownload;
    }

}

Create a byte based storage requirement rule.


package me.haosdent.cgroup.subsystem;

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

public class TestFreezer {

  @Before
  public void setUp() {}

  @After
  public void tearDown() {}

  @Test
  public void testSetState() {}

  @Test
  public void testGetState() {}
}

Add freezer subsystem test class.


/*
 * Licensed to the University of California, Berkeley 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 tachyon.examples.keyvalue;

import tachyon.TachyonURI;
import tachyon.Version;
import tachyon.client.keyvalue.KeyValueStoreReader;
import tachyon.client.keyvalue.KeyValueStoreWriter;
import tachyon.client.keyvalue.KeyValueStores;

/**
 * A quick start tutorial for creating a key-value store, putting and getting some key-value pairs.
 */
public class KeyValueStoreQuickStart {
  /**
   * The main program.
   *
   * @param args one argument which is the path of the new key-value store
   * @throws Exception if any exception happens
   */
  public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      System.out.println("java -cp " + Version.TACHYON_JAR + " "
          + KeyValueStoreQuickStart.class.getName() + " <key-value store URI>");
      System.exit(-1);
    }

    TachyonURI storeUri = new TachyonURI(args[0]);
    KeyValueStores kvStore = KeyValueStores.Factory.create();

    // Creates a store.
    KeyValueStoreWriter writer = kvStore.create(storeUri);

    // Puts a key-value pair ("key", "value").
    String key = "key";
    String value = "value";
    writer.put(key.getBytes(), value.getBytes());
    System.out.println(String.format("(%s, %s) is put into the key-value store", key, value));

    // Completes the store.
    writer.close();

    // Opens a store.
    KeyValueStoreReader reader = kvStore.open(storeUri);

    // Gets the value for "key".
    System.out.println(String.format("Value for key '%s' got from the store is '%s'", key,
        new String(reader.get(key.getBytes()))));

    // Closes the reader.
    reader.close();
  }
}

Add a quickstart example for key-value store


package org.ngrinder.security;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.ngrinder.infra.annotation.TestOnlyComponent;

@TestOnlyComponent("pluggablePreAuthFilter")
public class MockPluggablePreAuthFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
					throws IOException,
					ServletException {
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}

Fix unit test errors and improve test coverage


package leetcode.largest_number;

import java.util.Arrays;
import java.util.Comparator;

public class Solution {
    public String largestNumber(int[] num) {
        if(num == null || num.length == 0) return "";
        int length = num.length;
        String[] num_str = new String[length];
        for(int i = 0; i < length; i++){
            num_str[i] = String.valueOf(num[i]);
        }
        Arrays.sort(num_str, new Comparator<String>() {

            @Override
            public int compare(String o1, String o2) {
                return -(o1 + o2).compareTo(o2 + o1);
            }
        });
        StringBuilder ret = new StringBuilder();
        for(String str : num_str){
            ret.append(str);
        }
        String r = ret.toString().replaceAll("^0+", "");
        if(r.length() == 0){
            return "0";
        }else{
            return r;
        }
    }

    public static void main(String[] args){
        System.err.println(new Solution().largestNumber(new int[]{ 0, 0, 0, 1}));
    }
}

Add java solution for 179. Largest Number


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

public class Solution {

    public boolean isSameTree(TreeNode p, TreeNode q) {

        if (p == null || q == null) {
            return p == q;
        }

        if (p.val == q.val) {
            return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        } else {
            return false;
        }

    }

}

Create : 100 Same Tree


/*
 * Copyright 2015 Datalogics, Inc.
 */

package com.datalogics.pdf.samples.sig;

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

import com.adobe.pdfjt.core.exceptions.PDFIOException;
import com.adobe.pdfjt.core.exceptions.PDFInvalidDocumentException;
import com.adobe.pdfjt.core.exceptions.PDFSecurityException;
import com.adobe.pdfjt.pdf.document.PDFDocument;
import com.adobe.pdfjt.services.digsig.SignatureFieldInterface;
import com.adobe.pdfjt.services.digsig.SignatureManager;

import com.datalogics.pdf.samples.SampleTest;

import org.junit.Test;

import java.io.File;
import java.nio.file.Files;
import java.util.Iterator;

/**
 * Tests the DocSigning Sample.
 */
public class DocSigningTest extends SampleTest {
    static final String FILE_NAME = "SignedField1.pdf";
    static final String QUALIFIED_SIGNATURE_FIELD_NAME = "SB1_Sig1";

    @Test
    public void testMain() throws Exception {
        final File file = newOutputFile(FILE_NAME);
        if (file.exists()) {
            Files.delete(file.toPath());
        }
        // The complete file name will be set in the DocSigning class.
        final String path = file.getCanonicalPath().replaceAll("1.pdf", "");

        DocSigning.main(path);
        // Make sure the Output file exists.
        assertTrue(file.getPath() + " must exist after run", file.exists());

        final PDFDocument doc = openPdfDocument(file.getCanonicalPath());

        try {
            // Make sure that Signature field is signed.
            final SignatureFieldInterface sigField = getSignedSignatureField(doc);
            assertTrue(sigField.isSigned());
            assertTrue(sigField.isVisible());
            assertEquals(QUALIFIED_SIGNATURE_FIELD_NAME, sigField.getQualifiedName());

        } finally {
            doc.close();
        }
    }

    private static SignatureFieldInterface getSignedSignatureField(final PDFDocument doc)
                    throws PDFInvalidDocumentException, PDFIOException, PDFSecurityException {
        // Set up a signature service and get the first signature field.
        final SignatureManager sigService = SignatureManager.newInstance(doc);
        if (sigService.hasSignedSignatureFields()) {
            final Iterator<SignatureFieldInterface> iter = sigService.getDocSignatureFieldIterator();
            if (iter.hasNext()) {
                return iter.next();
            }
        }
        return null;
    }
}

Add Unit test for DocSigning Sample.


package tests;

import static org.junit.Assert.*;

import org.junit.Test;
import logic.Score;

public class ScoreTests {

	@Test
	public void test_initScore() {
		Score score = new Score(2, 1);

		assertEquals("Score for Player 1 is not 2", 2, score.p1());
		assertEquals("Score for Player 2 is not 1", 1, score.p2());
	}

	@Test
	public void test_toString() {
		Score score = new Score(2, 1);

		assertEquals("toString is not correct", "Score for Player 1: 2 - Score for Player 2: 1", score.toString());
	}

}

Test cases for Score class


package starpunk;

import com.badlogic.gdx.Game;

final class StarPunkGame
  extends Game
{
  public static final int WIDTH = 1280;
  public static final int HEIGHT = 900;

  StarPunkGame()
  {
  }

  @Override
  public void create()
  {
    setScreen( new GameScreen( this ) );
  }
}

Add in minimalistic game class


/*
 * 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-10-01
 * Site       : https://www.acmicpc.net/problem/1157
 */

public class Boj1157 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String inputs = br.readLine().toLowerCase();
        int[] atoz = new int[26];
        for(int i=0; i<inputs.length(); i++){
            atoz[(int) inputs.charAt(i) - 97]++;
        }
        int max = -1;
        int maxi = 0;
        for(int i=0; i<atoz.length; i++){
            if(max < atoz[i]){
                max = atoz[i];
                maxi = i;
            }else if(max == atoz[i]){
                maxi = -2;
            }
        }
        System.out.println((char)(maxi+65));
    }

}

Solve No.1157 from Baekjoon Online Judge


package net.imagej.ops.viewOp;

import org.scijava.ItemIO;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.ExtendRandom;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.type.numeric.RealType;
import net.imglib2.view.ExtendedRandomAccessibleInterval;
import net.imglib2.view.Views;

@Plugin(type = ViewOps.ExtendRandom.class, name = ViewOps.ExtendRandom.NAME)
public class DefaultExtendRandom<T extends RealType<T>, F extends RandomAccessibleInterval<T>>
		extends AbstractView<F, ExtendedRandomAccessibleInterval<T, F>>
		implements ExtendRandom<F, ExtendedRandomAccessibleInterval<T, F>> {

	@Parameter(type = ItemIO.INPUT)
	private double min;

	@Parameter(type = ItemIO.INPUT)
	private double max;

	@Override
	public ExtendedRandomAccessibleInterval<T, F> compute(F input) {
		return Views.extendRandom(input, min, max);
	}
}

Add default implementation of ExtendRandom interface.


/*
 * Copyright 2014 Rackspace
 *
 *    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.rackspacecloud.blueflood.utils;

import com.rackspacecloud.blueflood.outputs.serializers.BasicRollupsOutputSerializer;
import com.rackspacecloud.blueflood.outputs.utils.PlotRequestParser;
import junit.framework.Assert;
import org.junit.Test;

import java.util.*;

public class PlotRequestParserTest {

    @Test
    public void testSelectParams() {
        List<String> stats = new ArrayList<String>();
        stats.add("average");
        stats.add("min");
        stats.add("max");
        Set<BasicRollupsOutputSerializer.MetricStat> filters = PlotRequestParser.getStatsToFilter(stats);

        Assert.assertTrue(filters.contains(BasicRollupsOutputSerializer.MetricStat.AVERAGE));
        Assert.assertTrue(filters.contains(BasicRollupsOutputSerializer.MetricStat.MIN));
        Assert.assertTrue(filters.contains(BasicRollupsOutputSerializer.MetricStat.MAX));

        // Alternate comma delimited notation
        stats = new ArrayList<String>();
        stats.add("average,min,max");
        filters = PlotRequestParser.getStatsToFilter(stats);
        Assert.assertTrue(filters.contains(BasicRollupsOutputSerializer.MetricStat.AVERAGE));
        Assert.assertTrue(filters.contains(BasicRollupsOutputSerializer.MetricStat.MIN));
        Assert.assertTrue(filters.contains(BasicRollupsOutputSerializer.MetricStat.MAX));
    }
}

Add test cases for parsing filters in plot requests


/*
 * Copyright 2013 The Netty Project
 *
 * The Netty Project 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.jboss.netty.handler.codec.http.multipart;

import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.handler.codec.http.*;
import org.jboss.netty.util.CharsetUtil;
import org.junit.Test;

import java.util.Arrays;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertTrue;

/** {@link HttpPostRequestDecoder} test case. */
public class HttpPostRequestDecoderTest {
    @Test
    public void testBinaryStreamUpload() throws Exception {
        final String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO";

        final DefaultHttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "http://localhost");

        req.setContent(ChannelBuffers.EMPTY_BUFFER);
        req.setHeader(HttpHeaders.Names.CONTENT_TYPE, "multipart/form-data; boundary=" + boundary);
        req.setHeader(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
        req.setChunked(true);

        // Force to use memory-based data.
        final DefaultHttpDataFactory inMemoryFactory = new DefaultHttpDataFactory(false);

        for (String data : Arrays.asList("", "\r", "\r\r", "\r\r\r")) {
            final String body = ""
                + "--" + boundary + "\r\n" +
                "Content-Disposition: form-data; name=\"file\"; filename=\"tmp-0.txt\"\r\n" +
                "Content-Type: image/gif\r\n" +
                "\r\n" +
                data + "\r\n" +
                "--" + boundary + "--\r\n";

            // Create decoder instance to test.
            final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(inMemoryFactory, req);

            decoder.offer(new DefaultHttpChunk(ChannelBuffers.copiedBuffer(body, CharsetUtil.UTF_8)));
            decoder.offer(new DefaultHttpChunk(ChannelBuffers.EMPTY_BUFFER));

            // Validate it's enough chunks to decode upload.
            assertTrue(decoder.hasNext());

            // Decode binary upload.
            MemoryFileUpload upload = (MemoryFileUpload) decoder.next();

            // Validate data has been parsed correctly as it was passed into request.
            assertArrayEquals("Invalid decoded data [data=" + data + "upload=" + upload + ']',
                data.getBytes(), upload.get());
        }
    }
}

Add test for HttpPostRequestDecoder: validate '\r' symbols in the end of binary stream are parsed correctly.


package org.matthewjwhite.stata.error;

import com.stata.sfi.SFIToolkit;

public class StataError {
	public static void display(String message, Throwable throwable) {
		if (message != null & !message.equals(""))
			SFIToolkit.errorln(message);
		SFIToolkit.errorln("Java error message:\n" + throwable.getMessage());
	}

	public static void display(Throwable throwable) {
		display(null, throwable);
	}
}

Add class for managing Stata errors


/**
 * Copyright (C) 2015 Red Hat, Inc.
 *
 * 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 io.fabric8.kubernetes.clnt;

/**
 * This is just used so that we can force the genration of xxx-soruces.jar and xxx-javadoc.jar.
 */
public interface Uberjar {
}

Add a dummy interface inside the uberjar in order to force generation of sources and javadoc jars.


package editor.gui.ccp;

import static java.awt.event.ActionEvent.ACTION_PERFORMED;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.function.Supplier;

import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
import javax.swing.TransferHandler;

/**
 * This is a convenience class for creating a set of cut, copy, and paste menu items
 * with commonly-used keyboard accelerators (Ctrl+X, Ctrl+C, Ctrl+V, respectively)
 * optionally already installed. The menu text and keyboard accelerators are not
 * customizable.
 *
 * @author Alec Roelke
 */
public class CCPItems
{
    /** Cut menu item. */
    public final JMenuItem cut;
    /** Copy menu item. */
    public final JMenuItem copy;
    /** Paste menu item. */
    public final JMenuItem paste;

    /**
     * Create a new set of cut, copy, and paste menu items that allow the reference to the source
     * component performing the action to change what it points to over time.
     *
     * @param source function for getting the component performing the actions
     * @param accelerate add keyboard accelerators
     */
    public CCPItems(Supplier<? extends Component> source, boolean accelerate)
    {
        cut = new JMenuItem("Cut");
        copy = new JMenuItem("Copy");
        paste = new JMenuItem("Paste");

        cut.addActionListener((e) -> TransferHandler.getCutAction().actionPerformed(new ActionEvent(source.get(), ACTION_PERFORMED, null)));
        copy.addActionListener((e) -> TransferHandler.getCopyAction().actionPerformed(new ActionEvent(source.get(), ACTION_PERFORMED, null)));
        paste.addActionListener((e) -> TransferHandler.getPasteAction().actionPerformed(new ActionEvent(source.get(), ACTION_PERFORMED, null)));

        if (accelerate)
        {
            cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, KeyEvent.CTRL_DOWN_MASK));
            copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_DOWN_MASK));
            paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, KeyEvent.CTRL_DOWN_MASK));
        }
    }

    /**
     * Create a new set of cut, copy, and paste menu items with a static source reference
     * (i.e. if the reference passed here changes later, these items won't see the change).
     *
     * @param source component performing the actions
     * @param accelerate add keyboard accelerators
     */
    public CCPItems(Component source, boolean accelerate)
    {
        this(() -> source, accelerate);
    }
}

Add convenience class for CCP menu items


/**
 * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.integration.viewer.status;

import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;

import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.testng.annotations.Test;

import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.livedata.UserPrincipal;
import com.opengamma.util.test.TestGroup;

/**
 * Tests {@link ViewStatusOption}
 */
@Test(groups = TestGroup.UNIT)
public class ViewStatusOptionTest {

  private static final Options s_options = ViewStatusOption.createOptions();
  private static final CommandLineParser s_parser = new PosixParser();

  public void defaultUser() throws Exception {
    String[] args = {"-n", "PORTFOLIO_NAME"};

    ViewStatusOption statusOption = ViewStatusOption.getViewStatusReporterOption(s_parser.parse(s_options, args));
    assertNotNull(statusOption);
    assertNotNull(statusOption.getUser());
    assertEquals(UserPrincipal.getLocalUser(), statusOption.getUser());
  }

  public void userOption() throws Exception {
    String[] args = {"-n", "PORTFOLIO_NAME", "-u", "test/127.0.0.1"};
    ViewStatusOption statusOption = ViewStatusOption.getViewStatusReporterOption(s_parser.parse(s_options, args));
    assertNotNull(statusOption);
    assertNotNull(statusOption.getUser());
    assertEquals("test", statusOption.getUser().getUserName());
    assertEquals("127.0.0.1", statusOption.getUser().getIpAddress());
  }

  @Test(expectedExceptions = OpenGammaRuntimeException.class)
  public void invalidUserOption() throws Exception {
    String[] args = {"-n", "PORTFOLIO_NAME", "-u", "test~127.0.0.1"};
    ViewStatusOption.getViewStatusReporterOption(s_parser.parse(s_options, args));
  }
}

Add unit testcase for ViewStatusOption


/*
 * Copyright 2012 Shared Learning Collaborative, 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
 *
 * 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.slc.sli.api.security.context.resolver;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import org.slc.sli.api.constants.EntityNames;
import org.slc.sli.api.security.context.AssociativeContextHelper;
import org.slc.sli.api.security.context.traversal.cache.impl.SessionSecurityCache;
import org.slc.sli.domain.Entity;
import org.slc.sli.domain.NeutralCriteria;
import org.slc.sli.domain.NeutralQuery;
import org.slc.sli.domain.Repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

/**
 * Resolves Teachers context to Students. Finds accessible students through section, program, and cohort associations.
 */
@Component
public class TeacherToStudentCompetencyResolver implements EntityContextResolver {

    @Autowired
    private AssociativeContextHelper helper;
    @Autowired
    private SessionSecurityCache securityCachingStrategy;

    @Autowired
    private TeacherStudentResolver studentResolver;

    @Autowired
    @Qualifier("validationRepo")
    private Repository<Entity> repo;

    @Override
    public boolean canResolve(String fromEntityType, String toEntityType) {
//        return false;
        return EntityNames.TEACHER.equals(fromEntityType) && EntityNames.STUDENT_COMPETENCY.equals(toEntityType);
    }

    @Override
    public List<String> findAccessible(Entity principal) {
        List<String> studentIds = new ArrayList<String>();
        if (!securityCachingStrategy.contains(EntityNames.STUDENT)) {
            studentIds = studentResolver.findAccessible(principal);
        } else {
            studentIds = new ArrayList<String>(securityCachingStrategy.retrieve(EntityNames.STUDENT));
        }
        Iterable<String> assocIds = repo.findAllIds(EntityNames.STUDENT_SECTION_ASSOCIATION, new NeutralQuery(new NeutralCriteria(
                "studentId", NeutralCriteria.CRITERIA_IN, studentIds)));
        List<String> ids = new ArrayList<String>();
        for (String id : assocIds) {
            ids.add(id);
        }
        List<String> finalIds = helper.findEntitiesContainingReference(EntityNames.STUDENT_COMPETENCY, "studentSectionAssociationId", ids);
        securityCachingStrategy.warm(EntityNames.STUDENT_COMPETENCY, new HashSet<String>(finalIds));
        return finalIds;
    }
}

Add an ugly competency resolver


package org.jenkinsci.plugins.relution_publisher.unittest.mocks;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.jenkinsci.plugins.relution_publisher.net.responses.ApiResponse;
import org.jenkinsci.plugins.relution_publisher.unittest.io.ResourceReader;

import java.io.IOException;

public class ResponseBuilder {

    public ApiResponse create(final String resourceName, final int httpStatus, final String reason) throws IOException {
        final StatusLine statusLine = new MockStatusLine(httpStatus, reason);

        final HttpResponse httpResponse = new MockHttpResponse();
        httpResponse.setStatusLine(statusLine);

        final ResourceReader reader = new ResourceReader();
        final String json = reader.readString(resourceName);

        final ApiResponse response = ApiResponse.fromJson(json);
        response.setHttpResponse(httpResponse);
        return response;
    }
}

Add response builder for unit tests


// 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;
import com.google.auto.value.AutoValue;

/**
 * Class representing each user object
 */
@AutoValue
public abstract class RecentBuy {
    public static RecentBuy create(String name, String email, int amtInvested, String searchQuery, long dateInvested) {
        return new AutoValue_RecentBuy(name, email, amtInvested, searchQuery, dateInvested);
    }
    public abstract String name();
    public abstract String email();
    public abstract int amtInvested();
    public abstract String searchQuery();
    public abstract long dateInvested();
}

Add object for recent buy data


/* This file is part of SableCC ( http://sablecc.org ).
 *
 * See the NOTICE file distributed with this work for copyright information.
 *
 * 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.sablecc.sablecc.util;

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

import org.sablecc.sablecc.exception.InternalException;

public class WorkSet<T> {

    private final Set<T> done = new HashSet<T>();

    private final LinkedHashSet<T> toDo = new LinkedHashSet<T>();

    public boolean hasNext() {

        return !this.toDo.isEmpty();
    }

    public T next() {

        T next = this.toDo.iterator().next();

        this.toDo.remove(next);
        this.done.add(next);

        return next;
    }

    public void add(
            T element) {

        if (element == null) {
            throw new InternalException("element may not be null");
        }

        if (!this.done.contains(element)) {
            this.toDo.add(element);
        }
    }
}

Add class to manage work sets.


package org.opennms.core.test;

import java.util.Arrays;
import java.util.List;

import org.junit.Assert;

public abstract class OnmsAssert {

    public static void assertArrayEqualsIgnoreOrder(final Object[] a, final Object[] b) {
        final List<?> aList = Arrays.asList(a);
        final List<?> bList = Arrays.asList(b);
        Assert.assertTrue(aList.containsAll(bList) && bList.containsAll(aList));
    }

}

Add a utility method for asserting array equality regardless of order


/*
 * Copyright 2014 Google. Inc.
 *
 * 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.
 */

/**
 * Contains all classes and exceptions for the key storage framework.
 *
 * @see com.google.k2crypto.storage.K2Storage
 *
 * @author darylseah@gmail.com (Daryl Seah)
 */
package com.google.k2crypto.storage;

Add javadoc for storage package.


package org.ojalgo.matrix;

import static org.ojalgo.function.aggregator.Aggregator.*;

import org.junit.jupiter.api.Test;
import org.ojalgo.TestUtils;
import org.ojalgo.matrix.BasicMatrix.Builder;

public class ReductionTest {

    public ReductionTest() {
        super();
    }

    /**
     * https://stackoverflow.com/questions/49682219/how-to-get-average-of-elements-along-columns-or-rows-in-an-ojalgo-matrix
     * <br>
     * https://github.com/optimatika/ojAlgo/issues/91#issuecomment-379399975
     */
    @Test
    public void testReduction() {

        Builder<PrimitiveMatrix> builder = PrimitiveMatrix.FACTORY.getBuilder(2, 3);
        builder.set(0, 0, 1.0);
        builder.set(0, 1, 2.0);
        builder.set(0, 2, 3.0);
        builder.set(1, 0, 4.0);
        builder.set(1, 1, 5.0);
        builder.set(1, 2, 6.0);
        PrimitiveMatrix matrix = builder.get();

        PrimitiveMatrix reducedRows = matrix.reduceRows(AVERAGE);
        PrimitiveMatrix reducedColumns = matrix.reduceColumns(AVERAGE);

        TestUtils.assertEquals(2, reducedRows.count());
        TestUtils.assertEquals(2, reducedRows.countRows());
        TestUtils.assertEquals(1, reducedRows.countColumns());

        TestUtils.assertEquals(2.0, reducedRows.doubleValue(0, 0));
        TestUtils.assertEquals(5.0, reducedRows.doubleValue(1, 0));

        TestUtils.assertEquals(2.0, reducedRows.doubleValue(0));
        TestUtils.assertEquals(5.0, reducedRows.doubleValue(1));

        TestUtils.assertEquals(3, reducedColumns.count());
        TestUtils.assertEquals(1, reducedColumns.countRows());
        TestUtils.assertEquals(3, reducedColumns.countColumns());

        TestUtils.assertEquals(2.5, reducedColumns.doubleValue(0, 0));
        TestUtils.assertEquals(3.5, reducedColumns.doubleValue(0, 1));
        TestUtils.assertEquals(4.5, reducedColumns.doubleValue(0, 2));

        TestUtils.assertEquals(2.5, reducedColumns.doubleValue(0));
        TestUtils.assertEquals(3.5, reducedColumns.doubleValue(1));
        TestUtils.assertEquals(4.5, reducedColumns.doubleValue(2));
    }

}

Add test case for the original example


package com.haxademic.demo.draw.image;

import com.haxademic.core.app.P;
import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.draw.image.ImageUtil;
import com.haxademic.core.file.DemoAssets;

import processing.core.PGraphics;
import processing.core.PImage;

public class Demo_BlurByTextureTransfer
extends PAppletHax {
	public static void main(String args[]) { PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); }

	protected PImage sourceImg;
	protected PGraphics copySmallBuffer;
	protected PGraphics copyBackBuffer;

	public void setupFirstFrame() {
		// prep buffers
		sourceImg = DemoAssets.smallTexture();
		float scaleDown = 0.2f;
		copySmallBuffer = p.createGraphics(P.round(sourceImg.width * scaleDown), P.round(sourceImg.height * scaleDown), P.P3D);
		copyBackBuffer = p.createGraphics(sourceImg.width, sourceImg.height, P.P3D);

		// copy image down and back up for blur
		ImageUtil.copyImage(sourceImg, copySmallBuffer);
		ImageUtil.copyImage(copySmallBuffer, copyBackBuffer);

	}

	public void drawApp() {
		// set up context
		p.background(100);
		p.noStroke();

		// draw steps/results to screen
		p.image(sourceImg, 0, 0);
		p.image(copySmallBuffer, sourceImg.width, 0);
		p.image(copyBackBuffer, sourceImg.width + copySmallBuffer.width, 0);
	}
}

Test blur effect by texture resampling


/**
 * Copyright (C) 2015 Deutsches Forschungszentrum für Künstliche Intelligenz (http://freme-project.eu)
 *
 * 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 eu.freme.eservices.pipelines;

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import eu.freme.conversion.rdf.RDFConstants;
import org.apache.http.HttpStatus;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * @author Gerald Haesendonck
 */
public class TestWrongRequests extends LocalServerTestBase {

	/**
	 * Send a pipelines request without body. This is not acceptable!
	 * @throws UnirestException
	 */
	@Test
	public void testNoBody() throws UnirestException {
		HttpResponse<String> response = Unirest.post("http://localhost:9000/pipelining/chain")
				.header("content-type", RDFConstants.RDFSerialization.JSON.contentType())
				.asString();
		assertEquals(HttpStatus.SC_NOT_ACCEPTABLE, response.getStatus());
	}

}

Test send request without body.


package moe.tristan.easyfxml.model.fxml;

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

import static org.assertj.core.api.Assertions.assertThat;

public class FxmlLoaderTest {

    private int succ = 0;
    private int fail = 0;
    private FxmlLoader fxmlLoader;

    @Before
    public void setUp() {
        fxmlLoader = new FxmlLoader();
        fxmlLoader.setOnSuccess(n -> succ++);
        fxmlLoader.setOnFailure(e -> fail++);
    }

    @Test
    public void onSuccess() {
        fxmlLoader.onSuccess(null);
        assertThat(succ).isEqualTo(1);
        assertThat(fail).isEqualTo(0);
    }

    @Test
    public void onFailure() {
        fxmlLoader.onFailure(null);
        assertThat(succ).isEqualTo(0);
        assertThat(fail).isEqualTo(1);
    }
}

Add some very light contract-testing to FxmlLoader


/**
 * 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.shindig.gadgets;

import junit.framework.TestCase;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.net.URI;

public class CachedContentFetcherTest extends TestCase {
  private RemoteContentFetcher fetcher
      = new CachedContentFetcher(new BasicRemoteContentFetcher(Integer.MAX_VALUE));

  public void testFetch() throws Exception {
    String content = "Hello, world!";
    File temp = File.createTempFile(this.getName(), ".txt");
    temp.deleteOnExit();
    BufferedWriter out = new BufferedWriter(new FileWriter(temp));
    out.write(content);
    out.close();
    RemoteContentRequest request = new RemoteContentRequest(temp.toURI());
    RemoteContent response = fetcher.fetch(request);
    assertEquals(RemoteContent.SC_OK, response.getHttpStatusCode());
    assertEquals(content, response.getResponseAsString());
    temp.delete();
    response = fetcher.fetch(request);
    assertEquals(RemoteContent.SC_OK, response.getHttpStatusCode());
    assertEquals(content, response.getResponseAsString());
  }

  public void testDontCache() throws Exception {
    String content = "Hello, world!";
    File temp = File.createTempFile(this.getName(), ".txt");
    temp.deleteOnExit();
    BufferedWriter out = new BufferedWriter(new FileWriter(temp));
    out.write(content);
    out.close();
    RemoteContentRequest request = RemoteContentRequest.getRequest(temp.toURI(), true);
    RemoteContent response = fetcher.fetch(request);
    assertEquals(RemoteContent.SC_OK, response.getHttpStatusCode());
    assertEquals(content, response.getResponseAsString());
    temp.delete();
    response = fetcher.fetch(request);
    assertEquals(RemoteContent.SC_NOT_FOUND, response.getHttpStatusCode());
  }

  public void testNotExists() throws Exception {
    RemoteContentRequest request
        = new RemoteContentRequest(new URI("file:///does/not/exist"));
    RemoteContent response = fetcher.fetch(request);
    assertEquals(RemoteContent.SC_NOT_FOUND, response.getHttpStatusCode());
  }

  // TODO test caching of POST requests, headers, options, etc.
}

Test that nocache is honored by CachedContentFetcher


/*
 * Copyright (c) 2011-2019, Meituan Dianping. All Rights Reserved.
 *
 * 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 com.site.lookup.util;

import java.util.ArrayList;
import java.util.Arrays;

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

public class StringUtilsTest {

    @Test
    public void testIsEmpty() {
        Assert.assertTrue(StringUtils.isEmpty(""));
        Assert.assertTrue(StringUtils.isEmpty(null));
        Assert.assertFalse(StringUtils.isEmpty("foo"));
    }

    @Test
    public void testIsNotEmpty() {
        Assert.assertFalse(StringUtils.isNotEmpty(""));
        Assert.assertFalse(StringUtils.isNotEmpty(null));
        Assert.assertTrue(StringUtils.isNotEmpty("foo"));
    }

    @Test
    public void testJoinArray() {
        Assert.assertEquals("", StringUtils
                .join(new String[0], ","));
        Assert.assertEquals("foo", StringUtils
                .join(new String[]{"foo"}, ","));
        Assert.assertEquals("foo,bar,baz", StringUtils
                .join(new String[]{"foo", "bar", "baz"}, ","));
    }

    @Test
    public void testJoinCollection() {
        Assert.assertEquals("", StringUtils
                .join(new ArrayList<String>(), ","));
        Assert.assertEquals("foo", StringUtils
                .join(new ArrayList<>(Arrays.asList("foo")), ","));
        Assert.assertEquals("foo,bar,baz", StringUtils
                .join(new ArrayList<>(
                        Arrays.asList("foo", "bar", "baz")), ","));
    }

    @Test
    public void testNormalizeSpace() {
        Assert.assertEquals(" f o o b a r",
                StringUtils.normalizeSpace(" f\to\ro\nb a r "));
    }

    @Test
    public void testTrimAll() {
        Assert.assertNull(StringUtils.trimAll(null));
        Assert.assertEquals("foobar", StringUtils.trimAll(" f\to\ro\nb a r "));
    }
}

Add unit tests for com.site.lookup.util.StringUtils


/**
 * Project Distributed Transactions.
 * Copyright Michał Szczygieł, 2013.
 * Created at Dec 29, 2013.
 */
package com.m4gik.busisess;

import static org.junit.Assert.assertEquals;

import java.sql.Timestamp;

import org.junit.Test;
import org.springframework.test.context.transaction.AfterTransaction;
import org.springframework.test.context.transaction.BeforeTransaction;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * This class test behavior during testing distributed transaction.
 *
 * @author m4gik <michal.szczygiel@wp.pl>
 *
 */
public class DistrbutedTransactionDataSourceTest extends BaseDataSourceTest {

    @AfterTransaction
    public void checkPostConditions() {

        int count = getJdbcWarehousePoland().queryForInt(
                "SELECT COUNT(*) FROM DEPOT");
        // This change was rolled back by the test framework
        assertEquals(0, count);

        count = getJdbcWarehouseFinland().queryForInt(
                "SELECT COUNT(*) FROM DEPOT");
        // This rolled back as well because of the XA
        assertEquals(0, count);

    }

    @BeforeTransaction
    public void clearData() {
        getJdbcFinance().update("DELETE FROM REGISTER");
        getJdbcWarehouseFinland().update("DELETE FROM DEPOT");
        getJdbcWarehousePoland().update("DELETE FROM DEPOT");
    }

    @Transactional
    @Test
    public void testInsertIntoTwoDataSources() throws Exception {

        assertEquals(
                1,
                getJdbcFinance()
                        .update("INSERT INTO REGISTER (id, name, register_date, price) VALUES (?,?,?,?)",
                                0, "stuff", (new Timestamp(0)), 16.0));

        assertEquals(
                1,
                getJdbcWarehouseFinland()
                        .update("INSERT INTO DEPOT (id, name, depot_date, amount) VALUES (?,?,?,?)",
                                0, "stuff", (new Timestamp(0)), 16.0));

        assertEquals(
                1,
                getJdbcWarehousePoland()
                        .update("INSERT INTO DEPOT (id, name, depot_date, amount) VALUES (?,?,?,?)",
                                0, "stuff", (new Timestamp(0)), 16.0));

    }

}

Add test for distributed transaction for data sources


package de.developgroup.mrf.rover.collision;

import com.pi4j.io.gpio.GpioController;
import de.developgroup.mrf.server.ClientManager;
import de.developgroup.mrf.server.rpc.JsonRpc2Request;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;

import static org.mockito.Mockito.verify;

public class CollisionRunnableTest {

    CollisionRunnable runnable;
    IRSensorFactory irSensorFactory;
    GpioController gpio;
    ClientManager clientManager;

    @Before
    public void setUp() {
        irSensorFactory = Mockito.mock(IRSensorFactory.class);
        gpio = Mockito.mock(GpioController.class);
        clientManager = Mockito.mock(ClientManager.class);

        runnable = new CollisionRunnable(irSensorFactory, gpio, clientManager);
    }

    @Test
    public void testSendToClients() {
        ArgumentCaptor<JsonRpc2Request> requestCaptor = ArgumentCaptor.forClass(JsonRpc2Request.class);
        RoverCollisionInformation info = new RoverCollisionInformation();

        runnable.sendToClients(info);

        verify(clientManager).notifyAllClients(requestCaptor.capture());
        JsonRpc2Request actualRequest = requestCaptor.getValue();
        Assert.assertEquals(info, actualRequest.getParams().get(0));
        Assert.assertEquals("updateCollisionInformation", actualRequest.getMethod());
    }

    @Test
    public void testConvertSensorReadingToCollisionState() {
        Assert.assertEquals(CollisionState.None, runnable.convertSensorReadingToCollisionState(0.2));
        Assert.assertEquals(CollisionState.None, runnable.convertSensorReadingToCollisionState(0.34));
        Assert.assertEquals(CollisionState.Far, runnable.convertSensorReadingToCollisionState(0.35));
        Assert.assertEquals(CollisionState.Far, runnable.convertSensorReadingToCollisionState(0.39));
        Assert.assertEquals(CollisionState.Medium, runnable.convertSensorReadingToCollisionState(0.4));
        Assert.assertEquals(CollisionState.Medium, runnable.convertSensorReadingToCollisionState(0.49));
        Assert.assertEquals(CollisionState.Close, runnable.convertSensorReadingToCollisionState(0.5));
    }
}

Add unit tests for CollisionRunnable


package com.mindoo.domino.jna.test;

import java.util.EnumSet;
import java.util.List;
import java.util.Map;

import org.junit.Test;

import com.mindoo.domino.jna.NotesCollection;
import com.mindoo.domino.jna.NotesDatabase;
import com.mindoo.domino.jna.NotesViewEntryData;
import com.mindoo.domino.jna.constants.Navigate;
import com.mindoo.domino.jna.constants.ReadMask;

import lotus.domino.Session;

/**
 * Test case to read counts from the view index
 *
 * @author Karsten Lehmann
 */
public class TestViewTraversalReadCounts extends BaseJNATestClass {

	@Test
	public void testReadingCounts() {
		runWithSession(new IDominoCallable<Object>() {

			@Override
			public Object call(Session session) throws Exception {
				NotesDatabase dbData = getFakeNamesDb();
				NotesCollection companiesView = dbData.openCollectionByName("CompaniesHierarchical");

				String[] categoriesToLookUp = new String[] {"A", "A\\Abbas", "B", "B\\Balbus", "XYZXYZ--doesnotexist--"};

				for (String category : categoriesToLookUp) {
					List<NotesViewEntryData> catEntries = companiesView.getAllEntriesInCategory(category, 0,
							//stay at the category entry:
							EnumSet.of(Navigate.CURRENT),
							//pre-buffer only one row:
							1,
							//read index counts from view index;
							//ReadMask.SUMMARYVALUES is just here so that we can print the column values
							EnumSet.of(
									ReadMask.SUMMARYVALUES,
									ReadMask.INDEXCHILDREN,
									ReadMask.INDEXDESCENDANTS,
									ReadMask.INDEXSIBLINGS
									),
							//return entry data for exactly one entry:
							new NotesCollection.EntriesAsListCallback(1)
							);

					if (!catEntries.isEmpty()) {
						NotesViewEntryData catEntry = catEntries.get(0);
						Map<String,Object> colValues = catEntry.getColumnDataAsMap();
						int descendants = catEntry.getDescendantCount();
						int siblings = catEntry.getSiblingCount();
						int children = catEntry.getChildCount();

						System.out.println("Category found: "+category);
						System.out.println("Column values: "+colValues);
						System.out.println("descendants: "+descendants);
						System.out.println("siblings: "+siblings);
						System.out.println("children: "+children);
					}
					else {
						System.out.println("Category not found: "+category);
					}
					System.out.println("==============");
				}

				return null;
			}
		});
	};

}

Test case to read counts from view index (ignoring reader fields)


package org.intermine.webservice.server;

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

public enum Format {

    /** The format for when no value is given **/
    EMPTY(null),
    /** The Unknown format **/
    UNKNOWN(null),
    /** The HTML format **/
    HTML("text/html"),
    /** Plain Text **/
    TEXT("text/plain"),
    /** XML **/
    XML("application/xml"),
    /** Comma-separated-values **/
    CSV("text/comma-separated-values"),
    /** Tab-separated-values **/
    TSV("text/tab-separated-values"),
    /** Vanilla-JSON **/
    JSON("application/json"),
    /** JSON Object format constant **/
    OBJECTS("application/json;format=objects"),
    /** JSON Table format constant **/
    TABLE("application/json;format=table"),
    /** JSON Row format constant **/
    ROWS("application/json;format=rows");

    public static final Set<Format> BASIC_FORMATS = new HashSet<Format>(Arrays.asList(
        HTML, TEXT, XML, JSON
    ));

    public static final Set<Format> JSON_FORMATS = new HashSet<Format>(Arrays.asList(
        JSON, OBJECTS, TABLE, ROWS
    ));

    public static final Set<Format> FLAT_FILES = new HashSet<Format>(Arrays.asList(
        TSV, CSV
    ));

    private final String contentType;

    private Format(String contentType) {
        this.contentType = contentType;
    }

    public String getContentType() {
        return contentType;
    }

    @Override
    public String toString() {
        return super.toString() + ((contentType == null) ? "" : (" (" + contentType + ") "));
    }

}

Move to a much cleaner format implementation


// 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.servlets;

import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Delivers a list of strings representing today's trending searches worldwide
@WebServlet("/trending")
public class TrendingServlet extends HttpServlet {

    private List<String> trendingSearches = new ArrayList<>();

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        getTrendingSearches();
        Gson gson = new Gson();
        response.setContentType("text/html;");
        response.getWriter().println(gson.toJson(trendingSearches));
    }

    public void getTrendingSearches() {
        //fetch trending searches from db - hard coded data for now
        trendingSearches.add("Giraffes");
        trendingSearches.add("Chicken nuggets");
    }
}

Add servlet to deliver today's trending searches


/*-
 * Copyright 2015 Diamond Light Source Ltd.
 *
 * 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
 */

package org.eclipse.dawnsci.analysis.api.io;

import org.eclipse.dawnsci.analysis.api.dataset.IDataset;
import org.eclipse.dawnsci.analysis.api.dataset.SliceND;
import org.eclipse.dawnsci.analysis.api.monitor.IMonitor;

/**
 * Used by lazy writeable datasets to write slices to a file
 */
public interface ILazySaver extends ILazyLoader {
	/**
	 *
	 * @return true if file is writeable
	 */
	public boolean isFileWriteable();

	/**
	 * @param mon
	 * @param data
	 * @param slice
	 * @throws Exception
	 */
	public void setSlice(IMonitor mon, IDataset data, SliceND slice) throws Exception;
}

Add new saver interface for use by lazy writeable dataset


/******************************************************************
 * File:        SecurityAccess.java
 * Created by:  Dave Reynolds
 * Created on:  2 May 2016
 *
 * (c) Copyright 2016, Epimorphics Limited
 *
 *****************************************************************/

package com.epimorphics.appbase.security;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;

import com.epimorphics.appbase.core.ComponentBase;
import com.epimorphics.appbase.security.AppRealm;
import com.epimorphics.appbase.security.UserInfo;

/**
 * Component to support access to the security features
 */
public class SecurityAccess extends ComponentBase {

    public Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public List<UserInfo> listUsers() {
        return AppRealm.getRealm().getUserStore().listUsers("");
    }

    public boolean checkPermission(UserInfo user, String permission) {
        AppRealm realm = AppRealm.getRealm();
        PrincipalCollection pc = new SimplePrincipalCollection(user, realm.getName());
        try {
            realm.checkPermission(pc, permission);
            return true;
        } catch (AuthorizationException e) {
            return false;
        }
    }
}

Add appbase helper component for accessing security info


package net.imagej.ops.viewOp;

import org.scijava.plugin.Plugin;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.ExtendMirrorDouble;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.view.ExtendedRandomAccessibleInterval;
import net.imglib2.view.Views;

@Plugin(type = ViewOps.ExtendMirrorDouble.class, name = ViewOps.ExtendMirrorDouble.NAME)
public class DefaultExtendMirrorDouble<T, F extends RandomAccessibleInterval<T>>
		extends AbstractView<F, ExtendedRandomAccessibleInterval<T, F>>
		implements ExtendMirrorDouble<F, ExtendedRandomAccessibleInterval<T, F>> {

	@Override
	public ExtendedRandomAccessibleInterval<T, F> compute(F input) {
		return Views.extendMirrorDouble(input);
	}

}

Add default implementation of ExtendMirrorDouble interface.


/*
 * https://leetcode.com/problems/swap-nodes-in-pairs/
 * Given a linked list, swap every two adjacent nodes and return its head.
 * For example,
 * Given 1->2->3->4, you should return the list as 2->1->4->3.
 * Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed
. */
class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null)
            return head;
        ListNode slow = head;
        ListNode fast = head.next;

        while(slow != null && fast != null) {
            int tmp = slow.val;
            slow.val = fast.val;
            fast.val = tmp;
            if(fast.next != null)
                fast = fast.next;
            else
                break;
            slow = fast;

            if(fast.next != null)
                fast = fast.next;
            else
                break;
        }

        return head;
    }
    public void print(ListNode head) {
      while(head != null) {
        System.out.println(head.val);
        head = head.next;
      }
    }
    public ListNode createList(int num) {
        ListNode head = null;
        ListNode tail = head;
        for(int i = 0; i < num; i++) {
            ListNode tmp = new ListNode(i);
            if(head == null) {
                head = tail = tmp;
            } else {
              tail.next = tmp;
              tail = tmp;
            }
        }
        return head;
    }
}

class Main {
  public static void main(String[] args) {
    Solution solution = new Solution();
    ListNode head = solution.createList(11);
    solution.print(head);
    System.out.println();
    solution.swapPairs(head);
    solution.print(head);
  }
}

Add solution 24. Swap Nodes in Pairs


package at.ac.tuwien.inso.method_security_tests;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import at.ac.tuwien.inso.service.UserAccountService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@SpringBootTest
@ActiveProfiles("test")
@Transactional
public class UserAccountServiceSecurityTests {

    @Autowired
    private UserAccountService userAccountService;

    @Test(expected = AuthenticationCredentialsNotFoundException.class)
    public void getCurrentLoggedInUserNotAuthenticated() {
        userAccountService.getCurrentLoggedInUser();
    }

    @Test(expected = UsernameNotFoundException.class)
    @WithMockUser
    public void getCurrentLoggedInUserAuthenticated() {
        userAccountService.getCurrentLoggedInUser();
    }
}

Add tests for UserAccountService security


/*
 * Copyright 2014 MovingBlocks
 *
 * 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.
 */

@API package org.terasology.rendering.nui.layers.ingame.inventory;

import org.terasology.engine.API;

Work stations and crafting in hand now is using NUI/


/*
 * Copyright 2012 Google Inc. 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 com.google.errorprone.bugpatterns;

import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.bugpatterns.InvalidStringEquality;
import com.google.errorprone.matchers.DescribingMatcher;

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

import java.io.File;
import java.net.URL;

/**
 * @author Bill Pugh (bill.pugh@gmail.com)
 */
public abstract class BugPatternUnitTest {

    protected CompilationTestHelper compilationHelper;
    protected String testname;

    protected void setScanner(com.google.errorprone.Scanner scanner) {

        Class<?> c = scanner.getClass().getEnclosingClass();
        if (c == null)
            throw new IllegalArgumentException("Scanner must be an inner class");
        if (!DescribingMatcher.class.isAssignableFrom(c))
            throw new IllegalArgumentException("Bad outer class for scanner: "
                    + c);
        testname = c.getSimpleName();
        compilationHelper = new CompilationTestHelper(
                scanner);
    }

    public void testPositiveCase() throws Exception {
        String name = testname + "PositiveCases.java";
        URL resource = this.getClass().getResource(name);
        if (resource == null)
            throw new RuntimeException("Could not find resource " + name);
        compilationHelper.assertCompileFailsWithMessages(new File(resource
                .toURI()));
    }

    public void testNegativeCase() throws Exception {
        String name = testname + "NegativeCases.java";
        URL resource = this.getClass().getResource(name);
        if (resource == null)
            throw new RuntimeException("Could not find resource " + name);
        compilationHelper.assertCompileSucceeds(new File(resource.toURI()));

    }

}

Add abstract base class for bug pattern unit tests


/**
 * Copyright 2014 Netflix, Inc.
 *
 * 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 rx.subjects;

import org.junit.Test;
import rx.Observer;
import rx.schedulers.TestScheduler;

import java.util.concurrent.TimeUnit;

import static org.mockito.Mockito.*;

public class TestSubjectTest {

    @Test
    public void testObserverPropagateValueAfterTriggeringActions() {
        final TestScheduler scheduler = new TestScheduler();

        final TestSubject<Integer> subject = TestSubject.create(scheduler);
        @SuppressWarnings("unchecked")
        Observer<Integer> observer = mock(Observer.class);
        subject.subscribe(observer);

        subject.onNext(1);
        scheduler.triggerActions();

        verify(observer, times(1)).onNext(1);
    }

    @Test
    public void testObserverPropagateValueInFutureTimeAfterTriggeringActions() {
        final TestScheduler scheduler = new TestScheduler();
        scheduler.advanceTimeTo(100, TimeUnit.SECONDS);

        final TestSubject<Integer> subject = TestSubject.create(scheduler);
        @SuppressWarnings("unchecked")
        Observer<Integer> observer = mock(Observer.class);
        subject.subscribe(observer);

        subject.onNext(1);
        scheduler.triggerActions();

        verify(observer, times(1)).onNext(1);
    }
}

Test that finds a TestScheduler bug


/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * 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.intellij.debugger.streams.exec;

/**
 * @author Vitaliy.Bibaev
 */
public class SpecialCasesTest extends TraceExecutionTestCase {
  public void testSortedSignedDoubleZeros() {
    doTest(false);
  }
}

/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * 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.intellij.debugger.streams.exec;

/**
 * @author Vitaliy.Bibaev
 */
public class SpecialCasesTest extends TraceExecutionTestCase {
  public void testSortedSignedDoubleZeros() {
    doTest(false);
  }

  public void testExceptionAsStreamResult() {
    doTest(false);
  }
}

Check that trace is correct if exception is a result of stream chain


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.biojava3.core.sequence;

/**
 *
 * @author Scooter
 */
public class SequenceOptimizationHints {

    /**
     * @return the sequenceUsage
     */
    public static SequenceUsage getSequenceUsage() {
        return sequenceUsage;
    }

    /**
     * @param aSequenceUsage the sequenceUsage to set
     */
    public static void setSequenceUsage(SequenceUsage aSequenceUsage) {
        sequenceUsage = aSequenceUsage;
    }

    /**
     * @return the sequenceColection
     */
    public static SequenceCollection getSequenceCollection() {
        return sequenceCollection;
    }

    /**
     * @param aSequenceColection the sequenceColection to set
     */
    public static void setSequenceCollection(SequenceCollection aSequenceColection) {
        sequenceCollection = aSequenceColection;
    }

    public enum SequenceUsage {

        FULL_SEQUENCE_DATA, SUB_SEQUENCE_DATA, MINIMAL_SEQUENCE_DATA;
    }

    public enum SequenceCollection {

        ALL_SEQUENCES, VARIABLE_SEQUENCES, MINIMINAL_SEQUENCES;
    }

    static private SequenceUsage sequenceUsage = SequenceUsage.FULL_SEQUENCE_DATA;
    static private SequenceCollection sequenceCollection = SequenceCollection.ALL_SEQUENCES;

}

Introduce class that can provide hints on how the sequences will be used to help optimize for performance or memory