/*
 * Copyright (c) 2015 Cisco Systems, Inc. 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.controller.netconf.mapping.api;

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

import org.junit.Test;

public class HandlingPriorityTest {

    @Test
    public void testHandlingPriority() throws Exception {

        assertTrue(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.compareTo(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY) == 0);
        assertTrue(HandlingPriority.CANNOT_HANDLE.compareTo(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY) == -1);
        assertTrue(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.compareTo(HandlingPriority.CANNOT_HANDLE) == 1);

        assertTrue(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.compareTo(HandlingPriority.HANDLE_WITH_MAX_PRIORITY) == -1);
        assertTrue(HandlingPriority.HANDLE_WITH_MAX_PRIORITY.compareTo(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY) == 1);
        assertTrue(HandlingPriority.getHandlingPriority(Integer.MIN_VALUE).compareTo(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY) == 0);

        HandlingPriority prio = HandlingPriority.getHandlingPriority(10);
        assertTrue(prio.increasePriority(1).compareTo(HandlingPriority.getHandlingPriority(11)) == 0);

        assertFalse(HandlingPriority.CANNOT_HANDLE.getPriority().isPresent());
        assertFalse(HandlingPriority.HANDLE_WITH_MAX_PRIORITY.equals(new Object()));
        assertEquals(HandlingPriority.HANDLE_WITH_MAX_PRIORITY, HandlingPriority.getHandlingPriority(Integer.MAX_VALUE));
        assertEquals(HandlingPriority.HANDLE_WITH_MAX_PRIORITY.hashCode(), HandlingPriority.getHandlingPriority(Integer.MAX_VALUE).hashCode());
    }
}

Add netconf-mapping-api test for HandlingPriority


package leetcode.decode_ways;

public class Solution {
    public int numDecodings(String s) {
    	char[] chars = s.toCharArray();
    	int lens = chars.length;
    	if(lens == 0) return 0;
    	char prev = 0;
    	int cur_end = 1, cur_prev = 0;
    	for(int i = 0; i < lens; i++){
    		int next_end = 0, next_prev = 0;
    		next_prev = cur_end;
    		if(chars[i] == '0'){
    			if(prev == '1' || prev == '2'){
    				next_end += cur_prev;
    			}else{
    				next_end = 0;
    			}
    		}else{
    			next_end = cur_end; // 1 digit ends at char[i]
    			if(prev == '2'){
    				if(chars[i] >= '1' && chars[i] <= '6'){
    					next_end += cur_prev; // 2 digit '2x' ends at char[i]
    				}
    			}else if(prev == '1'){
    				next_end += cur_prev;
    			}
    		}
    		prev = chars[i];
    		cur_end = next_end;
    		cur_prev = next_prev;
    	}
    	return cur_end;
    }

    public static void main(String[] args){
    	System.err.println(new Solution().numDecodings(""));
    }
}

Add java solution for 91. Decode Ways


package it.unibg.alasc.examples;

public class SemanticException extends Exception {

	public SemanticException() {
		// TODO Auto-generated constructor stub
	}

	public SemanticException(String arg0) {
		super(arg0);
		// TODO Auto-generated constructor stub
	}

	public SemanticException(Throwable arg0) {
		super(arg0);
		// TODO Auto-generated constructor stub
	}

	public SemanticException(String arg0, Throwable arg1) {
		super(arg0, arg1);
		// TODO Auto-generated constructor stub
	}

}

Add the exception class that implements the semantic exception.


package bullshit_paper;

import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Random;

public class MarkovChain {
	private HashMap<String, LinkedList<String> > graph;

	MarkovChain(){
		graph = new HashMap<>();
	}

	public void build(List<String> sentences){

		for(String s: sentences){
			List<String> cur = Parser.parseSentence(s);
			cur.add(".");

			for(int i=-1; i<cur.size()-1; ++i){
				LinkedList<String> tmp;
				String from;

				if(i == -1){
					from = "#";
					tmp = graph.get(from);
				}
				else{
					from = cur.get(i);
					tmp = graph.get(from);
				}

				if(tmp == null){
					tmp = new LinkedList<String>();
				}

				tmp.add(cur.get(i+1));
				graph.put(from, tmp);
			}
		}

		for(Entry<String, LinkedList<String>> entry: graph.entrySet()){
			LinkedList<String> tmp = entry.getValue();
			Collections.shuffle(tmp);
			graph.put(entry.getKey(),tmp);
		}

	}

	public String generateRandomText(int length){
		StringBuilder builder = new StringBuilder();
		Random random = new Random();

		for(int i=0; i<length; ++i){
			String cur = "#";

			while(cur != "."){
				LinkedList<String> list = graph.get(cur);
				int size = list.size();
				cur = list.get(random.nextInt(size));

				if(cur != "."){
					builder.append(" "+cur);
				}
			}

			builder.append(".");
		}

		return builder.toString();
	}

}

Add simple random text generator


package christmas;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

import static java.util.Calendar.*;

/**
 *  A program that counts down to Christmas.
 *
 *  @author  Joel Abrahamsson
 *  @version %G%
 */
public class Countdown extends JFrame
{
  private static long MILLIS_PER_DAY    = 86400000L;
  private static long MILLIS_PER_HOUR   = 3600000L;
  private static long MILLIS_PER_MINUTE = 60000L;

  private Calendar christmas;
  private JLabel label;

  /**
   *  Creates a new Coundown-object.
   */
  public Countdown()
  {
    super("Christmas countdown");

    christmas = getChristmasCalendar();

    setDefaultCloseOperation(EXIT_ON_CLOSE);

    // Create label
    label = new JLabel(formatTimeString(getTimeToChristmas()), JLabel.CENTER);

      label.setPreferredSize(new Dimension(320, 64));

    getContentPane().add(label);
    pack();

    // Create and start timer
    Timer timer = new Timer(250, new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        label.setText(formatTimeString(getTimeToChristmas()));
      }
    });
    timer.start();
  }

  /**
   *  Formats a string from the given time.
   *
   *  @param milliseconds time in milliseconds
   *
   *  @return             formatted string
   */
  private String formatTimeString(long milliseconds)
  {
    long days = milliseconds / MILLIS_PER_DAY;
    milliseconds %= MILLIS_PER_DAY;

    long hours = milliseconds / MILLIS_PER_HOUR;
    milliseconds %= MILLIS_PER_HOUR;

    long minutes = milliseconds / MILLIS_PER_MINUTE;
    milliseconds %= MILLIS_PER_MINUTE;

    long seconds = milliseconds / 1000;

    return String.format("%d days %d hours %d minutes %d seconds", days, hours, minutes, seconds);
  }

  /**
   *  Returns a Calendar representing Christmas (December 24th) the current year.
   *
   *  @return Calendar-object representing Christmas
   */
  private Calendar getChristmasCalendar()
  {
    Calendar christmas = Calendar.getInstance();

    christmas.set(Calendar.MONTH, 12);
    christmas.set(Calendar.DAY_OF_MONTH, 24);

    return christmas;
  }

  /**
   *  Returns the time left to Christmas (in milliseconds).
   *
   *  @return time left to Christmas (in milliseconds)
   */
  private long getTimeToChristmas()
  {
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(christmas.getTimeInMillis() - calendar.getTimeInMillis());

    calendar.set(MONTH, 0);

    return calendar.getTimeInMillis();
  }

  public static void main(String[] args)
  {
    Countdown countdown = new Countdown();
    countdown.setVisible(true);
  }
}

Create a program that countdown to Christmas (December 24th)


package forklift.decorators;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Marks an object to have its properties populated with data from the JMS message
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface Message {
}

Add a way to mark a field within a processor to have the data injected into the field from the JMS message.


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

package com.google.sps.data;

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

/**
 *
 */
public class ProductDetectionData {
  private List<String> labels;
  private List<String> logos;
  private List<String> colors;

  public ProductDetectionData(List<String> labels, List<String> logos, List<String> colors) {
    // shallow copy
    this.labels = new ArrayList<String>(labels);
    this.logos = new ArrayList<String>(logos);
    this.colors = new ArrayList<String>(colors);
  }

  public List<String> getLabels() {
    return labels;
  }

  public List<String> getLogos() {
    return logos;
  }

  public List<String> getColors() {
    return colors;
  }
}

Add data class for storing image recognition data


package sed;

import java.io.IOException;

import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import com.jme3.asset.AssetInfo;
import com.jme3.asset.AssetLoader;

public class XMLLoader implements AssetLoader {

    @Override
    public Object load(AssetInfo assetInfo) throws IOException {
        SAXBuilder builder = new SAXBuilder();
        try {
            return builder.build(assetInfo.openStream()).getRootElement();
        } catch(JDOMException ex) {
            throw new IOException(ex);
        }
    }

}

Add XML loader for jME3 asset loader architecture


package org.msgpack;

import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.msgpack.annotation.Message;
import org.msgpack.type.ArrayValue;
import org.msgpack.type.Value;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * User: takeshita
 * Create: 11/10/17 23:17
 */
public class TestNestedList {

    MessagePack messagePack;

    @Before
    public void before(){
        messagePack = new MessagePack();
    }

    @Test
    public void testTestNestedList() throws IOException {
        NestedList obj = new NestedList();
        obj.list.add(list("aaa", "bbb"));
        obj.list.add(list(new MyClass("obj1"), new MyClass("obj2")));

        byte[] bytes = messagePack.write(obj);

        // Can't unpack as NestedList
        Value unpacked = messagePack.read(bytes);
        ArrayValue root = unpacked.asArrayValue();
        ArrayValue list1 = root.getElementArray()[0].asArrayValue();
        ArrayValue list2 = root.getElementArray()[1].asArrayValue();

        Assert.assertEquals("aaa",list1.getElementArray()[0].asIntegerValue().getInt());
        Assert.assertEquals("bbb",list1.getElementArray()[1].asIntegerValue().getInt());
        Assert.assertEquals("obj1",messagePack.convert(list2.getElementArray()[0],MyClass.class).name);
        Assert.assertEquals("obj2",messagePack.convert(list2.getElementArray()[1],MyClass.class).name);

    }

