package leetcode.min_stack;

class MinStack {
	private static final int SIZE = 100000;
	private int[] mList = new int[SIZE];
	private int[] mMinList = new int[SIZE];
	private int mSize = 0;

	public void push(int x) {
		mList[mSize] = x;
		int minVal = x;
		if(mSize > 0){
			minVal = Math.min(mMinList[mSize - 1], x);
		}
		mMinList[mSize] = minVal;
		mSize++;
    }

    public void pop() {
    	mSize--;
    }

    public int top() {
        return mList[mSize - 1];
    }

    public int getMin() {
        return mMinList[mSize - 1];
    }
}

Add java solution for 155. Min Stack


package problems;

public class FindMinInRotatedSortedArray {
    public int findMin(int[] num) {
        if (num == null || num.length == 0)
            return 0;

        return findMinHelper(num, 0, num.length - 1);
    }

    int findMinHelper(int[] A, int l, int r) {
        if (r - l <= 1)
            return Math.min(A[l], A[r]);

        int mid = (l + r) / 2;
        if (A[mid] >= A[l] && A[mid] > A[r])
            return findMinHelper(A, mid, r);
        if (A[mid] == A[l] && A[mid] == A[r])
            return Math.min(findMinHelper(A, mid, r), findMinHelper(A, l, mid - 1));
        return findMinHelper(A, l, mid);
    }

    public static void main(String[] args) {
        FindMinInRotatedSortedArray fm = new FindMinInRotatedSortedArray();
        int[] num = { 4, 5, 6, 7, 0, 1, 2, 2 };
        System.out.println(fm.findMin(num));
    }
}

Add Find Minimum in Rotated Sortes Array


package us.crast.mondochest.util;

public class GenericUtil {
    @SuppressWarnings("unchecked")
    public static <T> T cast(Object x) {
        return (T) x;
    }
}

Add in Generic Typecast support


package com.opcoach.e4.modelmerger.test;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class TestMergeDuration extends TestMerge {

	@Test
	public void testMergeDuration() {

		long start = System.currentTimeMillis();
		merger.mergeModels(master, model);
		long end = System.currentTimeMillis();

		System.out.println("Merge duration is : " + (end-start) + " ms");
		assertTrue("Merge must be done in less than 10 ms ", ((end-start) <= 10));
	}

}

Add a test to watch merge duration during dev.


package readinstruction;

import java.util.UUID;

/**
 * Created by Karol on 2017-04-20.
 */
public class ReadInstructionImpl extends ReadInstruction {
    public ReadInstructionImpl(UUID instructionId, int readAddres, int arrivalTime, boolean hasDeadline) {
        super(instructionId, readAddres, arrivalTime, hasDeadline);
    }
}

Implement concrete implementation of ReadInstruction


package net.imagej.ops.views;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.Subsample;
import net.imglib2.RandomAccessible;
import net.imglib2.view.SubsampleView;
import net.imglib2.view.Views;

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

@Plugin(type = ViewOps.Subsample.class, name = ViewOps.Subsample.NAME)
public class DefaultSubsample<T> extends
		AbstractView<RandomAccessible<T>, SubsampleView<T>> implements
		Subsample<RandomAccessible<T>, SubsampleView<T>> {

	@Parameter(type = ItemIO.INPUT)
	private long step;

	@Override
	public SubsampleView<T> compute(RandomAccessible<T> input) {
		return Views.subsample(input, step);
	}

}

Add default implementation of Subsample interface.


package scratchlib.objects;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import org.junit.Test;

import scratchlib.objects.fixed.data.ScratchObjectString;
import scratchlib.objects.inline.ScratchObjectBoolean;
import scratchlib.project.ScratchProject;
import scratchlib.project.ScratchVersion;
import scratchlib.reader.ScratchInputStream;

public class ScratchObjectsTest
{
    @Test
    public void looksUpConstructor()
    {
        assertSame(ScratchObjectBoolean.NIL,
                ScratchObjects.lookupConstructor(1).get());
        assertSame(ScratchObjectBoolean.FALSE,
                ScratchObjects.lookupConstructor(3).get());

        assertThat(ScratchObjects.lookupConstructor(9).get(),
                instanceOf(ScratchObjectString.class));
    }

    @Test
    public void readsReferences() throws IOException
    {
        ScratchProject project = new ScratchProject(ScratchVersion.SCRATCH14);

        ByteArrayInputStream bin = new ByteArrayInputStream(
                new byte[] { 99, 0, 1, 37 });

        ScratchOptionalField result = ScratchObjects
                .read(new ScratchInputStream(bin), project);

        assertFalse(result.isResolved());
        assertEquals(293, result.getReferenceID());
    }

    @Test
    public void readsObjects() throws IOException
    {
        ScratchProject project = new ScratchProject(ScratchVersion.SCRATCH14);

        ByteArrayInputStream bin = new ByteArrayInputStream(
                new byte[] { 9, 0, 0, 0, 0 });

        ScratchOptionalField result = ScratchObjects
                .read(new ScratchInputStream(bin), project);

        assertTrue(result.isResolved());
        assertThat(result.get(), instanceOf(ScratchObjectString.class));
    }

    @Test(expected = IOException.class)
    public void throwsForUnknownClassID() throws IOException
    {
        ScratchProject project = new ScratchProject(ScratchVersion.SCRATCH14);

        ByteArrayInputStream bin = new ByteArrayInputStream(
                new byte[] { (byte) 255, 0, 0, 0, 0 });

        ScratchObjects.read(new ScratchInputStream(bin), project);
    }
}

Add unit tests for ScratchObjects


/*
 * IteratorComposite.java
 *
 * Author: Ming Tsang
 * Copyright (c) 2015 Ming Tsang
 * Refer to LICENSE for details
 */

package com.nkming.utils.type;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class IteratorComposite<T> implements Iterator<T>
{
	public IteratorComposite(Iterator<T> a, Iterator<T> b)
	{
		mItA = a;
		mItB = b;
		mItActive = mItA;
	}

	@Override
	public boolean hasNext()
	{
		return (mItA.hasNext() || mItB.hasNext());
	}

	@Override
	public T next()
	{
		if (!hasNext())
		{
			throw new NoSuchElementException();
		}
		else
		{
			if (mItA.hasNext())
			{
				mItActive = mItA;
				return mItA.next();
			}
			else
			{
				mItActive = mItB;
				return mItB.next();
			}
		}
	}

	@Override
	public void remove()
	{
		mItActive.remove();
	}

	private Iterator<T> mItA;
	private Iterator<T> mItB;
	private Iterator<T> mItActive;
}

Add composite iterator to join 2 iterators together


package net.openhft.chronicle.wire;

/**
 * Created by peter on 05/06/2017.
 */
public interface MethodFilter {
    boolean shouldHandleMessage(String method, Object firstArg);
}

Add periodic update and heartbeat messages


/*
 * ARX: Powerful Data Anonymization
 * Copyright 2012 - 2016 Fabian Prasser, Florian Kohlmayer and contributors
 *
 * 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.deidentifier.arx.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.deidentifier.arx.gui.resources.Resources;
import org.junit.Assert;
import org.junit.Test;

/**
 * A simple test which checks for duplicate message in the resource bundle
 * @author Fabian Prasser
 */
public class TestResourceBundle {

    /**
     * Helper class which wraps Properties
     * @author Fabian Prasser
     */
    private static class WrappedProperties extends Properties {

        /** SVUID*/
        private static final long serialVersionUID = 7390022720344169366L;

        @Override
        public synchronized Object put(Object key, Object value) {
            if (get(key) != null) {
                throw new IllegalStateException("Duplicate key: " + key + " - Current value: " + value + " - Original value: " + (String) get(key));
            }
            return super.put(key, value);
        }
    }

    @Test
    public void test() throws IOException {
        try {
            WrappedProperties resources = new WrappedProperties();
            InputStream stream = Resources.class.getClassLoader().getResourceAsStream("org/deidentifier/arx/gui/resources/messages.properties");
            resources.load(stream);
            stream.close();
        } catch (IllegalStateException e) {
            Assert.fail(e.getMessage());
        }
    }
}

Add test which checks for duplicate entries in messages.properties


/*
 * 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.flink.runtime.rest.messages.taskmanager;

import org.apache.flink.runtime.rest.messages.ResponseBody;
import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase;

import java.util.Arrays;

/**
 * Tests for (un)marshalling of {@link LogListInfo}.
 */
public class LogListInfoTest extends RestResponseMarshallingTestBase {

	@Override
	protected Class getTestResponseClass() {
		return LogListInfo.class;
	}

	@Override
	protected ResponseBody getTestResponseInstance() throws Exception {
		return new LogListInfo(Arrays.asList(
			new LogInfo("taskmanager.log", 0),
			new LogInfo("taskmanager.out", Integer.MAX_VALUE)));
	}
}

Add tests for (un)marshalling LogListInfo


/* LanguageTool, a natural language style checker
 * Copyright (C) 2018 Daniel Naber (http://www.danielnaber.de)
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301
 * USA
 */
package org.languagetool.rules.es;

import org.junit.Before;
import org.junit.Test;
import org.languagetool.JLanguageTool;
import org.languagetool.TestTools;
import org.languagetool.language.Spanish;
import org.languagetool.rules.RuleMatch;

