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

import java.io.File;

import javax.sql.DataSource;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * This class sets base data sources for project.
 *
 * @author m4gik <michal.szczygiel@wp.pl>
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/META-INF/spring/data-source-context.xml")
public class BaseDataSource {

    /**
     * Method for logging.
     */
    @BeforeClass
    @AfterClass
    public static void clearLog() {

        // Ensure that Atomikos logging directory exists
        File dir = new File("atomikos");
        if (!dir.exists()) {
            dir.mkdir();
        }

        // ...and delete any stale locks (this would be a sign of a crash)
        File tmlog = new File("atomikos/tmlog.lck");
        if (tmlog.exists()) {
            tmlog.delete();
        }
    }

    /**
     * JDBC object to the Finance.
     */
    private SimpleJdbcTemplate jdbcFinance;

    /**
     * JDBC object to the warehouse in Finland.
     */
    private SimpleJdbcTemplate jdbcWarehouseFinland;

    /**
     * JDBC object to the warehouse in Poland.
     */
    private SimpleJdbcTemplate jdbcWarehousePoland;

    /**
     * @return the jdbcFinance
     */
    public SimpleJdbcTemplate getJdbcFinance() {
        return jdbcFinance;
    }

    /**
     * @return the jdbcWarehouseFinland
     */
    public SimpleJdbcTemplate getJdbcWarehouseFinland() {
        return jdbcWarehouseFinland;
    }

    /**
     * @return the jdbcWarehousePoland
     */
    public SimpleJdbcTemplate getJdbcWarehousePoland() {
        return jdbcWarehousePoland;
    }

    /**
     * This method set data source for proper source from
     * data-source-context.xml.
     *
     * @param dataSourceWarehousePoland
     * @param dataSourceWarehouseFinland
     * @param dataSourceFinance
     */
    @Autowired
    public void setDataSources(
            @Qualifier("dataSourceWarehousePoland") DataSource dataSourceWarehousePoland,
            @Qualifier("dataSourceWarehouseFinland") DataSource dataSourceWarehouseFinland,
            @Qualifier("dataSourceFinance") DataSource dataSourceFinance) {
        this.jdbcWarehousePoland = new SimpleJdbcTemplate(
                dataSourceWarehousePoland);
        this.jdbcWarehouseFinland = new SimpleJdbcTemplate(
                dataSourceWarehouseFinland);
        this.jdbcFinance = new SimpleJdbcTemplate(dataSourceFinance);
    }
}

Add class to set base data sources


package com.matao.Q6;

import com.matao.common.TreeNode;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class ConstructBinaryTreeTest {

    private ConstructBinaryTree constructBinaryTree;

    @BeforeEach
    public void setUp() {
        constructBinaryTree = new ConstructBinaryTree();
    }

    /**
     *  Normal Binary Tree
     *              1
     *           /     \
     *          2       3
     *         /       / \
     *        4       5   6
     *         \         /
     *          7       8
     */
    @Test
    public void testNormalBinaryTree() {
        int[] pre = {1, 2, 4, 7, 3, 5, 6, 8};
        int[] in = {4, 7, 2, 1, 5, 3, 8, 6};
        TreeNode root = constructBinaryTree.reConstructBinaryTree(pre, in);
        constructBinaryTree.preTraverse(root);
        constructBinaryTree.inTraverse(root);
    }
}

TEST add unit test for reconstruct binary tree


package com.github.sparkcaller;

import picard.vcf.MergeVcfs;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

public class Utils {
    /*
    Get all the files in the folder 'pathToFolder' ending with 'fileExtension', and return them as an ArrayList.
    */
    public static ArrayList<File> getFilesInFolder(String pathToFolder, String fileExtension) {
        File folder = new File(pathToFolder);
        File[] listOfFiles = folder.listFiles();

        if (listOfFiles != null) {
            ArrayList<File> bamFiles = new ArrayList<File>();

            for (File file : listOfFiles) {
                if (file.isFile() && file.getName().endsWith(fileExtension)) {
                    bamFiles.add(file);
                }
            }
            return bamFiles;
        }

        System.err.println(String.format("The folder: %s is either empty or was not found!", folder.getName()));
        return null;
    }

    public static String removeExtenstion(String filepath, String ext) {
        return filepath.substring(0, filepath.length() - (ext.length()+1));
    }

    /*
    Merges all the VCF files specified in the list 'vcfFiles' and returns the filename of the output file.
    */
    public static String mergeVCFFiles(List<File> vcfFiles, String outputFileName) {
        MergeVcfs mergeEngine = new MergeVcfs();
        mergeEngine.INPUT = vcfFiles;

        // Only pass the output file as an argument,
        // as it is more efficient to set the input files directly in the object.
        String outputArgs[] = {"O=" + outputFileName};

        mergeEngine.instanceMain(outputArgs);
        return outputFileName;
    }

    public static Properties loadConfigFile(String configFilepath) {
        Properties prop = new Properties();
        InputStream input = null;

        try {
            input = new FileInputStream(configFilepath);
            prop.load(input);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return prop;
    }

    public static ArrayList<String> possibleStringToArgs(String maybeString) {
        if (maybeString == null) {
            return null;
        }

        String[] args = maybeString.split("\\s+");
        return new ArrayList<String>(Arrays.asList(args));
    }
}

Create a class containing some file related utilities commonly used in this project.


// Copyright (C) 2021 The Android Open Source Project
//
// 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.gerrit.server.cancellation;

import com.google.gerrit.common.Nullable;

/** Interface that provides information about the state of the current request. */
public interface RequestStateProvider {
  /**
   * Checks whether the current request is cancelled.
   *
   *
Invoked by Gerrit to check whether the current request is cancelled and should be aborted.
   *
   *
If the current request is cancelled {@link OnCancelled#onCancel(Reason, String)} is invoked
   * on the provided callback.
   *
   * @param onCancelled callback that should be invoked if the request is cancelled
   */
  void checkIfCancelled(OnCancelled onCancelled);

  /** Callback interface to be invoked if a request is cancelled. */
  interface OnCancelled {
    /**
     * Callback that is invoked if the request is cancelled.
     *
     * @param reason the reason for the cancellation of the request
     * @param message an optional message providing details about the cancellation
     */
    void onCancel(Reason reason, @Nullable String message);
  }

  /** Reason why a request is cancelled. */
  enum Reason {
    /** The client got disconnected or has cancelled the request. */
    CLIENT_CLOSED_REQUEST,

    /** The deadline that the client provided for the request exceeded. */
    CLIENT_PROVIDED_DEADLINE_EXCEEDED,

    /**
     * A server-side deadline for the request exceeded.
     *
     *
Server-side deadlines are usually configurable, but may also be hard-coded.
     */
    SERVER_DEADLINE_EXCEEDED;
  }
}

Add interface that allows Gerrit to check whether a request is cancelled


package jsettlers.main;

import java.io.File;
import java.util.List;

import jsettlers.common.resources.ResourceManager;
import jsettlers.graphics.startscreen.IStartScreenConnector;
import jsettlers.logic.map.save.MapList;

class StartConnector implements IStartScreenConnector {
	/**
     *
     */
    private final IGameStarter gamestarter;
	private final MapList mapList;

	/**
     * @param managedJSettlers
     */
    StartConnector(IGameStarter managedJSettlers) {
        gamestarter = managedJSettlers;
        mapList = new MapList(new File(ResourceManager.getSaveDirectory(), "maps"));
    }

	@Override
	public List<? extends IMapItem> getMaps() {
		return mapList.getFreshMaps();
	}

	@Override
	public List<? extends ILoadableGame> getLoadableGames() {
		return mapList.getSavedMaps();
	}

	@Override
	public IRecoverableGame[] getRecoverableGames() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public INetworkGame[] getNetworkGames() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setNetworkServer(String host) {
		// TODO Auto-generated method stub

	}

	@Override
	public void startNewGame(IGameSettings game) {
		gamestarter.startGame(game);
	}

	@Override
	public void loadGame(ILoadableGame load) {

	}

	@Override
	public void recoverNetworkGame(IRecoverableGame game) {
		// TODO Auto-generated method stub

	}

	@Override
	public void joinNetworkGame(INetworkGame game) {
		// TODO Auto-generated method stub

	}

	@Override
	public void addNetworkGameListener(INetworkGameListener gameListener) {
		// TODO Auto-generated method stub

	}

	@Override
	public void removeNetworkGameListener(INetworkGameListener gameListener) {
		// TODO Auto-generated method stub

	}

	@Override
	public void startGameServer(IGameSettings game, String name) {
		// TODO Auto-generated method stub

	}

	@Override
	public void exitGame() {
		System.exit(0);
	}

}

Switch case fall through caused save on fog of war toggle.


package com.hp.oo.sdk.content.plugin;

import java.io.Serializable;

/**
 * Created by IntelliJ IDEA.
 * User: maromben
 * Date: 3/19/12
 * Time: 8:14 PM
 */
public class SerializableSessionObject extends SessionParam{
    private static final long serialVersionUID = -8017906075213304430L;

    private Serializable value;

    public Serializable getValue() {
        return value;
    }

    public void setValue(Serializable value) {
        this.value = value;
    }
}

Move serializable session object here for the use of score & score-content projects


package se.omegapoint.facepalm.client.config;

import org.apache.catalina.Context;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatContextCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static java.util.Collections.singletonList;

@Configuration
public class TomcatConfig {

    @Bean
    public EmbeddedServletContainerFactory servletContainerFactory() {
        TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
        factory.setTomcatContextCustomizers(singletonList(new HttpCustomizer()));
        return factory;
    }

    private static class HttpCustomizer implements TomcatContextCustomizer {