    private List<?> list( Object ... elements){
        List<Object> list = new ArrayList();
        for(Object o : elements){
            list.add(o);
        }
        return list;
    }

    @Message
    public static class NestedList{
        public List<List> list = new ArrayList<List>();

    }

    @Message
    public static class MyClass{
        String name;

        public MyClass(){}
        public MyClass(String n ){ name = n;}
    }

}

Add new test case which serialize nested list.


package leetcode.rotate_array;

public class Solution {
    int gcd(int a, int b){
        while(b != 0){
            int tmp = a;
            a = b;
            b = tmp % b;
        }
        return a;
    }
    public void rotate(int[] nums, int k) {
        if(nums == null || nums.length == 0) return;
        int length = nums.length;
        k = (k % length + length) % length;
        int g = gcd(length, k);
        for(int i = 0; i < g; i++){
            int tmp = nums[i];
            int cur = i;
            for(int j = 0; j < length / g - 1; j++){
                nums[cur] = nums[(cur - k + length) % length];
                cur = (cur - k + length) % length;
            }
            nums[cur] = tmp;
        }
    }

    public static void main(String[] args){
        int[] ary = new int[]{1, 2, 3, 4};
        new Solution().rotate(ary, 4);
        for(int x : ary){
            System.err.print(x + " ");
        }
        System.err.println("");
    }
}

Add java solution for 189. Rotate Array


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

package org.apache.jorphan.math;

/**
 * Class to calculate various items that don't require all previous results to be saved:
 * - mean = average
 * - standard deviation
 * - minimum
 * - maximum
 */
public class Calculator {

	private double sum = 0;

	private double sumOfSquares = 0;

	private double mean = 0;

	private double deviation = 0;

	private int count = 0;

	private long bytes = 0;

	private long maximum = Long.MIN_VALUE;

	private long minimum = Long.MAX_VALUE;

	public void clear() {
		maximum = Long.MIN_VALUE;
		minimum = Long.MAX_VALUE;
		sum = 0;
		sumOfSquares = 0;
		mean = 0;
		deviation = 0;
		count = 0;
	}

	public void addValue(long newValue) {
		count++;
		minimum=Math.min(newValue, minimum);
		maximum=Math.max(newValue, maximum);
		double currentVal = newValue;
		sum += currentVal;
		sumOfSquares += currentVal * currentVal;
		// Calculate each time, as likely to be called for each add
		mean = sum / count;
		deviation = Math.sqrt((sumOfSquares / count) - (mean * mean));
	}

	public void addBytes(long newValue) {
		bytes += newValue;
	}

	public long getTotalBytes() {
		return bytes;
	}

	public double getMean() {
		return mean;
	}

	public double getStandardDeviation() {
		return deviation;
	}

	public long getMin() {
		return minimum;
	}

	public long getMax() {
		return maximum;
	}

	public int getCount() {
		return count;
	}
}

Add cheaper calculator (no need to save results)


import java.util.Iterator;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;
import dk.netarkivet.common.utils.FilterIterator;
import dk.netarkivet.harvester.datamodel.Domain;
import dk.netarkivet.harvester.datamodel.DomainConfiguration;
import dk.netarkivet.harvester.datamodel.DomainDAO;

public class TestSnapShotHarvestDomainConfigRetrieval {

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println("Testing first step snapshot harvest" +  new Date());
        DomainDAO dao = DomainDAO.getInstance();

        Iterator<DomainConfiguration> i = new FilterIterator<Domain, DomainConfiguration>(
                dao.getAllDomainsInSnapshotHarvestOrder()) {
            public DomainConfiguration filter(Domain domain) {
                if (domain.getAliasInfo() == null
                        || domain.getAliasInfo().isExpired()) {
                    return domain.getDefaultConfiguration();
                } else {
                    return null;
                }
            }
        };
        System.out.println("Iterator initialized " + new Date());
        long count = 0;
        List<DomainConfiguration> subset = new ArrayList<DomainConfiguration>();
        while (i.hasNext()) {
            count++;
            if (subset.size() >= 10000) {
                subset = new ArrayList<DomainConfiguration>();
                System.out.println("collected " + subset.size() + "  configs at " + new Date());
            }
            DomainConfiguration dc = i.next();
            subset.add(dc);
            if (count % 100 == 0) {
                System.out.println("#" + count + ": (conf-name, domain)= (" + dc.getName()
                        + ", " + dc.getDomainName() + ") at " + new Date());
            }
        }
    }
}

Test program for testing speed on retrieving DomainConfigs for snapshot harvests


package model.effects;

import model.Effect;
import model.stats.Stat;
import model.unit.Unit;

public class ModifyAttribute extends Effect {

	public ModifyAttribute(String name, String attribute, double power) {
		super(name,attribute);
		this.addStat(new Stat("Power",power));
	}

	@Override
	public void enact(Unit target) {
		target.getStatCollection("Attributes").setStat(this.getID(),
				target.getStatCollection("Attributes").getValue(this.getID())+this.getValue("Power"));
	}

	@Override
	public Effect copy() {
		return new ModifyAttribute(this.getName(),this.getID(),this.getValue("Power"));
	}

}

package model.effects;

import model.Effect;
import model.stats.Stat;
import model.unit.Unit;

public class ModifyAttribute extends Effect {

	public ModifyAttribute(String name, String attribute, double power) {
		super(name,attribute);
		this.addStat(new Stat("Power",power));
	}

	@Override
	public void enact(Unit target) {
		target.getStatCollection("Attributes").setStat(this.getID(),
				target.getStatCollection("Attributes").getValue(this.getID())+this.getValue("Power"));
		if(target.getStatCollection("Attributes").getValue("Health")<=0){
			target.getPlayer().removeUnit(target);
			target.getCurrentTile().removeUnit(target);
			target.getPlayer().getModel().destroyUnit(target);
		}
	}

	@Override
	public Effect copy() {
		return new ModifyAttribute(this.getName(),this.getID(),this.getValue("Power"));
	}

}

Destroy units properly using Custom Abilities


// Use a BufferedReader to read characters from the console.
import java.io.*;

class ReadChars {
	public static void main(String args[]) throws IOException {
		char c;
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		System.out.println("Enter characters, period to quit.");

		// read characters
		do {
			c = (char) br.read();
			System.out.println(c);
		} while(c != '.');
	}
}


package org.jstanier.tweetscheduler.main;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

import com.jstanier.tweetscheduler.main.Config;

@RunWith(MockitoJUnitRunner.class)
public class ConfigTest {

	@Test
	public void whenConfigIsCreated_thenNoExceptionIsThrown() {
		new Config();
	}
}

Add unit test for Config


import java.util.HashMap;

public class ContainsDuplicates {
    public boolean containsDuplicate(int[] nums) {
        HashMap<Integer, Integer> occurrenceCountMap = new HashMap<>();
        for (int num : nums) {
            if (occurrenceCountMap.containsKey (num))
                return true;
            else
                occurrenceCountMap.put (num, 1);
        }
        return false;
    }

    public static void main (String[] args) {
        ContainsDuplicates test = new ContainsDuplicates ();
        int[] testArray1 = {1, 2, 3, 4, 5};
        int[] testArray2 = {1, 1, 455};
        int[] testArray3 = {};
        System.out.println(test.containsDuplicate (testArray1));
        System.out.println(test.containsDuplicate (testArray2));
        System.out.println(test.containsDuplicate (testArray3));
    }
}

Check if array has duplicate values


package retryable.asyncTask;

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

import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class)
public class ConcreteAsyncTaskTest {

  ConcreteAsyncTask<String, Void, Object> concreteAsyncTask;

  @Mock RetryableAsyncTask retryableAsyncTask;

  @Before
  public void setUp() {
    initMocks(this);

    concreteAsyncTask = new ConcreteAsyncTask<>(retryableAsyncTask);
  }

  @Test
  public void itDelegatesToParentTaskOnPreExecute() {
    concreteAsyncTask.execute();

    verify(retryableAsyncTask).onPreExecute();
  }

  @Test
  public void itDelegatesToParentTaskOnDoingBackgroundTask() {
    String params = "foo";

    concreteAsyncTask.execute(params);

    verify(retryableAsyncTask).doInBackground(params);
  }

  @Test
  public void itDelegatesToParentTaskOnPostExecute() {
    concreteAsyncTask.execute();

    verify(retryableAsyncTask).onPostExecute(null);
  }

}

Add unit test for ConcreteAsyncTask


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

import static org.junit.Assert.*;

import org.junit.Test;

public class MinimalMapTest {

    @Test
    public void size_1() throws Exception {
	MinimalMap<MockEntry> map = new MockMap();
	assertEquals(0, map.size());
	String a = "a";
	map.get(a);
	assertEquals(1, map.size());
	map.get(a);
	assertEquals(1, map.size());
	map.get("b");
	assertEquals(2, map.size());
    }

    @Test
    public void get_1() throws Exception {
	MinimalMap<MockEntry> map = new MockMap();
	String a = "a";
	MockEntry x = map.get(a);
	MockEntry y = map.get(a);
	assertEquals(x, y);
    }

    static class MockMap extends MinimalMap<MockEntry> {

	@Override
	protected MockEntry[] createInitialArray(int size) {
	    return new MockEntry[size];
	}

