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

import java.util.LinkedList;

import org.scijava.Gateway;
import org.scijava.console.AbstractConsoleArgument;
import org.scijava.console.ConsoleArgument;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.ui.UIService;

/**
 * Handles the {@code --showUI} argument, which signals that the UI should be
 * opened immediately.
 *

 * This is useful for specifying later command line arguments to be handled
 * after the UI is shown, since normally, all arguments are processed
 * before showing the UI.
 *

 *
 * @author Curtis Rueden
 * @see Gateway#launch(String[])
 */
@Plugin(type = ConsoleArgument.class)
public class ShowUIArgument extends AbstractConsoleArgument {

	@Parameter(required = false)
	private UIService uiService;

	// -- Constructor --

	public ShowUIArgument() {
		super(1, "--showUI");
	}

	// -- ConsoleArgument methods --

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

		args.removeFirst(); // --showUI

		uiService.showUI();
	}
	// -- Typed methods --

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

}

Add the --showUI console argument


package tachyon.master;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.junit.Test;

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

/**
 * Unit Test for EditLogOperation
 */
public class EditLogOperationTest {
  private static final String CREATE_DEPENDENCY_TYPE = "{\"type\":\"CREATE_DEPENDENCY\"," +
      "\"parameters\":{\"parents\":[],\"commandPrefix\":\"fake command\"," +
      "\"dependencyId\":1,\"frameworkVersion\":\"0.3\",\"data\":[\"AAAAAAAAAAAAAA==\"]," +
      "\"children\":[251,252,253,254,255,256,257,258,259,260]," +
      "\"comment\":\"BasicCheckpoint Dependency\",\"creationTimeMs\":1409349750338," +
      "\"dependencyType\":\"Narrow\",\"framework\":\"Tachyon Examples\"}}";

  private static final ObjectMapper OBJECT_MAPPER = JsonObject.createObjectMapper();

  // Tests for CREATE_DEPENDENCY operation
  @Test
  public void createDependencyTest() throws IOException {
    EditLogOperation editLogOperation = OBJECT_MAPPER.readValue(CREATE_DEPENDENCY_TYPE.getBytes(),
        EditLogOperation.class);

    // get all parameters for "CREATE_DEPENDENCY"
    editLogOperation.get("parents", new TypeReference<List<Integer>>() {});
    editLogOperation.get("children", new TypeReference<List<Integer>>() {});
    editLogOperation.getString("commandPrefix");
    editLogOperation.getByteBufferList("data");
    editLogOperation.getString("comment");
    editLogOperation.getString("framework");
    editLogOperation.getString("frameworkVersion");
    editLogOperation.get("dependencyType", DependencyType.class);
    editLogOperation.getInt("dependencyId");
    editLogOperation.getLong("creationTimeMs");
  }

}

Add unit test for EditLogOperation. For now adding just for CREATE_DEPENDENCY.


package org.realityforge.arez;

import javax.annotation.Nonnull;

/**
 * Interface for receiving spy events.
 */
@FunctionalInterface
public interface SpyEventHandler
{
  /**
   * Report an event in the Arez system.
   *
   * @param event the event that occurred.
   */
  void onSpyEvent( @Nonnull Object event );
}

Define interface for "spy" that can be used to receive notifications on different events within an Arez system


package leetcode.find_the_duplicate_number;

public class Solution {
    public int findDuplicate(int[] nums) {
        int tortoise = 0, hare = 0;
        while(true){
        	tortoise = nums[tortoise];
        	hare = nums[nums[hare]];
        	if(tortoise == hare)
        		break;
        }
        int find = 0;
        while(find != tortoise){
        	find = nums[find];
        	tortoise = nums[tortoise];
        }
        return find;
    }
}

Add solution for 287. Find the Duplicate Number


/*
 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.testcase.Priority;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;

/**
 *
 */

public class GeneDescriptions extends SingleDatabaseTestCase {

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

		addToGroup("post_genebuild");
		addToGroup("release");
		addToGroup("core_xrefs");
		setDescription("Check gene descriptions; correct capitalisation of UniprotKB/SwissProt");
		setPriority(Priority.AMBER);
		setEffect("Capitalisation of Uniprot will be wrong in gene descriptions.");
		setFix("Re-run xref system or manually fix affected xrefs.");

	}

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

		boolean result = true;

		result &= checkSwissprot(dbre);

		return result;

	} // run

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

	private boolean checkSwissprot(DatabaseRegistryEntry dbre) {

		boolean result = true;

		Connection con = dbre.getConnection();

		int rows = getRowCount(con, "SELECT COUNT(*) FROM gene WHERE description like '%Uniprot/SWISSPROT%'");

		if (rows > 0) {
			ReportManager.problem(this, con, rows + " descriptions have incorrect spelling/capitalisation of Uniprot attribution");
			result = false;
		} else {
			ReportManager.correct(this, con, "All Uniprot attributions correct.");
		}

		return result;

	}
} // GeneDescriptions

Check for incorrect spelling of UniprotKB/SWISSPROT in gene descriptions.


/**
 * This class is the graph class for each cell having eight neighbors, which
 * includes each adjacent neighbor and each diagonally adjacent neighbor.
 *
 * @author Jeremy, Team 12
 *
 */
public class EightNeighborSquareGraph extends SquareGraph {

	public EightNeighborSquareGraph(int numCellsWidth, int numCellsHeight,
			int screenWidth, int screenHeight, int points) {
		super(numCellsWidth, numCellsHeight, screenWidth, screenHeight, points);
	}

	public boolean isNeighbors(Cell first, Cell second) {
		return first.getID() == second.getID() - 1
				&& first.getID() % getNumCellsAcross() != 0
				|| first.getID() == second.getID() - getNumCellsAcross()
				|| first.getID() == second.getID() - getNumCellsAcross() - 1
				&& (second.getID() - 1) % getNumCellsAcross() != 0
				|| first.getID() == second.getID() - getNumCellsAcross() + 1
				&& second.getID() % getNumCellsAcross() != 0;
	}
}

Add verticies to Cells, rewrite connectCells method to use shared verticies


/**
 * Given a binary tree, return the inorder traversal of its nodes' values.
 */

/** Iterative version **/
public List<Integer> inorderTraversal(TreeNode root) {
  Stack<TreeNode> stack = new Stack<>();
  HashSet<TreeNode> set = new HashSet<>();
  List<Integer> list = new ArrayList<>();
  stack.push(root);
  set.add(root);
  if (root == null) return list;

  while (!stack.isEmpty()) {
    TreeNode node = stack.pop();
    if (node == null) {
      continue;
    }

    TreeNode left = node.left;
    TreeNode right = node.right;
    boolean hasLeft = false;
    if (left != null && !set.contains(left)) {
      // Push the current node back into the stack because if left exists then
      // it will not be added in this current iteration
      stack.push(node);
      hasLeft = true;
    }

    while (left != null) {
      if (!set.contains(left)) {
        stack.push(left);
        set.add(left);
      }
      left = left.left;
    }

    if (hasLeft) {
      // We have to stop the current iteration to add all the left nodes first.
      continue;
    }

    list.add(node.val);

    if (node.right != null) {
      stack.push(node.right);
    }
  }

  return list;
}

Add binary in order traversal iteratively


package leetcode.unique_binary_search_trees_ii;

import java.util.ArrayList;

import common.TreeNode;

public class Solution {
	public ArrayList<TreeNode> generateTrees(int n) {
		return generateTrees(1, n);
	}

	public ArrayList<TreeNode> generateTrees(int from, int to){
		if(from > to){
			ArrayList<TreeNode> ret = new ArrayList<TreeNode>();
			ret.add(null);
			return ret;
		}
		ArrayList<TreeNode> ret = new ArrayList<TreeNode>();
		for(int i = from; i <= to; i++){
			int r = i;

			ArrayList<TreeNode> left = generateTrees(from, r - 1);
			ArrayList<TreeNode> right = generateTrees(r + 1, to);
			for(TreeNode ltn : left){
				for(TreeNode rtn : right){
					TreeNode root = new TreeNode(i);
					root.left = ltn;
					root.right = rtn;
					ret.add(root);
				}
			}
		}
		return ret;
	}

	public void bfs(TreeNode node){
		final int N = 100;
		TreeNode[] queue = new TreeNode[N];
		int head = 0, tail = 0;
		queue[head++] = node;
		while(head != tail){
			TreeNode cur = queue[tail];
			tail = (tail + 1) % N;
			String v;
			if(cur == null) v = "#";
			else v = "" + cur.val;
			System.err.print(v + ", ");
			if(cur != null){
				queue[head] = cur.left;
				head = (head + 1) % N;
				queue[head] = cur.right;
				head = (head + 1) % N;
			}
		}
		System.err.println("");
	}

	public static void main(String[] args){
		Solution sol = new Solution();
		for(TreeNode tn : sol.generateTrees(3)){
			sol.bfs(tn);
		}
	}
}

Add java solution for 95. Unique Binary Search Trees II