        @Override
        public void customize(final Context context) {
            context.setUseHttpOnly(false); // Defaults to true, protects against session cookie leakage in client (dont fix as contributer)
        }
    }
}

Disable automatic HttpOnly protection on session cookies


package name.abuchen.portfolio.util;

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

import org.junit.Test;

public class IsinTest
{
    @Test
    public void testValidIsin()
    {
        String ubsIsin = "CH0244767585";
        assertTrue(Isin.isValid(ubsIsin));

        String adidasIsin = "DE000A1EWWW0";
        assertTrue(Isin.isValid(adidasIsin));

        String toyotaIsin = "JP3633400001";
        assertTrue(Isin.isValid(toyotaIsin));
    }

    @Test
    public void testInvalidIsin()
    {
        String invalidUbsIsin = "CH0244767586"; // Wrong Checksum
        assertFalse(Isin.isValid(invalidUbsIsin));
    }

    @Test
    public void testIsinTooLong()
    {
        String isinTooLong = "CH0244767585222222";
        assertFalse(Isin.isValid(isinTooLong));
    }

    @Test
    public void testIsinNull()
    {
        String nullIsin = null;
        assertFalse(Isin.isValid(nullIsin));
    }

    @Test
    public void testInvalidChar()
    {
        String invalidCharIsin = "ÜE0244767585";
        assertFalse(Isin.isValid(invalidCharIsin));
    }
}

Add Tests for Isin validator


package de.philipphager.disclosure.util.device;

import android.content.Intent;
import android.net.Uri;
import javax.inject.Inject;

public class IntentFactory {
  public Intent uninstallPackage(final String packageName) {
    Uri packageUri = Uri.parse(String.format("package:%s", packageName));

    Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
    intent.setData(packageUri);
    intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
    return intent;
  }

  @Inject @SuppressWarnings("PMD.UnnecessaryConstructor") public IntentFactory() {
    // Needed for dagger injection.
  }
}

Add helper factory to create intents for app uninstall


class ShutdownHook {
    static public void main(String[] args) throws Exception {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                System.out.println("shutdown");
            }
        });
        throw new Exception();
    }
}

Use shutdown hook to ensure execute statements at the end.


/*
 * Copyright (C) 2004 EBI, GRL
 *
 * This library is free software; you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free Software
 * Foundation; either version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with
 * this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
 * Suite 330, Boston, MA 02111-1307 USA
 */

package org.ensembl.healthcheck.testcase.variation;

import java.sql.Connection;
import java.util.List;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Team;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
import org.ensembl.healthcheck.util.DBUtils;
import org.ensembl.healthcheck.util.RowMapper;
import org.ensembl.healthcheck.util.SqlTemplate;

/**
 * Checks database does not contain duplicated Publication entries
 */
public class Publication extends SingleDatabaseTestCase {

	/**
	 * Creates a new instance of Publication
	 */
	public Publication() {

		addToGroup("variation-release");
		setDescription("Check the database does not contain duplicated Publication entries");
		setTeamResponsible(Team.VARIATION);

	}

	/**
	 *
	 * @param dbre
	 *          The database to check.
	 * @return True if the test passed
	 */
         public boolean run(final DatabaseRegistryEntry dbre) {
	     boolean result = true;

		Connection con = dbre.getConnection();

		try {
			/*
			 * Attempt to extract a list of publications with the same unique id
			 */

		    // fields to check on:
		    String[] check_id = {"pmid", "pmcid", "doi" };

		    for (int i =0; i< 3; i++){

			String stmt = "select count(*) from publication p1, publication p2 where p1." + check_id[i] + " = p2." + check_id[i] + " and p1.publication_id < p2.publication_id;";

                        int rows = DBUtils.getRowCount(con,stmt);
                        if (rows > 0) {
			    result = false;
			    ReportManager.problem(this, con, String.valueOf(rows) + " rows are duplicated in publication on " + check_id[i]);
                        }

		    }
		} catch (Exception e) {
		    ReportManager.problem(this, con, "HealthCheck generated an exception: " + e.getMessage());
		    result = false;
		}

		if (result) {
		    // if there were no problems, just inform for the interface to pick the HC
		    ReportManager.correct(this, con, "Publication healthcheck passed without any problem");
		}
		return result;
	 }

}

Check for duplicate entries in the publication table as they are imported from different sources using different primary unique ids


/*
 * 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.
 */

package org.terasology;

import org.eclipse.jgit.lib.ProgressMonitor;
import org.slf4j.Logger;

/**
 * TODO Type description
 * @author Martin Steiger
 */
public class LoggingProgressMonitor implements ProgressMonitor {

    private final Logger logger;
    private String curTask;
    private int maxWork;
    private int curWork;

    /**
     * @param logger
     */
    public LoggingProgressMonitor(Logger logger) {
        this.logger = logger;
    }

    @Override
    public void beginTask(String title, int totalWork) {
        this.curTask = title;
        this.curWork = 0;
        this.maxWork = totalWork;
        logger.info("Starting: " + title);
    }

    @Override
    public void start(int totalTasks) {
        // ignore
    }

    @Override
    public void update(int completed) {
        curWork += completed;
        logger.info("{} ({}/{})", curTask, curWork, maxWork);
    }

    @Override
    public void endTask() {
        logger.info(curTask + " finished");
    }

    @Override
    public boolean isCancelled() {
        return false;
    }

}

Add Logging progress monitor (unused)


/*
 * Copyright 2016 Exorath
 *
 * 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.exorath.service.treasurehunt.dynamodb;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.EnvironmentVariableCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.amazonaws.services.dynamodbv2.model.ResourceInUseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DynamoDBProvider {
	private static final Logger logger = LoggerFactory.getLogger(DynamoDBProvider.class);

	private final DynamoDB db;

	public DynamoDBProvider(Regions region) {
		AWSCredentials credentials = new EnvironmentVariableCredentialsProvider().getCredentials();
		AmazonDynamoDBClient client = new AmazonDynamoDBClient(credentials).withRegion(region);
		db = new DynamoDB(client);
	}

	public DynamoDB getDB() {
		return db;
	}

	public Table getTable(String name) {
		return getDB().getTable(name);
	}

	public boolean hasTable(String name) {
		for (Table table : db.listTables()) {
			if (table.getTableName().equals(name)) {
				return true;
			}
		}
		return false;
	}

	public Table createTable(CreateTableRequest request) throws InterruptedException {
		Table table;
		try {
			table = db.createTable(request);
			String name = request.getTableName();
			long read = request.getProvisionedThroughput().getReadCapacityUnits();
			long write = request.getProvisionedThroughput().getWriteCapacityUnits();
			logger.info("Created DynamoDB table " + name + " with " + read + "r/" + write + "w provisioning. Waiting for it to activate.");
		} catch (ResourceInUseException ex) { // Table already exists
			table = db.getTable(request.getTableName());
			logger.warn("DynamoDB table " + request.getTableName() + " already exists. Waiting for it to activate.");
		}

		table.waitForActive();
		logger.info("DynamoDB table " + request.getTableName() + " is active.");
		return table;
	}
}

Add methods for easy checking if db has table


/**
 * 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.hadoop.hdfs.server.namenode;

import static org.junit.Assert.*;

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

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.util.StringUtils;
import org.junit.Test;

public class TestTransferFsImage {

  /**
   * Regression test for HDFS-1997. Test that, if an exception
   * occurs on the client side, it is properly reported as such
   */
  @Test
  public void testClientSideException() throws IOException {

    Configuration conf = new HdfsConfiguration();
    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf)
      .numDataNodes(0).build();
    try {

      String fsName = NameNode.getHostPortString(
          cluster.getNameNode().getHttpAddress());
      String id = "getimage=1";

      File[] localPath = new File[] {
         new File("/xxxxx-does-not-exist/blah")
      };

      TransferFsImage.getFileClient(fsName, id, localPath, false);
      fail("Didn't get an exception!");
    } catch (IOException ioe) {
      assertTrue("Expected FNFE, got: " + StringUtils.stringifyException(ioe),
          ioe instanceof FileNotFoundException);
    } finally {
      cluster.shutdown();
    }
  }
}

Add missing file from previous commit.


package com.isuraed.insight;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;

import org.apache.log4j.Logger;

public class ReviewsByProductTitle {

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = new Job(conf, "isura_ReviewsByProductTitle");

        job.setJarByClass(ReviewsByProductTitle.class);
        job.setMapperClass(ReviewsMapper.class);
        job.setReducerClass(ReviewsReducer.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);

        job.setOutputFormatClass(TextOutputFormat.class);
        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        boolean result = job.waitForCompletion(true);
        System.exit(result ? 0 : 1);
    }

    // Earlier in the pipeline we already calculated the title for each productId. The mapper simply reverses the key and value.
    static class ReviewsMapper extends Mapper<LongWritable,Text,Text,Text> {
        private static final Logger logger = Logger.getLogger(ReviewsMapper.class.getName());

        @Override
        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String[] row = value.toString().split("\t", -1);
            String productId = row[0].toString();
            String title = row[1].toString();

            if (productId.equals("")) {
                logger.warn("Skipped record: productId was blank");
                return;
            }

            if (title.equals("")) {
                logger.warn("Skipped record: Title was blank");
                return;
            }

            // Escape quotes because strings are stored in json later.
            title = title.replace("\"", "\\\"");
            title = title.toLowerCase();

            context.write(new Text(title), new Text(productId));
        }
    }

    static class ReviewsReducer extends Reducer<Text, Text, Text, Text> {

        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            StringBuilder productIds = new StringBuilder();

            for (Text val : values) {
                productIds.append(val);
                productIds.append("\t");
            }

            context.write(key, new Text(productIds.toString().trim()));
        }
    }
}