import java.io.IOException;

import static org.junit.Assert.assertEquals;

/**
 *
 * @author (adapted from Portuguese version by David Méndez)
 * @since 4.1
 */
public class SpanishWikipediaRuleTest {

  private SpanishWikipediaRule rule;
  private JLanguageTool langTool;

  @Before
  public void setUp() throws Exception {
    rule = new SpanishWikipediaRule(TestTools.getMessages("es"));
    langTool = new JLanguageTool(new Spanish());
  }

  @Test
  public void testRule() throws IOException {

    // correct sentences:
    assertEquals(0, rule.match(langTool.getAnalyzedSentence("Estas frases no tienen errores frecuentes en la Wikipedia.")).length);

    // incorrect sentences:

    // at the beginning of a sentence (replace rule is case-sensitive)
    checkSimpleReplaceRule("Sucedió ayer. Murio sin que nadie lo esperase.", "Murió");
    // inside sentence
    checkSimpleReplaceRule("Ayer murio sin que nadie lo esperase.", "murió");
  }

  /**
   * Check if a specific replace rule applies.
   * @param sentence the sentence containing the incorrect/misspelled word.
   * @param word the word that is correct (the suggested replacement).
   */
  private void checkSimpleReplaceRule(String sentence, String word) throws IOException {
    RuleMatch[] matches = rule.match(langTool.getAnalyzedSentence(sentence));
    assertEquals("Invalid matches.length while checking sentence: "
            + sentence, 1, matches.length);
    assertEquals("Invalid replacement count wile checking sentence: "
            + sentence, 1, matches[0].getSuggestedReplacements().size());
    assertEquals("Invalid suggested replacement while checking sentence: "
            + sentence, word, matches[0].getSuggestedReplacements().get(0));
  }
}

Add a test for SpanishWikipediaRule


/*
 * This file is part of Mapyrus, software for plotting maps.
 * Copyright (C) 2003 Simon Chenery.
 *
 * Mapyrus 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 of the License, or
 * (at your option) any later version.
 *
 * Mapyrus 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 Mapyrus; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

/*
 * @(#) $Id$
 */
package org.mapyrus.function;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.mapyrus.Argument;
import org.mapyrus.ContextStack;
import org.mapyrus.MapyrusException;

/**
 * Function replacing all instances of a regular expression in a string with another string.
 * For example, replace('foobar', 'o+', '_') = 'f_bar'.
 */
public class Replace extends Function
{
	/**
	 * @see org.mapyrus.function.Function#evaluate(org.mapyrus.ContextStack,
	 * 	org.mapyrus.Argument, org.mapyrus.Argument, org.mapyrus.Argument)
	 */
	public Argument evaluate(ContextStack context, Argument arg1, Argument arg2, Argument arg3)
		throws MapyrusException
	{
		Argument retval;

		/*
		 * Replace all occurrences of pattern given in second string
		 * with the third string.
		 */
		Pattern pattern = Match.compileRegex(arg2.toString());
		Matcher matcher = pattern.matcher(arg1.toString());
		if (matcher.find())
		{
			/*
			 * Replace all matching patterns.
			 */
			retval = new Argument(Argument.STRING, matcher.replaceAll(arg3.toString()));
		}
		else
		{
			/*
			 * No match so return original string.
			 */
			retval = arg1;
		}
		return(retval);
	}

	/**
	 * @see org.mapyrus.function.Function#getMaxArgumentCount()
	 */
	public int getMaxArgumentCount()
	{
		return(3);
	}

	/**
	 * @see org.mapyrus.function.Function#getMinArgumentCount()
	 */
	public int getMinArgumentCount()
	{
		return(3);
	}

	/**
	 * @see org.mapyrus.function.Function#getName()
	 */
	public String getName()
	{
		return("replace");
	}
}

Split functions out from Expression.java into separate classes.


package net.stickycode.plugin.bounds;

public enum LineSeparator {
  Mac {

    @Override
    public String value() {
      return "\r";
    }
  },
  Unix {

    @Override
    public String value() {
      return "\n";
    }
  },
  Windows {

    @Override
    public String value() {
      return "\r\n";
    }
  };

  abstract public String value();

  public static LineSeparator defaultValue() {
    if (System.lineSeparator().equals("\n"))
      return Unix;

    if (System.lineSeparator().equals("\r"))
      return Mac;

    return Windows;
  }
}

Allow the line separator to be configured to match your source control if you like. Otherwise it will now use the platform default


class NonShortCircuit {
  boolean and( boolean x, boolean y) {
	return x & y;
	}
  boolean ordered(int x, int y, int z) {
	if (x >= y | y >= z) System.out.println("Not ordered");
	return x < y & y < z;
	}
  boolean nonEmpty(Object o[]) {
	return o != null & o.length > 0;
	}
}

Test cases for non-short-circuit evaluation


package org.flymine.web;

/*
 * Copyright (C) 2002-2003 FlyMine
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  See the LICENSE file for more
 * information or http://www.gnu.org/copyleft/lesser.html.
 *
 */

import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletContext;

import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;

import org.flymine.web.config.WebConfig;

/**
 * Initialiser for the FlyMine web application
 * Anything that needs global initialisation goes here.
 *
 * @author Andrew Varley
 */

public class InitialiserPlugin implements PlugIn
{

    /**
     * Init method called at Servlet initialisation
     *
     * @param servlet ActionServlet that is managing all the modules
     * in this web application
     * @param config ModuleConfig for the module with which this
     * plug-in is associated
     *
     * @throws ServletException if this PlugIn cannot
     * be successfully initialized
     */
    public void init(ActionServlet servlet, ModuleConfig config)
        throws ServletException {

        ServletContext context = servlet.getServletContext();

        try {
            InputStream is = context.getResourceAsStream("/WEB-INF/webconfig-model.xml");
            WebConfig wc = WebConfig.parse(is);
            context.setAttribute("webconfig", wc);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

    /**
     * Destroy method called at Servlet destroy
     */
    public void destroy() {
    }

}

Add anything to application context here


/**
 * Check that method without return is not accepted.
 *
 * @author Elvis Stansvik <elvstone@gmail.com>
 */
class MissingReturn {
    public static void main(String[] args) {
    }
}
class MissingReturnTest {
    public int foo() {
    }
}

Add another shared noncompile test.


package org.csstudio.utility.adlparser.fileParser;

import java.util.ArrayList;

import org.csstudio.utility.adlparser.internationalization.Messages;
import org.eclipse.swt.graphics.RGB;

public class ColorMap {
	private RGB[] colors = new RGB[0];
	private int numColors;

	public ColorMap(ADLWidget colorMap) throws WrongADLFormatException {
		// find out the number of colors

		for (FileLine fileLine : colorMap.getBody()){
			String bodyPart = fileLine.getLine();
			String[] row = bodyPart.trim().split("=");
			if (row.length < 2){
				throw new WrongADLFormatException(Messages.Label_WrongADLFormatException_Parameter_Begin + bodyPart + Messages.Label_WrongADLFormatException_Parameter_End);
			}
			if (row[0].trim().equals("ncolors")){
				numColors = Integer.parseInt(row[1].replaceAll("\"", "").trim());
			}
			colors = new RGB[numColors];
		}

		ADLWidget colorsWidget = colorMap.getObjects().get(0);
		if (colorsWidget.getType().equals("colors")){
			int colorCounter = 0;
			for (FileLine fileLine  : colorsWidget.getBody()){
				String bodyPart = fileLine.getLine();
				String[] row = bodyPart.split(",");
				if (row.length == 1){
					String color = row[0].trim();
					colors[colorCounter] = getRGBColor(color);
					colorCounter++;
				}
			}

		}
	}

	/**
	 * @return Object[] colors
	 */
	public RGB[] getColors() {
		return colors;
	}

	public int getNumColors() {
		return numColors;
	}
	public RGB getRGBColor(String inColor){
		String redStr = "#".concat(inColor.substring(0, 2));
		String greenStr = "#".concat(inColor.substring(2, 4));
		String blueStr = "#".concat(inColor.substring(4, 6));
		int red = Integer.decode(redStr);
		int green = Integer.decode(greenStr);
		int blue = Integer.decode(blueStr);
		System.out.println("Red, Green, Blue:"+ red +", " + green + ", " +blue);
		return new RGB(red, green, blue);
	}
}

Add to decode the color map


/*
 * Key point: fast/slow runner technique to find middle node,
 *    time complexity is O(nlgn) which comes from f(n) = 2f(n/2) + cn
 *
 *  There is a O(n) solution that build the BST bottom-up
 *    but it's hard to be implemented in java because of lacking passing by reference
 */

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; next = null; }
 * }
 */
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if(head==null)
            return null;
        if(head.next==null)
            return new TreeNode(head.val);

        //init fast runner and slow runner
        ListNode fast=head.next.next;
        ListNode slow=head;

        //partition the list from the middle, use the fast/slow runner technique
        //the slow pointer will be the prev of the middle node
        while(fast!=null && fast.next!=null)
        {
            fast=fast.next.next;
            slow=slow.next;
        }

        //find the middle node
        ListNode parent=slow.next;

        //partition the list into left and right sublist
        slow.next=null;
        ListNode left=head;
        ListNode right=parent.next;
        parent.next=null;

        //make the middle node as the root, then apply the function
        //to the left part and the right part recursively
        TreeNode root=new TreeNode(parent.val);
        root.left=sortedListToBST(left);
        root.right=sortedListToBST(right);

        return root;

    }

}