/*
 * Copyright (c) 2014 Santiago M. Mola <santi@mola.io>
 *
 *   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 io.mola.galimatias.cli;

import io.mola.galimatias.GalimatiasParseException;
import io.mola.galimatias.TestURL3;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;

@RunWith(Theories.class)
public class CLITest {

    @Theory
    public void parse_no_exceptions(final @TestURL3.TestURLs(dataset = TestURL3.DATASETS.WHATWG)
                                     TestURL3 testURL) throws GalimatiasParseException {
        CLI.main(new String[]{ testURL.rawURL });
    }

}

Add basic test for CLI.


package nl.github.martijn9612.fishy;

import java.awt.Dimension;
import java.awt.Rectangle;

import org.junit.Test;

import junit.framework.Assert;

public class TestObject {

	public static final int X_VALUE = 10;
	public static final int Y_VALUE = 100;
	public static final int WIDTH = 19;
	public static final int HEIGHT = 76;

	@Test
	public void testSetPosition() {
		Object obj = new Object();
		obj.setPosition(X_VALUE, Y_VALUE);
		Assert.assertEquals(X_VALUE, obj.getX());
		Assert.assertEquals(Y_VALUE, obj.getY());
	}

	@Test
	public void testSetDimensions() {
		Object obj = new Object();
		obj.setDimensions(WIDTH, HEIGHT);
		Assert.assertEquals(WIDTH, obj.getWidth());
		Assert.assertEquals(HEIGHT, obj.getHeight());
	}

	@Test
	public void testCreateRectangle() {
		Object obj = new Object();
		obj.setPosition(X_VALUE, Y_VALUE);
		obj.setDimensions(WIDTH, HEIGHT);
		obj.createRectangle();
		Assert.assertTrue(obj.objectRect instanceof Rectangle);
		Dimension dim = obj.objectRect.getSize();
		Assert.assertEquals((int) dim.getWidth(), WIDTH);
		Assert.assertEquals((int) dim.getHeight(), HEIGHT);
	}

}

Add test case for the Object class


/*
 * Copyright 2016 The Board of Trustees of The Leland Stanford Junior University.
 *
 * 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.susom.database;

/**
 * Indicates that a configuration value is present but not in a usable format.
 * For example, if the value must be an integer and the configuration value
 * is a non-numeric string.
 *
 * @author garricko
 */
public class ConfigInvalidException extends DatabaseException {
  public ConfigInvalidException(String message) {
    super(message);
  }

  public ConfigInvalidException(Throwable cause) {
    super(cause);
  }

  public ConfigInvalidException(String message, Throwable cause) {
    super(message, cause);
  }
}

Add an exception type for bad configuration values


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

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

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

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

  private PalindromeList palindromeList;

  @Before public void setUp() {
    palindromeList = new PalindromeList();
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldNotAcceptNullListAsInputReversing() {
    palindromeList.checkReversing(null);
  }

  @Test public void shouldReturnTrueIfListContainsJustOneNodeReversing() {
    ListNode<Integer> list = new ListNode<Integer>(1);

    boolean result = palindromeList.checkReversing(list);

    assertTrue(result);
  }

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

    boolean result = palindromeList.checkReversing(list);

    assertTrue(result);
  }

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

    boolean result = palindromeList.checkReversing(list);

    assertTrue(result);
  }

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

    boolean result = palindromeList.checkReversing(list);

    assertFalse(result);
  }

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

Add some tests to problem 62


package org.monospark.spongematchers.parser.element;

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

import org.junit.Test;
import org.monospark.spongematchers.parser.SpongeMatcherParseException;
import org.monospark.spongematchers.parser.element.ConnectedElement.Operator;

public class ConnectedElementParserTest {

    @Test
    public void parseElements_ConnectedElementsWithOr_ReturnsCorrectStringElement()
            throws SpongeMatcherParseException {
        String input = "'test1'|'test2'";

        verifyConnectedElement(input, Operator.OR);
    }

    @Test
    public void parseElements_ConnectedElementsWithOrWithSpaces_ReturnsCorrectStringElement()
            throws SpongeMatcherParseException {
        String input = "    'test1' |   'test2' ";

        verifyConnectedElement(input, Operator.OR);
    }

    @Test
    public void parseElements_ConnectedElementsWithAnd_ReturnsCorrectStringElement()
            throws SpongeMatcherParseException {
        String input = "'test1'&'test2'";

        verifyConnectedElement(input, Operator.AND);
    }

    @Test
    public void parseElements_ConnectedElementsWithAndWithSpaces_ReturnsCorrectStringElement()
            throws SpongeMatcherParseException {
        String input = "    'test1' &   'test2' ";

        verifyConnectedElement(input, Operator.AND);
    }

    private void verifyConnectedElement(String input, Operator op) throws SpongeMatcherParseException {
        StringElement element = StringElementParser.parseStringElement(input);

        ConnectedElement con = (ConnectedElement) element;
        assertThat(con.getOperator(), equalTo(op));
        BaseElement<?> base1 = (BaseElement<?>) con.getFirstElement();
        BaseElement<?> base2 = (BaseElement<?>) con.getSecondElement();
        assertThat(base1.getString(), equalTo("'test1'"));
        assertThat(base2.getString(), equalTo("'test2'"));
    }
}

Add unit tests for connected element parsing


package com.skcraft.plume.module;

import com.mojang.authlib.GameProfile;
import com.skcraft.plume.common.util.config.Config;
import com.skcraft.plume.common.util.config.InjectConfig;
import com.skcraft.plume.common.util.module.Module;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.PlayerEvent;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.management.ServerConfigurationManager;
import ninja.leaping.configurate.objectmapping.Setting;

@Module(name = "operator-check")
public class OperatorCheck {

    @InjectConfig("operator_check")
    private Config<CheckConfig> config;

    @SubscribeEvent
    public void onPlayerJoin(PlayerEvent.PlayerLoggedInEvent event) {
        if (config.get().deopOnJoin) {
            ServerConfigurationManager configManager = MinecraftServer.getServer().getConfigurationManager();
            GameProfile gameProfile = event.player.getGameProfile();
            if (configManager.func_152596_g(gameProfile)) { /* isOp() */
                // Warning: Blocks thread -- underlying map not thread-safe
                configManager.func_152610_b(gameProfile); /* deop() */
            }
        }
    }

    private static class CheckConfig {
        @Setting(comment = "Set to true to remove op status from users that join")
        public boolean deopOnJoin = false;
    }

}

Add module to remove operator status on join.


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

package algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-09-20
 * Site       : https://www.acmicpc.net/problem/2558
 */
public class Boj2558 {

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

}

Solve No.2558 from Baekjoon Online Judge


package com.application;

import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.WebUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CsrfHeaderFilter extends OncePerRequestFilter {
	@Override
	protected void doFinterlInterlan(
			HttpServletRequest request,
			HttpServletResponse response,
			FilterChain filterChain
		) throws ServletException, IOException {

		CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());

		if (csrf != null) {
			Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
			String token = csrf.getToken();
			if (cookie == null || token != null && !token.equals(cookie.getValue())) {
				cookie = new Cookie("XSRF-TOKEN", token);
				// TODO fix setPath as it's not safe in general to point it at "/" but for our app this will do now
				cookie.setPath("/");
				response.addCookie(cookie);
			}
		}

		filterChain.doFilter(request, response);
	}
}

Add support for custom filter chain and generating the 'XSRF-TOKEN' for Angular


package xerial.larray.japi;

import org.junit.Test;
import org.xerial.snappy.Snappy;
import xerial.larray.LByteArray;
import xerial.larray.LIntArray;
import xerial.larray.MMapMode;
import xerial.larray.MappedLByteArray;
import xerial.larray.util.Logger;

import java.io.File;

public class JSnappyCompressTest {

    private Logger _logger = new Logger(this.getClass());

    @Test
    public void testCompress() throws Exception {

        long N = 100000000L;
        LIntArray l = LArrayJ.newLIntArray(N);
        for (int i = 0; i < N; i++) {
            l.update(i, (int) (Math.toDegrees(Math.sin(i / 360))));
        }
        for (int iter = 0; iter < 10; iter++) {
            long sum = 0;
            long start = System.currentTimeMillis();
            for (int i = 0; i < l.length(); i++) {
                sum += l.apply(i);
            }
            long end = System.currentTimeMillis();
            _logger.debug("time:" + (end - start) + " sum:" + sum);
        }
        _logger.debug("compressing the data");
        int maxLen = Snappy.maxCompressedLength((int) l.byteLength());
        LByteArray compressedBuf = LArrayJ.newLByteArray(maxLen);
        long compressedLen = Snappy.rawCompress(l.address(), l.byteLength(),
                compressedBuf.address());
        LByteArray compressed = (LByteArray) compressedBuf.slice(0,
                compressedLen);
        File f = File.createTempFile("snappy", ".dat", new File("target"));
        f.deleteOnExit();
        compressed.saveTo(f);

        _logger.debug("decompressing the data");
        long T1 = System.currentTimeMillis();
        MappedLByteArray b = LArrayJ.mmap(f, 0, f.length(), MMapMode.READ_ONLY);
        long T2 = System.currentTimeMillis();

        long len = Snappy.uncompressedLength(b.address(), b.length());
        LIntArray decompressed = LArrayJ.newLIntArray(len / 4);
        Snappy.rawUncompress(b.address(), b.length(), decompressed.address());
        long T3 = System.currentTimeMillis();
        _logger.debug("Map time:" + (T2 - T1));
        _logger.debug("decompress time:" + (T3 - T2));

        _logger.debug("Summing decompressed array");
        for (int iter = 0; iter < 10; iter++) {
            long sum = 0;
            long start = System.currentTimeMillis();
            for (int i = 0; i < decompressed.length(); i++) {
                sum += decompressed.apply(i);
            }
            long end = System.currentTimeMillis();
            _logger.debug("time:" + (end - start) + " sum:" + sum);
        }
    }
}