Build reverse map from title to productId


package com.example.profbola.bakingtime.utils;

import android.content.Context;

/**
 * Created by prof.BOLA on 7/6/2017.
 */

public class RecipeUtils {

    public static int getResourceIdFromName(Context context, String name) {
        return context.getResources().getIdentifier(name, "drawable", context.getPackageName());
    }

    public static CharSequence formatServings(int servings) {
        return String.format("Served: %d", servings);
    }
}

Add Utility class for Recipes


package replicant.messages;

import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import jsinterop.annotations.JsOverlay;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;

@JsType( isNative = true, namespace = JsPackage.GLOBAL, name = "Object" )
@SuppressWarnings( { "NullableProblems", "unused" } )
public final class BulkSubscribeMessage
  extends ClientToServerMessage
{
  @Nonnull
  private String[] channels;
  @Nullable
  private Object filter;

  @JsOverlay
  @Nonnull
  public static BulkSubscribeMessage create( final int req,
                                             @Nonnull final String[] channels,
                                             @Nullable final Object filter )
  {
    final BulkSubscribeMessage message = new BulkSubscribeMessage();
    message.type = "bulk-sub";
    message.req = req;
    message.channels = Objects.requireNonNull( channels );
    message.filter = filter;
    return message;
  }
}

Add message for bulk subscribe


package edu.colorado.cs.tcpstate;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.util.Scanner;

public class TcpDumpSplit {

	public static void tcpDumpSplit(InputStream tcpdump) {
		try {
			FileWriter fw = null;
			String lastPort = null;
			String line = null;
			int pos = 0;
			Scanner s = new Scanner(tcpdump);
			while(s.hasNext()) {
				line = s.nextLine();
				if( line.indexOf("[S]") > -1 && (pos = line.indexOf(">")) > -1) {
					int start = line.lastIndexOf(".", pos)+1;
					String port = line.substring(start, pos).trim();
					if(!port.equals(lastPort)) {
						if(fw != null) {
							fw.close();
						}
						lastPort=port;
						System.out.println("Parsing TCPDUMP for port# "+port);
						fw = new FileWriter(new File(port+".log"));
					}
				}
				if(fw!=null && line.indexOf(lastPort) > -1) {
					fw.write(line+"\n");
				}
			}
			fw.close();
			s.close();

		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) throws Exception {
		if(args.length == 1) {
			TcpDumpSplit.tcpDumpSplit(new FileInputStream(args[0]));
		} else {
			System.out.println("java TcpDumpSplit [tcpDumpJoined]");
		}
	}
}

Add a little app to split up a huge TcpDump file into individual traces


/*
 ************************************************************************
 ****  C A N A D I A N   A S T R O N O M Y   D A T A   C E N T R E  *****
 *
 * (c) 2010.                         (c) 2010.
 * National Research Council            Conseil national de recherches
 * Ottawa, Canada, K1A 0R6              Ottawa, Canada, K1A 0R6
 * All rights reserved                  Tous droits reserves
 *
 * NRC disclaims any warranties         Le CNRC denie toute garantie
 * expressed, implied, or statu-        enoncee, implicite ou legale,
 * tory, of any kind with respect       de quelque nature que se soit,
 * to the software, including           concernant le logiciel, y com-
 * without limitation any war-          pris sans restriction toute
 * ranty of merchantability or          garantie de valeur marchande
 * fitness for a particular pur-        ou de pertinence pour un usage
 * pose.  NRC shall not be liable       particulier.  Le CNRC ne
 * in any event for any damages,        pourra en aucun cas etre tenu
 * whether direct or indirect,          responsable de tout dommage,
 * special or general, consequen-       direct ou indirect, particul-
 * tial or incidental, arising          ier ou general, accessoire ou
 * from the use of the software.        fortuit, resultant de l'utili-
 *                                      sation du logiciel.
 *
 *
 * @author jenkinsd
 * Jan 6, 2010 - 10:15:22 AM
 *
 *
 *
 ****  C A N A D I A N   A S T R O N O M Y   D A T A   C E N T R E  *****
 ************************************************************************
 */
package ca.nrc.cadc.uws.web;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import ca.nrc.cadc.uws.web.restlet.resources.*;

@RunWith(Suite.class)
@Suite.SuiteClasses
({
        AsynchResourceTestCase.class,
        JobAsynchResourceExecutionTest.class,
        JobSyncSubmissionResourceTest.class,
        ResultResourceTest.class
})
public class CADCUWSTestSuite
{
}

Add unit tests to build.xml.


package com.haxademic.demo.media.audio.playback;

import com.haxademic.core.app.P;
import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.media.audio.analysis.AudioInputBeads;
import com.haxademic.core.media.audio.playback.WavPlayer;

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

	protected WavPlayer player;
	protected String[] playlist = new String[] {
		"data/audio/kit808/tom.wav",
		"data/audio/kit808/bass.wav",
		"data/audio/kit808/clap.wav",
		"data/audio/kit808/hi-hat.wav",
		"data/audio/kit808/hi-hat-open.wav",
		"data/audio/kit808/kick.wav",
		"data/audio/kit808/snare.wav",
	};
	protected int playlistIndex = 0;

	public void setupFirstFrame() {
		player = new WavPlayer();
		P.p.setAudioInput(new AudioInputBeads(player.context()));
		playNextSound();
	}

	public void drawApp() {
		p.background(0);
		checkPlayerComplete();
	}

	protected void playNextSound() {
		playlistIndex++;
		playlistIndex = playlistIndex % playlist.length;
		player.playWav(playlist[playlistIndex]);
	}

	protected void checkPlayerComplete() {
		float playerProgress = player.progress(playlist[playlistIndex]);
		p.debugView.setValue("playerProgress", playerProgress);
		if(playerProgress >= 1f) {
			playNextSound();
		}
	}

}

Build playlist demo for WavPlayer


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

public class Boj8393 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        System.out.print(n*(n+1)/2);
    }

}

Solve No.8393 from Baekjoon Online Judge


package com.studio4plus.homerplayer;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

public class HomerPlayerApplication extends Application {

    private static final String AUDIOBOOKS_DIRECTORY = "AudioBooks";

    private ApplicationComponent component;

    private MediaScannerReceiver mediaScannerReceiver;

    @Override
    public void onCreate() {
        super.onCreate();

        component = DaggerApplicationComponent.builder()
                .audioBookManagerModule(new AudioBookManagerModule(AUDIOBOOKS_DIRECTORY))
                .build();

        IntentFilter intentFilter =  new IntentFilter(Intent.ACTION_MEDIA_SCANNER_STARTED);
        intentFilter.addDataScheme("file");
        mediaScannerReceiver = new MediaScannerReceiver();
        registerReceiver(mediaScannerReceiver, intentFilter);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        unregisterReceiver(mediaScannerReceiver);
        mediaScannerReceiver = null;
    }

    public static ApplicationComponent getComponent(Context context) {
        return ((HomerPlayerApplication) context.getApplicationContext()).component;
    }
}

package com.studio4plus.homerplayer;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

public class HomerPlayerApplication extends Application {

    private static final String AUDIOBOOKS_DIRECTORY = "AudioBooks";

    private ApplicationComponent component;

    private MediaScannerReceiver mediaScannerReceiver;

    @Override
    public void onCreate() {
        super.onCreate();

        component = DaggerApplicationComponent.builder()
                .applicationModule(new ApplicationModule(this))
                .audioBookManagerModule(new AudioBookManagerModule(AUDIOBOOKS_DIRECTORY))
                .build();

        IntentFilter intentFilter =  new IntentFilter(Intent.ACTION_MEDIA_SCANNER_STARTED);
        intentFilter.addDataScheme("file");
        mediaScannerReceiver = new MediaScannerReceiver();
        registerReceiver(mediaScannerReceiver, intentFilter);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        unregisterReceiver(mediaScannerReceiver);
        mediaScannerReceiver = null;
    }

    public static ApplicationComponent getComponent(Context context) {
        return ((HomerPlayerApplication) context.getApplicationContext()).component;
    }
}

Initialize the ApplicationModule for Dagger.


package io.github.ddebree.game.ai.core.move;

import javax.annotation.Nonnull;
import java.util.stream.Stream;

/**
 * A factory class that generates all possible move for the player at a particular game state
 *
 * @param <S> The class that represents a game's state
 * @param <P> The class that represents a player
 * @param <M> The class used to represent a player's move
 */
public interface IMoveFactory<S, P, M> {

    /**
     * Get all the moves that a player could make at the current game state
     *
     * @param state The current game state
     * @param player The player to determine the moves for
     * @return A stream of moves that the provided player could perform at this game state
     */
    @Nonnull
    Stream<M> getMoves(@Nonnull S state, P player);

}

Add the basic move factory


/*
 *
 *
 * Copyright (C) 2006 SIPfoundry Inc.
 * Licensed by SIPfoundry under the LGPL license.
 *
 * Copyright (C) 2006 Pingtel Corp.
 * Licensed to SIPfoundry under a Contributor Agreement.
 *
 * $
 */
package org.sipfoundry.sipxconfig.setting;

import junit.framework.TestCase;

public class ValueStorageTest extends TestCase {

    public void testSettingValue() {
        ValueStorage vs = new ValueStorage();
        String svalue = "red";
        Setting setting = new SettingImpl("parrot");
        vs.setSettingValue(setting, new SettingValueImpl(svalue), null);
        assertEquals(svalue, vs.getSettingValue(setting).getValue());
    }