	@Override
	protected MockEntry createEntry(Object key, int hashCode) {
	    return new MockEntry(key, hashCode);
	}

    }

    static class MockEntry implements MinimalMapEntry<MockEntry> {

	private final Object key;
	private final int hashCode;
	private MockEntry next;

	public MockEntry(Object key, int hashCode) {
	    this.key = key;
	    this.hashCode = hashCode;
	}

	@Override
	public int getHashCode() {
	    return hashCode;
	}

	@Override
	public Object getKey() {
	    return key;
	}

	@Override
	public MockEntry next() {
	    return next;
	}

	@Override
	public void setNext(MockEntry nextEntry) {
	    next = nextEntry;
	}

    }

}

Add initial tests for MinimalMap


package com.k13n.soliton;

import java.util.Random;

public class RobustSolitonGenerator implements SolitonGenerator {
  private Random random;
  private int k;
  private double c, delta, R, beta;

  public RobustSolitonGenerator(int k, double c, double delta, long seed) {
    this.k = k;
    this.c = c;
    this.delta = delta;
    random = new Random(seed);
    R = computeR();
    beta = computeBeta();
  }

  public RobustSolitonGenerator(int k, double c, double delta) {
    this(k, c, delta, new Random().nextLong());
  }

  private double computeR() {
    return c * Math.log(k / delta) * Math.sqrt(k);
  }

  private double computeBeta() {
    double sum = 0;
    for (int i = 1; i <= k; i++)
      sum += idealSoliton(i) + unnormalizedRobustSoliton(i);
    return sum;
  }

  @Override
  public int next() {
    double u = random.nextDouble();
    return inverseTransformSampling(u);
  }

  private int inverseTransformSampling(double u) {
     double sum = 0;
     int index = 1;
     while (sum <= u)
       sum += normalizedRobustSoliton(index++);
     return index - 1;
  }

  private double normalizedRobustSoliton(int i) {
    return (idealSoliton(i) + unnormalizedRobustSoliton(i)) / beta;
  }

  private double unnormalizedRobustSoliton(int i) {
    if (1 <= i && i <= Math.floor(k/R)-1)
      return R / (i*k);
    else if (i == Math.floor(k / R))
      return R * Math.log(R / delta) / k;
    else
      return 0;
  }

  private double idealSoliton(int i) {
    if (i == 1)
      return 1.0 / k;
    else
      return 1.0 / (i * (i-1));
  }

}

Implement a robust soliton random number generator


package net.sf.jabref.logic.pdf;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.List;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;

public class PdfCommentImporter {

    private List pdfPages;
    private PDPage page;
    public PdfCommentImporter() {

    }

    /**
     * Imports the comments from a pdf specified by its URI
     * @param pathToPDF the URI specifying the document
     * @return a hasmap with the unique name as key and the notes content as value
     */
    public HashMap<String, String> importNotes(final URI pathToPDF){

        PDDocument pdf;
        HashMap<String, String> annotationsMap = new HashMap<>();
        try {
            pdf = importPdfFile(pathToPDF);

            pdfPages = pdf.getDocumentCatalog().getAllPages();
            for(int i = 0; i < pdfPages.size(); i++){
                page = (PDPage) pdfPages.get(i);
                for(PDAnnotation annotation : page.getAnnotations()){
                    annotationsMap.put(annotation.getAnnotationName(), annotation.getContents());
                }
            }

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

    private PDDocument importPdfFile(final URI pathToPDF) throws IOException {
        File file = new File(pathToPDF);
        return PDDocument.load(file);
    }
}

Add importer class to extract pdf file comments


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

import org.junit.Before;
import org.junit.BeforeClass;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

import io.github.bonigarcia.wdm.WebDriverManager;
import io.github.bonigarcia.wdm.base.BrowserTestParent;

/**
 * Test with HtmlUnit browser (which uses void driver manager).
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 1.0.0
 */
public class HtmlUnitTest extends BrowserTestParent {

    private static Class<? extends WebDriver> webDriverClass;

    @BeforeClass
    public static void setupClass() {
        webDriverClass = HtmlUnitDriver.class;
        WebDriverManager.getInstance(webDriverClass).setup();
    }

    @Before
    public void htmlUnitTest()
            throws InstantiationException, IllegalAccessException {
        driver = webDriverClass.newInstance();
    }

}

Include HtmlUnit test (to check void driver manager)


package binarytree;

import datastructures.tree.BinarySearchTree;
import datastructures.tree.TreeNode;

public class CheckBSTHasDeadEnd {
  private BinarySearchTree<Integer> tree = null;
  private TreeNode<Integer> root = null;

  public CheckBSTHasDeadEnd() {
    tree = new BinarySearchTree<Integer>();
  }

  public void constructTree(String[] input) {
    for (String line : input) {
      String[] values = line.split(" ");
      String action = values[0];

      switch (action) {
      case "insertRoot":
        tree = new BinarySearchTree<Integer>();
        root = tree.insertRoot(Integer.parseInt(values[1]));
        break;
      case "insert":
        tree.insert(root, Integer.parseInt(values[1]));
        break;
      }
    }
  }

  public boolean hasDeadEnd() {
    return hasDeadEnd(root, new Range(0, Integer.MAX_VALUE));
  }

  private boolean hasDeadEnd(TreeNode<Integer> root, Range range) {
    if(root == null) {
      return false;
    } else if (root.left == null && root.right == null) {
      return Math.abs(root.data - range.min) <= 1 && Math.abs(range.max - root.data) <= 1;
    } else {
      return hasDeadEnd(root.left, new Range(range.min, root.data)) || hasDeadEnd(root.right, new Range(root.data, range.max));
    }
  }

  private class Range {
    private int min;
    private int max;

    Range(int min, int max) {
      this.min = min;
      this.max = max;
    }
  }
}

Add solution for CheckBST has dead end


package com.example.timber.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import timber.log.Timber;

@SuppressLint("Registered") //
public class LintActivity extends Activity {
  @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Below are some examples of how NOT to use Timber
    /*
    Log.d("TAG", "msg");

    Timber.w(String.format("%s", "arg0"));

    Exception e = new Exception();
    Timber.d("%s", e);

    Timber.d("Hello, " + "world!");

    Timber.d("%s %s", "arg0");

    Timber.d("%s", "arg0", "arg1");

    Timber.d("%d", "arg0");

    Timber.tag("abcdefghijklmnopqrstuvwx");

    Timber.tag("tag").d("%s %s", "arg0");

    Timber.tag("tag").d("%s", "arg0", "arg1");

    Timber.tag("tag").d("%d", "arg0");

    Timber.tag("abcdefghijklmnopqrstuvw" + "x");

    Timber.tag("abcdefghijklmnopqrstuvw" + new String("x"));
    */
  }
}

Add Timber lint failure examples


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

/**
 * Implement an algorithm to find the kth to last element of a singly linked list. Can you do it
 * using recursion?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class FindKthElement {

}

Add statement to problem 58


/*
 * 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.commons.imaging.formats.tiff.photometricinterpreters;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class PhotometricInterpreterLogLuvTest {

    @Test
    public void testConstructor() {
        int samplesPerPixel = 8;
        int[] bitsPerSample = new int[] {1, 2, 3};
        int predictor = 1;
        int width = 800;
        int height = 600;
        PhotometricInterpreterLogLuv p = new PhotometricInterpreterLogLuv(samplesPerPixel, bitsPerSample, predictor,
                width, height);
        assertEquals(samplesPerPixel, p.samplesPerPixel);
        for (int i = 0; i < bitsPerSample.length; i++) {
            assertEquals(bitsPerSample[i], p.getBitsPerSample(i));
        }
        assertEquals(predictor, p.predictor);
        assertEquals(width, p.width);
        assertEquals(height, p.height);
    }
}

Add base test for PhotometricInterpreterLogLuv


package io.github.saidie.plantuml_api;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Embeddable
@NoArgsConstructor
@AllArgsConstructor
public class IdpId implements Serializable {
    @NotNull
    @Enumerated(EnumType.STRING)
    private FederationType type;

    @NotNull
    @Column(nullable = false)
    private String id;

    public enum FederationType {
        TWITTER
    }
}

Add a class representing IdP identifier


package jmetest.renderer.loader;

import com.jme.app.SimpleGame;
import com.jme.scene.model.ms3d.MilkLoader;
import com.jme.scene.model.XMLparser.XMLWriter;
import com.jme.scene.model.XMLparser.SAXReader;
import com.jme.scene.Node;

import java.net.URL;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;

/**
 * Started Date: Jun 5, 2004
 *
 * Class test the XMLWriter and SAXReader classes
 *
 * @author Jack Lindamood
 */
public class TestXMLWriter extends SimpleGame{
    public static void main(String[] args) {
        new TestXMLWriter().start();
    }
    protected void simpleInitGame() {
        MilkLoader mi=new MilkLoader();
        URL MSFile=TestMilkLoader.class.getClassLoader().getResource(
        "jmetest/data/model/msascii/run.ms3d");
        mi.setBase(TestMilkLoader.class.getClassLoader().getResource(
        "jmetest/data/model/msascii/"));
        Node mi1=mi.load(MSFile);
        mi1.setLocalScale(.1f);
        ByteArrayOutputStream BO=new ByteArrayOutputStream();
        XMLWriter r=new XMLWriter(BO);
        try {
            r.writeScene(mi1);
        } catch (IOException e) {
            System.out.println("Error writting");
        }
        SAXReader sr=new SAXReader();
        Node qq=sr.loadXML(new ByteArrayInputStream(BO.toByteArray()));
        rootNode.attachChild(qq);

    }

}

Test the XMLWriter and SAXReader classes


package com.utilities;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Mene on 11/27/2016.
 */

public class HttpRequester {