Convert Sorted List to Binary Search Tree


/*
 * Copyright 2018 Volker Berlin (i-net software)
 *
 * 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 de.inetsoftware.jwebassembly.binary;

import java.io.IOException;

/**
 * Signature for an entry in a section
 *
 * @author Volker Berlin
 */
abstract class SectionEntry {

    /**
     * Write this single entry to a section
     *
     * @param stream
     *            the target
     * @throws IOException
     *             if any I/O error occur
     */
    abstract void writeSectionEntry( WasmOutputStream stream ) throws IOException;
}

Refactor the writing of sections more object oriented.


package rose.project.passmember.util;

/**
 * Created by Lord Rose on 07/04/2017.
 */
public enum EntryType {
    SIMPLE_PASSWORD,
    FOLDER
}

Add new enum to know kind of new node will be inserted in the tree (JTreeWrapper class)


/******************************************************************************
 *
 *  CS 6421 - Simple Conversation
 *  Compilation:  javac ConvServer.java
 *  Execution:    java ConvServer port
 *
 *  % java ConvServer portnum
 ******************************************************************************/

import java.net.Socket;
import java.net.ServerSocket;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.UnknownHostException;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class FunctionServer {
    static final boolean debug=true;

    public static void process (Socket clientSocket) throws IOException {
        // open up IO streams
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

        /* Write a welcome message to the client */
        //out.println("Welcome, you are connected to a Java-based server");

        /* read and print the client's request */
        // readLine() blocks until the server receives a new line from client
        String userInput;
        if ((userInput = in.readLine()) == null) {
            System.out.println("Error reading message");
            out.close();
            in.close();
            clientSocket.close();
        }

        String tokens[] = userInput.split(" ");
        switch(tokens[0]){
          case "set":
            if(debug) System.out.println("Set function");
            break;
          case "get":
            if(debug) System.out.println("Get function");
            break;
          default:
            out.println("Message not recognized : " + tokens[0]);
        }

        // close IO streams, then socket
        out.close();
        in.close();
        clientSocket.close();
    }

    public static void main(String[] args) throws Exception {

        //check if argument length is invalid
        if(args.length != 1) {
            System.err.println("Usage: java ConvServer port");
        }
        // create socket
        int port = Integer.parseInt(args[0]);
        ServerSocket serverSocket = new ServerSocket(port);
        System.err.println("Started server on port " + port);

        // wait for connections, and process
        try {
            while(true) {
                // a "blocking" call which waits until a connection is requested
                Socket clientSocket = serverSocket.accept();
                System.err.println("\nAccepted connection from client");
                process(clientSocket);
            }

        }catch (IOException e) {
            System.err.println("Connection Error");
        }
        System.exit(0);
    }
}

Implement basic function call server


package de.asw.java.training2016.net;

import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class UrlConnectionHttpPostRequestExample {

	public static void main(String[] args) throws Exception {

		HttpURLConnection urlConnection = (HttpURLConnection) new URL("https://httpbin.org/post").openConnection();
		urlConnection.setRequestProperty("Content-Type", "application/json");
		urlConnection.setDoOutput(true);
		urlConnection.setRequestMethod("POST");

		PrintStream requestBody = new PrintStream(urlConnection.getOutputStream());
		requestBody.print("{\"foo\":\"bar\"}");

		try (Scanner scanner = new Scanner(urlConnection.getInputStream())) {
			printResponseHeaders(urlConnection);
			printResponseBody(scanner);
		}

		urlConnection.disconnect();
	}

	private static void printResponseHeaders(URLConnection urlConnection) {
		for (Map.Entry<String, List<String>> header : urlConnection.getHeaderFields().entrySet()) {
			if (header.getKey() == null) {
				System.out.println(header.getValue().get(0));
				continue;
			}
			System.out.printf("%s: %s%n", header.getKey(), header.getValue());
		}
	}

	private static void printResponseBody(Scanner scanner) {
		while (scanner.hasNextLine()) {
			System.out.println(scanner.nextLine());
		}
	}
}

Add example for sending http post request via UrlConnection


/*
 * Copyright (c) 2015 Inocybe and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

package org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.services;

import org.junit.Test;

/**
 * Unit test for {@link L2RewriteService}
 */
public class L2RewriteServiceTest {

    @Test
    public void test() {
        // TODO nothing has been done in L2RewriteService class yet.
    }

}

Add JUnit testing for L2RewriteService class.


/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This 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 software 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 software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.xwiki.icon.test.ui;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.xwiki.test.docker.junit5.TestReference;
import org.xwiki.test.docker.junit5.UITest;
import org.xwiki.test.ui.TestUtils;

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

/**
 * Functional tests of the icon theme sheet.
 *
 * @version $Id$
 */
@UITest
class IconThemesSheetIT
{
    @BeforeEach
    void setUp(TestUtils testUtils)
    {
        // Login as superadmin to define the preferences.
        testUtils.loginAsSuperAdmin();
    }

    @Test
    @Order(1)
    void createIconTheme(TestUtils testUtils, TestReference testReference) throws Exception
    {
        testUtils.createPage(testReference, ")))**not bold**");
        testUtils.addObject(testReference, "IconThemesCode.IconThemeClass");

        testUtils.gotoPage(testReference);

        String content = testUtils.getDriver().findElementWithoutWaiting(By.id("xwikicontent")).getText();

        // Make sure the wiki syntax was not interpreted
        assertTrue(content.contains("**not bold**"));
    }
}

Fix escaping * add test


package babysteps.model;

import java.util.List;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.stream.Collectors;

public class TaskModel {

    /**
     * Top of the task B-tree. All subtasks should be contained within this instance.
     */
    private Task currentTask;

    /**
     * Constructor.
     */
    public TaskModel() {
        currentTask = new Task("Tasks");
    }

    /**
     * Provide all of the subtask titles.
     *
     * @return a List of strings
     */
    public List<String> subtaskNames() {
        return currentTask.getSubtasks().stream()
                .map(Task::getTitle)
                .collect(Collectors.toList());
    }

    /**
     * Return the head of the task tree.
     *
     * @return a Task instance
     */
    public Task getCurrentTask() {
        return currentTask;
    }

    /**
     * Add a child to the current task.
     *
     * @param title
     */
    public void createTask(String title) {
        currentTask.getSubtasks().add(new Task(title, currentTask));
    }

    /**
     * Move down the tree to a specific task.
     *
     * @param taskNumber
     */
    public void enterTask(int taskNumber) {
        currentTask = currentTask.getSubtasks().get(taskNumber);
    }

    /**
     * Go to the task above this one in the task tree.
     */
    public void moveUp() {
        currentTask.getParent().ifPresent(t -> currentTask = t);
    }

    /**
     * Find the top of the task tree. i.e. discover the most general task.
     *
     * @return the parent task
     */
    private Task headTask() {
        Task place = currentTask;
        while(place.getParent().isPresent()) {
            place = place.getParent().get();
        }
        return place;
    }