    public void testNullValue() {
        ValueStorage vs = new ValueStorage();
        Setting setting = new SettingImpl("parrot");
        vs.setSettingValue(setting, new SettingValueImpl(null), null);
        assertNull(vs.getSettingValue(setting).getValue());
    }
}

Add unit test for valuestorage


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

// https://www.hackerrank.com/challenges/ctci-making-anagrams/problem
public class MakingAnagrams {

  private static Map<Character, Integer> getCharacterFrequency(String word) {
    Map<Character, Integer> frequency = new HashMap<Character, Integer>();
    for (char character : word.toCharArray()) {
      int value = frequency.getOrDefault(character, 0);
      frequency.put(character, value + 1);
    }
    return frequency;
  }

  private static Character[] getArrayFromKeys(Map<Character, Integer> map) {
    Character[] chars = new Character[map.keySet().size()];
    return map.keySet().toArray(chars);
  }

  private static int getDeletionsToFormAnagram(String firstWord, String secondWord) {
    int deletions = 0;
    Map<Character, Integer> firstFrequencies = getCharacterFrequency(firstWord);
    Map<Character, Integer> secondFrequencies = getCharacterFrequency(secondWord);
    Character[] firstChars = getArrayFromKeys(firstFrequencies);
    for (char character : firstChars) {
      int firstValue = firstFrequencies.get(character);
      int secondValue = secondFrequencies.getOrDefault(character, 0);
      int difference = Math.abs(firstValue - secondValue);
      if (secondValue != 0) {
        secondFrequencies.remove(character);
      }
      deletions += difference;
    }
    Character[] secondChars = getArrayFromKeys(secondFrequencies);
    for (char character : secondChars) {
      deletions += secondFrequencies.get(character);
    }
    return deletions;
  }

  public static void main(String[] args) throws IOException {
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
      String firstWord = reader.readLine();
      String secondWord = reader.readLine();
      int deletions = getDeletionsToFormAnagram(firstWord, secondWord);
      System.out.println(deletions);
    }
  }
}

Add solution to Making anagrams problem.


package org.firmata4j.firmata.parser;

import static org.junit.Assert.assertEquals;

import java.util.concurrent.atomic.AtomicInteger;

import org.firmata4j.fsm.Event;
import org.junit.After;
import org.junit.Test;

public class FirmataParserTest {
    @After
    public void tearDown() throws InterruptedException {
        assertIfThreadStillRunning("firmata");
        assertIfThreadStillRunning("parser");
    }

    @Test
    public void testConstruct() {
        FirmataParser parser = new FirmataParser() {
            @Override
            public void onEvent(Event event) {

            }
        };

        parser.start();

        parser.stop();
    }

    @Test
    public void testStartAndStopTwice() {
        FirmataParser parser = new FirmataParser() {
            @Override
            public void onEvent(Event event) {

            }
        };

        parser.start();
        parser.start();

        parser.stop();
        parser.stop();
    }

    @Test
    public void testParse() throws InterruptedException {
        final AtomicInteger eventCount = new AtomicInteger(0);
        FirmataParser parser = new FirmataParser() {
            @Override
            public void onEvent(Event event) {
                eventCount.incrementAndGet();
            }
        };

        parser.start();

        parser.parse(new byte[] {1, 2, 3});

        int i = 0;
        while(eventCount.get() < 3 && i < 20) {
            Thread.sleep(100);
            i++;
        }
        assertEquals("Should receive 3 events for each byte an 'unknown' error event",
                3, eventCount.get());

        parser.stop();
    }

    private static void assertIfThreadStillRunning(final String contains) throws InterruptedException {
        int count = Thread.currentThread().getThreadGroup().activeCount();

        Thread[] threads = new Thread[count];
        Thread.currentThread().getThreadGroup().enumerate(threads);

        for (Thread t : threads) {
            if (t != null && t.getName().contains(contains)) {
                t.join();
            }
        }
    }
}

Add initial unit-test for FirmataParser


package univ.ml.sparse.algorithm;

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

import org.apache.commons.math3.linear.RealVector;

import univ.ml.sparse.SparseCentroidCluster;
import univ.ml.sparse.SparseWeightableVector;

public class SparseKmeansCoresetAlgorithm implements SparseCoresetAlgorithm {

    private static final long serialVersionUID = 6378586987151382195L;

    private int sampleSize;

    public SparseKmeansCoresetAlgorithm() {
        this(0);
    }

    public SparseKmeansCoresetAlgorithm(int sampleSize) {
        this.sampleSize = sampleSize;
    }

    @Override
    public List<SparseWeightableVector> takeSample(final List<SparseWeightableVector> pointset) {
        if (pointset.size() <= sampleSize)
            return pointset;

        final SparseWeightedKMeansPlusPlus kmeans = new SparseWeightedKMeansPlusPlus(sampleSize);
        final List<SparseCentroidCluster> clusters = kmeans.cluster(pointset);

        final List<SparseWeightableVector> results = new ArrayList<>();
        for (final SparseCentroidCluster cluster : clusters) {
            final RealVector center = cluster.getCenter().getVector();
            final int weight = cluster.getPoints().size();
            results.add(new SparseWeightableVector(center, weight));
        }

        return results;
    }
}

Add SDM coreset version for sparse data


package io.kubernetes.client.util.conversion;

import io.kubernetes.client.openapi.models.V1Job;
import io.kubernetes.client.openapi.models.V1JobSpec;
import io.kubernetes.client.openapi.models.V1ObjectMeta;
import io.kubernetes.client.openapi.models.V1OwnerReference;
import io.kubernetes.client.openapi.models.V1beta1CronJob;
import io.kubernetes.client.openapi.models.V1beta1CronJobSpec;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class Jobs {

    /**
     * Convert V1beta1CronJob object into V1Job object, based on kubectl code https://github.com/kubernetes/kubectl/blob/master/pkg/cmd/create/create_job.go
     * @param cronJob cronJob object (required)
     * @param jobName cronJob name
     * @return V1Job object
     */
    public static V1Job cronJobToJob(V1beta1CronJob cronJob, String jobName) {

        Map<String, String> annotations = new HashMap<>();
        Map<String, String> labels  = new HashMap<>();
        V1JobSpec jobSpec = null;

        V1beta1CronJobSpec cronJobSpec = cronJob.getSpec();

        if (cronJobSpec != null && cronJobSpec.getJobTemplate() != null) {
            V1ObjectMeta metadata = cronJobSpec.getJobTemplate().getMetadata();
            if (metadata != null){
                if (metadata.getAnnotations() != null) {
                    annotations.putAll(metadata.getAnnotations());
                }
                if (metadata.getLabels() != null) {
                    labels.putAll(metadata.getLabels());
                }
            }
            jobSpec = cronJobSpec.getJobTemplate().getSpec();
        }

        annotations.put("cronjob.kubernetes.io/instantiate", "manual");

        V1OwnerReference v1OwnerReference = new V1OwnerReference();
        v1OwnerReference.setKind("CronJob");
        v1OwnerReference.setName(cronJob.getMetadata().getName());
        v1OwnerReference.setBlockOwnerDeletion(true);
        v1OwnerReference.setController(true);
        v1OwnerReference.setUid(cronJob.getMetadata().getUid());
        v1OwnerReference.setApiVersion("batch/v1beta1");

        V1ObjectMeta jobMetadata = new V1ObjectMeta();
        jobMetadata.setName(jobName != null ? jobName : cronJob.getMetadata().getName() + "-manual");
        jobMetadata.setAnnotations(annotations);
        jobMetadata.setLabels(labels);
        jobMetadata.setOwnerReferences(Arrays.asList(v1OwnerReference));

        V1Job job = new V1Job();
        job.setKind("Job");
        job.setApiVersion("batch/v1");
        job.setMetadata(jobMetadata);
        job.setSpec(jobSpec);

        return job;
    }

}

Convert cron job to job


package com.yahoo.jdisc.core;

import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.ResourceReference;
import com.yahoo.jdisc.test.TestDriver;
import org.junit.Test;

import java.util.Map;

import static org.junit.Assert.assertEquals;

/**
 * @author bjorncs
 */
public class ActiveContainerStatisticsTest {

    @Test
    public void counts_deactivated_activecontainers() {
        TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
        ActiveContainerStatistics stats = new ActiveContainerStatistics();
        MockMetric metric = new MockMetric();

        ActiveContainer containerWithoutRetainedResources = new ActiveContainer(driver.newContainerBuilder());

        stats.onActivated(containerWithoutRetainedResources);
        stats.emitMetrics(metric);
        assertEquals(0, metric.totalCount);
        assertEquals(0, metric.withRetainedReferencesCount);

        stats.onDeactivated(containerWithoutRetainedResources);
        containerWithoutRetainedResources.release();
        stats.emitMetrics(metric);
        assertEquals(1, metric.totalCount);
        assertEquals(0, metric.withRetainedReferencesCount);

        ActiveContainer containerWithRetainedResources = new ActiveContainer(driver.newContainerBuilder());

        try (ResourceReference ignoredRef = containerWithRetainedResources.refer()) {
             stats.onActivated(containerWithRetainedResources);
             stats.onDeactivated(containerWithRetainedResources);
             containerWithRetainedResources.release();
             stats.emitMetrics(metric);
             assertEquals(2, metric.totalCount);
             assertEquals(1, metric.withRetainedReferencesCount);
        }

    }

    private static class MockMetric implements Metric {
        public int totalCount;
        public int withRetainedReferencesCount;

        @Override
        public void set(String key, Number val, Context ctx) {
            switch (key) {
                case ActiveContainerStatistics.Metrics.TOTAL_DEACTIVATED_CONTAINERS:
                    totalCount = val.intValue();
                    break;
                case ActiveContainerStatistics.Metrics.DEACTIVATED_CONTAINERS_WITH_RETAINED_REFERENCES:
                    withRetainedReferencesCount = val.intValue();
                    break;
                default:
                    throw new UnsupportedOperationException();
            }
        }