    private String host;
    private Integer port;

    private HttpRequester(){}

    public HttpRequester(String address){

        this();
        host = address.split(":")[0];
        port = Integer.parseInt(address.split(":")[1]);
    }

    public void postRequest(String enpoint, JSONObject params) throws IOException, URISyntaxException {
        CloseableHttpClient httpclient = HttpClients.createDefault();

        URI uriConfig = new URI("http", null, this.host, this.port, enpoint, null, null);
        HttpPost httpPostRequest = new HttpPost(uriConfig);

        StringEntity paramString = new StringEntity(params.toString());
        paramString.setContentType("application/json");
        httpPostRequest.setEntity(paramString);
        CloseableHttpResponse response = httpclient.execute(httpPostRequest);

        try {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                EntityUtils.consume(entity);
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status +", " + response.getStatusLine().getReasonPhrase());
            }

        } finally {
            response.close();
        }
    }

}

Add http request support and first snippet to perform game registration inside the Engine.


/*
 * Transient.java June 2007
 *
 * Copyright (C) 2007, Niall Gallagher <niallg@users.sf.net>
 *
 * 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.
 *
 * 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 simple.xml;

import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Retention;

/**
 * The Transient annotation is an optional annotation
 * that can be used within an XML class schema to mark a method or
 * field as being transient, which indicates that it does not take
 * part in serialization or deserialization. This is used only as
 * a means to illustrate to the reader of your class that this has
 * not impact on the XML representation of the object. Fields or
 * methods annotated with this will be ignored, as will those that
 * contain no XML annotations.
 *
 * @author Niall Gallagher
 */
@Retention(RetentionPolicy.RUNTIME)
public @interface Transient {
}

Add the optional transient annotation


package de.lmu.ifi.dbs.elki.visualization.batikutil;

import org.w3c.dom.Element;

import de.lmu.ifi.dbs.elki.visualization.svg.SVGPlot;

/**
 * This helper class will replace a node in an SVG plot,
 * as soon as the tree is unlocked by the rendering engine.
 *
 * @author Erich Schubert
 *
 */
public class NodeReplacer extends RunWhenReadyAndVisible {
  private SVGPlot plot;
  private String id;
  private Element newe;

  /**
   * Setup a SVG node replacement.
   *
   * @param newe New element
   * @param plot SVG plot to process
   * @param id Node ID to replace
   */
  public NodeReplacer(Element newe, SVGPlot plot, String id) {
    super();
    this.newe = newe;
    this.plot = plot;
    this.id = id;
  }

  @Override
  public void run() {
    Element olde = plot.getIdElement(id);
    if (olde != null) {
      olde.getParentNode().replaceChild(newe, olde);
      plot.putIdElement(id, newe);
    }
  }
}

Add Batik helper to replace a named node in the SVG tree.


package com.google.sps.servlets;

import com.google.sps.tasks.TaskScheduler;
import javax.servlet.http.HttpServlet;

public abstract class QueueServlet extends HttpServlet {
  protected TaskScheduler.Builder getTaskBuilder() {
    return TaskScheduler.builder();
  }
}

Add abstract class with TaskBuilder.Builder getter.


package fi.jgke.tagger.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import fi.jgke.tagger.domain.Tag;
import fi.jgke.tagger.domain.Type;
import fi.jgke.tagger.repository.TagRepository;
import fi.jgke.tagger.repository.TypeRepository;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.transaction.Transactional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringRunner.class)
@WebAppConfiguration
@SpringBootTest
@Transactional
public class HealthTest {

    @Autowired
    private WebApplicationContext webAppContext;
    private MockMvc mockMvc;

    @Before
    public void setUp() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build();
    }

    @Test
    public void isHealthy() throws Exception {
        mockMvc.perform(get("/health"))
                .andExpect(content().contentType("application/hal+json;charset=UTF-8"))
                .andExpect(jsonPath("$.version").exists())
                .andExpect(jsonPath("$.healthy").value(true));

    }
}

Add simple test for /health


package com.mistraltech.bog.core.annotation;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Identifies the property in the builder that the annotated method is a getter for.
 * <p>
 * Useful for overriding defaults assumed by the builder generators.
 */
@Target(METHOD)
@Retention(RUNTIME)
public @interface GetsProperty {
    /**
     * The name of the property to be returned
     *
     * @return the ValueContainer for the property
     */
    String value();
}

Add annotation for identifying a getter method (a method that returns the ValueContainer for a property).


/*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.openqa.selenium.lift;

import org.hamcrest.Matcher;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.lift.find.Finder;

/**
 * Interface for objects that provide a context (maintaining any state) for web tests.
 * @author rchatley (Robert Chatley)
 *
 */
public interface TestContext {

	public abstract void goTo(String url);

	public abstract void assertPresenceOf(Finder<WebElement, WebDriver> finder);

	public abstract void assertPresenceOf(
			Matcher<Integer> cardinalityConstraint,
			Finder<WebElement, WebDriver> finder);

	public abstract void type(String input, Finder<WebElement, WebDriver> finder);

	public abstract void clickOn(Finder<WebElement, WebDriver> finder);

	public abstract void waitFor(Finder<WebElement, WebDriver> finder, long timeout);

	public abstract void quit();

}

/*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.openqa.selenium.lift;

import org.hamcrest.Matcher;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.lift.find.Finder;

/**
 * Interface for objects that provide a context (maintaining any state) for web tests.
 * @author rchatley (Robert Chatley)
 *
 */
public interface TestContext {

  void goTo(String url);

  void assertPresenceOf(Finder<WebElement, WebDriver> finder);

  void assertPresenceOf(Matcher<Integer> cardinalityConstraint,
      Finder<WebElement, WebDriver> finder);

  void type(String input, Finder<WebElement, WebDriver> finder);

  void clickOn(Finder<WebElement, WebDriver> finder);

  void waitFor(Finder<WebElement, WebDriver> finder, long timeout);

  void quit();

}

Remove unnecessary modifiers and cleanup whitespace.


package com.redhat.ceylon.compiler.js;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.redhat.ceylon.compiler.typechecker.model.Module;

/** A container for things we need to keep per-module. */
class JsOutput {
    private File outfile;
    private Writer writer;
    private final Set<String> s = new HashSet<String>();
    final Map<String,String> requires = new HashMap<String,String>();
    final MetamodelVisitor mmg;
    protected JsOutput(Module m) throws IOException {
        mmg = new MetamodelVisitor(m);
    }
    protected Writer getWriter() throws IOException {
        if (writer == null) {
            outfile = File.createTempFile("jsout", ".tmp");
            writer = new FileWriter(outfile);
        }
        return writer;
    }
    protected File close() throws IOException {
        writer.close();
        return outfile;
    }
    void addSource(String src) {
        s.add(src);
    }
    Set<String> getSources() { return s; }
}

Move this class out of JsCompiler into its own


package com.sec.ax.restful.utils;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 *
 * @author heesik.jeon
 *
 */

public class FormatHelper {

	private static final Logger logger = Logger.getLogger(FormatHelper.class);

    /**
     * @param object
     * @return
     */
    public static String printPretty(Object object) {

		logger.debug("..");

    	Gson gson = new GsonBuilder().setPrettyPrinting().create();

    	String json = gson.toJson(object);

    	return json;

    }

}

Add util to enable json pretty print


package uk.ac.ebi.quickgo.annotation.validation;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import static uk.ac.ebi.quickgo.annotation.validation.QuickGoValidation.toDb;

/**
 * @author Tony Wardell
 * Date: 10/11/2016
 * Time: 13:22
 * Created with IntelliJ IDEA.
 */
public class ReferenceDBXRefEntityValidation implements ConstraintValidator<ReferenceValidator, String[]> {

    @Autowired
    DBXRefEntityValidation dbxRefEntityValidation;

    //@Value("${annotation.validation.reference.databases}")
    List<String> referenceDatabases = Arrays.asList("pmid","doi","go_ref","reactome");

    @Override public void initialize(ReferenceValidator constraintAnnotation) {}

    @Override public boolean isValid(String[] values, ConstraintValidatorContext context) {
        return values == null ||
                Stream.of(values).allMatch(this::validReference) && dbxRefEntityValidation.isValid(values, context);
    }

    private boolean validReference(String s) {

        if(s == null){
            return false;
        }

        if(s.trim().isEmpty()){
            return false;
        }

        if(!s.contains(":")){
            return true;
        }

        return referenceDatabases.contains(toDb.apply(s));
    }
}

Validate references against OK list of databases.


package fitnesse.testsystems.slim.tables;

import org.junit.Test;

import static org.junit.Assert.*;

public class DisgracerTest {

  @Test
  public void disgraceClassName() {
    assertEquals("classname", Disgracer.disgraceClassName("classname"));
    assertEquals("className", Disgracer.disgraceClassName("className"));
    assertEquals("ClassName", Disgracer.disgraceClassName("class name"));
  }

  @Test
  public void disgraceMethodName() {
    assertEquals("methodName", Disgracer.disgraceMethodName("method name"));
    assertEquals("methodname", Disgracer.disgraceMethodName("methodname"));
    assertEquals("MethodName", Disgracer.disgraceMethodName("Method name"));
  }
}

Add unit test for Disgracer class.


/*
 * Copyright © 2015 John H Uckele. All rights reserved.
 */

package io.vivarium.client.task;

import java.nio.channels.NotYetConnectedException;

import org.java_websocket.handshake.ServerHandshake;

import com.fasterxml.jackson.core.JsonProcessingException;