    /**
     * Save all tasks (including parents) to the given file.
     *
     * @param file
     * @return true if successful, false otherwise
     */
    public boolean serialize(String path) {
        try {
            FileOutputStream fileOut = new FileOutputStream(path);
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(headTask());
            out.close();
            fileOut.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Overwrite the entire model with a new task tree. The previous task tree is not saved.
     *
     * @param file
     * @return true if successful, false otherwise
     */
    public boolean deseriablize(String path) {
        try {
            FileInputStream fileIn = new FileInputStream(path);
            ObjectInputStream in = new ObjectInputStream(fileIn);
            currentTask = (Task) in.readObject();
            in.close();
            fileIn.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }
}

Implement a main model class with serialization


package leetcode.largest_rectangle_in_histogram;

import java.util.Stack;

public class Solution {
	public static class Histogram{
		int offset, height;
		public Histogram(int offset, int height){
			this.offset = offset;
			this.height = height;
		}
	}
    public int largestRectangleArea(int[] height) {
    	Stack<Histogram> stack = new Stack<Histogram>();
    	int length = height.length;
    	int max = 0;
    	for(int i = 0; i < length; i++){
    		int left = i;
    		while(!stack.isEmpty() && stack.peek().height >= height[i]){
    			Histogram hist = stack.pop();
    			int area = hist.height * (i - hist.offset);
    			left = hist.offset;
    			if(area > max) max = area;
    		}
    		stack.push(new Histogram(left, height[i]));
    	}
    	while(!stack.isEmpty()){
			Histogram hist = stack.pop();
			int area = hist.height * (length - hist.offset);
			if(area > max) max = area;
    	}
    	return max;
    }
    public static void main(String[] args){
    	System.err.println(new Solution().largestRectangleArea(new int[]{1,1,1,1,1,2,9,8,8, 5, 5}));
    }
}

Add java solution for 84. Largest Rectangle in Histogram


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

package net.imagej.ops.create;

import net.imagej.ops.Op;
import net.imagej.ops.Ops;
import net.imglib2.img.Img;
import net.imglib2.img.array.ArrayImgs;
import net.imglib2.type.numeric.real.DoubleType;

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

@Plugin(type = Op.class, name = Ops.CreateImg.NAME)
public class CreateImgSimple implements Ops.CreateImg
{

	@Parameter(type = ItemIO.OUTPUT)
	private Img<DoubleType> output;

	@Parameter
	private long[] dims;

	@Override
	public void run() {
		output = ArrayImgs.doubles(dims);
	}
}

Add a simple createimg that uses DoubleType


/*
 * Copyright 2017 Viktor Csomor
 *
 * 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 net.viktorc.pp4j.impl;

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

/**
 * A unit test class for {@link SimpleCommand}.
 *
 * @author Viktor Csomor
 */
public class SimpleCommandTest extends TestCase {

  @Test
  public void testGeneratesOutputFalseWhenNoCompletionPredicatesDefined() {
    SimpleCommand command = new SimpleCommand(null);
    Assert.assertFalse(command.generatesOutput());
  }

  @Test
  public void testGeneratesOutputTrueWhenCompletionPredicatesDefined() {
    SimpleCommand command = new SimpleCommand(null, (c, o) -> true, (c, o) -> false);
    Assert.assertTrue(command.generatesOutput());
  }

  @Test
  public void testThrowsExceptionWhenPredicateNull() {
    exceptionRule.expect(IllegalArgumentException.class);
    new SimpleCommand(null, (c, o) -> true, null);
  }

}

Add basic simple command unit test


package leetcode.combination_sum_iii;

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

public class Solution {

    public void dfs(int curN, int rest, int depth, int k, List<Integer> cur, List<List<Integer>> ret){
        if(depth == k && rest == 0){
            ret.add(new ArrayList<Integer>(cur));
        }else{
            for(int i = curN + 1; i <= 9; i++){
                if(rest - i >= 0){
                    cur.add(i);
                    dfs(i, rest - i, depth + 1, k, cur, ret);
                    cur.remove(depth);
                }
            }
        }
    }

    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> ret = new ArrayList<List<Integer>>();
        dfs(0, n, 0, k, new ArrayList<Integer>(), ret);
        return ret;
    }

    public static void main(String[] args){
        for(List<Integer> ans : new Solution().combinationSum3(3, 9)){
            for(int x : ans){
                System.err.print(x + " ");
            }
            System.err.println("");
        }
    }
}

Add java solution for 216. Combination Sum III


/*
 * Created on Nov 11, 2005
 */
package uk.org.ponder.rsf.uitype;

public class BooleanUIType implements UIType {
  public static final BooleanUIType instance = new BooleanUIType();
  public Boolean PLACEHOLDER = new Boolean(false);
  public Object getPlaceholder() {
    return PLACEHOLDER;
  }
  public String getName() {
    return "boolean";
  }
  public boolean valueUnchanged(Object oldvalue, Object newvalue) {
    return oldvalue.equals(newvalue);
  }
}

/*
 * Created on Nov 11, 2005
 */
package uk.org.ponder.rsf.uitype;

public class BooleanUIType implements UIType {
  public static final BooleanUIType instance = new BooleanUIType();
  public Boolean PLACEHOLDER = Boolean.FALSE;
  public Object getPlaceholder() {
    return PLACEHOLDER;
  }
  public String getName() {
    return "boolean";
  }
  public boolean valueUnchanged(Object oldvalue, Object newvalue) {
    return oldvalue.equals(newvalue);
  }
}

Use constant to generate Boolean


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

import com.facebook.buck.timing.Clock;
import com.facebook.buck.util.Scope;
import com.google.common.base.Supplier;

/** Event Class containing the perf data regarding action graph building */
public class ActionGraphPerfStatEvent extends AbstractBuckEvent {

  private static final String EVENT_NAME = "ActionGraphPerfStats";

  private final Long elapsedTime;
  private final int numberNodesGenerated;
  private final String targetNodeDescriptionName;
  private final String buildTargetName;

  private ActionGraphPerfStatEvent(
      Long time, int generatedNodesCount, String descriptionName, String buildName) {
    super(EventKey.unique());
    elapsedTime = time;
    numberNodesGenerated = generatedNodesCount;
    targetNodeDescriptionName = descriptionName;
    buildTargetName = buildName;
  }

  /**
   * Creates a Scope for the timing event
   *
   * @param clock
   * @param eventBus
   * @param getRuleSize
   * @param descriptionName
   * @param buildTargetName
   * @return
   */
  public static Scope start(
      Clock clock,
      BuckEventBus eventBus,
      Supplier<Integer> getRuleSize,
      String descriptionName,
      String buildTargetName) {
    ActionGraphPerfStatEvent.Start start = new Start(clock);
    int startSize = getRuleSize.get();
    return () ->
        eventBus.post(
            start.finish(getRuleSize.get() - startSize, descriptionName, buildTargetName));
  }

  @Override
  protected String getValueString() {
    return "";
  }

  @Override
  public String getEventName() {
    return EVENT_NAME;
  }

  public Long getElapsedTime() {
    return elapsedTime;
  }

  public int getNumberNodesGenerated() {
    return numberNodesGenerated;
  }

  public String getBuildTargetName() {
    return buildTargetName;
  }

  public String getTargetNodeDescriptionName() {
    return targetNodeDescriptionName;
  }

  /** Class representing the start of timing */
  public static class Start {

    private final Long startTime;
    private Clock clock;

    private Start(Clock clock) {
      this.clock = clock;
      this.startTime = clock.currentTimeMillis();
    }

    /** Generates the event representing the end of the timing */
    private ActionGraphPerfStatEvent finish(
        int generatedNodesCount, String descriptionName, String buildTargetName) {
      return new ActionGraphPerfStatEvent(
          clock.currentTimeMillis() - startTime,
          generatedNodesCount,
          descriptionName,
          buildTargetName);
    }
  }
}

Add scuba logging and action graph instrumentation event


/* @(#)SafeViewFlipper.java
 *
 *========================================================================
 * Copyright 2011 by Zeo Inc. All Rights Reserved
 *========================================================================
 *
 * Date: $Date$
 * Author: Christopher Souvey <christopher.souvey@myzeo.com>
 * Version: $Revision$
 */

package com.androsz.electricsleepbeta.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ViewFlipper;

/**
 * View flipper that protects against against crashes during screen rotations.
 *
 * @author Christopher Souvey
 * @version $Revision$
 */
public class SafeViewFlipper extends ViewFlipper {

    private static final String TAG = SafeViewFlipper.class.getSimpleName();

    public SafeViewFlipper(Context context) {
        super(context);
    }

    public SafeViewFlipper(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * Workaround for Android Bug 6191:
     * http://code.google.com/p/android/issues/detail?id=6191
     * <p/>
     * ViewFlipper occasionally throws an IllegalArgumentException after screen
     * rotations.
     */
    @Override
    protected void onDetachedFromWindow() {
        try {
            super.onDetachedFromWindow();
        } catch (IllegalArgumentException e) {
            Log.d(TAG, "SafeViewFlipper ignoring IllegalArgumentException");
            // Call stopFlipping() in order to kick off updateRunning()
            stopFlipping();
        }
    }
}

Add a safe view flipper to prevent crashes during screen rotations while flipper is flipping.


package net.imagej.ops.filter.max;

import net.imagej.ops.ComputerOp;
import net.imagej.ops.Ops;
import net.imagej.ops.filter.AbstractNonLinearFilter;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.type.numeric.RealType;

import org.scijava.Priority;
import org.scijava.plugin.Plugin;

/**
 * Default implementation of {@link MaxFilterOp}.
 *
 * @author Jonathan Hale (University of Konstanz)
 * @param <T> type
 */
@Plugin(type = Ops.Filter.Max.class, name = Ops.Filter.Max.NAME,
	priority = Priority.LOW_PRIORITY)
public class DefaultMaxFilter<T extends RealType<T>> extends
	AbstractNonLinearFilter<T, T> implements
	MaxFilterOp<RandomAccessibleInterval<T>>
{

	@SuppressWarnings("unchecked")
	@Override
	protected ComputerOp<Iterable<T>, T> getComputer(Class<?> inClass,
		Class<?> outClass)
	{
		return (ComputerOp<Iterable<T>, T>) ops.op(Ops.Stats.Max.class, Iterable.class,
			inClass);
	}

}

Add default implementation of MaxFilterOp


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

import java.util.List;
import org.junit.Before;
import org.junit.Test;

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

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

  private Anagrams anagrams;

  @Before public void setUp() {
    this.anagrams = new Anagrams();
  }

  @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullStrings() {
    anagrams.get(null);
  }

  @Test public void shouldReturnAnEmptyListIfInputStringIsEmpty() {
    assertTrue(anagrams.get("").isEmpty());
  }

  @Test public void shouldCalculateEveryAnagram() {
    String input = "abc";

    List<String> result = anagrams.get(input);
    String[] arrayResult = new String[result.size()];
    result.toArray(arrayResult);

    String[] expectedArray = { "abc", "acb", "bac", "bca", "cab", "cba" };
    assertArrayEquals(expectedArray, arrayResult);
  }
}

Add some tests to problem 25


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

import static org.junit.Assert.assertEquals;

import org.junit.Test;

/**
 * @author acoburn
 */
public class IdentifierServiceTest {

    @Test
    public void testConfig() {
        final Integer zero = 0;
        final IdentifierService.IdentifierConfiguration config = new IdentifierService.IdentifierConfiguration();
        assertEquals("", config.getPrefix());
        assertEquals(zero, config.getHierarchy());
        assertEquals(zero, config.getLength());
    }

    @Test
    public void testConfig2() {
        final Integer hierarchy = 4;
        final Integer length = 2;
        final String prefix = "foo:";
        final IdentifierService.IdentifierConfiguration config = new IdentifierService.IdentifierConfiguration(
                prefix, hierarchy, length);
        assertEquals(prefix, config.getPrefix());
        assertEquals(hierarchy, config.getHierarchy());
        assertEquals(length, config.getLength());
    }
}

Add inner class for configuration


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.ccsu;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

/**
 * Web application lifecycle listener.
 *
 * @author cw1491
 */
@WebListener()
public class SessionAttributeListener implements HttpSessionAttributeListener {

    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
       event.getSession().getServletContext().log("Session Attribute created "+event.getName()+"="+event.getValue());
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
       event.getSession().getServletContext().log("Session Attribute removed "+event.getName());
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
       event.getSession().getServletContext().log("Session Attribute changed "+event.getName()+"="+event.getValue());
    }
}

Add example session attribute listener


package java8intro.java8.stream;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamExample {
	private final List<Integer> integers = Arrays.asList(5, 7, 34, 12, 4, 5, 76, 2, 1, 67, 52, 74);

	private void filterAndSort() {
		integers.stream()
				.filter(i -> i % 2 == 0)
				.sorted()
				.forEach(System.out::println);
	}

	private void multiplyByTwo() {
		integers.stream()
				.map(i -> i * 2)
				.forEach(System.out::println);
	}

	private void parallelStream() {
		List<Integer> sortedIntegers = integers.stream().sorted().collect(Collectors.toList());
		System.out.println(sortedIntegers);
		sortedIntegers.parallelStream().forEach(System.out::println);
	}

	public static void main(String[] args) {
		StreamExample streamExample = new StreamExample();
		streamExample.filterAndSort();
		System.out.println("===================");
		streamExample.multiplyByTwo();
		System.out.println("===================");
		streamExample.parallelStream();
	}
}

Add stream and parallel stream example


package processbuilder.utils;

import java.io.*;

/**
 * Created on 4/21/2015.
 */
public class ProcessBuilderUtilities {