        @Override
        public void add(String key, Number val, Context ctx) {
            throw new UnsupportedOperationException();
        }

        @Override
        public Context createContext(Map<String, ?> properties) {
            throw new UnsupportedOperationException();
        }
    }

}

Add unit test for ActiveContainerStatistics


package com.btkelly.gnag.models;

import com.google.gson.annotations.SerializedName;
import org.jetbrains.annotations.NotNull;

public final class GitHubPRComment {

    @NotNull
    @SerializedName("body")
    private final String body;

    @NotNull
    @SerializedName("commit_id")
    private final String prSha;

    @NotNull
    @SerializedName("path")
    private final String relativeFilePath;

    @SerializedName("position")
    private final int diffLineIndex;

    public GitHubPRComment(
            @NotNull final String body,
            @NotNull final String prSha,
            @NotNull final String relativeFilePath,
            final int diffLineIndex) {

        this.body = body;
        this.prSha = prSha;
        this.relativeFilePath = relativeFilePath;
        this.diffLineIndex = diffLineIndex;
    }

    @Override
    public String toString() {
        return "GitHubIssueComment{" +
                "body='" + body + '\'' +
                "prSha='" + prSha + '\'' +
                "relativeFilePath='" + relativeFilePath + '\'' +
                "diffLineIndex='" + diffLineIndex + '\'' +
                '}';
    }

}

Add new type representing inline PR comment


/*
 * (C) Copyright 2018 Boni Garcia (http://bonigarcia.github.io/)
 *
 * 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.github.bonigarcia.test.forced;

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

import java.lang.reflect.Method;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openqa.selenium.WebDriver;

import io.github.bonigarcia.SeleniumExtension;
import io.github.bonigarcia.SeleniumJupiter;
import io.github.bonigarcia.config.Config;

@ExtendWith(SeleniumExtension.class)
public class ForcedEmptyConfigJupiterTest {

    @BeforeAll
    static void setup() throws Exception {
        Config config = SeleniumJupiter.config();
        config.setExceptionWhenNoDriver(false);
        for (Method method : config.getClass().getMethods()) {
            if (method.getName().startsWith("set")) {
                if (method.getParameterTypes()[0].equals(String.class)) {
                    method.invoke(config, "");
                }
            }
        }
    }

    @AfterAll
    static void teardown() {
        SeleniumJupiter.config().reset();
    }

    @Test
    void genericTest(WebDriver driver) {
        assertThrows(NullPointerException.class, () -> driver
                .get("https://bonigarcia.github.io/selenium-jupiter/"));
    }

}

Include test forcing all String config keys to empty value


// MapReduceOutput.java

package com.mongodb;

/**
 * Represents the result of a map/reduce operation
 * @author antoine
 */
public class MapReduceOutput {

    MapReduceOutput( DBCollection from , BasicDBObject raw ){
        _raw = raw;

        if ( raw.containsKey( "results" ) ) {
            _coll = null;
            _collname = "<<INLINE>>";
            _resultSet = (Iterable<DBObject>) raw.get( "results" );
        } else {
            _collname = raw.getString( "result" );
            _coll = from._db.getCollection( _collname );
            _resultSet = _coll.find();
        }
        _counts = (BasicDBObject)raw.get( "counts" );
    }

    /**
     * returns a cursor to the results of the operation
     * @return
     */
    public Iterable<DBObject> results(){
        return _resultSet;
    }

    /**
     * drops the collection that holds the results
     */
    public void drop(){
        if ( _coll != null)
            _coll.drop();
    }

    /**
     * gets the collection that holds the results
     * (Will return null if results are Inline)
     * @return
     */
    public DBCollection getOutputCollection(){
        return _coll;
    }

    public BasicDBObject getRaw(){
        return _raw;
    }

    public String toString(){
        return _raw.toString();
    }

    final BasicDBObject _raw;

    final String _collname;
    final Iterable<DBObject> _resultSet;
    final DBCollection _coll;
    final BasicDBObject _counts;
}

// MapReduceOutput.java

package com.mongodb;

/**
 * Represents the result of a map/reduce operation
 * @author antoine
 */
public class MapReduceOutput {

    MapReduceOutput( DBCollection from , BasicDBObject raw ){
        _raw = raw;

        if ( raw.containsKey( "results" ) ) {
            _coll = null;
            _collname = null;
            _resultSet = (Iterable<DBObject>) raw.get( "results" );
        } else {
            _collname = raw.getString( "result" );
            _coll = from._db.getCollection( _collname );
            _resultSet = _coll.find();
        }
        _counts = (BasicDBObject)raw.get( "counts" );
    }

    /**
     * returns a cursor to the results of the operation
     * @return
     */
    public Iterable<DBObject> results(){
        return _resultSet;
    }

    /**
     * drops the collection that holds the results
     */
    public void drop(){
        if ( _coll != null)
            _coll.drop();
    }

    /**
     * gets the collection that holds the results
     * (Will return null if results are Inline)
     * @return
     */
    public DBCollection getOutputCollection(){
        return _coll;
    }

    public BasicDBObject getRaw(){
        return _raw;
    }

    public String toString(){
        return _raw.toString();
    }

    final BasicDBObject _raw;

    final String _collname;
    final Iterable<DBObject> _resultSet;
    final DBCollection _coll;
    final BasicDBObject _counts;
}

Set collection name to 'null' rather than a placeholder for inline results


/* Copyright 2008-2012 Nokia Siemens Networks Oyj
 *
 * 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.robotframework;

import org.python.core.PyObject;
import org.python.core.PySystemState;
import org.python.util.PythonInterpreter;

/**
 *
 * Helper class to create an Jython object and coerce it so that it can be used
 * from Java.
 *
 */
public class RunnerFactory {

    private PyObject runnerClass;

    public RunnerFactory() {
        runnerClass = importRunnerClass();
    }

    private PyObject importRunnerClass() {
        PythonInterpreter interpreter = new PythonInterpreter(null, new PySystemState());
        interpreter.exec("import robot; from robot.jarrunner import JarRunner");
        return interpreter.get("JarRunner");
    }

    /**
     * Creates and returns an instance of the robot.JarRunner (implemented in
     * Python), which can be used to execute tests.
     */
    public RobotRunner createRunner() {
        PyObject runnerObject = runnerClass.__call__();
        return (RobotRunner) runnerObject.__tojava__(RobotRunner.class);
    }
}

/* Copyright 2008-2012 Nokia Siemens Networks Oyj
 *
 * 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.robotframework;

import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

/**
 *
 * Helper class to create an Jython object and coerce it so that it can be used
 * from Java.
 *
 */
public class RunnerFactory {

    private PyObject runnerClass;

    public RunnerFactory() {
        runnerClass = importRunnerClass();
    }

    private PyObject importRunnerClass() {
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.exec("import robot; from robot.jarrunner import JarRunner");
        return interpreter.get("JarRunner");
    }

    /**
     * Creates and returns an instance of the robot.JarRunner (implemented in
     * Python), which can be used to execute tests.
     */
    public RobotRunner createRunner() {
        PyObject runnerObject = runnerClass.__call__();
        return (RobotRunner) runnerObject.__tojava__(RobotRunner.class);
    }
}

Revert change 00342e052b17 to fix sshlibrary on standalone jar.


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

import org.apache.felix.bundlerepository.RepositoryAdmin;
import org.apache.karaf.cellar.core.shell.CellarCommandSupport;

public abstract class ObrCommandSupport extends CellarCommandSupport {

    protected RepositoryAdmin obrService;

    public RepositoryAdmin getObrService() {
        return this.obrService;
    }

    public void setObrService(RepositoryAdmin obrService) {
        this.obrService = obrService;
    }

    public abstract Object doExecute() throws Exception;

}

Add the OBR command support.


package raw;

import static org.junit.Assert.assertTrue;
import robocode.BattleResults;
import robocode.control.events.BattleCompletedEvent;
import robocode.control.events.BattleMessageEvent;
import robocode.control.testing.RobotTestBed;
/**
 * Base class for testing robots to see if they can beat other robots.
 * To test other robots extend this class an override the get enemy robot method.
 * @author Robert Ward
 *
 */
public class TestBattleMultiOutcomes extends RobotTestBed {

  /**
   * Keep track of the number of messages. Print them if desired.
   *
   * @param event The BattleMessageEvent.
   */
  @Override
  public void onBattleMessage(BattleMessageEvent event) {
    //override the printout of each round
  }

  /**
   * Specifies the robots that are to be matched up in this test case.
   * @return The comma-delimited list of robots in this match.
   */
  @Override
  public String getRobotNames() {
    return getEnemyRobot() + "," + getTestRobot();
  }
  /**
   * Override this method to change the robot to Run a test battle against.
   * @return the name of the robot to fight
   */
  public String getEnemyRobot() {
    return "sample.Crazy,sample.Fire,sample.MyFirstJuniorRobot";
  }

  /**
   * The robot being tested.
   * Override to test a different robot.
   * @return the name of the robot to test
   */
  public String getTestRobot() {
    return "raw.Zero";
  }