import io.vivarium.client.TaskClient;
import io.vivarium.net.jobs.Job;
import io.vivarium.net.messages.CreateJob;

public class CreateJobTask extends Task
{
    private Job _job;

    public CreateJobTask(Job job)
    {
        _job = job;
    }

    @Override
    public void onOpen(TaskClient client, ServerHandshake handshakedata)
    {
        try
        {
            CreateJob message = new CreateJob(_job);
            client.send(client.getMapper().writeValueAsString(message));
        }
        catch (NotYetConnectedException | JsonProcessingException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void onMessage(TaskClient client, String message)
    {
        // No reply expected
        // TODO: We should get an ack, and if we don't get the ack we should resend a CreateJob message periodically.
    }

    @Override
    public void onClose(TaskClient client, int code, String reason, boolean remote)
    {
    }

    @Override
    public void onError(TaskClient client, Exception ex)
    {
    }
}

Create Job task for TaskClient


import java.util.Scanner;

public class CountBitsOne {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int n = scan.nextInt();
        System.out.println(countPositiveBits(n));
    }

    public static int countPositiveBits(int n) {
        int count = 0;

        while (n > 0) {
            if ((n & 1) == 1) {
                count++;
            }
            n >>= 1;
        }

        return count;
    }
}

Solve homework2-problem7: Count of Bits One


package leetcode.restore_ip_addresses;

import java.util.ArrayList;

public class Solution {
	public static final int IP_BYTES = 4;
	public void dfs(ArrayList<String> ans, char[] input, int offset, int length, int[] ipaddr, int depth){
		if(offset == length && depth == IP_BYTES){
			ans.add(ipaddr[0] + "." + ipaddr[1] + "." + ipaddr[2] + "." + ipaddr[3]);
		}else if(offset < length && depth < IP_BYTES){
			ipaddr[depth] = input[offset] - '0';
			dfs(ans, input, offset + 1, length, ipaddr, depth + 1);
			if(offset + 2 <= length){
				int d = (input[offset] - '0') * 10 + (input[offset + 1] - '0');
				if(d >= 10){
					ipaddr[depth] = d;
					dfs(ans, input, offset + 2, length, ipaddr, depth + 1);
				}
			}
			if(offset + 3 <= length){
				int d = (input[offset] - '0') * 100 + (input[offset + 1] - '0') * 10 + (input[offset + 2] - '0');
				if(d >= 100 && d < 256){
					ipaddr[depth] = d;
					dfs(ans, input, offset + 3, length, ipaddr, depth + 1);
				}
			}
		}
	}

	public ArrayList<String> restoreIpAddresses(String s) {
        ArrayList<String> ans = new ArrayList<String>();
        dfs(ans, s.toCharArray(), 0, s.length(), new int[4], 0);
        return ans;
    }

	public static void main(String[] args){
		ArrayList<String> ans = new Solution().restoreIpAddresses("999101");
		for(String s : ans){
			System.err.println(s);
		}
	}
}

Add java solution for 93. Restore IP Addresses


package integration;

import com.codeborne.selenide.*;
import org.junit.Before;
import org.junit.Test;

import static com.codeborne.selenide.CollectionCondition.*;
import static com.codeborne.selenide.Condition.visible;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Selenide.$$;

public class LazyEvaluationTest extends IntegrationTest {

  static SelenideElement h1 = $("h1");
  static SelenideElement button = $("#double-clickable-button");

  static SelenideElement input1 = $$("input").first();
  static SelenideElement input2 = $$("input").last();
  static SelenideElement input3 = $$("input").get(1);

  static ElementsCollection inputs = $$("input").filterBy(visible);

  @Before
  public void openTestPageWithImages() {
    openFile("page_with_jquery.html");
  }

  @Test
  public void singleElementLazyFound() {
    h1.shouldBe(visible);
    button.click();
  }

  @Test
  public void collectionRelatedLazyOperations() {
    input1.shouldBe(visible);
    input2.shouldBe(visible);
    input3.shouldBe(visible);
    inputs.shouldHave(sizeGreaterThanOrEqual(1));
  }

}

Test for lazy evaluations is added (failing at the moment)


/*****************************************************************
JADE - Java Agent DEvelopment Framework is a framework to develop
multi-agent systems in compliance with the FIPA specifications.
Copyright (C) 2000 CSELT S.p.A.

The updating of this file to JADE 2.0 has been partially supported by the IST-1999-10211 LEAP Project

GNU Lesser General Public License

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

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

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 jade.domain.KBManagement;

/**
 * @author Elisabetta Cortese - TILab
 *
 */
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.KBManagement.*;

import java.util.Date;

public class DFLeaseManager implements LeaseManager{

	public Date getLeaseTime(Object item){
		if(item instanceof DFAgentDescription){
			return ((DFAgentDescription) item).getLeaseTime();
		}
		else{
			return DEFAULT_LEASE_TIME;
		}
	}

	public void setLeaseTime(Object item, Date lease){

		if(item instanceof DFAgentDescription){
			if(isValid(lease)){
				((DFAgentDescription) item).setLeaseTime(lease);
			}
			else{
				((DFAgentDescription) item).setLeaseTime(DEFAULT_LEASE_TIME);
			}
		}
	}

	public Object grantLeaseTime(Object item){
		// Always grant the requested lease time
		return item;
	}

	public boolean isValid(Date lease){

		if(lease.getTime() >= System.currentTimeMillis() || lease.getTime() == -1)
			return true;
		return false;
	}

}

Implement the lease manager for DF


package leetcode;

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

/**
 * https://leetcode.com/problems/lru-cache/
 */
public class Problem146 {
    public static class LRUCache {
        private final Map<Integer, Integer> map = new HashMap<>();
        private final LinkedList<Integer> list = new LinkedList<>();
        private final int capacity;

        public LRUCache(int capacity) {
            this.capacity = capacity;
        }

        public int get(int key) {
            if (map.containsKey(key)) {
                list.addLast(key);
                list.removeFirst();
            }
            return map.getOrDefault(key, -1);
        }

        public void set(int key, int value) {
            if (!map.containsKey(key)) {
                list.addLast(key);
            }
            map.put(key, value);
            if (map.size() -1 == capacity) {
                int removedKey = list.removeFirst();
                map.remove(removedKey);
            }
        }
    }

    public static void main(String[] args) {
        LRUCache lru = new LRUCache(2);
//        lru.set(2, 1);
//        lru.set(1, 1);
//        System.out.println(lru.get(2)); // 1
//        lru.set(4, 1);
//        System.out.println(lru.get(1)); // -1
//        System.out.println(lru.get(2)); // 1
//        lru.set(5, 1);
//        lru.set(6, 1);
//        System.out.println(lru.get(1)); // -1
//        System.out.println(lru.get(2)); // -1
//        System.out.println(lru.get(3)); // -1
//        System.out.println(lru.get(4)); // -1
//        System.out.println(lru.get(5)); // 1
//        System.out.println(lru.get(6)); // 1

        lru.set(2, 1);
        System.out.println("1. " + lru.map);
        System.out.println("1. " + lru.list);
        lru.set(1, 1);
        System.out.println("2. " + lru.map);
        System.out.println("2. " + lru.list);
        lru.set(2, 3);
        System.out.println("3. " + lru.map);
        System.out.println("3. " + lru.list);
        lru.set(4, 1);
        System.out.println("4. " + lru.map);
        System.out.println("4. " + lru.list);
        System.out.println(lru.get(1)); // -1
        System.out.println(lru.get(2)); // 3
        System.out.println("5. " + lru.map);
        System.out.println("5. " + lru.list);
    }
}

Create a skeleton for problem 146


/*
 * Copyright 2017 The Chromium Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
package io.flutter.actions;

import com.intellij.openapi.actionSystem.AnActionEvent;

public interface AnalyticAction {

  void actionPerformed(AnActionEvent e, String analyticId);
}

Define interface for actions to run with custom analytics


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

import com.github.pedrovgs.sortingalgorithm.SortingAlgorithm;

/**
 * Given an array full of integers implement a merge sort algorithm to sort the content inside
 * the array.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class MergeSort extends SortingAlgorithm {

  @Override public void sort(int[] numbers) {

  }
}

Add statement to problem 79


package guitests;

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

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

import seedu.malitio.commons.exceptions.DataConversionException;
import seedu.malitio.commons.util.ConfigUtil;
import seedu.malitio.model.Malitio;
import seedu.malitio.storage.StorageManager;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;

/**
 * Assumes storage and file utils are working
 *
 */
//@@author a0126633j
public class SaveCommandTest extends MalitioGuiTest {
    private static final String DEFAULT_FILE_NAME = "malitio.xml";
    private static final String TEST_FILE_PATH = "src/test/data/tempDataForSaveCommand/test1/";
    private static final String DEFAULT_FILE_PATH = "src/test/data/tempDataForSaveCommand/";

    // a storage manager to read data from xml file
    private StorageManager storageManager = new StorageManager("random", "random");

    private Malitio original = getInitialData();
    private String originalFilePath;

    @Before
    public void getOriginalFilePath() throws DataConversionException {
        originalFilePath = ConfigUtil.readConfig("./config.json/").get().getMalitioFilePath();
    }

    @Test
    public void save() throws DataConversionException, IOException {

    //save default file location
    commandBox.runCommand("save " + DEFAULT_FILE_PATH);
    assertSaveSuccessful(DEFAULT_FILE_PATH);

    //save in new file location
    commandBox.runCommand("save " + TEST_FILE_PATH);
    assertSaveSuccessful(TEST_FILE_PATH);
    assertFileDeletionSuccessful(DEFAULT_FILE_PATH);

    //save default file location again
    commandBox.runCommand("save " + DEFAULT_FILE_PATH);
    assertSaveSuccessful(DEFAULT_FILE_PATH);
    assertFileDeletionSuccessful(TEST_FILE_PATH);

    //orginal save file location should be preserved after the tests
    ConfigUtil.changeMalitioSaveDirectory(originalFilePath);
    }