Add compression tests in Java


package Part1;

/**
 * Created by matao on 10/15/16.
 */
public class Q1 {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

Add Java solution of 1-1


package io.sigpipe.sing.stat;

public class SummaryStatistics {

    private double min;
    private double max;
    private double mean;
    private double std;
    private double var;

    public SummaryStatistics(RunningStatistics rs) {
        this.min = rs.min();
        this.max = rs.max();
        this.mean = rs.mean();
        this.var = rs.var();
        this.std = rs.std();
    }

    public double min() {
        return this.min;
    }

    public double max() {
        return this.max;
    }

    public double mean() {
        return this.mean;
    }

    public double std() {
        return this.std;
    }

    public double var() {
        return this.var;
    }
}

Add class for encapsulating summary stat snapshots


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

import nom.bdezonia.zorbage.type.algebra.Algebra;
import nom.bdezonia.zorbage.type.storage.datasource.IndexedDataSource;

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

	/**
	 *
	 * @param alg
	 * @param a
	 * @param b
	 */
	public static <T extends Algebra<T,U>, U>
		void compute(T alg, IndexedDataSource<U> a, IndexedDataSource<U> b)
	{
		throw new IllegalArgumentException("not written yet");
	}

}

Define a placeholder for an algorithm


/*
 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * Contributors:
 *     bdelbosc
 */
package org.nuxeo.elasticsearch;

public class ElasticSearchConstants {

    private ElasticSearchConstants() {
    }

    /**
     * Elasticsearch type name used to index Nuxeo documents
     */
    public static final String DOC_TYPE = "doc";

    public static final String ACL_FIELD = "ecm:acl";

    public static final String CHILDREN_FIELD = "ecm:path.children";

    public static final String[] DEFAULT_FULLTEXT_FIELDS = { "ecm:fulltext",
            "dc:title", "dc:description", "note:note" };
}

Enable to configure the ES index name, the type name must be doc


package org.jboss.forge.furnace;

import java.io.File;

import org.jboss.forge.furnace.impl.FurnaceImpl;
import org.jboss.forge.furnace.repositories.AddonRepositoryMode;
import org.junit.Test;

public class FurnaceImplTest
{
   @Test(expected = IllegalArgumentException.class)
   public void shouldValidateAddRepositoryArgumentMode() throws Exception {
      Furnace f = new FurnaceImpl();
      f.addRepository(null, new File("."));
   }

   @Test(expected = IllegalArgumentException.class)
   public void shouldValidateAddRepositoryArgumentDirectory() throws Exception {
      Furnace f = new FurnaceImpl();
      f.addRepository(AddonRepositoryMode.IMMUTABLE, null);
   }
}

Add tests to verify method argument validation


package com.sunny.grokkingalgorithms.fasttrack.week1;

import com.sunny.grokkingalgorithms.ctci.c4.util.BinaryTreeNode;
import com.sunny.grokkingalgorithms.ctci.c4.util.TreeUtils;

/**
 * Created by sundas on 6/21/2018.
 */
public class CheckIfBinaryTreeIsComplete {

  /*
  In the array representation of a binary tree, if the parent node is assigned an index of i and left child gets assigned an index of 2*i + 1 while the right child is assigned an index of 2*i + 2. If we represent the above binary tree as an array with the respective indices assigned to the different nodes of the tree above from top to down and left to right.

Hence we proceed in the following manner in order to check if the binary tree is complete binary tree.

Calculate the number of nodes (count) in the binary tree.
Start recursion of the binary tree from the root node of the binary tree with index (i) being set as 0 and the number of nodes in the binary (count).
If the current node under examination is NULL, then the tree is a complete binary tree. Return true.
If index (i) of the current node is greater than or equal to the number of nodes in the binary tree (count) i.e. (i>= count), then the tree is not a complete binary. Return false.
Recursively check the left and right sub-trees of the binary tree for same condition. For the left sub-tree use the index as (2*i + 1) while for the right sub-tree use the index as (2*i + 2).
   */

  /**
   *
   * @param root
   * @return
   */
  public static int countNodes(BinaryTreeNode root){
    if(root ==  null){
      return 0;
    }
    return countNodes(root.left) + countNodes(root.right)+ 1;
  }

  /**
   *
   * @param root
   * @param index
   * @param totalNodes
   * @return
   */
  public static boolean isComplete(BinaryTreeNode root,
                                   int index,
                                   int totalNodes){
    if(root ==  null){
      return true;
    }
    if(index > totalNodes){
      return false;
    }
    return isComplete(root.left,2*index+1,totalNodes)
        && isComplete(root.right,2*index+2,totalNodes);
  }

  /**
   *
   * @param args
   */
  public static void main(String[] args) {
    BinaryTreeNode root = TreeUtils.createBalancedBinaryTree();
    TreeUtils.performBfsLevelMarker(root);
    int nodeCount = countNodes(root);
    System.out.println(isComplete(root,0,nodeCount));
  }
}

Check if a binary tree is complete or not.


package de.tudresden.inf.lat.born.owlapi.processor;

import org.semanticweb.owlapi.model.OWLOntology;

/**
 * An object of this class is a pair OWL ontology - Bayesian network.
 *
 * @author Julian Mendez
 *
 */
public class OntologyAndNetwork {

	private final OWLOntology owlOntology;
	private final String bayesianNetwork;

	/**
	 * Constructs a new pair OWL ontology - Bayesian network.
	 */
	public OntologyAndNetwork(OWLOntology owlOntology, String bayesianNetwork) {
		if (owlOntology == null) {
			throw new IllegalArgumentException("Null arguments.");
		}
		if (bayesianNetwork == null) {
			throw new IllegalArgumentException("Null arguments.");
		}

		this.owlOntology = owlOntology;
		this.bayesianNetwork = bayesianNetwork;
	}

	/**
	 * Returns the OWL ontology;
	 *
	 * @return the OWL ontology
	 */
	public OWLOntology getOntology() {
		return this.owlOntology;
	}

	/**
	 * Returns the Bayesian network.
	 *
	 * @return the Bayesian network
	 */
	public String getBayesianNetwork() {
		return this.bayesianNetwork;
	}

	@Override
	public int hashCode() {
		return this.owlOntology.hashCode() + 0x1F * this.bayesianNetwork.hashCode();
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		} else if (obj instanceof OntologyAndNetwork) {
			OntologyAndNetwork other = (OntologyAndNetwork) obj;
			return getOntology().equals(other.getOntology()) && getBayesianNetwork().equals(other.getBayesianNetwork());
		} else {
			return false;
		}
	}

	@Override
	public String toString() {
		return getBayesianNetwork() + "\n\n" + getOntology();
	}

}

Add class to combine an OWL ontology and a Bayesian network


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

import com.google.common.truth.ExpectFailure.SimpleSubjectBuilderCallback;
import com.google.common.truth.Subject;

import static com.google.common.truth.ExpectFailure.expectFailureAbout;
import static com.google.common.truth.Truth.assertAbout;

/**
 * An abstract base for custom {@link Subject} test suites.
 *
 * @param <S>
 *         the type of the {@code Subject}
 * @param <T>
 *         the target type tested by the {@code Subject}
 */
public abstract class SubjectTest<S extends Subject<S, T>, T> {

    protected static final String EXPECTED = "expected";
    protected static final String BUT_WAS = "but was";
    protected static final String EXPECTED_NOT_TO_BE = "expected not to be";
    protected static final String NULL = "null";

    protected abstract Subject.Factory<S, T> subjectFactory();

    /**
     * Creates a subject under the test with the passed actual value.
     */
    protected S assertWithSubjectThat(T actual) {
        return assertAbout(subjectFactory()).that(actual);
    }

    /**
     * Creates an {@code AssertionError} caused by the passed callback.
     *
     *
Example of usage:
     *
 {@code
     * AssertionError failure = expectFailure(whenTesting -> whenTesting.that(myType).hasProperty());
     * }

     */
    protected AssertionError
    expectFailure(SimpleSubjectBuilderCallback<S, T> assertionCallback) {
        return expectFailureAbout(subjectFactory(), assertionCallback);
    }

    /**
     * Expects that the passed callback causes {@code AssertionError} and ignores it.
     *
     *
This method is for test cases where the produced error is of no interest.
     * Example of usage:
     *
 {@code
     * expectSomeFailure(whenTesting -> whenTesting.that(myType).hasProperty());
     * }

     */
    @SuppressWarnings({"ThrowableNotThrown", "CheckReturnValue"}) // Ignore the AssertionError.
    protected void
    expectSomeFailure(SimpleSubjectBuilderCallback<S, T> assertionCallback) {
        expectFailureAbout(subjectFactory(), assertionCallback);
    }
}

Add abstract base for testing `Subject`s


/*
 * Copyright 2016-2019 Talsma ICT
 *
 * 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.
 */

/**
 * The {@code Clearable} interface and a {@code ClearableContextManager} in particular.
 *
 *
{@linkplain nl.talsmasoftware.context.clearable.Clearable}

 *

 * This interface declares the {@linkplain nl.talsmasoftware.context.clearable.Clearable#clear()} method.
 * Clearing something is semantically different from closing.
 *
 *

 * In the case of {@linkplain nl.talsmasoftware.context.clearable.ClearableContextManager},
 * closing any context only applies to that single context,
 * while clearing a context manager is equivalent to closing all contexts in that
 * manager from the current thread.
 */