    /**
     * Attaches standard and error writer as well as input to a process.
     * @param process Process which to attach Output, Error and Input to.
     * @param processOutput A data sink for the process standard output. If null nothing will ne attached.
     * @param processError A data sink for the process' error output. If null nothing will be attached.
     * @param processInput A data source to be streamed to the process. If null nothing will be attached.
     */
    public static void attachStreamsToProcess(Process process, Writer processOutput, Writer processError,
                                       Reader processInput) {
      if (processOutput != null ) {
          // Attach to std output
          attachToInputStream(new InputStreamReader(process.getInputStream()), processOutput);
      }

        if (processError != null) {
            // Attach error output
            attachToInputStream(new InputStreamReader(process.getErrorStream()), processError);
        }

        if (processInput != null) {
            // Attach process input
            attachToInputStream(processInput,new OutputStreamWriter(process.getOutputStream()));
        }
    }

    /**
     * Creates a thread which will constantly pipe data, only active when new data is available, from a source to an attached sink. After
     * reaching the end of the source stream the @Thread will silently be destroyed.
     * @param source Data source.
     * @param attachedSink Data sink.
     */
    public static void attachToInputStream(final Reader source, final Writer attachedSink) {
        new Thread() {
            public void run() {
                try {
                    pipe(source, attachedSink);
                } catch (IOException e) {
                    //Done
                }
            }
        }.start();
    }

    /**
     * Pipes all data from a reader (source) to a writer (sink) until an I/O exection occurs or the
     * end of the source is reached.
     * @param from Source of data.
     * @param to Sink of data.
     * @throws IOException
     */
    public static void pipe(Reader from, Writer to) throws IOException {
        char[] buff = new char[1024];
        int n = from.read(buff);
        while (n != -1) {
            to.write(buff, 0, n);
            to.flush();
            n = from.read(buff);
        }
        from.close();
    }
}

Add util methods to attach other streams to the process' streams. That is important in order to directly read the output from the process. With that it will be possible to determine the version of docker compose.


/*
 * $Id: TranslatableMarker.java 1417 2006-11-03 14:57:33 +0000 (Fri, 03 Nov 2006) rodneykinney $
 *
 * Copyright (c) 2000-2006 by Rodney Kinney, Brent Easton
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License (LGPL) as published by the Free Software Foundation.
 *
 * 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, copies are available
 * at http://www.opensource.org.
 */
package VASSAL.i18n;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import VASSAL.build.AbstractConfigurable;
import VASSAL.build.Buildable;
import VASSAL.build.module.documentation.HelpFile;
import VASSAL.counters.GamePiece;
import VASSAL.counters.PlaceMarker;

/**
 *
 * @author Brent Easton
 *
 * A dummy AbstractConfigurable to hold a PlaceMarker or Replace definition while translating
 */
public class TranslatableMarker extends AbstractConfigurable {

  protected GamePiece markerDefinition;
  protected String[] names;
  protected String[] values;

  public TranslatableMarker(PlaceMarker p) {
    markerDefinition = p.createBaseMarker();
    setConfigureName(p.getDescription());

  }

  public static String getConfigureTypeName() {
    return "Marker Definition";
  }

  public ComponentI18nData getI18nData() {
    return new ComponentI18nData(this, markerDefinition);
  }

  public String getAttributeValueString(String attr) {
    return getI18nData().getLocalUntranslatedValue(attr);
  }

  public void setAttribute(String attr, Object value) {

  }

  public void add(Buildable child) {
  }

  public void addTo(Buildable parent) {

  }

  public void build(Element e) {

  }

  public Element getBuildElement(Document doc) {
    return null;
  }

  public String[] getAttributeDescriptions() {
    return null;
  }

  public Class[] getAttributeTypes() {
    return null;
  }

  public String[] getAttributeNames() {
    return null;
  }
  public Class[] getAllowableConfigureComponents() {
    return null;
  }
  public HelpFile getHelpFile() {
    return null;
  }
  public void removeFrom(Buildable parent) {

  }

}

Add missing file from previous merge


package Mapper;

public class InstanceEventListener {
    /*! The set of possible actions on an instance, used to
     *  register callbacks to inform them of what is happening. */
    public final int IN_NEW = 0x01;
    public final int IN_UPSTREAM_RELEASE = 0x02;
    public final int IN_DOWNSTREAM_RELEASE = 0x04;
    public final int IN_OVERFLOW = 0x08;
    public final int IN_ALL = 0xFF;

    public void onEvent(Mapper.Device.Signal sig,
                        Mapper.Db.Signal props,
                        int instance_id,
                        int event) {};
}

package Mapper;

public class InstanceEventListener {
    /*! The set of possible actions on an instance, used to
     *  register callbacks to inform them of what is happening. */
    public static final int IN_NEW = 0x01;
    public static final int IN_UPSTREAM_RELEASE = 0x02;
    public static final int IN_DOWNSTREAM_RELEASE = 0x04;
    public static final int IN_OVERFLOW = 0x08;
    public static final int IN_ALL = 0xFF;

    public void onEvent(Mapper.Device.Signal sig,
                        Mapper.Db.Signal props,
                        int instance_id,
                        int event) {};
}

Declare instance event type flags static.


package me.zhengjie.utils;

import org.junit.Test;
import org.springframework.mock.web.MockMultipartFile;

import static org.junit.Assert.*;
import static me.zhengjie.utils.FileUtil.*;

public class FileUtilTest {

    @Test
    public void testToFile() {
        long retval = toFile(new MockMultipartFile("foo", (byte[]) null)).getTotalSpace();
        assertEquals(500695072768L, retval);
    }

    @Test
    public void testGetExtensionName() {
        assertEquals("foo", getExtensionName("foo"));
        assertEquals("exe", getExtensionName("bar.exe"));
    }

    @Test
    public void testGetFileNameNoEx() {
        assertEquals("foo", getFileNameNoEx("foo"));
        assertEquals("bar", getFileNameNoEx("bar.txt"));
    }

    @Test
    public void testGetSize() {
        assertEquals("1000B   ", getSize(1000));
        assertEquals("1.00KB   ", getSize(1024));
        assertEquals("1.00MB   ", getSize(1048576));
        assertEquals("1.00GB   ", getSize(1073741824));
    }
}

Add unit tests for me.zhengjie.utils.FileUtil


package com.alsash.reciper.ui;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;

import com.alsash.reciper.R;

public abstract class DrawerActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    protected abstract PagerAdapter getPagerAdapter(FragmentManager fm);