    /**
     * Asserts new file is present and consistent with Malitio data
     * @throws DataConversionException
     * @throws IOException
     */
    public void assertSaveSuccessful(String newFileLocation) throws DataConversionException, IOException {
        File f = new File(newFileLocation + DEFAULT_FILE_NAME);
        if(f.exists()) {
            assertEquals(original, new Malitio(storageManager.readMalitio(newFileLocation + DEFAULT_FILE_NAME).get()));
        } else {
            assertTrue(false);
        }
    }

    /**
     * Asserts old file is successfully deleted
     */
    public void assertFileDeletionSuccessful(String oldFileLocation) {
        File f = new File(oldFileLocation + DEFAULT_FILE_NAME);
        assertFalse(f.exists());
    }
}

Add testing for save command


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

package com.google.gerrit.server;

import com.google.gerrit.client.Gerrit;
import com.google.gwtjsonrpc.client.CookieAccess;
import com.google.gwtjsonrpc.server.ActiveCall;
import com.google.gwtjsonrpc.server.JsonServlet;
import com.google.gwtjsonrpc.server.SignedToken;
import com.google.gwtjsonrpc.server.XsrfException;
import com.google.gwtorm.client.OrmException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

/**
 * Base JSON servlet to ensure the current user is not forged.
 */
public abstract class GerritJsonServlet extends JsonServlet {
  private GerritServer server;

  @Override
  public void init(final ServletConfig config) throws ServletException {
    super.init(config);

    try {
      server = GerritServer.getInstance();
    } catch (OrmException e) {
      throw new ServletException("Cannot configure GerritServer", e);
    } catch (XsrfException e) {
      throw new ServletException("Cannot configure GerritServer", e);
    }
  }

  @Override
  protected SignedToken createXsrfSignedToken() throws XsrfException {
    try {
      return GerritServer.getInstance().getXsrfToken();
    } catch (OrmException e) {
      throw new XsrfException("Cannot configure GerritServer", e);
    }
  }

  @Override
  protected abstract Object createServiceHandle() throws Exception;

  @Override
  protected String xsrfUser(final ActiveCall call) {
    final String idstr = CookieAccess.getTokenText(Gerrit.ACCOUNT_COOKIE);
    return idstr != null ? "account" + idstr : "anonymous";
  }

  @Override
  protected boolean xsrfValidate(final ActiveCall call) throws XsrfException {
    final String usertok = CookieAccess.get(Gerrit.ACCOUNT_COOKIE);
    if (usertok == null || server.getAccountToken().checkToken(usertok, null)) {
      return super.xsrfValidate(call);
    } else {
      LoginServlet.forceLogout(call.getHttpServletResponse());
      return false;
    }
  }
}

Define a base servlet for use within Gerrit RPC servers


package org.matthewjwhite.stata.util;

import com.stata.sfi.SFIToolkit;

public class Conversion {
	public static double real(boolean b) {
		return b ? 1.0 : 0.0;
	}

	public static String string(double x) {
		return SFIToolkit.formatValue(x, "%24.0g").trim();
	}

	public static String string(boolean b) {
		return string(real(b));
	}
}

Add class for converting to Stata values


package com.christofferklang.pyxl;

import com.intellij.psi.tree.TokenSet;
import com.jetbrains.python.PythonDialectsTokenSetContributor;
import com.jetbrains.python.PythonTokenSetContributor;
import org.jetbrains.annotations.NotNull;

public class PyxlTokenSetContributor extends PythonTokenSetContributor {
    @NotNull
    @Override
    public TokenSet getExpressionTokens() {
        return TokenSet.orSet(super.getExpressionTokens(), TokenSet.create(PyxlElementTypes.PYXL_TAG_REFERENCE));
    }
}

Add PYXL_TAG_REFERENCE as a reference token


package com.librato.metrics;

import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import junit.framework.TestCase;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;

import java.io.IOException;
import java.util.SortedMap;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

public class LibratoReporterTest extends TestCase {

    class FailingRegistry extends MetricRegistry {
        AtomicInteger timesAttempted = new AtomicInteger();

        @Override
        public SortedMap<String, Gauge> getGauges(MetricFilter filter) {
            timesAttempted.addAndGet(1);
            throw new RuntimeException("test-exception");
        }
    }

    public void testIsResilientToExceptionsInReport() throws Exception {
        FailingRegistry registry = new FailingRegistry();
        HttpPoster poster = new HttpPoster() {
            public Future<Response> post(String userAgent, String payload) throws IOException {
                return null;
            }
        };
        LibratoReporter reporter = LibratoReporter.builder(registry, "test-username", "test-token", "test-source")
                .setHttpPoster(poster)
                .build();
        // assert that it doesn't throw an exception
        reporter.report();
        // verify the failure occurred
        Assert.assertThat(registry.timesAttempted.get(), CoreMatchers.equalTo(1));
    }
}

Test case for librato-reporter not failing from report


package ca.ualberta.lard.model;

/**
 * A CommentRequest is a structure that aids in the retrieving of comments. It unifies the arguments passed around, by being a single structure
 * in which the client can say any number of things they expect of the comment they want. All parameters are optional, and if any of them are set
 * it is assumed the user is requesting Comments relevant to that parameter.
 * @author Troy Pavlek
 *
 */
public class CommentRequest {

	/**
	 * The most important parameter. If the CommentRequest contains an ID, then the user is searching for a specific, single comment.
	 */
	private String id;
	/**
	 * If the location property is set, Comments nearest this location will be returned over those further from this location.
	 */
	private GeoLocation location;
	/**
	 * Do we only want to search threads, or are replies acceptable also?
	 */
	private boolean topLevel;
	/**
	 * Do we only want comments with pictures?
	 */
	private boolean hasPicture;
	/**
	 * The number of results we want returned
	 */
	private int resultSize;

	/**
	 * Instantiates the Comment Request
	 * <p>
	 * All the constructor does is instantiates the object with our expected return size. The user should be setting the remainder of the parameters of the
	 * CommentRequest with the available setters.
	 * </p>
	 * @param num The number of results we want. We may get less, but we will never get more.
	 */
	public CommentRequest(int num) {
		this.resultSize = num;
	}

	public void setId(String id) {
		this.id = id;
	}

	public void setLocation(GeoLocation loc) {
		this.location = loc;
	}

	public void onlyThreads() {
		this.topLevel = true;
	}

	public void onlyReplies() {
		this.topLevel = false;
	}

	public void withPictures() {
		this.hasPicture = true;
	}

	public void withoutPictures() {
		this.hasPicture = false;
	}

}

Comment request created. No tests created, because it has literally zero logic. It's a glorified struct


package google.main;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class MessageBuilderTest {

	@Test
	public void testBuilderWithNull() {
		String expected = "Dla zapytania 'foo' Google niczego nie znalazło.";
		String actual = new MessageBuilder().withQuery("foo").withNumberOfResults(null).build();
		assertEquals(expected, actual);
	}

	@Test
	public void testBuilderWithZero() {
		String expected = "Dla zapytania 'foo' Google niczego nie znalazło.";
		String actual = new MessageBuilder().withQuery("foo").withNumberOfResults(0L).build();
		assertEquals(expected, actual);
	}

	@Test
	public void testBuilderWithoutFormatting() {
		String expected = "Dla zapytania 'foo' Google znalazło ok. 700 wyników.";
		String actual = new MessageBuilder().withQuery("foo").withNumberOfResults(700L).build();
		assertEquals(expected, actual);
	}

	@Test
	public void testBuilderWithFormatting() {
		String number = String.format("%,d", 50_000L);
		String expected = String.format("Dla zapytania 'foo' Google znalazło ok. %s wyników.",
				number);
		String actual = new MessageBuilder().withQuery("foo").withNumberOfResults(50_000L).build();
		assertEquals(expected, actual);
	}

}

Add JUnit tests for MessageBuilder.


package com.greenyetilab;

import com.greenyetilab.utils.log.NLog;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

/**
 * Various file utilities
 */
public class FileUtils {
    public static String readUtf8(final InputStream in) throws IOException {
        InputStreamReader reader = new InputStreamReader(in, "UTF-8");
        StringBuilder sb = new StringBuilder();
        char[] buffer = new char[1024];
        while (true) {
            int length = reader.read(buffer);
            if (length == -1) {
                break;
            }
            sb.append(buffer);
        }
        return sb.toString();
    }

    public static void writeUtf8(final OutputStream out, String text) throws IOException {
        byte[] buffer = text.getBytes("UTF-8");
        out.write(buffer);
        out.flush();
    }
}

Add utils to read and write strings from/to files


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

package com.legendzero.lzlib.util;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class Lambdas {

    public static boolean isNull(Object object) {
        return object == null;
    }

    public static boolean notNull(Object object) {
        return object != null;
    }

    public static <T extends Comparable<T>> boolean greaterThan(T object1, T object2) {
        return object1.compareTo(object2) > 0;
    }

    public static <T extends Comparable<T>> boolean lessThan(T object1, T object2) {
        return object1.compareTo(object2) < 0;
    }

    public static <T extends Comparable<T>> boolean greaterThanOrEqual(T object1, T object2) {
        return object1.compareTo(object2) >= 0;
    }

    public static <T extends Comparable<T>> boolean lessThanOrEqual(T object1, T object2) {
        return object1.compareTo(object2) <= 0;
    }
}

Add some common lambda conditions


/*
 *  Copyright 2004-2006 Stefan Reuter
 *
 *  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.asteriskjava.manager.action;

import org.asteriskjava.manager.action.AbstractManagerAction;

/**
 * LocalOptimizeAway action -- Optimize away a local channel when possible.
 *

 * Available since Asterisk 1.8
 *
 * @author SYON Communications Inc.
 */
public class LocalOptimizeAwayAction extends AbstractManagerAction
{
    /**
     * Serializable version identifier.
     */
    private static final long serialVersionUID = 1L;
    private String channel;