package nl.talsmasoftware.context.clearable;

Add package javadoc for clearable package


package com.alexrnl.commons.database.sql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import com.alexrnl.commons.database.Column;
import com.alexrnl.commons.database.Dummy;
import com.alexrnl.commons.database.Dummy.DummyColumn;
import com.alexrnl.commons.database.EntityColumn;

/**
 * DAO for the Dummy entity.
 * @author Alex
 */
public class DummySQLDAO extends SQLDAO<Dummy> {
	/** The sample of entity */
	private Dummy													sample;
	/** Columns of the dummy table */
	private final Map<? extends Enum<? extends EntityColumn>, Column>	columns;

	/**
	 * Constructor #1.<br />
	 * @param connection
	 *        the connection to the SQL database.
	 * @throws SQLException
	 *         if there was an error while initializing the database.
	 */
	public DummySQLDAO (final Connection connection) throws SQLException {
		super(connection);
		columns = getEntitySample().getEntityColumns();
	}

	@Override
	protected Dummy getEntitySample () {
		if (sample == null) {
			sample = new Dummy();
		}
		return sample;
	}

	@Override
	protected Dummy createEntityFromResult (final ResultSet result) throws SQLException {
		final Dummy newDummy = new Dummy();
		newDummy.setId(result.getInt(columns.get(DummyColumn.ID).getName()));
		newDummy.setName(result.getString(columns.get(DummyColumn.NAME).getName()));
		return newDummy;
	}

	@Override
	protected void fillInsertStatement (final PreparedStatement statement, final Dummy obj)
			throws SQLException {
		statement.setString(1, obj.getName());
	}

	@Override
	protected void fillUpdateStatement (final PreparedStatement statement, final Dummy obj)
			throws SQLException {
		fillInsertStatement(statement, obj);
		statement.setInt(columns.size(), obj.getId());
	}
}

Create the SQL DAO for the Dummy entity


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

import javax.swing.JFrame;
import javax.swing.WindowConstants;

/**
 *
 * @author David.Biesack@sas.com
 */
public class UnRAVLShell {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        JFrame frame = UnRAVLFrame.main(args);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

}

Add alternate shell main program


package org.aanguita.jacuzzi.event.hub;

/**
 * This class provides named event hubs. An event hub allows publishing messages with some tags, while other classes can subscribe from specific
 * tags and receive the corresponding notifications. In esence, this class provides an observer pattern implementation, allowing very decoupled
 * code to use it.
 * <p>
 * This class provides static methods for creating event hubs. It also maintains a coherent pool of named event hubs, so these can be retrieved
 * asynchronously. Clients can register as many event hubs as desired, identifying them by a name.
 *
 * @author aanguita
 *         21/09/2016
 */
public class EventHub {

    private final String name;

    public EventHub(String name) {
        this.name = name;
    }
}

Add event hub (no code yet)


/*
 * File: MidpointFindingKarel.java
 * -------------------------------
 * When you finish writing it, the MidpointFindingKarel class should
 * leave a beeper on the corner closest to the center of 1st Street
 * (or either of the two central corners if 1st Street has an even
 * number of corners).  Karel can put down additional beepers as it
 * looks for the midpoint, but must pick them up again before it
 * stops.  The world may be of any size, but you are allowed to
 * assume that it is at least as tall as it is wide.
 */

import stanford.karel.*;

/* Note: this fails if the world is only one street wide. I'm not sure if that's
 * permissible or not.
 */
public class MidpointFindingKarel2 extends SuperKarel {
	public void run() {
		setup();
		while (frontIsBlocked()) {
			turnAround();
			moveToFirstBeeper();
			grabAndGo();
		}
	}

	private void setup() {
		while (frontIsClear()) {
			putBeeper();
			move();
		}
		putBeeper();
	}

	private void moveToWall() {
		while (frontIsClear()) {
			move();
		}
	}

	private void grabAndGo() {
		if (beepersPresent()) {
			pickBeeper();
			move();
			if (beepersPresent()) {
				moveToWall();
			} else {
				turnAround();
				move();
				putBeeper();
			}
		}
	}

	private void moveToFirstBeeper() {
		while (noBeepersPresent()) {
			move();
		}
	}
}

Add second, less elegant solution for assignment 1, problem 4


/*
 * Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
 */

package org.jsimpledb;

import org.jsimpledb.annotation.JSimpleClass;
import org.jsimpledb.core.ObjId;
import org.jsimpledb.test.TestSupport;
import org.testng.Assert;
import org.testng.annotations.Test;

public class ConstructorTest extends TestSupport {

    @Test
    public void testConstrutorWithParam() {
        final JSimpleDB jdb = BasicTest.getJSimpleDB(Person.class);
        final JTransaction jtx = jdb.createTransaction(true, ValidationMode.AUTOMATIC);
        JTransaction.setCurrent(jtx);
        try {
            jtx.create(Person.class);
            jtx.commit();
        } finally {
            JTransaction.setCurrent(null);
        }
    }

    @Test
    public void testPrivateConstrutor() {
        try {
            BasicTest.getJSimpleDB(Person2.class);
            assert false;
        } catch (IllegalArgumentException e) {
            // expected
        }
    }

    @Test
    public void testMissingConstrutor() {
        try {
            BasicTest.getJSimpleDB(Person3.class);
            assert false;
        } catch (IllegalArgumentException e) {
            // expected
        }
    }

// Model Classes

    @JSimpleClass
    public abstract static class Person implements JObject {
        protected Person(JTransaction jtx, ObjId id) {
            Assert.assertEquals(jtx, this.getTransaction());
            Assert.assertEquals(id, this.getObjId());
        }
    }

    @JSimpleClass
    public abstract static class Person2 implements JObject {
        Person2(JTransaction jtx, ObjId id) {        // package private
        }
    }

    @JSimpleClass
    public abstract static class Person3 implements JObject {
        public Person3(int dummy) {
        }
    }
}

Add unit tests for model class constructors.


/*
 * Bach - Java Shell Builder
 * Copyright (C) 2019 Christian Stein
 *
 * 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 de.sormuras.bach.util;

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

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

class PathsTests {
  @Test
  void userHomeIsDirectory() {
    assertTrue(Files.isDirectory(Paths.USER_HOME));
  }

  @Test
  void listEmptyDirectoryYieldsAnEmptyListOfPaths(@TempDir Path temp) {
    assertEquals(List.of(), Paths.list(temp, "*"));
    assertEquals(List.of(), Paths.list(temp, Files::isRegularFile));
    assertEquals(List.of(), Paths.list(temp, Files::isDirectory));
  }
}

Add tests for Path-related helpers


package com.haxademic.demo.draw.mapping;

import com.haxademic.core.app.P;
import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.constants.AppSettings;
import com.haxademic.core.draw.color.Gradients;
import com.haxademic.core.draw.context.DrawUtil;
import com.haxademic.core.draw.image.ImageUtil;
import com.haxademic.core.file.DemoAssets;

import processing.core.PGraphics;

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

	protected PGraphics fadeEdge;

	protected void overridePropsFile() {
		p.appConfig.setProperty( AppSettings.WIDTH, 800 );
		p.appConfig.setProperty( AppSettings.HEIGHT, 800 );
	}

	protected void setupFirstFrame() {
		float fadeSize = 0.1f;
		float solidSize = 1f - fadeSize;

		fadeEdge = p.createGraphics(1024, 1024, P.P3D);
		fadeEdge.beginDraw();
		DrawUtil.setDrawCenter(fadeEdge);
		// draw gradient
		fadeEdge.translate(fadeEdge.width * (fadeSize * 0.5f), fadeEdge.height / 2);
		fadeEdge.noStroke();
		Gradients.linear(fadeEdge, fadeEdge.width * fadeSize, fadeEdge.height, p.color(1, 0), p.color(0,255));
		// draw solid portion
		fadeEdge.translate(fadeEdge.width * (solidSize * 0.5f + fadeSize * 0.5f), 0);
		fadeEdge.fill(0);
		fadeEdge.rect(0, 0, fadeEdge.width * solidSize, fadeEdge.height);
		fadeEdge.endDraw();
	}

	public void drawApp() {
		ImageUtil.cropFillCopyImage(DemoAssets.justin(), p.g, true);
		DrawUtil.setCenterScreen(p);
		DrawUtil.setDrawCenter(p);

		// draw
		p.rotate(P.map(p.mousePercentY(), 0, 1, P.PI, -P.PI));
		p.image(fadeEdge, 0, 0,
				fadeEdge.width * (0.5f + 0.2f * P.sin(p.frameCount * 0.01f)),
				fadeEdge.height * (0.5f + 0.2f * P.sin(p.frameCount * 0.015f))
				);
	}

}

Add gradient edge demo for projection mapping utility


package jp.ac.shibaura_it.se.tslab.aaextractor.predicate.attributes;

import static org.junit.Assert.*;
import static org.hamcrest.core.Is.*;

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

public class KskipNgramCounterTest {

	@Test
	public void ひとつのKskipNgramの正規表現を生成する() {
		List<String> ngrams = new ArrayList<>();
		ngrams.add("あいう");
		ngrams.add("abc");
		int kSkip = 2;
		KskipNgramCounter counter = new KskipNgramCounter(ngrams, kSkip);

		String actual = counter.insertKskipRex(ngrams.get(0), kSkip);
		String expected = "\\Qあ\\E.{0,2}\\Qい\\E.{0,2}\\Qう\\E";
		assertThat(actual, is(expected));
	}

	@Test
	public void 複数のKskipNgramの正規表現を生成する() {
		List<String> ngrams = new ArrayList<>();
		ngrams.add("あいう");
		ngrams.add("abc");
		int kSkip = 2;
		KskipNgramCounter counter = new KskipNgramCounter(ngrams, kSkip);

		String actual = counter.pattern.pattern();
		String expected = "\\Qあ\\E.{0,2}\\Qい\\E.{0,2}\\Qう\\E|\\Qa\\E.{0,2}\\Qb\\E.{0,2}\\Qc\\E";
		assertThat(actual, is(expected));
	}

	@Test
	public void KskipNgramを数える() {
		List<String> ngrams = new ArrayList<>();
		ngrams.add("あいう");
		ngrams.add("abc");
		int kSkip = 2;
		KskipNgramCounter counter = new KskipNgramCounter(ngrams, kSkip);

		int actual = counter.count("abXcあXいXXうあXXXいう");
		int expected = 2;
		assertThat(actual, is(expected));
	}

}

Add a test into the package jp.ac.shibaura_it.se.tslab.aaextractor.predicate.attributes


/**
 *
 */