    protected abstract void setupFab(FloatingActionButton fab);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_drawer_tab);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        setupFab(fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
                R.string.drawer_open, R.string.drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.drawer_nav);
        navigationView.setNavigationItemSelectedListener(this);

        // Set up the ViewPager with the implemented PagerAdapter.
        ViewPager viewPager = (ViewPager) findViewById(R.id.tab_container);
        viewPager.setAdapter(getPagerAdapter(getSupportFragmentManager()));

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

Add abstract activities for navigation drawer implementation


package org.zeromq.czmq;

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

public class ZSockTest {
    @Test
    public void testZSockSendRecv() {
        try (final ZSock push = new ZSock(ZMQ.ZMQ_PUSH);
             final ZSock pull = new ZSock(ZMQ.ZMQ_PULL)) {
            ZMsg msg = new ZMsg();
            pull.bind("tcp://*:1234");
            push.connect("tcp://localhost:1234");
            String expected = "hello";
            msg.pushstr(expected);
            ZMsg.send(msg, push);
            ZMsg resp = ZMsg.recv(pull);
            String actual = resp.popstr();
            Assert.assertEquals(expected, actual);
            resp.close();
        }
    }
}

package org.zeromq.czmq;

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

public class ZSockTest {
    @Test
    public void testZSockSendRecv() {
        try (final ZSock push = new ZSock(ZMQ.ZMQ_PUSH);
             final ZSock pull = new ZSock(ZMQ.ZMQ_PULL)) {
            ZMsg msg = new ZMsg();
            pull.bind("tcp://*:1234");
            push.connect("tcp://127.0.0.1:1234");
            String expected = "hello";
            msg.pushstr(expected);
            ZMsg.send(msg, push);
            ZMsg resp = ZMsg.recv(pull);
            String actual = resp.popstr();
            Assert.assertEquals(expected, actual);
            resp.close();
        }
    }
}

Use 127.0.0.1 instead of localhost


package jfoley.vocabpress.feature;

import jfoley.vocabpress.movement.Mover;
import jfoley.vocabpress.scoring.CountPosting;
import jfoley.vocabpress.scoring.impl.SimpleCountPosting;
import org.junit.Test;

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

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

public class MapFeatureTest {

	@Test
	public void testHasFeature() throws Exception {
		Map<Integer, CountPosting> priors = new HashMap<>();
		priors.put(1, new SimpleCountPosting(1, 9));
		priors.put(2, new SimpleCountPosting(2, 6));
		priors.put(3, new SimpleCountPosting(3, 4));

		MapFeature<CountPosting> fpriors = new MapFeature<>(priors);

		assertTrue(fpriors.hasFeature(1));
		assertTrue(fpriors.hasFeature(2));
		assertTrue(fpriors.hasFeature(3));
		assertEquals(9, fpriors.getFeature(1).getCount());
		assertEquals(6, fpriors.getFeature(2).getCount());
		assertEquals(4, fpriors.getFeature(3).getCount());
	}

	@Test
	public void testMovement() throws Exception {
		Map<Integer, CountPosting> priors = new HashMap<>();
		priors.put(1, new SimpleCountPosting(1, 9));
		priors.put(2, new SimpleCountPosting(2, 6));
		priors.put(3, new SimpleCountPosting(3, 4));

		MapFeature<CountPosting> fpriors = new MapFeature<>(priors);

		int count = 0;
		for(Mover m = fpriors.getMover(); !m.isDone(); m.next()) {
			int doc = m.currentKey();
			count++;
			assertEquals(priors.get(doc).getCount(), fpriors.getFeature(doc).getCount());
			assertEquals(doc, fpriors.getFeature(doc).getKey());
		}

		assertEquals(3, count);
	}

}

Add a test for MapFeature


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

import com.github.pedrovgs.problem70.ReverseOrderOfBinaryNumber;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

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

  private ReverseOrderOfBinaryNumber reverseOrder;

  @Before public void setUp() {
    reverseOrder = new ReverseOrderOfBinaryNumber();
  }

  @Test public void shouldReturnZeroIfInputIsZero() {
    int input = 0; // 0

    int result = reverseOrder.reverse(input);

    assertEquals(0, result); // 0
  }

  @Test public void shouldReturnOneIfInputIsOne() {
    int input = 1; // 1

    int result = reverseOrder.reverse(input);

    assertEquals(1, result); // 1
  }

  @Test public void shouldReturnTheSameNumberIfIsFullOfOnes() {
    int input = 7; // 111

    int result = reverseOrder.reverse(input);

    assertEquals(7, result); // 11
  }

  @Test public void shouldReturnBinaryNumberOrder() {
    int input = 13; // 1101

    int result = reverseOrder.reverse(input);

    assertEquals(11, result); // 1011
  }
}

Add some tests to problem 70


package org.realityforge.replicant.client;

import java.io.Serializable;
import java.util.Map;
import javax.annotation.Nullable;

/**
 * The ChangeMapper is responsible for applying changes to the world.
 *
 *
The mapper will be invoked for each change message and is responsible for;

 *
 *

 *
creating the entity if it does not already exist

 *
registering or de-registering the entity in the {@link EntityRepository}

 *
applying the state changes to the entity

 *
generating change messages and propagating them through the {@link EntityChangeBroker}

 *

 *
 *
As the ChangeMapper is very specific to the domain model that is being replicated, the ChangeMapper
 * is typically generated from a description via a tool such as Domgen.

 */
public interface ChangeMapper
{
  /**
   * Apply a single change to the world.
   *
   * @param typeID the type code of the entities type.
   * @param designator the entities designator,
   * @param data the data to use to update the entity or null if the entity should be removed from the system.
   * @return the entity that was created, updated or removed.
   */
  Object applyChange( int typeID, Object designator, @Nullable Map<String, Serializable> data );
}

Add in an interface to map changes to a particular world. It will ultimately be implemented for each world


package leetcode;

import java.util.Arrays;

/**
 * https://leetcode.com/problems/rotate-image/
 */
public class Problem48 {
    public void rotate(int[][] matrix) {

    }

    public static void main(String[] args) {
		Problem48 prob = new Problem48();
		int n = 3;
		int[][] matrix = new int[n][n];
		int val = 0;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				matrix[i][j] = val++;
			}
		}
		prob.rotate(matrix);
		for (int i = 0; i < n; i++) {
			System.out.println(Arrays.toString(matrix[i]));
		}
	}
}

Create skeleton for problem 48


/*
 * Copyright 2017, TeamDev Ltd. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.spine3.server.storage;

import org.spine3.SPI;

/**
 * A marker interface for the {@code enum}s representing the names of the fields used by the framework to store
 * its data.
 *
 *
Naming conventions for the {@code enum}s' fields may be changed in favor of the field names to be represented
 * accurately.
 *
 *
Owing to that, we may simply call {@link Enum#toString()} or {@link Enum#name()} to get a valid field name.
 *
 * @author Dmytro Dashenkov
 */
@SPI
public interface StorageField {
}

Add a marker interface for the storage field names.


package helpers;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * Operations regarding PID.
 */
public class PidManipulation {
    private static Logger logger = LoggerFactory.getLogger(PidManipulation.class);

    /**
     * Write program PID to file.
     * @param path where to write the pid.
     */
    public static void writeOwnPidToFile(String path) {
        try {
            File file = new File(path);
            file.getParentFile().mkdir();
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }

            FileWriter fw = new FileWriter(file.getAbsolutePath());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(getPid());
            bw.close();

        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * Obtain PID.
     *
     * @return PID of program.
     */
    public static String getPid() {
        String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
        return processName.split("@")[0];
    }
}

Add class for operations regarding PID.


@Value.Style(
    // @formatter:off
    typeAbstract = { "*" },
    get = { "is*", "get*" },
    with = "with*",
    defaults = @Value.Immutable(builder = false, prehash = true)
    // @formatter:on
)
package mb.nabl2.constraints;

import org.immutables.value.Value;

Add prehashing for NaBL2 constraints.


package com.mattbachmann.nlpexperiments.apps;

import com.mattbachmann.nlpexperiments.extraction.ExtractionException;
import com.mattbachmann.nlpexperiments.extraction.TextExtractor;

import java.io.File;

public class ExtractFile {
    public static void main(String[] args) {
        if(args.length != 1) {
            System.out.println("I only take one arg, which is the file to extract text from");
            return;
        }

        try {
            System.out.println(TextExtractor.extractText(new File(args[0])));
        } catch (ExtractionException e) {
            System.out.println("Failed to extract text from file");
        }
    }
}

Add utility to print the extracted text of a file


/*
 * Copyright (C) 2013 Brett Wooldridge
 *
 * 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.zaxxer.hikari.proxy;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Timer;

import com.zaxxer.hikari.util.ConcurrentBag.IBagManagable;

/**
 *
 * @author Brett Wooldridge
 */
public interface IHikariConnectionProxy extends Connection, IBagManagable
{
    void unclose();

    void realClose() throws SQLException;

    void untrackStatement(Object statement);

    void checkException(SQLException sqle);

    boolean isBrokenConnection();

    boolean isTransactionIsolationDirty();

    boolean isAutoCommitDirty();

    long getCreationTime();

    long getLastAccess();