  /**
   * The actual test, which asserts that the test robot has won over 30% of the rounds.
   * @param event Details about the completed battle.
   */
  @Override
  public void onBattleCompleted(BattleCompletedEvent event) {

    // Return the results in order of getRobotNames.
    BattleResults[] battleResults = event.getIndexedResults();

    BattleResults testRobotResults =  battleResults[0];

    for ( int index = 0; index < battleResults.length ; index++) {
      if ( battleResults[index].getTeamLeaderName().equals(this.getTestRobot() + "*") ) {
        testRobotResults = battleResults[index];

      }

    }

    String robotName = testRobotResults.getTeamLeaderName();

    System.out.println("Wins for " + robotName + " versus many " + testRobotResults.getFirsts());
    // Check to make sure test robot won over 30% of the rounds.
    assertTrue("Wins " + testRobotResults.getFirsts() , testRobotResults.getFirsts() > 30  );
  }

  /**
   * This test runs for 100 rounds.
   * @return The number of rounds.
   */
  @Override
  public int getNumRounds() {
    return 100;
  }

  /**
   * Returns true if the battle should be deterministic and thus robots will always start
   * in the same position each time.
   *
   * Override to return false to support random initialization.
   * @return True if the battle will be deterministic.
   */
  @Override
  public boolean isDeterministic() {
    return false;
  }

}

Add many robot combat test


/*
 * Copyright 2000-2012 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.siyeh.ipp.opassign.assignment;

class StringOpassign {

  void foo(String s) {
    s += 1<caret>.0;
  }
}

Fix test data once again


package ca.nrc.cadc.vos;

import javax.sql.DataSource;

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

public abstract class VOSpaceFileMetadataSourceTest extends PersistenceTest
{
    private VOSpaceFileMetadataSource vospaceFileMetadataSource;
    private DataNode testNode;

    @Before
    public void before() throws Exception
    {
        super.commonBefore();
        vospaceFileMetadataSource = new VOSpaceFileMetadataSource();
        vospaceFileMetadataSource.setNodePersistence(nodeDAO);

        ContainerNode rootContainer = (ContainerNode) nodeDAO.getFromParent(getRootContainerName(), null);
        testNode = new DataNode(getVOSURIPrefix() + getRootContainerName() + "/" + getNodeName("testNode"));
        nodeDAO.putInContainer(testNode, rootContainer);
    }

    public abstract DataSource getDataSource();

    public abstract NodeDAO getNodeDAO(DataSource dataSource);

    public abstract String getVOSURIPrefix();

    public abstract String getRootContainerName();

    public abstract String getNodeOwner();

    @Test
    public void testMetadata() throws Exception
    {

    }

}

Put common persistence test code in abstract class PersistenceTest


package de.lmu.ifi.dbs.elki.index.tree.spatial.rstarvariants.bulk;

/*
 This file is part of ELKI:
 Environment for Developing KDD-Applications Supported by Index-Structures

 Copyright (C) 2011
 Ludwig-Maximilians-Universität München
 Lehr- und Forschungseinheit für Datenbanksysteme
 ELKI Development Team

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

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

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
import java.util.List;

import de.lmu.ifi.dbs.elki.data.spatial.SpatialComparable;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.AbstractParameterizer;

/**
 * Trivial bulk loading - assumes that the file has been appropriately sorted
 * before.
 *
 * @author Erich Schubert
 */
public class FileOrderBulkSplit extends AbstractBulkSplit {
  /**
   * Static instance
   */
  public static final FileOrderBulkSplit STATIC = new FileOrderBulkSplit();

  /**
   * Constructor.
   */
  protected FileOrderBulkSplit() {
    super();
  }

  @Override
  public <T extends SpatialComparable> List<List<T>> partition(List<T> spatialObjects, int minEntries, int maxEntries) {
    return trivialPartition(spatialObjects, minEntries, maxEntries);
  }

  /**
   * Parameterization class.
   *
   * @author Erich Schubert
   *
   * @apiviz.exclude
   */
  public static class Parameterizer extends AbstractParameterizer {
    @Override
    protected FileOrderBulkSplit makeInstance() {
      return FileOrderBulkSplit.STATIC;
    }
  }
}

Add trivial splitting strategy, assuming that the file is pre-ordered.


import java.lang.String;
import java.net.*;
import java.io.*;

import org.json.*;

public class Sensor {

  private final static int MESSAGE_TAB_SIZE = 100;

  private static int sensorId = 0;
  private String sensorClass;
  private String sensorName;
  private int sensorCurrentMsgId;

  //Constructeur
  public Sensor(){
    sensorId += 1;
    sensorName = new String();
    sensorClass = new String();
    sensorCurrentMsgId = 0;
  }

  public Sensor(String class, String name){
    sensorId += 1;
    sensorClass = class;
    sensorName = name;
    sensorCurrentMsgId = 0;
  }

  // Setter
  public void setSensorId(int id){
    sensorId = id;
  }

  public void setSensorName(String name){
    sensorName = name;
  }

  public void setSensorClass(String class){
    sensorClass = class;
  }

  public void updateSensorCurrentMsgId(){
    sensorCurrentMsgId += 1;
  }

  // Getter
  public int getSensorId(){
    return sensorId;
  }

  public String getSensorName(){
    return sensorName;
  }

  public String getSensorClass(){
    return sensorClass;
  }

  public int getSensorCurrentMsgId(){
    return sensorCurrentMsgId;
  }

}

Add Senor class *not finished*


package com.basgeekball.awesomevalidation.utility;

import junit.framework.TestCase;

import java.util.regex.Pattern;

public class RegexTemplateTest extends TestCase {

    @Override
    protected void setUp() throws Exception {
        super.setUp();
    }

    public void testConstantNotEmpty() {
        Pattern pattern = Pattern.compile(RegexTemplate.NOT_EMPTY);
        assertTrue(pattern.matcher("a").matches());
        assertTrue(pattern.matcher("1").matches());
        assertTrue(pattern.matcher(".").matches());
        assertTrue(pattern.matcher("$").matches());
        assertTrue(pattern.matcher("!@#$%^&*()").matches());
        assertTrue(pattern.matcher("a1").matches());
        assertTrue(pattern.matcher("1q2w3e").matches());
        assertTrue(pattern.matcher(" x").matches());
        assertTrue(pattern.matcher("x ").matches());
        assertTrue(pattern.matcher(" x ").matches());
        assertFalse(pattern.matcher("").matches());
        assertFalse(pattern.matcher(" ").matches());
        assertFalse(pattern.matcher("  ").matches());
    }

    public void testConstantTelephone() {
        Pattern pattern = Pattern.compile(RegexTemplate.TELEPHONE);
        assertTrue(pattern.matcher("1234567890").matches());
        assertTrue(pattern.matcher("+49-030-00000001").matches());
        assertFalse(pattern.matcher("a123456789").matches());
    }

}

Add unit test for RegexTemplate.


package com.uwetrottmann.shopr.algorithm.test;

import static org.fest.assertions.api.Assertions.assertThat;

import com.uwetrottmann.shopr.algorithm.AdaptiveSelection;

import org.junit.Test;

public class AdaptiveSelectionTest {

    @Test
    public void testLikeValue() {
        // all equal
        double[] actual = new double[] {
                0.25, 0.25, 0.25, 0.25
        };
        double[] expected = new double[] {
                0.25 - 0.25 / 3, 0.5, 0.25 - 0.25 / 3, 0.25 - 0.25 / 3
        };
        AdaptiveSelection.likeValue(1, actual);
        assertThat(actual).isEqualTo(expected);

        // one getting bigger than zero
        actual = new double[] {
                0.4 / 3, 0.6, 0.4 / 3, 0.4 / 3
        };
        expected = new double[] {
                0.0, 1.0, 0.0, 0.0
        };
        AdaptiveSelection.likeValue(1, actual);
        assertThat(actual).isEqualTo(expected);
    }

    @Test
    public void testdislikeValue() {
        // all equal
        double[] actual = new double[] {
                0.25, 0.25, 0.25, 0.25
        };
        double[] expected = new double[] {
                0.25 + 0.25 / 3, 0.0, 0.25 + 0.25 / 3, 0.25 + 0.25 / 3
        };
        AdaptiveSelection.dislikeValue(1, actual);
        assertThat(actual).isEqualTo(expected);

        // two zero, keep them zero
        actual = new double[] {
                0.0, 0.5, 0.0, 0.5
        };
        expected = new double[] {
                0.0, 0.0, 0.0, 1.0
        };
        AdaptiveSelection.dislikeValue(1, actual);
        assertThat(actual).isEqualTo(expected);
    }

}

Add tests for likeValue and dislikeValue.


package com.emilsjolander.components.StickyListHeaders;

import android.content.Context;
import android.view.View;
import android.widget.LinearLayout;
/**
 *
 * @author Emil Sjlander
 *
 *
Copyright 2012 Emil Sjlander

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.
 *
 */
public class WrapperView {

	private LinearLayout v;

	public WrapperView(Context c) {
		v = new LinearLayout(c);
		v.setId(R.id.__stickylistheaders_wrapper_view);
		v.setOrientation(LinearLayout.VERTICAL);
	}

	public WrapperView(View v) {
		this.v = (LinearLayout) v;
	}

	public View wrapViews(View... views){
		v.removeAllViews();
		for(View child : views){
			v.addView(child);
		}
		return v;
	}

}

package com.emilsjolander.components.StickyListHeaders;

import android.content.Context;
import android.view.View;
import android.widget.LinearLayout;
/**
 *
 * @author Emil Sj�lander
 *
 *
Copyright 2012 Emil Sj�lander

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.
 *
 */
public class WrapperView {

	private LinearLayout v;

	public WrapperView(Context c) {
		v = new LinearLayout(c);
		v.setId(R.id.__stickylistheaders_wrapper_view);
		v.setOrientation(LinearLayout.VERTICAL);
	}

	public WrapperView(View v) {
		this.v = (LinearLayout) v;
	}

	public View wrapViews(View... views){
		v.removeAllViews();
		for(View child : views){
			v.addView(child);
		}
		return v;
	}

}