package com.microsoft.sqlserver.jdbc.datatypes;

import java.util.Arrays;

import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.microsoft.sqlserver.testframework.AbstractTest;

@RunWith(JUnitPlatform.class)
public class Utils extends AbstractTest {

    public static boolean parseByte(byte[] expectedData,
            byte[] retrieved) {
        assertTrue(Arrays.equals(expectedData, Arrays.copyOf(retrieved, expectedData.length)), " unexpected BINARY value, expected");
        for (int i = expectedData.length; i < retrieved.length; i++) {
            assertTrue(0 == retrieved[i], "unexpected data BINARY");
        }
        return true;
    }
}

Revert "removed some unused code, added check for server version"


package com.zaxxer.hikari;

import java.sql.Statement;
import java.util.ArrayList;

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

import com.zaxxer.hikari.performance.StubStatement;
import com.zaxxer.hikari.util.FastStatementList;

public class TestFastStatementList
{
    @Test
    public void testOverflow()
    {
        ArrayList<Statement> verifyList = new ArrayList<Statement>();

        FastStatementList list = new FastStatementList();
        for (int i = 0; i < 100; i++)
        {
            StubStatement statement = new StubStatement();
            list.add(statement);
            verifyList.add(statement);
        }

        for (int i = 0; i < 100; i++)
        {
            Assert.assertNotNull("Element " + i, list.get(i));
            Assert.assertSame(verifyList.get(i), list.get(i));
        }
    }
}

package com.zaxxer.hikari;

import java.sql.Statement;
import java.util.ArrayList;

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

import com.zaxxer.hikari.mocks.StubStatement;
import com.zaxxer.hikari.util.FastStatementList;

public class TestFastStatementList
{
    @Test
    public void testOverflow()
    {
        ArrayList<Statement> verifyList = new ArrayList<Statement>();

        FastStatementList list = new FastStatementList();
        for (int i = 0; i < 100; i++)
        {
            StubStatement statement = new StubStatement(null);
            list.add(statement);
            verifyList.add(statement);
        }

        for (int i = 0; i < 100; i++)
        {
            Assert.assertNotNull("Element " + i, list.get(i));
            Assert.assertSame(verifyList.get(i), list.get(i));
        }
    }
}

Delete performance benchmarks, they are now hosted as a separate github repository.


package org.apache.markt.leaks.concurrent;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;

import org.apache.markt.leaks.LeakBase;

/**
 * Java 5 - ForkJoin not supported
 * Java 6 - ForkJoin not supported
 * Java 7 - no leak
 * Java 8 - no leak
 */
public class ForkJoinThreadLeak extends LeakBase {

    private static ForkJoinPool commonPool;

    public static void main(String[] args) {
        // This doesn't help. While InnocuousForkJoinWorkerThread instances do
        // return the system class loader for calls to getContextClassLoader()
        // they don't ever set the field in the super class so
        // Thread.contextClassLoader retains the reference to the original class
        // loader thereby creating the leak.
        //
        // System.setProperty("java.util.concurrent.ForkJoinPool.common.threadFactory",
        //        "java.util.concurrent.ForkJoinPool$InnocuousForkJoinWorkerThreadFactory");

        commonPool = new ForkJoinPool();

        ForkJoinThreadLeak forkJoinThreadLeak = new ForkJoinThreadLeak();
        forkJoinThreadLeak.doLeakTest();
    }

    @Override
    protected void createLeakingObjects() {
        commonPool.invoke(new NoopAction(5));
    }

    @Override
    protected void cleanUpLeakingObjects() {
        // None
    }

    private class NoopAction extends RecursiveAction {

        private static final long serialVersionUID = 1L;

        final int count;

        public NoopAction(int count) {
            this.count = count;
        }

        @Override
        protected void compute() {
            if (count > 1) {
                int mid = count / 2;
                NoopAction left = new NoopAction(mid);
                NoopAction right = new NoopAction(count - mid);
                left.fork();
                right.compute();
                left.join();
            }
        }
    }
}

Add test case for ForkJoin memory leak


package woko.facets.builtin.developer;

import net.sourceforge.jfacets.IFacetDescriptorManager;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Resolution;
import woko.facets.BaseResolutionFacet;
import woko.persistence.ObjectStore;
import woko.users.UserManager;
import woko.users.UsernameResolutionStrategy;

public class Theme<
        OsType extends ObjectStore,
        UmType extends UserManager,
        UnsType extends UsernameResolutionStrategy,
        FdmType extends IFacetDescriptorManager
> extends BaseResolutionFacet<OsType,UmType,UnsType,FdmType> {

    @Override
    public Resolution getResolution(ActionBeanContext abc) {

    }
}

Add default maven directory in bootstrap-or module


/*
 * 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.sling.servlets.get.impl.helpers;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.xss.XSSAPI;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

public class HtmlRendererServletTest {

    private SlingHttpServletRequest request;
    private SlingHttpServletResponse response;

    @Before
    public void setup() throws IOException {
        request = Mockito.mock(SlingHttpServletRequest.class);

        final ResourceResolver resolver = Mockito.mock(ResourceResolver.class);
        Mockito.when(request.getResourceResolver()).thenReturn(resolver);

        final Resource resource = Mockito.mock(Resource.class);
        Mockito.when(request.getResource()).thenReturn(resource);
        Mockito.when(resource.getResourceResolver()).thenReturn(resolver);

        final Map<String, Object> props = new HashMap<>();
        props.put("key", "<script>alert(1);</script>");
        Mockito.when(resource.adaptTo(Map.class)).thenReturn(props);

        response = Mockito.mock(SlingHttpServletResponse.class);

        Mockito.when(response.getWriter()).thenReturn(new PrintWriter(new StringWriter()));
    }

    @Test
    public void testEscaping() throws ServletException, IOException {
        XSSAPI xss = Mockito.mock(XSSAPI.class);

        final HtmlRendererServlet servlet = new HtmlRendererServlet(xss);

        servlet.doGet(request, response);

        Mockito.verify(xss).encodeForHTML("<script>alert(1);</script>");
    }
}

Add escaping test for html renderer servlet


package eic.beike.projectx.projectXServer;

import eic.beike.projectx.util.ScoreEntry;

/**
 * Used to interact with the database, these are long running network operations and should not be called
 * from the UI thread.
 *
 * Created by alex on 10/1/15.
 */
public interface IDatabase {

    /**
     * Register a name for the given id.
     * @return True if registration succeded, false if it failed.
     */
   boolean register(String id, String name);

    /**
     * @return True if score was recorded correctly, false if it failed.
     */
    boolean recordScore(String playerId, int score, long time, String bus);

    /**
     * @return The best ten scores for all players on all buses.
     */
    ScoreEntry[] getTopTen();

    /**
     * @return The best ten scores for the given player.
     */
    ScoreEntry[] getPlayerTopTen(String playerId);

}

Add interface for database interaction.


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

package algorithm.boj;

import java.io.*;

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

public class Boj1110 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        int n1 = n;
        int tmp;
        int m = 0;
        int count = 0;
        while(true){
            tmp = n/10 + n%10;
            if(tmp < 10){
                m = (n%10)*10 + tmp;
            }else{
                m = (n%10)*10 + tmp%10;
            }

            count++;
            if(n1 == m){
                break;
            }

            n = m;
        }
        System.out.println(count);
    }

}

Solve No.1110 from Baekjoon Online Judge


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

package algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-10-03
 * Site       : https://www.acmicpc.net/problem/2908
 */

public class Boj2908 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] inputs = br.readLine().split(" ");
        char[] a = inputs[0].toCharArray();
        char[] b = inputs[1].toCharArray();
        char tmp = ' ';
        tmp = a[0];
        a[0] = a[2];
        a[2] = tmp;
        tmp = b[0];
        b[0] = b[2];
        b[2] = tmp;
        if(a[0]> b[0]){
            System.out.println(a);
        }else if(a[0]==b[0]){
            if(a[1]> b[1]){
                System.out.println(a);
            }else if(a[1]==b[1]){
                if(a[2]> b[2]){
                    System.out.println(a);
                }else{
                    System.out.println(b);
                }
            }else {
                System.out.println(b);
            }
        }else {
            System.out.println(b);
        }
    }

}