    /**
     * Creates a new empty LocalOptimizeAwayAction.
     */
    public LocalOptimizeAwayAction()
    {

    }

    /**
     * Creates a new LocalOptimizeAwayAction with channel name.
     *
     * @param channel Name of the channel for clears the flag.
     */
    public LocalOptimizeAwayAction(String channel)
    {
	this.channel = channel;
    }

    /**
     * Returns the name of this action, i.e. "LocalOptimizeAway".
     */
    @Override
    public String getAction()
    {
	return "LocalOptimizeAway";
    }

    /**
     * Sets the name of the channel.
     *
     * @return Name of the channel for clears the flag.
     */
    public String getChannel()
    {
	return channel;
    }

    /**
     * Returns the name of tha channel.
     *
     * @param channel Name of the channel for clears the flag.
     */
    public void setChannel(String channel)
    {
	this.channel = channel;
    }

}

Add support for LocalOptimizeAway action.


package com.amalgam.content;

/**
 */
public final class ContentProviderUtils {
    private static final String PLURAL_MIME_TYPE = "vnd.android.cursor.dir";
    private static final String SINGULAR_MIME_TYPE = "vnd.android.cursor.item";
    private ContentProviderUtils() {}

    public static final String buildPluralMimeType(String subType) {
        return PLURAL_MIME_TYPE + "/" + subType;
    }

    public static final String buildSingularMimeType(String subType) {
        return SINGULAR_MIME_TYPE + "/" + subType;
    }
}

Add utility for content provider


package tk.wlemuel.cotable.activity.blog.view;

import java.lang.ref.WeakReference;

import tk.wlemuel.cotable.activity.common.SimpleBackActivity;
import tk.wlemuel.cotable.base.BaseFragment;

/**
 * DetailActivity
 *
 * @author Steve Lemuel
 * @version 0.1
 * @desc DetailActivity
 * @created 2015/05/11
 * @updated 2015/05/11
 */
public class DetailActivity extends SimpleBackActivity {

    public static final int DISPLAY_BLOG = 0;
    public static final int DIESPLAY_NEWS = 1;
    public static final String BUNDLE_KEY_DISPLAY_TYPE = "BUNDLE_KEY_DISPLAY_TYPE";

    private WeakReference<BaseFragment> mFragment;

}

Add Detail Activity for display the blog or news details


package com.stefanhoth.ropasclisp.achievements;

import android.content.Context;
import android.support.annotation.StringRes;

import com.stefanhoth.ropasclisp.R;

public enum LEADERBOARD {

    PLAYED_GAMES(R.string.leaderboard_playedgames),
    WON_IN_A_ROW(R.string.leaderboard_wongamesinarow);

    private final int leaderboardId;

    LEADERBOARD(@StringRes int leaderboardId) {
        this.leaderboardId = leaderboardId;
    }

    public String getLeaderboardId(final Context context) {
        return context.getString(leaderboardId);
    }

}

Introduce Leaderboard class for holding internal ids


/*
 * #%L
 * ImageJ server for RESTful access to ImageJ.
 * %%
 * Copyright (C) 2013 - 2016 Board of Regents of the University of
 * Wisconsin-Madison.
 * %%
 * 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.
 * #L%
 */

package net.imagej.server.console;

import java.util.LinkedList;

import net.imagej.server.ImageJServer;
import net.imagej.server.ImageJServerService;

import org.scijava.console.AbstractConsoleArgument;
import org.scijava.console.ConsoleArgument;
import org.scijava.object.ObjectService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

/**
 * Handles the {@code --server} argument to signal that an ImageJ Server
 * should be started immediately when ImageJ launches.
 *
 * @author Curtis Rueden
 */
@Plugin(type = ConsoleArgument.class)
public class ServerArgument extends AbstractConsoleArgument {

	@Parameter(required = false)
	private ImageJServerService imagejServerService;

	@Parameter(required = false)
	private ObjectService objectService;

	// -- Constructor --

	public ServerArgument() {
		super(1, "--server");
	}

	// -- ConsoleArgument methods --

	@Override
	public void handle(final LinkedList<String> args) {
		if (!supports(args)) return;

		args.removeFirst(); // --server

		final ImageJServer server = imagejServerService.start();
		objectService.addObject(server);
	}
	// -- Typed methods --

	@Override
	public boolean supports(final LinkedList<String> args) {
		return imagejServerService != null && objectService != null &&
			super.supports(args);
	}
}

Add --server command line flag


/*
 * Copyright 2020 Martin Winandy
 *
 * 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.tinylog.core.formatters;

/**
 * Message formatter can replace placeholders with real values in strings.
 */
public interface MessageFormatter {

	/**
	 * Replaces all placeholders with real values.
	 *
	 * @param message
	 *            Text message with placeholders
	 * @param arguments
	 *            Replacements for placeholders
	 * @return Formatted text message
	 */
	String format(String message, Object[] arguments);

}

Add interface for message formatters


package myservlet;
import org.junit.*;
import org.amc.servlet.model.*;
import static org.junit.Assert.*;

public class TestMouldClosingData
{
	@Test
	public void testGetMouldClosingTimeData()
	{
		int i=0;
		while(i<1000)
		{
			MouldingProcess p=new MouldingProcess();
			float openlimit=420f;
			float mouldClosingLimitPos=openlimit-(20*(float)Math.random());
			float mouldClosedLimitPos=mouldClosingLimitPos-(200*(float)Math.random());
			float clsSlowPos=mouldClosedLimitPos-(100*(float)Math.random());
			float clsSPPos=clsSlowPos-(clsSlowPos*(float)Math.random());
			p.setMouldClosingOpenLimitPos(mouldClosingLimitPos);
			p.setMouldClosedLimitPos(mouldClosedLimitPos);
			p.setClsSlowPos(clsSlowPos);
			p.setClsSPPos(clsSPPos);

			float mouldClosingOpenLimitSpeed=420*(float)Math.random();
			float mouldClosedLimitSpeed=420*(float)Math.random();
			float clsSPSpeed=100*(float)Math.random();

			p.setMouldClosingOpenLimitSpeed(mouldClosingOpenLimitSpeed);
			p.setMouldClosedLimitSpeed(mouldClosedLimitSpeed);
			p.setClsSPSpeed(clsSPSpeed);

			float[][] data=MouldingProcessUtil.getMouldClosingTimeData(p);
			float result=0f;
			System.out.printf("Expected:%f + %f + %f + %f = %f%n",mouldClosingLimitPos-mouldClosedLimitPos,mouldClosedLimitPos-clsSlowPos,clsSlowPos-clsSPPos,clsSPPos,(mouldClosingLimitPos-mouldClosedLimitPos)+(mouldClosedLimitPos-clsSlowPos)+(clsSlowPos-clsSPPos)+(clsSPPos));
			System.out.print("Actual:");
			for(float[] t:data)
			{
				result+=t[1];
				System.out.printf("%f +",t[1]);
			}
			System.out.printf("=%f%n", result);
			System.out.printf("(%d)Expected:%f,Actual:%f%n",i,mouldClosingLimitPos,result);
			assertEquals(mouldClosingLimitPos,result,0.01);
			i++;
		}
	}

}

Create test case for MouldOpening Chart


/*
 * Java Genetic Algorithm Library (@__identifier__@).
 * Copyright (c) @__year__@ Franz Wilhelmstötter
 *
 * 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
 *
 * Author:
 *     Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
 *
 */
package org.jenetics.util;

/**
 * This implementation is not thread-safe.
 *
 *
 * @author Franz Wilhelmstötter
 * @since 1.1
 * @version 1.1 — $Date: 2012-11-16 $
 */
public class HQ64Random {

}

Implement PRNG recommended by 'Numerical Recipes'.


package com.haxademic.core.ui;

import com.haxademic.core.app.P;
import com.haxademic.core.debug.DebugUtil;

import processing.event.KeyEvent;

public class CursorToggle {

	protected boolean isHidden;

	public CursorToggle(boolean defaultHidden) {
		if(P.p == null) DebugUtil.printErr("===========\n Please wait until setup() to init CursorToggle \n===========");
		isHidden = defaultHidden;
		P.p.registerMethod("keyEvent", this);
	}

	public void keyEvent(KeyEvent e) {
		if(e.getKey() == 'm') isHidden = !isHidden;
		if(isHidden == true) {
			P.p.noCursor();
		} else {
			P.p.cursor();
		}
	}

}

Add cursor toggle key listener object


package leetcode.ugly_number_ii;

public class Solution {
    public int nthUglyNumber(int n) {
        int[] ugly = new int[1691];
        int ug_2 = 0, ug_3 = 0, ug_5 = 0;
        ugly[0] = 1;
        for(int i = 1; i < 1691; i++){
            int nxt = Math.min(ugly[ug_2] * 2, Math.min(ugly[ug_3] * 3, ugly[ug_5] * 5));
            ugly[i] = nxt;
            if(nxt == ugly[ug_2] * 2) ug_2++;
            if(nxt == ugly[ug_3] * 3) ug_3++;
            if(nxt == ugly[ug_5] * 5) ug_5++;
        }
        return ugly[n - 1];
    }
}

Add java solution for 264. Ugly Number II


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

import java.util.ServiceLoader;

/**
 * @author David BRASSELY (david at gravitee.io)
 * @author GraviteeSource Team
 */
public final class ServiceLoaderHelper {