    /* Leak Detection API */
    void captureStack(long leakThreshold, Timer houseKeepingTimer);
}

/*
 * Copyright (C) 2013 Brett Wooldridge
 *
 * 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.zaxxer.hikari.proxy;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Timer;

import com.zaxxer.hikari.util.ConcurrentBag.IBagManagable;

/**
 *
 * @author Brett Wooldridge
 */
public interface IHikariConnectionProxy extends Connection, IBagManagable
{
    void unclose();

    void realClose() throws SQLException;

    void untrackStatement(Object statement);

    void checkException(SQLException sqle);

    boolean isBrokenConnection();

    long getCreationTime();

    long getLastAccess();

    /* Leak Detection API */
    void captureStack(long leakThreshold, Timer houseKeepingTimer);
}

Remove unused methods from signature


package com.kgp.core;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

/**
 * Generic Adapater for Handling the interfacing of Key and Mouse interactions
 * @author Nicholas Hydock
 *
 */
public class GameController implements KeyListener, MouseMotionListener, MouseListener {

	@Override
	public void mouseClicked(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseDragged(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseMoved(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void keyPressed(KeyEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void keyReleased(KeyEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void keyTyped(KeyEvent arg0) {
		// TODO Auto-generated method stub

	}

}

Add generic class that's an adapter for Keys and Mouse input


package com.codingbat.test;

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

import com.codingbat.array1.Array1Test;
import com.codingbat.array2.Array2Test;
import com.codingbat.string1.String1Test;
import com.codingbat.string2.String2Test;
import com.codingbat.warmup1.Warmup1Test;
import com.codingbat.warmup2.Warmup2Test;

@RunWith(Suite.class)
@SuiteClasses({Warmup1Test.class, Warmup2Test.class, Array1Test.class, Array2Test.class,
    String1Test.class, String2Test.class})
public class AllTests {

}

Create test suite to run 6 test classes at once.


package pro.extsoft.comments.elements;

import org.testng.annotations.Test;

/**
 * @author Dmytro Serdiuk (dmytro.serdiuk@gmail.com)
 * @version $Id$
 * @since 0.1
 */
public class SmartCheckBoxTest {
    @Test
    public void testChecked() throws Exception {
        assert new SmartCheckBox(new CheckBox() {
            @Override
            public void check() {

            }

            @Override
            public void uncheck() {

            }

            @Override
            public boolean checked() {
                return true;
            }
        }).checked();
    }
}

Add unit test for SmartCheckBox


package peergos.server;

import peergos.shared.*;
import peergos.shared.corenode.*;
import peergos.shared.crypto.hash.*;
import peergos.shared.merklebtree.*;
import peergos.shared.user.*;

import java.net.*;
import java.time.*;
import java.util.*;
import java.util.stream.*;

public class UserStats {

    public static void main(String[] args) throws Exception {
        Crypto crypto = Crypto.initJava();
        NetworkAccess network = NetworkAccess.buildJava(new URL("https://demo.peergos.net")).get();
        List<String> usernames = network.coreNode.getUsernames("").get();
        List<Summary> summaries = usernames.stream().parallel().flatMap(username -> {
            try {
                List<UserPublicKeyLink> chain = network.coreNode.getChain(username).get();
                UserPublicKeyLink last = chain.get(chain.size() - 1);
                LocalDate expiry = last.claim.expiry;
                Set<PublicKeyHash> ownedKeysRecursive = WriterData.getOwnedKeysRecursive(username, network.coreNode, network.mutable, network.dhtClient);
                long total = 0;
                for (PublicKeyHash writer : ownedKeysRecursive) {
                    MaybeMultihash target = network.mutable.getPointerTarget(writer, network.dhtClient).get();
                    if (target.isPresent())
                        total += network.dhtClient.getRecursiveBlockSize(target.get()).get();
                }
                String summary = "User: " + username + ", expiry: " + expiry + " usage: " + total + "\n";
                System.out.println(summary);
                return Stream.of(new Summary(username, expiry, total));
            } catch (Exception e) {
                System.err.println("Error for " + username);
                e.printStackTrace();
                return Stream.empty();
            }
        }).collect(Collectors.toList());

        summaries.sort((a, b) -> (int) (b.usage - a.usage));
        summaries.forEach(System.out::println);
    }

    private static class Summary {
        public final String username;
        public final LocalDate expiry;
        public final long usage;

        public Summary(String username, LocalDate expiry, long usage) {
            this.username = username;
            this.expiry = expiry;
            this.usage = usage;
        }

        public String toString() {
            return "User: " + username + ", expiry: " + expiry + " usage: " + usage;
        }
    }
}

Add util for calculating global public stats


import java.math.BigInteger;

/**
 * Problem: #278 First Bad Version
 *
 * Idea:
 *
 * Solutions:
 *  firstBadVersion: uses basic binary search, but StackOverflowError occurs.
 *
 * Note: #canbefaster
 */

/* The isBadVersion API is defined in the parent class VersionControl.
      boolean isBadVersion(int version); */
public class FirstBadVersion {
    public int binarySearch(int left, int right) {
        int middle = (left + right)/2;

        if (isBadVersion(middle)  == true) {
            if (isBadVersion(middle - 1) == false) {
                return middle;
            } else {
                return binarySearch(left, middle-1);
            }
        }

        if (isBadVersion(middle) == false) {
            return binarySearch(middle + 1, right);
        }

        return -1;
    }

    public int firstBadVersion(int n) {
        return binarySearch(1, n);
    }

    private boolean isBadVersion(int n) {
        if (n >= 1702766719) return true;
        return false;
    }

    public static void main(String[] args) {
        System.out.println(new FirstBadVersion().firstBadVersion(2126753390));
    }
}

Add new solution but StackOverflowError exists


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fi.jgke.tagger.domain;

import java.util.UUID;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author jgke
 */
public class TypeTest {

    @Test
    public void testSetGetValue() {
        String value = UUID.randomUUID().toString();
        Tag instance = new Tag();
        instance.setValue(value);
        assertEquals(value, instance.getValue());
    }

}

Add simple test for Type


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

/**
 * Core classes for the {@code gcloud-java} library.
 */
package com.google.gcloud;

Use groups to separate packages in javadoc's index


package org.jpos.qi.util;

import com.vaadin.data.ValidationResult;
import com.vaadin.data.Validator;
import com.vaadin.data.ValueContext;
import org.jpos.ee.DB;
import org.jpos.ee.DBManager;
import org.jpos.qi.QIHelper;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

public class UniqueValidator<T, FieldType> implements Validator<FieldType> {
    protected QIHelper helper;
    Class<T> clazz;
    Method idGetter;
    Method fieldGetter;
    String field;
    String errorMessageCode;

    public UniqueValidator(QIHelper helper, Class<T> clazz, String field)
            throws IntrospectionException
    {
        this(helper, clazz, field, "errorMessage." + field + "AlreadyExists");
    }

    public UniqueValidator(QIHelper helper, Class<T> clazz, String field, String errorMessageCode)
            throws IntrospectionException
    {
        this(helper, clazz, field, errorMessageCode, "id");
    }

    public UniqueValidator(QIHelper helper, Class<T> clazz, String field, String errorMessageCode, String idField)
            throws IntrospectionException
    {
        this.helper = helper;
        this.clazz = clazz;
        this.field = field;
        this.errorMessageCode = errorMessageCode;
        for (PropertyDescriptor property : Introspector.getBeanInfo(clazz).getPropertyDescriptors()) {
            if (property.getName().equals(field)) fieldGetter = property.getReadMethod();
            else if (property.getName().equals(idField)) idGetter = property.getReadMethod();
        }
    }

    /**
     * Validates the given value. Returns a {@code ValidationResult} instance
     * representing the outcome of the validation.
     *
     * @param value   the input value to validate
     * @param context the value context for validation
     * @return the validation result
     */
    @Override
    public ValidationResult apply(FieldType value, ValueContext context) {
        @SuppressWarnings("unchecked")
        T originalEntity = (T) helper.getOriginalEntity();
        try {
            T found = DB.exec(db -> new DBManager<>(db, clazz).getItemByParam(field, value));
            if (found == null ||
                    originalEntity != null && idGetter.invoke(found).equals(idGetter.invoke(originalEntity)))
            {
                return ValidationResult.ok();
            } else {
                return ValidationResult.error(helper.getApp().getMessage(errorMessageCode, value));
            }
        } catch (Exception e) {
            helper.getApp().getLog().error(e);
            return ValidationResult.error(helper.getApp().getMessage(e.getClass().getName(), e.getMessage()));
        }

    }
}

Add generic unique QI validator for entities by field


package leetcode.lru_cache;

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

public class LRUCache {
	private static class CacheEntry{
		int key, val;
		CacheEntry prev, next;
		public CacheEntry(int key, int val){
			this.key = key;
			this.val = val;
		}
	}
	private int capacity;
	private CacheEntry mCacheHead, mCacheTail;
	private int mCacheSize;
	private Map<Integer, CacheEntry> mIndexMap;
    public LRUCache(int capacity) {
        this.capacity = capacity;
        mCacheHead = mCacheTail = null;
        mIndexMap = new HashMap<Integer, CacheEntry>();
        mCacheSize = 0;
    }

    public void moveToFirst(CacheEntry entry){
    	if(entry.prev != null){
    		CacheEntry next = entry.next;
    		CacheEntry prev = entry.prev;
    		prev.next = next;
    		if(next == null){
    			mCacheTail = prev;
    		}else{
    			next.prev = prev;
    		}
    		entry.next = mCacheHead;
    		entry.prev = null;
    		mCacheHead.prev = entry;
    		mCacheHead = entry;
    	}
    }

    public int get(int key) {
    	CacheEntry entry = mIndexMap.get(key);
    	if(entry == null) return -1;
    	moveToFirst(entry);
    	return entry.val;
    }

    public void set(int key, int value) {
        CacheEntry entry = mIndexMap.get(key);
        if(entry != null){
        	entry.val = value;
        	moveToFirst(entry);
        }else{
        	if(mCacheSize >= capacity){
        		moveToFirst(mCacheTail);
        		mIndexMap.remove(mCacheHead.key);
        		mCacheHead.val = value;
        		mCacheHead.key = key;
        	}else{
        		entry = new CacheEntry(key, value);
        		if(mCacheHead == null){
        			mCacheTail = mCacheHead = entry;
        		}else{
        			entry.next = mCacheHead;
        			mCacheHead.prev = entry;
        			mCacheHead = entry;
        		}
        		mCacheSize++;
        	}
        	mIndexMap.put(key, mCacheHead);
        }
    }

    public static void main(String[] args){
    	LRUCache cache = new LRUCache(8);
    	for(int i = 0; i < 10; i++){
    		cache.set(i, i + 100);
    	}
    	for(int i = 0; i < 10; i++){
    		System.err.println(cache.get(i));
    	}
    	cache.get(5);
    	cache.set(10, 110);
    	cache.set(11, 111);
    	CacheEntry entry = cache.mCacheHead;
    	while(entry != null){
    		System.err.println(entry.key + ": " + entry.val);
    		entry = entry.next;
    	}
    }
}

Add java solution for 146. LRU Cache


package jocket.bench;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import jocket.net.JocketSocket;

/**
 * Infinite benchmark, meant for profiling.
 *
 * @author pcdv
 */
public final class BenchClient2 implements Settings {

  private final byte[] buf;

  private final DataInputStream in;

  private final DataOutputStream out;

  public BenchClient2() throws IOException {
    this.buf = new byte[REPLY_SIZE];
    JocketSocket s = new JocketSocket(PORT);
    in = new DataInputStream(s.getInputStream());
    out = new DataOutputStream(s.getOutputStream());
  }

  /**
   * Benchmark's main loop.
   */
  public void bench() throws IOException {

    out.writeInt(REPS * BATCH + WARMUP);
    out.writeInt(REPLY_SIZE);

    while (true) {
      iter(BATCH);
    }
  }

  public void iter(int batch) throws IOException {
    for (int i = 0; i < batch; i++) {
      out.write(buf, 0, 4);
      out.flush();
      in.readFully(buf, 0, REPLY_SIZE);
    }
  }

  public static void main(String[] args) throws IOException {
    new BenchClient2().bench();
  }
}

Add infinite client benchmark for profiling.


/*
 * Copyright (C) 2004 - 2013 Brian McCallister
 *
 * 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.skife.jdbi.v2.sqlobject;

import java.sql.Connection;
import java.sql.SQLException;

import org.h2.jdbcx.JdbcDataSource;
import org.junit.Test;
import org.skife.jdbi.v2.DBI;

import junit.framework.TestCase;

/**
 * Sometimes the GC will call {@link #finalize()} on a SqlObject from
 * extremely sensitive places from within the GC machinery.  JDBI should not
 * open a {@link Connection} just to satisfy a (no-op) finalizer.
 * Issue #82.
 */
public class TestFinalizeBehavior extends TestCase
{
    private DBI    dbi;

    interface UselessDao
    {
        public void finalize();
    }

    @Test
    public void testFinalizeDoesntConnect() throws Exception
    {
        final UselessDao dao = dbi.onDemand(UselessDao.class);
        dao.finalize(); // Normally GC would do this, but just fake it
    }

    @Override
    public void setUp() throws Exception
    {
        final JdbcDataSource ds = new JdbcDataSource() {
            private static final long serialVersionUID = 1L;

            @Override
            public Connection getConnection() throws SQLException
            {
                throw new UnsupportedOperationException();
            }
        };
        dbi = new DBI(ds);
    }
}

Add a test case showing that SqlObject finalize() calls open Connections.


/*
 Copyright (C) 2003 EBI, GRL

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

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

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

import java.sql.Connection;

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

/**
 * Check that certain views/tables required for the Biomart build are present.
 */

public class PreMartTables extends SingleDatabaseTestCase {

	/**
	 * Constructor.
	 */
	public PreMartTables() {

		// TODO - group specifically for this?
		setDescription("Check that certain views/tables required for the Biomart build are present.");

	}

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

		boolean result = true;

		Connection con = dbre.getConnection();

		for (String table : getBiomartFuncgenTablesAndViews()) {

			if (checkTableExists(con, table)) {

				ReportManager.correct(this, con, "Requried table " + table + " exists.");

			} else {

				ReportManager.problem(this, con, "Required table or view " + table + " does not exist");
				result = false;

			}

		}

		return result;

	} // run

} // PreMartTablesAndViews


package com.expidev.gcmapp.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by William.Randall on 1/15/2015.
 */
public class JsonStringReader
{
    public static String readFully(InputStream inputStream, String encoding) throws IOException
    {
        return new String(readFully(inputStream), encoding);
    }

    private static byte[] readFully(InputStream inputStream) throws IOException
    {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1)
        {
            byteArrayOutputStream.write(buffer, 0, length);
        }
        return byteArrayOutputStream.toByteArray();
    }
}

Create a util class to handle turning the input stream into a string


package org.luxons.sevenwonders.game;

import java.util.Collection;

import org.junit.Test;
import org.luxons.sevenwonders.game.api.Action;
import org.luxons.sevenwonders.game.api.CustomizableSettings;
import org.luxons.sevenwonders.game.api.HandCard;
import org.luxons.sevenwonders.game.api.PlayerMove;
import org.luxons.sevenwonders.game.api.PlayerTurnInfo;
import org.luxons.sevenwonders.game.data.GameDefinitionLoader;
import org.luxons.sevenwonders.game.moves.MoveType;
import org.luxons.sevenwonders.game.test.TestUtils;

import static org.junit.Assert.assertEquals;

public class GameTest {

    @Test
    public void test() {
        int nbPlayers = 5;
        Game game = createGame(nbPlayers);
        Collection<PlayerTurnInfo> turnInfos = game.getCurrentTurnInfo();

        assertEquals(nbPlayers, turnInfos.size());

        for (PlayerTurnInfo turnInfo : turnInfos) {
            Action action = turnInfo.getAction();
            assertEquals(Action.PLAY, action);
            assertEquals(1, turnInfo.getCurrentAge());
            assertEquals(7, turnInfo.getHand().size());
            PlayerMove move = getFirstAvailableMove(turnInfo);
            game.prepareCard(turnInfo.getPlayerIndex(), move);
        }
    }

    private PlayerMove getFirstAvailableMove(PlayerTurnInfo turnInfo) {
        for (HandCard handCard : turnInfo.getHand()) {
            if (handCard.isPlayable()) {
                return createMove(handCard, MoveType.PLAY);
            }
        }
        return createMove(turnInfo.getHand().get(0), MoveType.DISCARD);
    }

    private PlayerMove createMove(HandCard handCard, MoveType play) {
        PlayerMove move = new PlayerMove();
        move.setCardName(handCard.getCard().getName());
        move.setType(play);
        return move;
    }

    private static Game createGame(int nbPlayers) {
        CustomizableSettings settings = TestUtils.createCustomizableSettings();
        return new GameDefinitionLoader().getGameDefinition().initGame(0, settings, nbPlayers);
    }
}

Add first draft of Game test


package com.team254.lib.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;

public class Subsystem implements Tappable {

	String name;
	public Subsystem(String name) {
		this.name = name;
		SystemManager.getInstance().add(this.getComponents());
	}

	public final Collection<Serializable> getComponents() {
		Field[] allFields = this.getClass().getDeclaredFields();
		Collection<Serializable> components = new ArrayList<Serializable>();

		for (Field f : allFields) {
			Serializable cur = null;
			if (Serializable.class.isAssignableFrom(f.getClass())) {
				Object obj = null;
				try {
					obj = f.get(this);
				} catch (IllegalArgumentException | IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				cur = (Serializable) obj;
			} else {
				cur = new SerialFieldContainer(name, f, this);
			}
			if (cur != null) {
				components.add(cur);
			}
		}
		return components;
	}

}

Add serializable Subsytem base class


/*******************************************************************************
 * Copyright (c) 2013 Benjamin Pabst and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Benjamin Pabst - initial API and implementation
 ******************************************************************************/

package com.xeviox.commons;

import com.xeviox.commons.util.Version;

/**
 * Common constants and info of the blackstrap library.
 */
public final class PackageInfo {

	/**
	 * Current blackstrap version.
	 */
	public static final Version VERSION = new Version(0, 0, 1);

	// prevent instantiation
	private PackageInfo() { }
}

Add new class to provide package info.