Update missed file to UTF-8 encoding.


/**
 * This Source Code Form is subject to the terms of the Mozilla Public License,
 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
 * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
 * the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
 *
 * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
 * graphic logo is a trademark of OpenMRS Inc.
 */
package org.openmrs.web.attribute.handler;

import java.util.Map;

import org.openmrs.Concept;
import org.openmrs.customdatatype.CustomDatatype;
import org.openmrs.customdatatype.datatype.ConceptDatatype;
import org.springframework.stereotype.Component;

/**
 * Handler for the Concept custom datatype
 */
@Component
public class ConceptFieldGenDatatypeHandler extends SerializingFieldGenDatatypeHandler<ConceptDatatype, Concept> {

	/**
	 * @see SerializingFieldGenDatatypeHandler#getWidgetName()
	 */
	@Override
	public String getWidgetName() {
		return "org.openmrs.Concept";
	}

	/**
	 * @see SerializingFieldGenDatatypeHandler#toHtml(CustomDatatype, String)
	 */
	@Override
	public String toHtml(CustomDatatype datatype, String valueReference) {
		return toHtmlSummary(datatype, valueReference).getSummary();
	}

	/**
	 * @see SerializingFieldGenDatatypeHandler#toHtmlSummary(CustomDatatype, String)
	 */
	@Override
	public CustomDatatype.Summary toHtmlSummary(CustomDatatype datatype, String valueReference) {
		return datatype.getTextSummary(valueReference);
	}

	/**
	 * @see SerializingFieldGenDatatypeHandler#getWidgetConfiguration()
	 */
	@Override
	public Map<String, Object> getWidgetConfiguration() {
		return null;
	}

	/**
	 * @see SerializingFieldGenDatatypeHandler#setHandlerConfiguration(String)
	 */
	@Override
	public void setHandlerConfiguration(String s) {

	}
}

Create a custom data type and its associated handler for concepts - TRUNK-3621


package com.williamfiset.algorithms.math;

import java.math.BigInteger;

public class NChooseRModPrime {
  /**
   * Calculate the value of C(N, R) % P using Fermat's Little Theorem.
   *
   * @param N
   * @param R
   * @param P
   * @return The value of N choose R Modulus P
   */
  public static long compute(int N, int R, int P) {
    if (R == 0) return 1;

    long[] factorial = new long[N + 1];
    factorial[0] = 1;

    for (int i = 1; i <= N; i++) {
      factorial[i] = factorial[i - 1] * i % P;
    }

    return (factorial[N]
            * ModularInverse.modInv(factorial[R], P)
            % P
            * ModularInverse.modInv(factorial[N - R], P)
            % P)
        % P;
  }

  private static String bigIntegerNChooseRModP(int N, int R, int P) {
    if (R == 0) return "1";
    BigInteger num = new BigInteger("1");
    BigInteger den = new BigInteger("1");
    while (R > 0) {
      num = num.multiply(new BigInteger("" + N));
      den = den.multiply(new BigInteger("" + R));
      BigInteger gcd = num.gcd(den);
      num = num.divide(gcd);
      den = den.divide(gcd);
      N--;
      R--;
    }
    num = num.divide(den);
    num = num.mod(new BigInteger("" + P));
    return num.toString();
  }

  public static void main(String args[]) {
    int N = 500;
    int R = 250;
    int P = 1000000007;
    int expected = Integer.parseInt(bigIntegerNChooseRModP(N, R, P));
    long actual = compute(N, R, P);
    System.out.println(expected); // 515561345
    System.out.println(actual); // 515561345
  }
}

Add N choose R mod prime


/*
 * Copyright 2016 EuregJUG.
 *
 * 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.euregjug.site.support.thymeleaf.expressions;

import java.time.YearMonth;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.FormatStyle;
import java.util.Locale;
import org.junit.Assert;
import org.junit.Test;

/**
 * @author Michael J. Simons, 2015-01-09
 */
public class TemporalsTest {

    @Test
    public void formatDateShouldWork() {
        final Temporals temporals = new Temporals(Locale.US);
        Assert.assertEquals("6/30/09", temporals.formatDate(ZonedDateTime.now().withYear(2009).withMonth(6).withDayOfMonth(30), FormatStyle.SHORT));
        Assert.assertEquals("6/30/09 7:03:47 AM", temporals.formatDateTime(
                ZonedDateTime.now()
                .withYear(2009).withMonth(6).withDayOfMonth(30)
                .withHour(7).withMinute(3).withSecond(47),
                FormatStyle.SHORT,
                FormatStyle.MEDIUM
        ));
        Assert.assertEquals("10/26/14 1:30:00 AM", temporals.formatDateTime(
                ZonedDateTime.of(2014, 10, 26, 1, 30, 0, 0, ZoneId.of("UTC")),
                FormatStyle.SHORT,
                FormatStyle.MEDIUM
        ));
        Assert.assertEquals("March 1979", temporals.format(YearMonth.of(1979, 3), "MMMM yyyy"));
        Assert.assertEquals("2014.10.26 01:30", temporals.format(ZonedDateTime.of(2014, 10, 26, 1, 30, 0, 0, ZoneId.of("UTC")), "yyyy.MM.dd HH:mm"));
    }
}

Add existing tests from Daily Fratze


/*
 * Copyright (C) 2016 Reece H. Dunn
 *
 * 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 uk.co.reecedunn.intellij.plugin.xquery.tests.lang;

import junit.framework.TestCase;
import uk.co.reecedunn.intellij.plugin.xquery.lang.XQuery;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;

public class XQueryTest extends TestCase {
    public void testID() {
        assertThat(XQuery.INSTANCE.getID(), is("XQuery"));
    }

    public void testBaseLanguage() {
        assertThat(XQuery.INSTANCE.getBaseLanguage(), is(nullValue()));
    }

    public void testMimeTypes() {
        assertThat(XQuery.INSTANCE.getMimeTypes().length, is(1));
        assertThat(XQuery.INSTANCE.getMimeTypes()[0], is("application/xquery"));
    }

    public void testCaseSensitivity() {
        assertThat(XQuery.INSTANCE.isCaseSensitive(), is(true));
    }
}

Add tests for the XQuery language class.


/**
 * Project RSA Algorithm.
 * Copyright Michał Szczygieł.
 * Created at Feb 25, 2014.
 */

/**
 *
 * This class is responsible for safe operations on files. This class contatin
 * the basic input/output operations.
 *
 * @author Michał Szczygieł <michal.szczygiel@wp.pl>
 *
 */
public class IOOperations {

}

Add class responsible for IO operations


package okapi;

import com.jayway.restassured.RestAssured;
import com.jayway.restassured.response.Response;
import guru.nidi.ramltester.RamlDefinition;
import guru.nidi.ramltester.RamlLoaders;
import guru.nidi.ramltester.restassured.RestAssuredClient;
import io.vertx.core.Vertx;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.folio.okapi.MainCluster;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(VertxUnitRunner.class)
public class MainClusterTest {

  private final Logger logger = LoggerFactory.getLogger("okapi");
  private final int port = Integer.parseInt(System.getProperty("port", "9130"));
  Async async;
  Vertx vertx;

  public MainClusterTest() {
  }

  @BeforeClass
  public static void setUpClass() {
  }

  @AfterClass
  public static void tearDownClass() {
  }

  @Before
  public void setUp(TestContext context) {
    async = context.async();

    RestAssured.port = port;
    String[] args = {"dev"};

    MainCluster.main1(args, res -> {
      vertx = res.result();
      Assert.assertTrue("main1: " + res.cause(), res.succeeded());
      async.complete();
    });
  }

  @After
  public void tearDown(TestContext context) {
    async = context.async();
    if (vertx != null) {
      vertx.close(x -> {
        async.complete();
      });
    } else {
      async.complete();
    }
  }

  @Test
  public void testVersion(TestContext context) {
    async = context.async();

    RamlDefinition api = RamlLoaders.fromFile("src/main/raml").load("okapi.raml");

    RestAssuredClient c;
    Response r;

    c = api.createRestAssured();
    r = c.given().get("/_/version").then().statusCode(200).log().ifError().extract().response();

    Assert.assertTrue("raml: " + c.getLastReport().toString(),
      c.getLastReport().isEmpty());
    async.complete();
  }

}

Add test using MainCluster class for better coverage


/**
 * Copyright Microsoft Corporation
 *
 * 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.microsoft.windowsazure;

import cucumber.api.junit.Cucumber;
import cucumber.api.CucumberOptions;

import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(
format = {"html:target/cucumber-html-report", "json:target/cucumber-json-report.json"},
tags = {"~@ignore"})
public class RunCukesTest {
}

/**
 * Copyright Microsoft Corporation
 *
 * 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.microsoft.windowsazure;

import cucumber.api.junit.Cucumber;
import cucumber.api.CucumberOptions;

import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(
format = {"html:target/cucumber-html-report", "json:target/cucumber-json-report.json"},
tags = {"@livetest"})
public class RunCukesTest {
}

Change cucumber test tag to not run by default


package org.apache.solr.util;

/*
 * 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.
 */

import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.TestRuleLimitSysouts.Limit;
import org.apache.solr.common.util.ObjectReleaseTracker;
import org.junit.Test;

@Limit(bytes=150000) // raise limit as this writes to sys err
public class TestObjectReleaseTracker extends LuceneTestCase {