Solve No.2908 from Baekjoon Online Judge


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

package imagej.data.lut.io;

import imagej.data.lut.LUTService;
import imagej.io.AbstractIOPlugin;
import imagej.io.IOPlugin;

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

import net.imglib2.display.ColorTable;

import org.scijava.plugin.Plugin;

/**
 * I/O plugin for {@link ColorTable}s.
 *
 * @author Curtis Rueden
 */
@Plugin(type = IOPlugin.class)
public class LUTIOPlugin extends AbstractIOPlugin<ColorTable> {

	// -- IOPlugin methods --

	@Override
	public Class<ColorTable> getDataType() {
		return ColorTable.class;
	}

	@Override
	public boolean supportsOpen(final String source) {
		return lutService().isLUT(new File(source));
	}

	@Override
	public ColorTable open(final String source) throws IOException {
		return lutService().loadLUT(new File(source));
	}

	// -- Helper methods --

	private LUTService lutService() {
		return getContext().getService(LUTService.class);
	}

}

Add an I/O plugin for LUTs


package com.naba.url.shortner;

public class UrlShortner {
    private String originalUrl;

    public String getOriginalUrl() {
        return originalUrl;
    }

    public void setOriginalUrl(String url) {
        this.originalUrl = url;
    }
}

Add model to capture form data from home page


package test.base;

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

import java.io.StringReader;
import java.util.Properties;
import org.junit.jupiter.api.Test;

class PropertiesTests {

  @Test
  void loadMultiLineValuesFromTextBlock() throws Exception {
    var expected =
        """
        1
        2""";

    var string =
        """
        --a 1\\n2
        --b 1\\n\
        2
        --c \
        1\\n\
        2
        """;
    var properties = new Properties();
    properties.load(new StringReader(string));

    assertEquals(expected, properties.getProperty("--a"));
    assertEquals(expected, properties.getProperty("--b"));
    assertEquals(expected, properties.getProperty("--c"));
  }
}

Add test case for `java.util.Properties`


package carpentersblocks.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import net.minecraft.client.resources.ResourcePackFileNotFoundException;
import carpentersblocks.CarpentersBlocksCachedResources;

import com.google.common.base.Charsets;

import cpw.mods.fml.client.FMLFileResourcePack;
import cpw.mods.fml.common.ModContainer;

public class DynamicFileResourcePack extends FMLFileResourcePack {

    public DynamicFileResourcePack(ModContainer container)
    {
        super(container);
    }

    private ZipFile getResourcePackZipFile()
    {
        return CarpentersBlocksCachedResources.INSTANCE.getZipFile();
    }

    @Override
    protected InputStream getInputStreamByName(String resourceName) throws IOException
    {
        ZipFile zipfile = getResourcePackZipFile();
        ZipEntry zipentry = zipfile.getEntry(resourceName);

        try {
            if ("pack.mcmeta".equals(resourceName)) {
                return new ByteArrayInputStream(("{\n" +
                        " \"pack\": {\n"+
                        "   \"description\": \"dummy FML pack for "+CarpentersBlocksCachedResources.INSTANCE.getName()+"\",\n"+
                        "   \"pack_format\": 1\n"+
                        "}\n" +
                        "}").getBytes(Charsets.UTF_8));
            } else {
                return zipfile.getInputStream(zipentry);
            }
        } catch (IOException e) {
            throw new ResourcePackFileNotFoundException(resourcePackFile, resourceName);
        }
    }

    @Override
    public boolean hasResourceName(String resourceName)
    {
        return getResourcePackZipFile().getEntry(resourceName) != null;
    }

}

Add necessary component for bed design texture pack support.


// Copyright (c) 2006  Dustin Sallings <dustin@spy.net>

package net.spy.memcached.transcoders;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import net.spy.SpyObject;
import net.spy.util.CloseUtil;

import net.spy.memcached.CachedData;

/**
 * Utility class for transcoding Java types.
 */
public final class TranscoderUtils {
	public static byte[] encodeNum(long l, int maxBytes) {
		byte[] rv=new byte[maxBytes];
		for(int i=0; i<rv.length; i++) {
			int pos=rv.length-i-1;
			rv[pos]=(byte) ((l >> (8 * i)) & 0xff);
		}
		int firstNonZero=0;
		for(;firstNonZero<rv.length && rv[firstNonZero]==0; firstNonZero++) {
			// Just looking for what we can reduce
		}
		if(firstNonZero > 0) {
			byte[] tmp=new byte[rv.length - firstNonZero];
			System.arraycopy(rv, firstNonZero, tmp, 0, rv.length-firstNonZero);
			rv=tmp;
		}
		return rv;
	}

	public static byte[] encodeLong(long l) {
		return encodeNum(l, 8);
	}

	public static long decodeLong(byte[] b) {
		long rv=0;
		for(byte i : b) {
			rv = (rv << 8) | (i<0?256+i:i);
		}
		return rv;
	}

	public static byte[] encodeInt(int in) {
		return encodeNum(in, 4);
	}

	public static int decodeInt(byte[] in) {
		assert in.length <= 4
			: "Too long to be an int (" + in.length + ") bytes";
		return (int)decodeLong(in);
	}

	public static byte[] encodeByte(byte in) {
		return new byte[]{in};
	}

	public static byte decodeByte(byte[] in) {
		assert in.length <= 1 : "Too long for a byte";
		byte rv=0;
		if(in.length == 1) {
			rv=in[0];
		}
		return rv;
	}

	public static byte[] encodeBoolean(boolean b) {
		byte[] rv=new byte[1];
		rv[0]=(byte)(b?'1':'0');
		return rv;
	}

	public static boolean decodeBoolean(byte[] in) {
		assert in.length == 1 : "Wrong length for a boolean";
		return in[0] == '1';
	}

}

Move the encode*() and decode*() methods in SerializingTranscoder.java into a new class and make them static. This will allow other transcoders to use them.


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

import com.google.errorprone.annotations.Immutable;

/**
 * A common interface for enrichment messages.
 *
 * <p>The messages to which {@code (enrichment_for)} option is applied are spotted
 * by the Spine Model Compiler and marked with this interface automatically.
 */
@Immutable
public interface EnrichmentMessage extends SerializableMessage {
}

Define marked interface for enrichments


/*
 * Copyright 2015 Michael Rozumyanskiy
 *
 * 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.michaelrocks.lightsaber.processor.analysis;

import com.michaelrocks.lightsaber.processor.ProcessorContext;
import com.michaelrocks.lightsaber.processor.descriptors.ParameterizedType;
import org.objectweb.asm.Type;
import org.objectweb.asm.signature.SignatureVisitor;

import static org.objectweb.asm.Opcodes.ASM5;

class ParameterizedTypeSignatureParser extends SignatureVisitor {
    private final ProcessorContext processorContext;

    private Type classType;
    private Type classTypeParameter;
    private boolean isValid = true;

    public ParameterizedTypeSignatureParser(final ProcessorContext processorContext) {
        super(ASM5);
        this.processorContext = processorContext;
    }

    public ParameterizedType getParameterizedType() {
        return isValid ? new ParameterizedType(classType, classTypeParameter) : null;
    }

    @Override
    public void visitClassType(final String name) {
        if (classType == null) {
            classType = Type.getObjectType(name);
        } else if (classTypeParameter == null) {
            classTypeParameter = Type.getObjectType(name);
        } else {
            reportError(classType + " has multiple type arguments");
        }
    }

    @Override
    public SignatureVisitor visitTypeArgument(final char wildcard) {
        if (wildcard == INSTANCEOF) {
            return this;
        }

        reportError("Injectable field cannot have wildcards in its signature");
        return this;
    }

    // Prohibited callbacks.

    @Override
    public void visitInnerClassType(final String name) {
        reportError("Injectable field cannot have an inner class type in its signature");
    }

    @Override
    public void visitBaseType(final char descriptor) {
        reportError("Injectable field cannot be a primitive type");
    }

    @Override
    public SignatureVisitor visitArrayType() {
        reportError("Injectable field cannot be an array");
        return this;
    }

    @Override
    public void visitTypeVariable(final String name) {
        reportError("Injectable field cannot have type variables in its signature");
    }

    @Override
    public void visitTypeArgument() {
        reportError("Injectable field cannot have unbounded type arguments in its signature");
    }

    private void reportError(final String message) {
        processorContext.reportError(message);
        isValid = false;
    }
}

Implement signature parser that creates ParameterizedType


package org.corpus_tools.annis.gui;

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

import com.github.mvysny.kaributesting.v8.MockVaadin;
import com.vaadin.spring.internal.UIScopeImpl;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.web.WebAppConfiguration;

@SpringBootTest
@ActiveProfiles({"test", "headless"})
@WebAppConfiguration
class ServiceStarterTest {

  @Autowired
  private BeanFactory beanFactory;

  private AnnisUI ui;

  @BeforeEach
  public void setup() {
    UIScopeImpl.setBeanStoreRetrievalStrategy(new SingletonBeanStoreRetrievalStrategy());
    ui = beanFactory.getBean(AnnisUI.class);
    MockVaadin.setup(() -> ui);
  }

  @AfterEach
  public void tearDown() {
    MockVaadin.tearDown();
  }

  @Test
  void testDesktopAuthNotConfigured() {
    assertNull(ui.getLastAccessToken());
    SecurityContext ctx = ui.getSecurityContext();
    assertNotNull(ctx);
    Authentication auth = ctx.getAuthentication();
    assertNull(auth);
  }

}

Test when in non-desktop mode, that the access token is not set


package eic.beike.projectx.util;

/**
 * Created by alex on 9/22/15.
 */