    public static <T> T loadFactory(Class<T> clazz) {
        ServiceLoader<T> factories = ServiceLoader.load(clazz);
        if (factories.iterator().hasNext()) {
            return factories.iterator().next();
        } else {
            factories = ServiceLoader.load(clazz, ServiceLoaderHelper.class.getClassLoader());
            if (factories.iterator().hasNext()) {
                return factories.iterator().next();
            } else {
                throw new IllegalStateException("Cannot find META-INF/services/" + clazz.getName() + " on classpath");
            }
        }
    }
}

Add a service loader helper


package net.imagej.ops.viewOp;

import org.scijava.plugin.Plugin;

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

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

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

Add default implementation of ExtendPeriodic interface.


import java.net.*;
import java.io.*;
import java.net.URLEncoder;

public class ServletTest {
  public static void main(String[] args) throws Exception {
	String param = "Hopefully this is a successful testing of language translation POC";
	System.out.println(URLEncoder.encode(param, "UTF-8"));
    URL yahoo = new URL("https://clarkjavaliberty.mybluemix.net/SimpleServlet?content=" + URLEncoder.encode(param, "UTF-8"));
    URLConnection yc = yahoo.openConnection();
    //BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()), "UTF-8");
	InputStreamReader isr = new InputStreamReader(yc.getInputStream(), "UTF-8");
	BufferedReader in = new BufferedReader(isr);
    String inputLine;
    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);
    in.close();
  }
}

Include java file to invoke SimpleServlet


package com.splunk.shep.customsearch;

import java.net.URI;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

public class HDFSCat {

    public static void main(String args[]) {
	try {
	    Configuration conf = new Configuration();
	    URI fileuri = URI.create(args[0]);
	    String host = fileuri.getHost();
	    int port = fileuri.getPort();
	    FileSystem fs = FileSystem.get(
		    URI.create("hdfs://" + host + ":" + port), conf);
	    Path filenamePath = new Path(args[0]);
	    if (!fs.exists(filenamePath)) {
		System.exit(1);
	    }
	    FSDataInputStream in = fs.open(filenamePath);
	    while (true) {
		String line = in.readLine();
		if (line == null) {
		    break;
		}
		System.out.println(line);
	    }
	    in.close();
	} catch (Exception e) {
	    e.printStackTrace();
	    System.exit(2);
	}
	System.exit(0);
    }
}

Use to cat an HDFS file


package com.github.aureliano.edocs.app.gui.menu;

import javax.swing.JMenuItem;

public class CloseAllTabsMenuItem extends JMenuItem {

	private static final long serialVersionUID = 5402503871207802801L;

	public CloseAllTabsMenuItem() {
		super.setText("Close all");
	}
}

Create close all tabs menu item.


package nanomsg;

import java.lang.Runnable;
import nanomsg.NativeLibrary;

public class Device implements Runnable {
    private final int sourceSocket;
    private final int destSocket;

    public Device(final int sourceSocket, final int destSocket) {
        this.sourceSocket = sourceSocket;
        this.destSocket = destSocket;
    }

    public void run() {
        NativeLibrary.nn_device(sourceSocket, destSocket);
    }
}

Add device support to java bindings.


// ========================================================================
// Copyright 2011 NEXCOM Systems
// ------------------------------------------------------------------------
// 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.cipango.plus.sipapp;

import javax.servlet.sip.SipErrorEvent;
import javax.servlet.sip.SipErrorListener;

public class Listener implements SipErrorListener
{

	public void noAckReceived(SipErrorEvent arg0)
	{
	}

	public void noPrackReceived(SipErrorEvent arg0)
	{
	}

}

Fix CIPANGO-139: cipango-plus is broken


package me.haosdent.cgroup.util;

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

public class TestShell {

  @Before
  public void setUp() {}

  @After
  public void tearDown() {}

  @Test
  public void testExec() {}

  @Test
  public void testMount() {}

  @Test
  public void testUmount() {}
}

Add shell util test class.


package de.timroes.axmlrpc.serializer;

import static org.junit.Assert.*;

import java.util.Date;

import org.junit.Test;

import de.timroes.axmlrpc.xmlcreator.XmlElement;

public class TestSerializers {

	@Test
	public void canSerializeBase64(){
		assertExpectedSerialized("<base64>AQIDBA==</base64>", new Base64Serializer().serialize(new Byte[]{1, 2, 3, 4}));
	}

	@Test
	public void canSerializeBoolean(){
		assertExpectedSerialized("<boolean>1</boolean>", new BooleanSerializer().serialize(true));
		assertExpectedSerialized("<boolean>0</boolean>", new BooleanSerializer().serialize(false));
	}

	@Test
	public void canSerializeDouble(){
		assertExpectedSerialized("<double>3.2</double>", new DoubleSerializer().serialize(3.2));
	}

	@Test
	public void canSerializeDate(){
		assertExpectedSerialized("<dateTime.iso8601>19850503T122334</dateTime.iso8601>",
				new DateTimeSerializer().serialize(new Date(85, 4, 3, 12, 23, 34)));
	}

	@Test
	public void canSerializeInt(){
		assertExpectedSerialized("<int>4</int>", new IntSerializer().serialize(4));
	}

	@Test
	public void canSerializeLong(){
		assertExpectedSerialized("<i8>1234</i8>", new LongSerializer().serialize(1234L));
	}

	@Test
	public void canSerializeNullElement(){
		assertExpectedSerialized("<nil/>", new NullSerializer().serialize(null));
	}

	@Test
	public void canSerializeString(){
		boolean encodeString = true;
		assertExpectedSerialized("<string>te<&>st</string>", new StringSerializer(encodeString, true).serialize("te<&>st"));

		encodeString = false;
		assertExpectedSerialized("<string>te<&>st</string>", new StringSerializer(encodeString, true).serialize("te<&>st"));
	}

	private static void assertExpectedSerialized(String expected, XmlElement actual){
		assertEquals(expected, actual.toString().trim());
	}
}

Add some unit tests on serializers


/*
 Copyright (C) 2003 EBI, GRL

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

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

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

import java.sql.Connection;

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

/**
 * Check that the gene_stable_id table is populated in EST databases.
 */

public class ESTStableIDs extends SingleDatabaseTestCase {

    /**
     * Create a new ESTStableIDs testcase.
     */
    public ESTStableIDs() {

        addToGroup("post_genebuild");
        addToGroup("release");
        setDescription("Check the gene_stable_id table is populated in EST databases.");

    }

    /**
     * This only applies to EST databases.
     */
    public void types() {

        removeAppliesToType(DatabaseType.CORE);
        removeAppliesToType(DatabaseType.VEGA);

    }

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

        boolean result = true;

	Connection con = dbre.getConnection();

	int rows = getRowCount(con, "SELECT COUNT(*) FROM gene_stable_id");

	if (rows == 0) {
	    ReportManager.problem(this, con, "gene_stable_id is empty");
	    return false;
	} else {
	    ReportManager.correct(this, con, "gene_stable_id has " + rows + " rows");
	}

        return result;

    } // run

} // ESTStableIDs

Check that the gene_stable_id table is populated in EST databases (needs to be a separate healthcheck from StableIDs since this is required at a different point in the release process).


/*
 * Copyright 2019, TeamDev. 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 io.spine.validate.diags;

import com.google.common.collect.ImmutableList;
import com.google.common.testing.NullPointerTester;
import com.google.common.truth.StringSubject;
import com.google.protobuf.Timestamp;
import io.spine.base.FieldPath;
import io.spine.base.FieldPaths;
import io.spine.type.TypeName;
import io.spine.validate.ConstraintViolation;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

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

@DisplayName("ViolationText should")
class ViolationTextTest {

    @Test
    @DisplayName("not accept null violations")
    void nullTolerance() {
        new NullPointerTester()
                .testAllPublicStaticMethods(ViolationText.class);
    }

    @Test
    @DisplayName("include type info in the violation text")
    void includeType() {
        TypeName type = TypeName.of(Timestamp.class);
        ConstraintViolation violation = ConstraintViolation
                .newBuilder()
                .setTypeName(type.value())
                .build();
        ViolationText text = ViolationText.of(violation);
        assertThat(text.toString()).contains(type.value());
    }

    @Test
    @DisplayName("include field info in the violation text")
    void includeField() {
        FieldPath field = FieldPaths.parse("msg.foo.bar");
        ConstraintViolation violation = ConstraintViolation
                .newBuilder()
                .setFieldPath(field)
                .build();
        ViolationText text = ViolationText.of(violation);
        assertThat(text.toString()).contains(FieldPaths.toString(field));
    }

    @Test
    @DisplayName("compile tests for many violations into one")
    void compileManyTexts() {
        ConstraintViolation first = ConstraintViolation
                .newBuilder()
                .setMsgFormat("Errored with a message")
                .build();
        ConstraintViolation second = ConstraintViolation
                .newBuilder()
                .setMsgFormat("Messaged with an error")
                .build();
        String text = ViolationText.ofAll(ImmutableList.of(first, second));
        StringSubject assertText = assertThat(text);
        assertText.contains(ViolationText.of(first).toString());
        assertText.contains(ViolationText.of(second).toString());
    }
}

Add a test for ViolationText.


package to.etc.function;

/**
 * @author Frits Jalvingh
 * Created on 26-1-19.
 */
@FunctionalInterface
public interface RunnableEx {
	void run() throws Exception;
}

Convert all of the HubServer packets so far to protobufs, and implement core message response structures.