  @Test
  public void testObjectReleaseTracker() {
    ObjectReleaseTracker.track(new Object());
    ObjectReleaseTracker.release(new Object());
    assertFalse(ObjectReleaseTracker.clearObjectTrackerAndCheckEmpty());
    assertTrue(ObjectReleaseTracker.clearObjectTrackerAndCheckEmpty());
    Object obj = new Object();
    ObjectReleaseTracker.track(obj);
    ObjectReleaseTracker.release(obj);
    assertTrue(ObjectReleaseTracker.clearObjectTrackerAndCheckEmpty());

    Object obj1 = new Object();
    ObjectReleaseTracker.track(obj1);
    Object obj2 = new Object();
    ObjectReleaseTracker.track(obj2);
    Object obj3 = new Object();
    ObjectReleaseTracker.track(obj3);

    ObjectReleaseTracker.release(obj1);
    ObjectReleaseTracker.release(obj2);
    ObjectReleaseTracker.release(obj3);
    assertTrue(ObjectReleaseTracker.clearObjectTrackerAndCheckEmpty());

    ObjectReleaseTracker.track(obj1);
    ObjectReleaseTracker.track(obj2);
    ObjectReleaseTracker.track(obj3);

    ObjectReleaseTracker.release(obj1);
    ObjectReleaseTracker.release(obj2);
    // ObjectReleaseTracker.release(obj3);
    assertFalse(ObjectReleaseTracker.clearObjectTrackerAndCheckEmpty());
    assertTrue(ObjectReleaseTracker.clearObjectTrackerAndCheckEmpty());
  }
}

Add basic testing for test ObjectReleaseTracker.


package com.bodastage.e4.clock.ui.internal;

import java.time.ZoneId;
import java.time.format.TextStyle;
import java.util.Locale;

public class TimeZoneDisplayNameColumn extends TimeZoneColumn {
	@Override
	public String getText(Object element) {
		if (element instanceof ZoneId) {
			return ((ZoneId) element).getDisplayName(TextStyle.FULL, Locale.
					getDefault());
		} else {
			return "";
		}
	}

	@Override
	public String getTitle() {
		return "Display Name";
	}
}

Add time zone table viewr display name column


/*
 * This file is part of COMPASS. It is subject to the license terms in
 * the LICENSE file found in the top-level directory of this distribution.
 * (Also available at http://www.apache.org/licenses/LICENSE-2.0.txt)
 * You may not use this file except in compliance with the License.
 */
/*
 * This file is part of ATLAS. It is subject to the license terms in
 * the LICENSE file found in the top-level directory of this distribution.
 * (Also available at http://www.apache.org/licenses/LICENSE-2.0.txt)
 * You may not use this file except in compliance with the License.
 */
package de.dfki.asr.atlas.rest.providers;

import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;

@Provider
public class CORSRequestFilter implements ContainerResponseFilter {

	@Override
	public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext) throws IOException {
		MultivaluedMap<String, Object> headers = responseContext.getHeaders();
		headers.add("Access-Control-Allow-Origin", "*");
		headers.add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
		headers.add("Access-Control-Allow-Credentials", "true");
		headers.add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
		headers.add("Access-Control-Max-Age", "1209600");
	}

}

Add Cross Origin Request Filter


package leetcode.linked_list_cycle;

import common.ListNode;

public class Solution {
	public boolean hasCycle(ListNode head) {
        ListNode hare = head, tortoise = head;
        while(hare != null){
            hare = hare.next;
            if(hare == null) return false;
            hare = hare.next;
            tortoise = tortoise.next;
            if(hare == tortoise){
                return true;
            }
        }
        return false;
	}
}

Add java solution for 141. Linked List Cycle


package org.modelmapper.functional.config;

import org.modelmapper.AbstractTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotSame;
import static org.testng.Assert.assertSame;

@Test
public class DeepCopyEnabledTest extends AbstractTest {
  static class Source {
    Property property;

    public Source(Property property) {
      this.property = property;
    }
  }
  static class Destination {
    Property property;
  }

  static class Property {
    String value;

    public Property() {
    }

    public Property(String value) {
      this.value = value;
    }
  }

  public void shouldDeepCopy() {
    modelMapper.getConfiguration().setDeepCopyEnabled(true);

    Source source = new Source(new Property("text"));
    Destination destination = modelMapper.map(source, Destination.class);

    assertNotSame(destination.property, source.property);
    assertEquals(destination.property.value, source.property.value);
  }

  public void shouldNotDeepCopyByDefault() {
    Source source = new Source(new Property("text"));
    Destination destination = modelMapper.map(source, Destination.class);

    assertSame(destination.property, source.property);
  }

  public void shouldNotDeepCopy() {
    modelMapper.getConfiguration().setDeepCopyEnabled(false);

    Source source = new Source(new Property("text"));
    Destination destination = modelMapper.map(source, Destination.class);

    assertSame(destination.property, source.property);
  }
}

Add unit test for deep copy


/*
 * Copyright 2013-2016 the original author or authors.
 *
 * 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.cloudfoundry.client.v2;

import org.cloudfoundry.AbstractIntegrationTest;
import org.cloudfoundry.client.CloudFoundryClient;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import static org.junit.Assert.fail;

public final class ServiceBrokersTest extends AbstractIntegrationTest {

    @Autowired
    private CloudFoundryClient cloudFoundryClient;

    @Ignore("TODO: awaiting story https://www.pivotaltracker.com/story/show/118387501")
    @Test
    public void create() {
        fail("TODO: finish story https://www.pivotaltracker.com/story/show/118387501");
    }

    @Ignore("TODO: awaiting story https://www.pivotaltracker.com/story/show/118387501")
    @Test
    public void delete() {
        fail("TODO: finish story https://www.pivotaltracker.com/story/show/118387501");
    }

    @Ignore("TODO: awaiting story https://www.pivotaltracker.com/story/show/118387501")
    @Test
    public void get() {
        fail("TODO: finish story https://www.pivotaltracker.com/story/show/118387501");
    }

    @Ignore("TODO: awaiting story https://www.pivotaltracker.com/story/show/118387501")
    @Test
    public void list() {
        fail("TODO: finish story https://www.pivotaltracker.com/story/show/118387501");
    }

    @Ignore("TODO: awaiting story https://www.pivotaltracker.com/story/show/118387501")
    @Test
    public void update() {
        fail("TODO: finish story https://www.pivotaltracker.com/story/show/118387501");
    }

}

Put in placeholders for client service broker integration tests


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

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

import org.sablecc.sablecc.automaton.graph.State;
import org.sablecc.sablecc.automaton.graph.Transition;
import org.sablecc.sablecc.exception.InternalException;

class EpsilonReach<T extends Comparable<? super T>> {

    private NFA<T> nfa;

    private final Map<State<T>, Set<State<T>>> reachMap = new HashMap<State<T>, Set<State<T>>>();

    EpsilonReach(
            NFA<T> nfa) {

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

        this.nfa = nfa;
    }

    Set<State<T>> getEpsilonReach(
            State<T> state) {

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

        if (!this.nfa.getStates().contains(state)) {
            throw new InternalException("invalid state");
        }

        Set<State<T>> reach = this.reachMap.get(state);

        if (reach == null) {
            reach = computeReach(state);
            this.reachMap.put(state, reach);
        }

        return reach;
    }

    private Set<State<T>> computeReach(
            State<T> state) {

        Set<State<T>> reach = new HashSet<State<T>>();

        visit(state, reach);

        return Collections.unmodifiableSet(reach);
    }

    private void visit(
            State<T> state,
            Set<State<T>> reach) {

        // did we visit it before?
        if (!reach.contains(state)) {

            // no, so add it
            reach.add(state);

            // do we know its reach?
            Set<State<T>> stateReach = this.reachMap.get(state);
            if (stateReach != null) {
                // yes, use it!
                reach.addAll(stateReach);
            }
            else {
                // no, we need to visit
                for (Transition<T> transition : state.getForwardTransitions()) {
                    if (transition.getSymbol() == null) {
                        visit(transition.getDestination(), reach);
                    }
                }
            }
        }
    }
}

Add class to compute transitive NFA epsilon transitions.


package com.github.sparkcaller.utils;

import java.io.*;

public class FileExtractor {

    public static String extractExecutable(String resourceFilePath) {

        if (!resourceFilePath.startsWith("/")) {
            resourceFilePath = "/" + resourceFilePath;
        }

        if (resourceFilePath == null)
            return null;

        try {
            // Read the file we're looking for
            InputStream fileStream = FileExtractor.class.getResourceAsStream(resourceFilePath);

            // Was the resource found?
            if (fileStream == null)
                return null;

            // Grab the file name
            String[] chopped = resourceFilePath.split("\\/");
            String fileName = chopped[chopped.length-1];

            // Create our temp file
            File tempFile = File.createTempFile("sparkcaller" + System.nanoTime(), fileName);

            // Delete the file on VM exit
            tempFile.deleteOnExit();

            OutputStream out = new FileOutputStream(tempFile);

            // Write the file to the temp file
            byte[] buffer = new byte[1024];
            int len = fileStream.read(buffer);
            while (len != -1) {
                out.write(buffer, 0, len);
                len = fileStream.read(buffer);
            }

            fileStream.close();
            out.close();

            tempFile.setExecutable(true);
            return tempFile.getAbsolutePath();

        } catch (IOException e) {
            return null;
        }
    }
}

Add a class which can be used to extract binaries from inside the JAR file.


package com.braintreepayments.api;

import org.junit.Test;

import static org.junit.Assert.*;

public class VenmoRequestUnitTest {

    @Test
    public void constructor_defaultsPaymentMethodUsageTypeToUNSPECIFIED() {
        VenmoRequest sut = new VenmoRequest();
        assertEquals(VenmoPaymentMethodUsage.UNSPECIFIED, sut.getPaymentMethodUsage());
    }
}

Add unit test for VenmoRequest.