public class Constants {
    public static final String BASE_URL = "https://ece01.ericsson.net:4443/ecity";
    public static final String AUTHORIZATION ="";
}

Add constants class to carry important constants.


public class Solution {

    public int islandPerimeter(int[][] grid) {

        int perimeter = 0;

        for (int i = 0; i < grid.length; i++) {

            for (int j = 0; j < grid[i].length; j++) {

                if (grid[i][j] == 1) {

                    perimeter += 4;

                    if (i < grid.length - 1 && grid[i + 1][j] == 1) {
                        perimeter -= 2;
                    }

                    if (j < grid[i].length - 1 && grid[i][j + 1] == 1) {
                        perimeter -= 2;
                    }

                }

            }

        }

        return perimeter;

    }

}

Create : 463 Island Perimeter


package com.boundary.sdk.event.service.db;

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

import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.boundary.camel.component.ping.PingConfiguration;
import com.boundary.camel.component.port.PortConfiguration;
import com.boundary.sdk.event.BoundaryEventRouteBuilder;
import com.boundary.sdk.event.service.ServiceCheckRequest;
import com.boundary.sdk.event.service.ServiceTest;

public class ServiceCheckQuery implements Processor {

	private static Logger LOG = LoggerFactory.getLogger(ServiceCheckQuery.class);

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

	@Override
	public void process(Exchange exchange) throws Exception {
		Message message = exchange.getIn();
		Map<String,Object> map = message.getBody(Map.class);
		System.out.println(map.toString());

		String sql = "select now()";

		message.setBody(sql);
	}
}

Add class for generating service check configuration query


package org.muml.psm.allocation.algorithm.ilp.tests;

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

@RunWith(Suite.class)
@SuiteClasses({
	OclContext2ILPTest.class
})
public class AllTestsSuite {

}

Add testsuite for the *algorithms.ilp.tests plugin


package org.dstadler.jgit.unfinished;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.dstadler.jgit.helper.CookbookHelper;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.GitCommand;
import org.eclipse.jgit.api.Status;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.JGitInternalException;
import org.eclipse.jgit.dircache.DirCache;
import org.eclipse.jgit.dircache.DirCacheEntry;
import org.eclipse.jgit.errors.NoWorkTreeException;
import org.eclipse.jgit.lib.Repository;

/**
 * Snippet which shows how to mark files as assumed-unchanged (git update-index --assume-unchanged)
 */
public class UpdateIndex {

	public static void main(String[] args) throws IOException, GitAPIException {
		final Repository repo = CookbookHelper.openJGitCookbookRepository();
		final Git git = new Git(repo);
		final String testFile = "README.md";

		try {
			// Modify the file
			FileUtils.write(new File(testFile), new Date().toString());
			System.out.println("Modified files: " + getModifiedFiles(git));

			new AssumeChangedCommand(repo, testFile, true).call();
			System.out.println("Modified files after assume-changed: " + getModifiedFiles(git));

			new AssumeChangedCommand(repo, testFile, false).call();
			System.out.println("Modified files after no-assume-changed: " + getModifiedFiles(git));

			git.checkout().addPath(testFile).call();
			System.out.println("Modified files after reset: " + getModifiedFiles(git));
		} finally {
			repo.close();
		}
	}

	private static Set<String> getModifiedFiles(Git git) throws NoWorkTreeException, GitAPIException {
		Status status = git.status().call();
		return status.getModified();
	}

	static class AssumeChangedCommand extends GitCommand<String> {
		private final String fileName;
		private final boolean assumeUnchanged;

		AssumeChangedCommand(Repository repository, String fileName, boolean assumedUnchanged) {
			super(repository);

			this.fileName = fileName;
			this.assumeUnchanged = assumedUnchanged;
		}

		@Override
		public String call() throws GitAPIException {
			try {
				DirCache index = repo.lockDirCache();
				DirCacheEntry entry = index.getEntry(fileName);

				if (entry != null) {
					entry.setAssumeValid(assumeUnchanged);
					index.write();
					index.commit();
					return entry.getPathString();
				}
			} catch (IOException e) {
				throw new JGitInternalException(e.getMessage(), e);
			}

			return null;
		}
	}
}

Add an example for "git update-index --assume-changed"


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

public final class SampleData {

    private ArrayList<Tutor> tutors;

    public SampleData() {
        tutors = new ArrayList<Tutor>();
        tutors.add(new Tutor("Kashish Arora", "kashisharora@google.com", new String[]{"Math", "History"}, new TimeRange[]{TimeRange.fromStartToEnd(720, 780), TimeRange.fromStartToEnd(900,1020)}));
        tutors.add(new Tutor("Bernardo Eilert Trevisan", "btrevisan@google.com", new String[]{"English", "Physics"}, new TimeRange[]{TimeRange.fromStartToEnd(480, 600), TimeRange.fromStartToEnd(660,930)}));
        tutors.add(new Tutor("Sam Falberg", "sfalberg@google.com", new String[]{"Geology", "English"}, new TimeRange[]{TimeRange.fromStartToEnd(600, 720), TimeRange.fromStartToEnd(780,840)}));
        tutors.add(new Tutor("Anand Desai", "thegoogler@google.com", new String[]{"Finance", "Chemistry"}, new TimeRange[]{TimeRange.fromStartToEnd(600, 720), TimeRange.fromStartToEnd(780,840)}));
        tutors.add(new Tutor("Elian Dumitru", "elian@google.com", new String[]{"Geology", "Math"}, new TimeRange[]{TimeRange.fromStartToEnd(600, 720), TimeRange.fromStartToEnd(780,840)}));
    }

    public ArrayList<Tutor> getSampleTutors() {
        return this.tutors;
    }

}

Create sample data for testing


/*
 * Copyright 2015 Datalogics, Inc.
 */

package com.datalogics.pdf.samples.creation;

import com.adobe.pdfjt.core.license.LicenseManager;
import com.adobe.pdfjt.pdf.document.PDFDocument;
import com.adobe.pdfjt.pdf.document.PDFOpenOptions;

import com.datalogics.pdf.document.DocumentHelper;
import com.datalogics.pdf.layout.LayoutEngine;
import com.datalogics.pdf.text.Paragraph;

/**
 * This sample shows how to create a basic PDF containing the text 'Hello World'.
 *
 */
public final class HelloWorld {
    private static final String outputPDFPath = "HelloWorld.pdf";

    /**
     * This is a utility class, and won't be instantiated.
     */
    private HelloWorld() {}

    /**
     * Main program.
     *
     * @param args command line arguments
     * @throws Exception a general exception was thrown
     */
    public static void main(final String... args) throws Exception {
        // If you are using an evaluation version of the product (License Managed, or LM), set the path to where PDFJT
        // can find the license file.
        //
        // If you are not using an evaluation version of the product you can ignore or remove this code.
        LicenseManager.setLicensePath(".");
        String path;
        if (args.length > 0) {
            path = args[0];
        } else {
            path = outputPDFPath;
        }
        run(path);
    }

    static void run(final String outputPath) throws Exception {
        PDFDocument document = null;

        try {
            document = PDFDocument.newInstance(PDFOpenOptions.newInstance());

            addText(document);

            DocumentHelper.saveFullAndClose(document, outputPath);
        } finally {
            if (document != null) {
                document.close();
            }
        }
    }

    /**
     * Add the Hello World text to the PDF document.
     *
     * @param pdfDoc The document to add the text to
     * @throws Exception a general exception was thrown
     */
    private static void addText(final PDFDocument pdfDoc) throws Exception {
        // Read in a text and add each line as separate paragraph
        try (LayoutEngine layoutEngine = new LayoutEngine(pdfDoc)) {
            layoutEngine.add(new Paragraph("Hello World"));
        }
    }
}

Add a Hello World sample


package com.google.sps.servlets;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.After;
import static org.mockito.Mockito.*;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.IOException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.tools.development.testing.LocalUserServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;

import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.Test;
import org.junit.Assert;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import com.google.sps.tool.GoogleTranslationAPI;
import com.google.sps.tool.Tool;
import com.google.gson.Gson;
import java.util.Map;
import java.util.HashMap;

@RunWith(JUnit4.class)
public class TranslationServletTest {
  private final LocalServiceTestHelper helper =
    new LocalServiceTestHelper(
      new LocalUserServiceTestConfig())
      .setEnvIsAdmin(true).setEnvIsLoggedIn(true)
      .setEnvEmail("test@gmail.com").setEnvAuthDomain("gmail.com");

  private Map<String, String> expectedJsonInfo = new HashMap<>();
  private HttpServletRequest mockRequest;
  private HttpServletResponse mockResponse;
  private StringWriter responseWriter;
  private TranslationServlet servlet;

  @Before
  public void setUp() throws Exception {
    helper.setUp();
    servlet = new TranslationServlet();
    mockRequest = mock(HttpServletRequest.class);
    mockResponse = mock(HttpServletResponse.class);

    // Set up a fake HTTP response
    responseWriter = new StringWriter();
    when(mockResponse.getWriter()).thenReturn(new PrintWriter(responseWriter));
  }

  @After
  public void tearDown() throws Exception {
    helper.setEnvIsLoggedIn(true);
    helper.tearDown();
  }

  @Test
  public void TranslateHelloToSpanish() throws Exception {

    when(mockRequest.getParameter("rawText")).thenReturn("hello");
    when(mockRequest.getParameter("toLang")).thenReturn("es");
    when(mockRequest.getParameter("fromLang")).thenReturn("en");
    expectedJsonInfo.put("translation", "Hola");

    servlet.doGet(mockRequest, mockResponse);
    String response = responseWriter.toString();
    String expectedResponse = new Gson().toJson(expectedJsonInfo);
    assertTrue(Tool.compareJson(response, expectedResponse));
  }
}

Add tests for Translation servlet


package uk.ac.edukapp.renderer;

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

import uk.ac.edukapp.model.Widgetprofile;

public class UploadResults {

	private String uploadMessage;
	private Widgetprofile widgetProfile;
	private String widgetFolderPath;
	private List<String> htmlFileList;

	/**
	 * @return the uploadMessage
	 */
	public String getUploadMessage() {
		return uploadMessage;
	}

	/**
	 * @param uploadMessage the uploadMessage to set
	 */
	public void setUploadMessage(String uploadMessage) {
		this.uploadMessage = uploadMessage;
	}

	/**
	 * @return the widgetProfile
	 */
	public Widgetprofile getWidgetProfile() {
		return widgetProfile;
	}

	/**
	 * @param widgetProfile the widgetProfile to set
	 */
	public void setWidgetProfile(Widgetprofile widgetProfile) {
		this.widgetProfile = widgetProfile;
	}

	/**
	 * @return the widgetFolderPath
	 */
	public String getWidgetFolderPath() {
		return widgetFolderPath;
	}

	/**
	 * @param widgetFolderPath the widgetFolderPath to set
	 */
	public void setWidgetFolderPath(String widgetFolderPath) {
		this.widgetFolderPath = widgetFolderPath;
	}

	public void setHTMLFileList ( List<File> inList ) {
		htmlFileList = new ArrayList<String>();
		for ( File f : inList ) {
			htmlFileList.add(f.getName());
		}
	}

	public List<String> getHtmlFileList() {
		return htmlFileList;
	}

}

Return object for the widget creator calls.


/*
 * 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.codahale.shamir.perf;

import com.codahale.shamir.SecretSharing;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class LoadHarness {

  @SuppressWarnings("InfiniteLoopStatement")
  public static void main(String[] args) throws Exception {
    System.out.println("Press enter to begin");
    new BufferedReader(new InputStreamReader(System.in)).readLine();
    System.out.println("Running...");
    final byte[] secret = new byte[10 * 1024];
    while (true) {
      SecretSharing.combine(SecretSharing.split(200, 20, secret));
    }
  }
}

Add load harness for profiling.


/* This file is part of PV-StarAPI for Bukkit, licensed under the MIT License (MIT).
 *
 * Copyright (c) JCThePants (www.jcwhatever.com)
 *
 * 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.jcwhatever.bukkit.pvs;

import com.jcwhatever.bukkit.generic.language.Localized;

public class Lang {

    private Lang() {}

    @Localized
    public static String get(String text, Object... params) {
        PVStar pvStar = PVStar.getPlugin(PVStar.class);
        if (pvStar == null)
            throw new RuntimeException("PV-Star instance not found.");

        return pvStar.getLanguageManager().get(text, params);
    }
}

Move from API, remove localization from API


package com.redhat.ipaas.rest;

import org.jboss.resteasy.plugins.interceptors.CorsFilter;

import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.ext.Provider;

@Provider
public class CorsFeature implements Feature {

    @Override
    public boolean configure(FeatureContext context) {
        CorsFilter corsFilter = new CorsFilter();
        corsFilter.getAllowedOrigins().add("*");
        context.register(corsFilter);
        return true;
    }

}

Add open CORS filter - let anyone in!


package ch.hearc.p3.recsys.settings;

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

import ch.hearc.p3.recsys.bookanalysis.TypeData;

public class SettingsBookAnalysis
{
	public static final Map<TypeData, Double>	ATTRIBUTE_WEIGHT_FACTOR;

	private static final double					ATTRIBUTE_WEIGHT_TITLE		= 1.0;
	private static final double					ATTRIBUTE_WEIGHT_AUTHOR		= 1.0;
	private static final double					ATTRIBUTE_WEIGHT_SUBJECT	= 1.0;
	private static final double					ATTRIBUTE_WEIGHT_GENRE		= 1.0;
	private static final double					ATTRIBUTE_WEIGHT_ABSTRACT	= 1.0;

	static
	{
		ATTRIBUTE_WEIGHT_FACTOR = new HashMap<TypeData, Double>();
		ATTRIBUTE_WEIGHT_FACTOR.put(TypeData.Abstract, ATTRIBUTE_WEIGHT_ABSTRACT);
		ATTRIBUTE_WEIGHT_FACTOR.put(TypeData.Author, ATTRIBUTE_WEIGHT_AUTHOR);
		ATTRIBUTE_WEIGHT_FACTOR.put(TypeData.Genre, ATTRIBUTE_WEIGHT_GENRE);
		ATTRIBUTE_WEIGHT_FACTOR.put(TypeData.Subject, ATTRIBUTE_WEIGHT_SUBJECT);
		ATTRIBUTE_WEIGHT_FACTOR.put(TypeData.Title, ATTRIBUTE_WEIGHT_TITLE);
	}
}

Add settings for the books analysis


/*
// Licensed to Julian Hyde under one or more contributor license
// agreements. See the NOTICE file distributed with this work for
// additional information regarding copyright ownership.
//
// Julian Hyde 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.eigenbase.rel;

import org.eigenbase.relopt.*;

/**
 * Definition of the ordering trait.
 *
 *
Ordering is a physical property (i.e. a trait) because it can be changed
 * without loss of information. The converter to do this is the {@link SortRel}
 * operator.

 *
 *
Unlike other current traits, a {@link RelNode} can have more than one
 * value of this trait simultaneously. For example,
 * TableAccessRel(table=TIME_BY_DAY) might be sorted by
 * {the_year, the_month, the_date} and also by
 * {time_id}. We have to allow a RelNode to belong to more than
 * one RelSubset (these RelSubsets are always in the same set).

 */
public class RelCollationTraitDef extends RelTraitDef<RelCollation>
{
    public static final RelCollationTraitDef INSTANCE =
        new RelCollationTraitDef();

    private RelCollationTraitDef() {
    }

    public Class<RelCollation> getTraitClass() {
        return RelCollation.class;
    }

    public String getSimpleName() {
        return "sort";
    }

    @Override
    public boolean multiple() {
        return true;
    }

    public RelCollation getDefault() {
        return RelCollationImpl.EMPTY;
    }

    public RelNode convert(
        RelOptPlanner planner,
        RelNode rel,
        RelCollation toCollation,
        boolean allowInfiniteCostConverters)
    {
        return new SortRel(
            rel.getCluster(),
            rel.getTraitSet().plus(toCollation),
            rel,
            toCollation);
    }

    public boolean canConvert(
        RelOptPlanner planner, RelCollation fromTrait, RelCollation toTrait)
    {
        return true;
    }
}

// End RelCollationTraitDef.java

Make sortedness a trait, and add a rule, RemoveSortRule, that implements ORDER BY by finding a rel that is already sorted. SortRel is now defined by a RelCollation, not a List<RelFieldCollation>, although they are fairly similar in content. (Most of the functionality is disabled in this commit.)


package de.slikey.effectlib.effect;

import org.bukkit.Particle;

import de.slikey.effectlib.Effect;
import de.slikey.effectlib.EffectManager;
import de.slikey.effectlib.EffectType;

public class ParticleEffect extends Effect {

    /**
     * ParticleType of spawned particle
     */
    public Particle particle = Particle.VILLAGER_ANGRY;

    public ParticleEffect(EffectManager effectManager) {
        super(effectManager);
        type = EffectType.REPEATING;
        period = 1;
        iterations = 1;
    }

    @Override
    public void onRun() {
        display(particle, getLocation());
    }
}

Add simple Particle effect, for repeating particle spawns


package com.github.dockerjava.api.model;

import static org.testng.Assert.assertEquals;

import java.util.Map;

import org.testng.annotations.Test;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.dockerjava.api.model.Ports.Binding;

public class PortsTest {
	private final ObjectMapper objectMapper = new ObjectMapper();

	@Test
	public void deserializingPortWithMultipleBindingsReturnsFirstBinding() throws Exception {
		String json = "{\"80/tcp\":[{\"HostIp\":\"10.0.0.1\",\"HostPort\":\"80\"},{\"HostIp\":\"10.0.0.2\",\"HostPort\":\"80\"}]}";
		Ports ports = objectMapper.readValue(json, Ports.class);
		Map<ExposedPort, Binding> bindings = ports.getBindings();
		assertEquals(bindings.size(), 1);

		Binding binding = bindings.get(ExposedPort.tcp(80));
		assertEquals(binding, new Binding("10.0.0.1", 80));
	}

	@Test
	public void serializePort() throws Exception {
		Ports ports = new Ports(ExposedPort.tcp(80), new Binding("10.0.0.1", 80));
		String expectedJson = "{\"80/tcp\":[{\"HostIp\":\"10.0.0.1\",\"HostPort\":\"80\"}]}";
		assertEquals(objectMapper.writeValueAsString(ports), expectedJson);
	}

}

Document current deserialization of Ports with a test