package sagan.projects.support;

import org.junit.Test;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import saganx.AbstractIntegrationTests;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

public class ProjectPageTests extends AbstractIntegrationTests {

    @Test
    public void getProjectPage() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/project/spring-boot")).andExpect(status().isOk());
    }
}

Add integration test for project page in sagan.


package com.skogsrud.halvard.sparkjava.spike;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;

import static spark.Spark.*;

public class Image {
    public static void main(String[] args) {
        get("/image", (request, response) -> {
            response.status(200);
            response.type("image/jpeg");

            BufferedImage image = new BufferedImage(256, 256, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = image.createGraphics();
            graphics.setColor(Color.WHITE);
            graphics.fillOval(64, 64, 128, 128);
            try (ServletOutputStream out = response.raw().getOutputStream()) {
                ImageIO.write(image, "JPEG", out);
            }
            return response.raw();
        });

         before((request, response) -> {
            response.header("cache-control", "no-cache, no-store, must-revalidate");
        });
    }
}

Add endpoint for returning image as JPEG


package net.tridentsdk.world.opt;

public class BlockState {

    private int id;
    private byte data;

    public BlockState(int id, byte data) {
        this.id = id;
        this.data = data;
    }

    public int getId() {
        return this.id;
    }

    public byte getData() {
        return this.data;
    }

    public int toRaw() {
        return (id << 4) | (data & 0xF);
    }

    public char toChar() {
        return (char) (id << 4 | data);
    }

    @Override
    public boolean equals(Object o) {
        return this == o || o instanceof BlockState && id == ((BlockState) o).id && data == ((BlockState) o).data;

    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (int) data;
        return result;
    }

    @Override
    public String toString() {
        return "BlockState{" +
                "id=" + id +
                ", data=" + data +
                '}';
    }

}

Add back used block state

Add back used block state


package leetcode;

import java.awt.List;

/**
 * https://leetcode.com/problems/rotate-list/
 */
public class Problem61 {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public ListNode rotateRight(ListNode head, int k) {
        return head;
    }

    public static void main(String[] args) {
        Problem61 prob = new Problem61();

        ListNode node = new ListNode(1);
        node.next = new ListNode(2);
        node.next.next = new ListNode(3);
        node.next.next.next = new ListNode(4);
        node.next.next.next.next = new ListNode(5);

        node = prob.rotateRight(node, 2);
        for (ListNode n = node; n != null; n = n.next) {
            System.out.print(n.val + " ");
        }
        System.out.println();
    }
}

Create a skeleton for problem 61

Create a skeleton for problem 61


package com.betato.gamedisplay;

public interface Game {
	// Called once when GameLoop begins
	public void init();

	// Called n times per second depending on target ups
	public void update();

	// Called n times per second depending on target fps
	public void render();

	// Called once per second to update fps and ups
	public void updateFps(int fps, int ups);
}

Add game interface to be implemented by games


package leetcode.length_of_last_word;

public class Solution {
    public int lengthOfLastWord(String s) {
    	if(s == null || s.length() == 0) return 0;
    	char[] chars = s.toCharArray();
    	int endIdx = -1, startIdx = -1;
    	for(int i = chars.length - 1; i >= 0; i--){
    		if(endIdx == -1){
	    		if(chars[i] != ' '){
	    			endIdx = i;
	    		}
    		}else if(startIdx == -1){
    			if(chars[i] == ' '){
    				startIdx = i;
    				break;
    			}
    		}
    	}
    	return endIdx - startIdx;
    }

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

Add java solution for 58. Length of Last Word

58. Length of Last Word: https://leetcode.com/problems/length-of-last-word/


// Copyright since 2016 : Evgenii Shatunov (github.com/FrankStain/jnipp-test)
// Apache 2.0 License
package com.pfs.jnipptest;

final class TestStaticFieldStorage
{
	private static boolean	bool_field		= true;
	private static String	string_field	= "Jni++";
	private static float	float_field		= 13.0f;
	private static double	double_field	= 42.0;
	private static byte		byte_field		= 28;
	private static char		char_field		= 'S';
	private static short	short_field		= 24;
	private static int		int_field		= 65536;
	private static long		long_field		= 1L << 48;
}

Test class for testing the static field handle.


/*
 * Copyright (c) 2013 by Johannes Dillmann, Zuse Institute Berlin
 *
 * Licensed under the BSD License, see LICENSE file for details.
 *
 */

package org.xtreemfs.osd;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

import org.xtreemfs.common.statusserver.StatusServerModule;
import org.xtreemfs.foundation.json.JSONParser;
import org.xtreemfs.osd.rwre.RWReplicationStage;
import org.xtreemfs.pbrpc.generatedinterfaces.DIR.ServiceType;

import com.sun.net.httpserver.HttpExchange;

public class ReplicatedFileStatusJSON extends StatusServerModule {

    private OSDRequestDispatcher myDispatcher;

    @Override
    public String getDisplayName() {
        return "OSD Replicated File Table JSON Interface";
    }

    @Override
    public String getUriPath() {
        return "/rft.json";
    }

    @Override
    public boolean isAvailableForService(ServiceType service) {
        return service == ServiceType.SERVICE_TYPE_OSD;
    }

    @Override
    public void initialize(ServiceType service, Object serviceRequestDispatcher) {
        assert (service == ServiceType.SERVICE_TYPE_OSD);
        myDispatcher = (OSDRequestDispatcher) serviceRequestDispatcher;
    }

    @Override
    public void shutdown() {
    }

    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
        try {
            final AtomicReference<Map<String, Map<String, String>>> result = new AtomicReference<Map<String, Map<String, String>>>();

            myDispatcher.getRWReplicationStage().getStatus(new RWReplicationStage.StatusCallback() {

                @Override
                public void statusComplete(Map<String, Map<String, String>> status) {
                    synchronized (result) {
                        result.set(status);
                        result.notifyAll();
                    }
                }
            });
            synchronized (result) {
                if (result.get() == null)
                    result.wait();
            }
            Map<String, Map<String, String>> status = result.get();

            String statusJSON = JSONParser.writeJSON(status);

            httpExchange.getResponseHeaders().set("Content-Type", "application/json");
            sendResponse(httpExchange, statusJSON);

        } catch (Throwable ex) {
            ex.printStackTrace();
            httpExchange.sendResponseHeaders(500, 0);
        }
    }

}

servers: Make ReplicatedFileStatus available as JSON


package com.github.davidcarboni.restolino.helpers;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

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

@RunWith(MockitoJUnitRunner.class)
public class PathTest {

	@Mock
	HttpServletRequest request;

	@Before
	public void setUp() throws Exception {
	}

	@Test
	public void shouldGeFirstSegment() {

		// Given
		when(request.getPathInfo()).thenReturn("/first/second/third");

		// When
		Path path = new Path(request);

		// Then
		assertEquals("first", path.firstSegment());
	}

	@Test
	public void shouldGeLastSegment() {

		// Given
		when(request.getPathInfo()).thenReturn("/first/second/third");

		// When
		Path path = new Path(request);

		// Then
		assertEquals("third", path.lastSegment());
	}

	@Test
	public void shouldGeSegments() {

		// Given
		when(request.getPathInfo()).thenReturn("/first/second/third");

		// When
		Path path = new Path(request);
		List<String> segments = path.segments();

		// Then
		assertEquals(3, segments.size());
		assertEquals("first", segments.get(0));
		assertEquals("second", segments.get(1));
		assertEquals("third", segments.get(2));
	}

	@Test
	public void shouldHandleEmptyPath() {

		// Given
		when(request.getPathInfo()).thenReturn("/");

		// When
		Path path = new Path(request);
		List<String> segments = path.segments();

		// Then
		assertEquals(0, segments.size());
	}

}

Test for the Path class.

Test for the Path class.


package net.ghostrealms.plot;

import net.ghostrealms.Metro;
import net.ghostrealms.Register;

import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.entity.Player;

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

public class Plot {

  private final Register register = Register.getInstance();

  private final int x;
  private final int z;
  private final Chunk chunk;

  private UUID owner;
  private List<UUID> permitted = new ArrayList<UUID>();

  public Plot(int x, int z) {
    this.x = x;
    this.z = z;
    this.chunk = Bukkit.getWorld(Metro.plugin().getConfig().getString("world")).getChunkAt(x, z);
  }

  public Plot(Player player) {
    Chunk c = player.getLocation().getChunk();
    this.chunk = c;
    x = c.getX();
    z = c.getZ();
  }

  public Plot(Location location) {
    this.chunk = location.getChunk();
    x = chunk.getX();
    z = chunk.getZ();
  }

  public void setOwner(UUID newOwner) {
    this.owner = newOwner;
  }

  private void serialize() {

  }

  private void deserialize() {

  }

}

Add multiple constructors for loading the plot object


package au.gov.ga.geodesy.support.spring;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "au.gov.ga.geodesy")
public class AppConfig {
}

Add (back in) Spring Configuration class


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

import static java.util.Objects.requireNonNull;

import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.function.Predicate;

/**
 * @author Franz Wilhelmstötter
 * @since !__version__!
 * @version !__version__! — $Date: 2015-01-06 $
 */
final class ExecutionTimeLimit implements Predicate<EvolutionResult<?, ?>>  {

	private final Duration _duration;
	private final Clock _clock;

	private Instant _start = Instant.MIN;

	ExecutionTimeLimit(final Duration duration, final Clock clock) {
		_duration = requireNonNull(duration);
		_clock = requireNonNull(clock);
	}

	@Override
	public boolean test(final EvolutionResult<?, ?> result) {
		if (_start == Instant.MIN) {
			_start = _clock.instant();
		}

		final Instant now = _clock.instant();
		return _start.plus(_duration).isAfter(now);
	}

}

Add termination strategy for maximal execution time.


package org.monospark.spongematchers.type;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.monospark.spongematchers.testutil.HamcrestSpongeMatchers.matches;

import org.junit.Test;
import org.monospark.spongematchers.matcher.SpongeMatcher;
import org.monospark.spongematchers.parser.SpongeMatcherParseException;
import org.monospark.spongematchers.parser.element.StringElement;
import org.monospark.spongematchers.parser.element.StringElementParser;
import org.spongepowered.api.block.BlockType;
import org.spongepowered.api.data.Property;

import com.google.common.collect.ImmutableSet;

public class BlockTypeTypeTest {

    @Test
    public void canMatch_NonBlockTypeObject_ReturnsFalse() throws SpongeMatcherParseException {
        Object o = 5;

        boolean canMatch = MatcherType.BLOCK_TYPE.canMatch(o);

        assertThat(canMatch, is(false));
    }

    @Test
    public void canMatch_BlockTypeObject_ReturnsTrue() throws Exception {
        Object o = mock(BlockType.class);

        boolean canMatch = MatcherType.BLOCK_TYPE.canMatch(o);

        assertThat(canMatch, is(true));
    }

    @SuppressWarnings("unchecked")
    @Test
    public void parseMatcher_ValidMapElement_ReturnsCorrectSpongeMatcher() throws SpongeMatcherParseException {
        StringElement element = StringElementParser.parseStringElement("{'id':'minecraft:appl.',"
                + "'properties':{'test1':1,'test2':false}}");

        SpongeMatcher<BlockType> matcher = MatcherType.BLOCK_TYPE.parseMatcher(element);

        Property<String, Integer> p1 = mock(Property.class);
        when(p1.getKey()).thenReturn("test1");
        when(p1.getValue()).thenReturn(1);
        Property<String, Boolean> p2 = mock(Property.class);
        when(p2.getKey()).thenReturn("test2");
        when(p2.getValue()).thenReturn(false);
        BlockType type = mock(BlockType.class);
        when(type.getId()).thenReturn("minecraft:apple");
        when(type.getApplicableProperties()).thenReturn(ImmutableSet.of(p1, p2));
        assertThat(matcher, matches(type));
    }
}

Add tests for BlockType matcher parsing

Add tests for BlockType matcher parsing


/*
 * Grapht, an open source dependency injector.
 * Copyright 2010-2012 Regents of the University of Minnesota and contributors
 *
 * This program 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 program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 51
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
package org.grouplens.grapht.graph;

import org.apache.commons.lang3.tuple.Pair;
import org.junit.Test;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertThat;

/**
 * @author GroupLens Research
 */
public class DAGNodeBuilderTest {
    @Test
    public void testGetLabel() {
        DAGNodeBuilder<String,String> bld = DAGNode.newBuilder();
        assertThat(bld.getLabel(), nullValue());
        bld.setLabel("foo");
        assertThat(bld.getLabel(), equalTo("foo"));
    }

    @Test
    public void testGetEdges() {
        DAGNodeBuilder<String,String> bld = DAGNode.newBuilder("foo");
        assertThat(bld.getEdges(), hasSize(0));
        DAGNode<String,String> nbr = DAGNode.singleton("bar");
        bld.addEdge(nbr, "piper");
        assertThat(bld.getEdges(),
                   contains(Pair.of(nbr, "piper")));
        DAGNode<String,String> node = bld.build();
        assertThat(node.getLabel(), equalTo("foo"));
        assertThat(node.getAdjacentNodes(), contains(nbr));
    }
}

Add tests for DAG node builder accessors


package com.intellij.debugger.streams.ui;

import com.intellij.debugger.streams.resolve.ResolvedTrace;
import com.intellij.debugger.streams.trace.smart.TraceElement;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * @author Vitaliy.Bibaev
 */
public class TraceControllerImpl implements TraceController, ValuesHighlightingListener {
  private static final ValuesHighlightingListener EMPTY_LISTENER = (values, direction) -> {
  };
  private final List<TraceContainer> myListeners = new CopyOnWriteArrayList<>();
  private final ValuesSelectionListener mySelectionListener;
  private final ResolvedTrace myResolvedTrace;

  private ValuesHighlightingListener myPrevListener = EMPTY_LISTENER;
  private ValuesHighlightingListener myNextListener = EMPTY_LISTENER;

  TraceControllerImpl(@NotNull ResolvedTrace trace) {
    myResolvedTrace = trace;
    mySelectionListener = elements -> {
      highlightAll(elements);
      final List<TraceElement> nextValues =
        elements.stream().flatMap(x -> myResolvedTrace.getNextValues(x).stream()).collect(Collectors.toList());
      final List<TraceElement> prevValues =
        elements.stream().flatMap(x -> myResolvedTrace.getPreviousValues(x).stream()).collect(Collectors.toList());
      myNextListener.highlightingChanged(nextValues, PropagationDirection.FORWARD);
      myPrevListener.highlightingChanged(prevValues, PropagationDirection.BACKWARD);
    };
  }

  void setPreviousListener(@NotNull ValuesHighlightingListener listener) {
    myPrevListener = listener;
  }

  void setNextListener(@NotNull ValuesHighlightingListener listener) {
    myNextListener = listener;
  }

  public List<TraceElement> getValues() {
    return myResolvedTrace.getValues();
  }

  @Override
  public void register(@NotNull TraceContainer listener) {
    myListeners.add(listener);
    listener.addSelectionListener(mySelectionListener);
  }

  @Override
  public void highlightingChanged(@NotNull List<TraceElement> values, @NotNull PropagationDirection direction) {
    highlightAll(values);

    if (direction.equals(PropagationDirection.BACKWARD)) {
      myPrevListener.highlightingChanged(values, PropagationDirection.BACKWARD);
    }
    else {
      myPrevListener.highlightingChanged(values, PropagationDirection.FORWARD);
    }
  }

  private void highlightAll(@NotNull List<TraceElement> values) {
    for (final TraceContainer listener : myListeners) {
      listener.highlight(values);
    }
  }
}

Add simple implementation fot trace controller


package net.gcdc.asn1.uper;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;

import net.gcdc.asn1.datatypes.Asn1SequenceOf;
import net.gcdc.asn1.datatypes.Asn1VarSizeBitstring;
import net.gcdc.asn1.datatypes.Bitstring;
import net.gcdc.asn1.datatypes.FixedSize;
import net.gcdc.asn1.datatypes.Sequence;
import net.gcdc.asn1.datatypes.SizeRange;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Example of encoding the following definitions:
 <pre>
 ON-PDU DEFINITIONS AUTOMATIC TAGS ::=
BEGIN
IMPORTS
    FOO
     FROM ON-API;
Packet ::= SEQUENCE {
    foo FOO
}
END

ON-API DEFINITIONS AUTOMATIC TAGS ::=
BEGIN
FOO ::= SEQUENCE {
    bar BAR,
    baz BAZ
}
BAR ::= OCTET STRING (SIZE(3))
BAZ ::= BIT STRING (SIZE(8))
END
</pre>
*
 *
 */
public class UperEncoderQuestion1Test {
    private final static Logger logger = LoggerFactory.getLogger(UperEncoderQuestion1Test.class);

    @Sequence
    public static class Foo {
        Bar bar;
        Baz baz;

        public Foo(Bar bar, Baz baz) { this.bar = bar; this.baz = baz; }
    }

    @SizeRange(maxValue = 3, minValue = 3)  // @SizeRange with equal bounds is a temporary solution until @FixedSize is implemented for SEQUENCE OF.
    public static class Bar extends Asn1SequenceOf<Byte> {
        // Two constructors -- choose any, or add more.
        public Bar(Byte... coll)          { this(Arrays.asList(coll)); }
        public Bar(Collection<Byte> coll) { super(coll); }
    }

    @Bitstring
    @FixedSize(8)
    public static class Baz extends Asn1VarSizeBitstring {

        // Two constructors -- choose any.
        public Baz(BitSet bitset)            { super(bitset); }
        public Baz(Collection<Boolean> coll) { super(coll); }
    }

    @Test public void QuestionTest() throws IllegalArgumentException, IllegalAccessException {
       Object pdu =
                new Foo(
                    new Bar( (byte) 0xff, (byte) 0xff, (byte) 0xff),
                    new Baz(BitSet.valueOf(new byte[] {(byte) 0xff}))
              );
        byte[] encoded = UperEncoder.encode(pdu);
        logger.debug("data hex: {}", UperEncoder.hexStringFromBytes(encoded));
        assertEquals("FFFFFFFF",
                UperEncoder.hexStringFromBytes(encoded));
    }
}

Add test with example of encoding Octet String and Bit String


package guitests;

import static org.junit.Assert.*;
import static seedu.jimi.logic.commands.DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS;

import org.junit.Test;

import seedu.jimi.testutil.TestFloatingTask;
import seedu.jimi.testutil.TestUtil;

public class CompleteCommandTest extends AddressBookGuiTest {

    @Test
    public void complete() {

        //complete the first task in the list
        TestFloatingTask[] currentList = td.getTypicalTasks();
        int targetIndex = 1;
        assertCompleteSuccess(targetIndex, currentList);

        //complete the last in the list
        currentList = TestUtil.completeTaskFromList(currentList, targetIndex);
        targetIndex = currentList.length;
        assertCompleteSuccess(targetIndex, currentList);

        //complete from the middle of the list
        currentList = TestUtil.completeTaskFromList(currentList, targetIndex);
        targetIndex = currentList.length/2;
        assertCompleteSuccess(targetIndex, currentList);

        //invalid index
        commandBox.runCommand("complete " + currentList.length + 1);
        assertResultMessage("The task index provided is invalid");

    }

    /**
     * Runs the complete command to complete the task at specified index and confirms the result is correct.
     * @param targetIndexOneIndexed e.g. to delete the first task in the list, 1 should be given as the target index.
     * @param currentList A copy of the current list of tasks (before completion).
     */
    private void assertCompleteSuccess(int targetIndexOneIndexed, final TestFloatingTask[] currentList) {
        TestFloatingTask taskToComplete = currentList[targetIndexOneIndexed-1]; //-1 because array uses zero indexing

        commandBox.runCommand("complete " + targetIndexOneIndexed);

        //confirm the list now contains the task being set to complete
        assertTrue(taskListPanel.getTask(targetIndexOneIndexed).isCompleted());

        //confirm the result message is correct
        assertResultMessage(String.format(MESSAGE_DELETE_TASK_SUCCESS, taskToComplete));
    }

}

Add JUnit tests for CompleteCommand

Add JUnit tests for CompleteCommand


package me.haosdent.cgroup.subsystem;

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

public class TestNetCls {

  @Before
  public void setUp() {}

  @After
  public void tearDown() {}

  @Test
  public void testSetClassId() {}

  @Test
  public void testGetClassId() {}
}

Add net_cls subsystem test class.

Add net_cls subsystem test class.


package leetcode;

/**
 * https://leetcode.com/problems/sum-of-two-integers/
 */
public class Problem371 {
    public int getSum(int a, int b) {
        return 0;
    }

    public static void main(String[] args) {
        Problem371 prob = new Problem371();
        System.out.println(prob.getSum(1, 3)); // 4
        System.out.println(prob.getSum(1, -3)); // -2
        System.out.println(prob.getSum(1, 1)); // 2
    }
}

Create a skeleton for problem 371

Create a skeleton for problem 371


package net.restlesscoder.sandbox.imagej;
/*
 * To the extent possible under law, the ImageJ developers have waived
 * all copyright and related or neighboring rights to this tutorial code.
 *
 * See the CC0 1.0 Universal license for details:
 *     http://creativecommons.org/publicdomain/zero/1.0/
 */

import net.imagej.ImageJ;

import org.scijava.ItemIO;
import org.scijava.command.Command;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.widget.ChoiceWidget;

/**
 * Demonstration of multiple choice parameters.
 *
 * @author Curtis Rueden
 */
@Plugin(type = Command.class,
	menuPath = "Plugins>ImageJ Tutorials>Multiple Choice")
public class MultipleChoice implements Command {

	@Parameter(label = "Favorite word",
		choices = { "The", "quick", "brown", "fox",
			"jumps", "over", "the", "lazy", "dog" })
	private String word;

	@Parameter(label = "Green eggs and ham",
		style = ChoiceWidget.RADIO_BUTTON_HORIZONTAL_STYLE,
		choices = { "Yes", "No", "Maybe" })
	private String eggsHam;

	@Parameter(label = "Rating",
		style = ChoiceWidget.RADIO_BUTTON_VERTICAL_STYLE,
		choices = {
			"Loved",
			"Really liked",
			"Liked",
			"Disliked",
			"Really disliked"
		})
	private String rating;

	@Parameter(type = ItemIO.OUTPUT)
	private String info;

	@Override
	public void run() {
		info = "" + //
			"word = " + word + "\n" + //
			"eggsHam = " + eggsHam + "\n" + //
			"rating = " + rating;
	}

	public static void main(final String... args) throws Exception {
		final ImageJ ij = new ImageJ();
		ij.launch(args);
		ij.command().run(MultipleChoice.class, true);
	}

}

Add demo of multiple-choice SciJava parameters


package us.kbase.common.utils;

/**
 * Miscellaneous methods for dealing with strings.
 *
 * @author gaprice@lbl.gov
 *
 */
public class StringUtils {

	/**
	 * Checks that a string is neither null or empty.
	 * @param s the string to check.
	 * @param sname the name of the variable. This name will be used in the
	 * thrown exception.
	 * @throws IllegalArgumentException if the string is null or empty.
	 */
	public static void isNonEmptyString(final String s, final String sname) {
		if (s == null || s.isEmpty()) {
			throw new IllegalArgumentException(sname +
					" cannot be null or the empty string");
		}
	}

}

Add simple method for checking a string is non-empty


/*
 * Copyright 2016 Martin Kamp Jensen
 *
 * 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.mkjensen.dml.ondemand;

import static org.junit.Assert.assertNotNull;

import android.view.View;

import com.github.mkjensen.dml.R;
import com.github.mkjensen.dml.test.RobolectricTest;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.robolectric.Robolectric;

/**
 * Tests for {@link SearchActivity}.
 */
@Ignore("See https://github.com/mkjensen/danish-media-license/issues/26")
public class SearchActivityTest extends RobolectricTest {

  private SearchActivity searchActivity;

  /**
   * Creates a {@link SearchActivity} instance.
   */
  @Before
  public void before() {
    searchActivity = Robolectric.buildActivity(SearchActivity.class)
        .create()
        .get();
  }

  @Test
  public void findViewById_onDemandSearchFragmentExists() {

    // When
    View searchFragment = searchActivity.findViewById(R.id.ondemand_search_fragment);

    // Then
    assertNotNull(searchFragment);
  }
}

Add (ignored, for now) tests for SearchActivity


/*
 * 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.trustedsolutions;
import gnu.io.CommPortIdentifier;
import java.util.Enumeration;
/**
 *
 * @author loki.chuang
 */
public class TestRxTx
{
    public static void main(String args[])
    {
        System.out.println("RXTX TEST!");

        Enumeration ports=CommPortIdentifier.getPortIdentifiers();
        while(ports.hasMoreElements())
        {
            CommPortIdentifier cpIdentifier = (CommPortIdentifier)ports.nextElement();
            System.out.println(cpIdentifier.getName());
        }

    }
}

Add test for RXTX comport library

Add test for RXTX comport library


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

/**
 * Provides lightweight, feature complete Raft client.
 *
 * @author Jordan Halterman
 */
package net.kuujo.copycat.raft.client;

Add package description to Raft client.

Add package description to Raft client.


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

package org.sablecc.sablecc.launcher;

import junit.framework.TestCase;

import org.sablecc.sablecc.exception.InternalException;

public class OptionArgumentTest
        extends TestCase {

    OptionArgument optionArgument;

    Option option;

    String operand;

    @Override
    protected void setUp()
            throws Exception {

        this.option = Option.DESTINATION;

        this.operand = "operand";

        this.optionArgument = new OptionArgument(this.option, this.operand);
    }

    public void testOptionArgument() {

        // Case with null option
        Option nullOption = null;
        try {
            this.optionArgument = new OptionArgument(nullOption, this.operand);
            fail("option may not be null");
        }
        catch (InternalException e) {
            // Expected
        }

        assertEquals("invalid option", this.option, this.optionArgument
                .getOption());
        assertEquals("invalid operand", this.operand, this.optionArgument
                .getOperand());
    }
}

Add JUnit tests. See ticket:59.

Add JUnit tests. See ticket:59.

Signed-off-by: Raymond Audet <281aa2b19aab01efe2941a7da076ec0616a9b992@gmail.com>
Signed-off-by: Etienne M. Gagnon <bf06ec0eb40152cd863534753d026b021022c851@j-meg.com>


package org.robockets.stronghold.robot.autonomous;

import org.robockets.stronghold.robot.Robot;
import org.robockets.stronghold.robot.drivetrain.AssistedDrive;
import org.robockets.stronghold.robot.drivetrain.AssistedRotateType;
import org.robockets.stronghold.robot.drivetrain.AssistedTranslateType;
import org.robockets.stronghold.robot.highgoalshooter.FreeFire;

import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 * NOTE: All values are temporary
 */
public class AutoShootHigh extends CommandGroup {

    public  AutoShootHigh(int defense) {
        Command turnCommand = null;
        Command translateCommand = null;

        switch (defense) {
	        case 1:
		        turnCommand = new AssistedDrive(AssistedRotateType.GYRO, 45);
		        translateCommand = new AssistedDrive(AssistedTranslateType.ENCODER, AssistedRotateType.ENCODER, 5, Robot.driveTrain.getEncodersOffset());
		        break;
	        case 2:
		        turnCommand = new AssistedDrive(AssistedRotateType.GYRO, 30);
		        translateCommand = new AssistedDrive(AssistedTranslateType.ENCODER, AssistedRotateType.ENCODER, 3, Robot.driveTrain.getEncodersOffset());
		        break;
	        case 3:
		        turnCommand = new AssistedDrive(AssistedRotateType.GYRO, 0);
		        translateCommand = new AssistedDrive(AssistedTranslateType.ENCODER, AssistedRotateType.ENCODER, 1, Robot.driveTrain.getEncodersOffset());
		        break;
	        case 4:
		        turnCommand = new AssistedDrive(AssistedRotateType.GYRO, -30);
		        translateCommand = new AssistedDrive(AssistedTranslateType.ENCODER, AssistedRotateType.ENCODER, 3, Robot.driveTrain.getEncodersOffset());
		        break;
	        case 5:
	        	turnCommand = new AssistedDrive(AssistedRotateType.GYRO, -45);
		        translateCommand = new AssistedDrive(AssistedTranslateType.ENCODER, AssistedRotateType.ENCODER, 5, Robot.driveTrain.getEncodersOffset());
	        	break;
        }

        addSequential(turnCommand);
        addSequential(translateCommand);
        addSequential(new FreeFire());
    }
}

Add auto shoot high command

Add auto shoot high command


package com.ushahidi.android.data.entity;

import com.ushahidi.android.BuildConfig;

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

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

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

    @Test
    public void shouldSetFormEntityTest() {
        FormEntity formEntity = TestEntityFixtures.getFormEntity();
        assertThat(formEntity).isNotNull();
        assertThat(formEntity).isInstanceOf(FormEntity.class);
        assertThat(formEntity.getName()).isNotNull();
        assertThat(formEntity.getName()).isEqualTo(TestEntityFixtures.getFormEntity().getName());
        assertThat(formEntity.getDeploymentId()).isNotNull();
        assertThat(formEntity.getDeploymentId()).isEqualTo(
                TestEntityFixtures.getFormEntity().getDeploymentId());
        assertThat(formEntity.getDescription()).isNotNull();
        assertThat(formEntity.getDescription())
                .isEqualTo(TestEntityFixtures.getFormEntity().getDescription());
        assertThat(formEntity.getCreated()).isNotNull();
        assertThat(formEntity.getCreated())
                .isEqualTo(TestEntityFixtures.getFormEntity().getCreated());
        assertThat(formEntity.getUpdated()).isNotNull();
        assertThat(formEntity.getUpdated())
                .isEqualTo(TestEntityFixtures.getFormEntity().getUpdated());
        assertThat(formEntity.isDisabled()).isTrue();
    }
}

Add test for form entity

Add test for form entity


package org.assertj.db.api;

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

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;

import org.assertj.db.common.AbstractTest;
import org.junit.Test;

/**
 * Test on the utility class {@code Assertions} : the private constructor.
 *
 * @author Régis Pouiller
 *
 */
public class Assertions_Constructor_Test extends AbstractTest {

  /**
   * This method tests the private constructor of {@code Assertions} for the tests coverage..
   * @throws NoSuchMethodException
   * @throws SecurityException
   * @throws InvocationTargetException
   * @throws IllegalAccessException
   * @throws InstantiationException
   * @throws IllegalArgumentException
   */
  @Test
  public void test_private_constructor_for_the_tests_coverage() throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
    Constructor<Assertions> constructor = Assertions.class.getDeclaredConstructor();
    assertThat(Modifier.isPrivate(constructor.getModifiers())).isTrue();
    constructor.setAccessible(true);
    constructor.newInstance();
    constructor.setAccessible(false);
  }
}

Add test on private constructor of Assertions


package phys2d.collisionLogic.tools;

import phys2d.entities.shapes.Shape;

/**
 * A small class to hold 2 pairs of shapes that have been checked for collision. <br>
 * Is more or less being used so that it's hashing can be used to make the the
 * check that prevents redundant collision checks, quicker.
 *
 * @author Afsheen
 *
 */
public class CollisionPairs {

    private Shape s1, s2;

    public CollisionPairs(Shape s1, Shape s2) {
        this.s1 = s1;
        this.s2 = s2;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime
                * (result + ((s1 == null) ? 0 : s1.hashCode()) + ((s2 == null) ? 0
                        : s2.hashCode()));
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        CollisionPairs other = (CollisionPairs) obj;
        if (s1 == null) {
            if (other.s1 != null)
                return false;
        }
        else if (!s1.equals(other.s1))
            return false;
        if (s2 == null) {
            if (other.s2 != null)
                return false;
        }
        else if (!s2.equals(other.s2))
            return false;
        return true;
    }

}

Create new class to make Speculative2 more effecient


import a.A;
import a.B;
import com.google.Foo;

@A
@B
module com.google.m {
    requires com.google.r1;
    requires transitive com.google.r2;
    requires static com.google.r3;

    exports com.google.e1;
    exports com.google.e1 to
            com.google.e2;
    exports com.google.e1 to
            com.google.e2,
            com.google.e3;
    exports com.google.e1 to
            com.google.e2,
            com.google.e3,
            com.google.e4;

    opens com.google.o1;
    opens com.google.o1 to
            com.google.o2;
    opens com.google.o1 to
            com.google.o2,
            com.google.o3;
    opens com.google.o1 to
            com.google.o2,
            com.google.o3,
            com.googleoe4;

    uses Foo;
    uses com.google.Bar;

    provides com.google.Baz with
            Foo;
    provides com.google.Baz with
            Foo,
            com.google.Bar;
}

Add missing test resource file

Add missing test resource file


import org.junit.Test;

public class palindrometest {

    @Test
    public void whenStringIsSingleLetterThenItIsAPalindrome() {
        assert (palindrome.isPalindrome("a"));
    }

    @Test
    public void checkForCaseInsensitivity(){
        assert (palindrome.isPalindrome("aAbbbBaa"));
    }

    @Test
    public void whenStringIsntPalindromeThenReturnFalse(){
        assert (!palindrome.isPalindrome("abbab"));
    }
}

Add string palindrom test for Java implementation


package com.github.jochenw.afw.core.cli;

public abstract class Option<O> {
	private final Class<O> type;
	private boolean required, given;
	private O value;
	private String strValue;
	private String[] names;
	private String defaultValue;
	private String[] description;

	protected Option(Class<O> pType) {
		type = pType;
	}

	public Class<O> getType() {
		return type;
	}

	public String getDefaultValue() {
		return defaultValue;
	}

	protected void setDefaultValue(String pDefaultValue) {
		defaultValue = pDefaultValue;
	}

	public boolean isRequired() {
		return required;
	}

	protected void setRequired(boolean pRequired) {
		required = pRequired;
	}

	public boolean isGiven() {
		return given;
	}

	protected void setGiven(boolean pGiven) {
		given = pGiven;
	}

	public O getValue() {
		return value;
	}

	protected void setValue(O pValue) {
		value = pValue;
	}

	public String getStrValue() {
		return strValue;
	}

	protected void setStrValue(String pStrValue) {
		strValue = pStrValue;
		setGiven(true);
		final O value = asValue(pStrValue);
		setValue(value);
	}

	public String[] getNames() {
		return names;
	}

	protected void setNames(String[] pNames) {
		names = pNames;
	}

	public String[] getDescription() {
		return description;
	}

	protected void setDescription(String[] pDescription) {
		description = pDescription;
	}

	protected abstract O asValue(String pStrValue);

	protected abstract boolean isValueRequired();
}

Work on the stream package.

Work on the stream package.


package tbx2rdf;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.vocabulary.RDF;
import java.io.FileReader;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import tbx2rdf.types.TBX_Terminology;
import tbx2rdf.vocab.ONTOLEX;

/**
 *
 * @author jmccrae
 */
public class Simple1Test {

    private Model model;

    public Simple1Test() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() throws Exception {
        final Mappings mappings = Mappings.readInMappings("mappings2.default");
        final TBX_Terminology terminology = new TBX2RDF_Converter().convert(new FileReader("samples/simple1.xml"), mappings);
        model = terminology.getModel("http://www.example.com/example#");
    }

    @After
    public void tearDown() {
    }

    /**
     * Test there is at least one triple in the model
     */
    @Test
    public void testNotEmpty() throws Exception {
        final List<Statement> stat = model.listStatements(null, null, (String)null).toList();
        assert(!stat.isEmpty());
    }

    /*
     * Test every lexical entry has a canonical form
    */
    @Test
    public void testCanonicalForm() throws Exception {
        final List<Statement> stats = model.listStatements(null, RDF.type, ONTOLEX.LexicalEntry).toList();
        for(Statement stat : stats) {
            final List<Statement> stats2 = model.listStatements(stat.getSubject(), ONTOLEX.canonicalForm, (RDFNode)null).toList();
            assert(!stats2.isEmpty());
        }
    }

}

Add unit test example for TDD with Philipp


/*
 * This file is part of ELKI:
 * Environment for Developing KDD-Applications Supported by Index-Structures
 *
 * Copyright (C) 2020
 * ELKI Development Team
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package elki.evaluation.clustering;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import elki.database.ids.DBIDRange;
import elki.database.ids.DBIDUtil;

/**
 * Validate the {@link PairSetsIndex} measures.
 *
 * @author Robert Gehde
 */
public class PairSetsIndexTest extends AbstractClusterEvaluationTest {
  @Test
  public void testPairSetsIndexEquals() {
    DBIDRange ids = DBIDUtil.generateStaticDBIDRange(SAMEA.length);
    PairSetsIndex psi = new PairSetsIndex(new ClusterContingencyTable(false, false, makeClustering(ids.iter(), SAMEA), makeClustering(ids.iter(), SAMEB)));

    assertEquals("PSI on an equal example should be 1.", 1, psi.psi, 1e-13);
    assertEquals("Simplified PSI on an equal example should be 1.", psi.simplifiedPSI, 1, 1e-13);
  }

  @Test
  public void tesPairSetsIndexSKLearn() {
    DBIDRange ids = DBIDUtil.generateStaticDBIDRange(SKLEARNA.length);
    PairSetsIndex psi = new PairSetsIndex(new ClusterContingencyTable(false, false, makeClustering(ids.iter(), SKLEARNA), makeClustering(ids.iter(), SKLEARNB)));

    assertEquals("PSI value not as expected", .516598639455782, psi.psi, 1e-13);
    assertEquals("Simplified PSI value not as expected", .502380952380952, psi.simplifiedPSI, 1e-13);
  }
}

Add unit test for Pair Sets Index

Add unit test for Pair Sets Index


package com.ushahidi.android.domain.entity;

import com.ushahidi.android.BuildConfig;

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

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

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

    @Test
    public void shouldSetFormAttribute() {
        FormAttribute formAttribute = TestFixtures.getFormAttribute();
        assertThat(formAttribute).isNotNull();
        assertThat(formAttribute.getKey()).isEqualTo("test_varchar");
        assertThat(formAttribute.getFormId())
                .isEqualTo(2l);
        assertThat(formAttribute.getKey())
                .isEqualTo("test_varchar");
        assertThat(formAttribute.getLabel())
                .isEqualTo("Test varchar");
        assertThat(formAttribute.getRequired())
                .isTrue();
        assertThat(formAttribute.getPriority())
                .isEqualTo(1);
        assertThat(formAttribute.getCardinality())
                .isEqualTo(1);
        assertThat(formAttribute.getOptions()).isNull();
    }
}

Add test for setting form attribute

Add test for setting form attribute


package org.graphstream.gama.extension;

import java.lang.management.ManagementFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.graphstream.gama.extension.sender.GSSender;

import org.graphstream.stream.sync.SinkTime;
import org.graphstream.stream.sync.SourceTime;

/**
 * This is the main extension class.
 *
 * It maintains a common sync mechanism for all senders and receivers, as well
 * as methods to access senders and receivers by their id, to add and to remove
 * them.
 *
 * @author Stefan Balev
 *
 */
public class GSManager {
	private static String sourceId;
	private static SourceTime sourceTime;
	private static SinkTime sinkTime;

	private static Map<String, GSSender> senders;
//	private static Map<String, GSReceiver> receivers;

	static {
		sourceId = "gs-gama@"
				+ ManagementFactory.getRuntimeMXBean().getName();
		sourceTime = new SourceTime(sourceId);
		sinkTime = new SinkTime();
		sourceTime.setSinkTime(sinkTime);
		senders = new HashMap<String, GSSender>();
//		receivers = new HashMap<String, GSReceiver>();
	}

	public static GSSender getSender(String senderId)  {
		GSSender sender = senders.get(senderId);
		if (sender == null)
			System.out.println("Sender \"" + senderId
					+ "\" does not exist");
		return sender;
	}

	public static void addSender(String senderId, String host, int port) {
		GSSender sender = senders.get(senderId);
		if (sender != null)
			System.out.println("Sender \"" + senderId
					+ "\" already exists");
		sender = new GSSender(sourceId, sourceTime, host, port);
		senders.put(senderId, sender);
	}

	public static void clearSenders() {
		for (GSSender sender : senders.values())
			sender.close();
		senders.clear();
	}

	/*public static GSReceiver getReceiver(String receiverId)
			throws ExtensionException {
		GSReceiver receiver = receivers.get(receiverId);
		if (receiver == null)
			throw new ExtensionException("Receiver \"" + receiverId
					+ "\" does not exist");
		return receiver;
	}

	public static void addReceiver(String receiverId, String host, int port,
			Set<String> attributeFilter) throws ExtensionException {
		GSReceiver receiver = receivers.get(receiverId);
		if (receiver != null)
			throw new ExtensionException("Receiver \"" + receiverId
					+ "\" already exists");
		receiver = new GSReceiver(sinkTime, host, port, attributeFilter);
		receivers.put(receiverId, receiver);
	}

	public static void clearReceivers() {
		for (GSReceiver receiver : receivers.values())
			receiver.close();
		receivers.clear();
	}*/
}

Add the main class of the plugin (almost a copy from the netlogo extension)


package org.textfiledatatools.core.mapper;

import org.textfiledatatools.core.Record;

/**
 * @author Mathias Kalb
 * @since 0.1
 */
public class IdentityMapper<T extends Record> implements UnaryRecordMapper<T> {

    @Override
    public T map(T record) {
        return record;
    }

}

Add a simple RecordMapper implementation


package de.lmu.ifi.dbs.elki.math;

import static org.junit.Assert.assertEquals;

import java.util.Random;

import org.junit.Test;

import de.lmu.ifi.dbs.elki.JUnit4Test;

/**
 * Unit test if negative weights in {@link MeanVariance} work as desired.
 *
 * @author Erich Schubert
 */
public class TestSlidingVariance implements JUnit4Test {
  /**
   * Size of test data set.
   */
  private static final int SIZE = 100000;

  /**
   * Sliding window size.
   */
  private static final int WINDOWSIZE = 100;

  @Test
  public void testSlidingWindowVariance() {
    MeanVariance mv = new MeanVariance();
    MeanVariance mc = new MeanVariance();

    Random r = new Random();
    double[] data = new double[SIZE];
    for(int i = 0; i < data.length; i++) {
      data[i] = r.nextDouble();
    }

    // Pre-roll:
    for(int i = 0; i < WINDOWSIZE; i++) {
      mv.put(data[i]);
    }
    // Compare to window approach
    for(int i = WINDOWSIZE; i < data.length; i++) {
      mv.put(data[i - WINDOWSIZE], -1.); // Remove
      mv.put(data[i]);

      mc.reset(); // Reset statistics
      for(int j = i + 1 - WINDOWSIZE; j <= i; j++) {
        mc.put(data[j]);
      }
      // Fully manual statistics, exact two-pass algorithm:
      double mean = 0.0;
      for(int j = i + 1 - WINDOWSIZE; j <= i; j++) {
        mean += data[j];
      }
      mean /= WINDOWSIZE;
      double var = 0.0;
      for(int j = i + 1 - WINDOWSIZE; j <= i; j++) {
        double v = data[j] - mean;
        var += v * v;
      }
      var /= (WINDOWSIZE - 1);
      assertEquals("Variance does not agree.", mv.getSampleVariance(), mc.getSampleVariance(), 1e-14);
      assertEquals("Variance does not agree.", mv.getSampleVariance(), var, 1e-14);
    }
  }
}

Test sliding window variance support.

Test sliding window variance support.


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class AppConfig {

    public static void main(String[] args) {
        SpringApplication.run(AppConfig.class, args);
    }
}

ROUT-7: Implement the spring application entry point


package edu.northwestern.bioinformatics.studycalendar.dao;

import edu.northwestern.bioinformatics.studycalendar.domain.ScheduledArm;

/**
 * @author Rhett Sutphin
 */
public class ScheduledArmDaoTest extends ContextDaoTestCase<ScheduledArmDao> {
    protected String getTestDataFileName() {
        return "testdata/ScheduledCalendarDaoTest.xml";
    }

    public void testGetById() throws Exception {
        ScheduledArm loaded = getDao().getById(-22);
        assertEquals("Wrong arm", -4, (int) loaded.getArm().getId());
        assertEquals("Wrong schedule", -20, (int) loaded.getScheduledCalendar().getId());
    }
}

Test for ScheduledArmDao (loading is more rigorously tested in ScheduledCalendarDaoTest)


package study.hard.javalib.nativelib.system;

import org.junit.Test;

public class GetenvTest {

	@Test
	public void testGetEnv() {
		final String value = System.getenv("TEMP");
		System.out.println(value);
	}

}

Add a test case to get OS environment variables.


package nz.ac.lconz.irr.dspace.app.xmlui.aspect.general;

import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.selection.Selector;
import org.dspace.app.xmlui.utils.ContextUtil;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.content.DSpaceObject;
import org.dspace.core.Constants;
import org.dspace.core.Context;

import java.sql.SQLException;
import java.util.Map;

/**
 * @author Andrea Schweer schweer@waikato.ac.nz
 *
 * Cocoon sitemap selector that indicates what type of item where looking at
 *
 */
public class HandleTypeSelector extends AbstractLogEnabled implements
		Selector {

	@Override
	public boolean select(String expression, Map objectModel, Parameters parameters) {

		try {
			Context context = ContextUtil.obtainContext(objectModel);
			DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
			if (dso == null) {
				return expression.equals("other");
			}
			int type = dso.getType();
			if (type == Constants.COMMUNITY && expression.equals("community")) {
				return true;
			} else if (type == Constants.COLLECTION && expression.equals("collection")) {
				return true;
			} else if (type == Constants.ITEM && expression.equals("item")) {
				return true;
			}
			return expression.equals("other");
		} catch (SQLException e) {
			getLogger().warn("Cannot obtain context", e);
		}
		return false; // fallback in case of errors
	}
}

Handle type selector, generic util selector


package ca.ulaval.ticketmaster.web.converter;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import ca.ulaval.ticketmaster.dao.util.DataManager;
import ca.ulaval.ticketmaster.model.Ticket;
import ca.ulaval.ticketmaster.web.viewmodels.TicketViewModel;

public class TicketConverterTest {

	@Test
	public void convertEntryToviewmodel() {
		Ticket t = new Ticket(1);
		t.setEvent(null);
		t.setOwner("owner");
		t.setPrice(1.0);
		t.setResellprice(1.0);
		t.setSeat("seat");
		t.setSection("section");

		TicketViewModel viewmodel = TicketConverter.convert(t);

		assertEquals(t.getEvent(), viewmodel.event);
		assertEquals(t.getOwner(), viewmodel.owner);
		assertEquals(t.getPrice(), viewmodel.price, 0.001);
		assertEquals(t.getResellprice(), viewmodel.resellprice, 0.001);
		assertEquals(t.getSeat(), viewmodel.seat);
		assertEquals(t.getSection(), viewmodel.section);
	}

	@Test
	public void convertviewmodelToEntry() {
		TicketViewModel viewmodel = new TicketViewModel();
		viewmodel.setEvent(null);
		viewmodel.setOwner("owner");
		viewmodel.setPrice(1.0);
		viewmodel.setResellprice(1.0);
		viewmodel.setSeat("seat");
		viewmodel.setSection("section");

		Ticket t = TicketConverter.convert(viewmodel, new DataManager());

		assertEquals(t.getEvent(), viewmodel.getEvent());
		assertEquals(t.getOwner(), viewmodel.getOwner());
		assertEquals(t.getPrice(), viewmodel.getPrice(), 0.001);
		assertEquals(t.getResellprice(), viewmodel.getResellprice(), 0.001);
		assertEquals(t.getSeat(), viewmodel.getSeat());
		assertEquals(t.getSection(), viewmodel.getSection());
	}
}

Add test for my converter

Add test for my converter


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

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

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static uk.ac.ebi.quickgo.annotation.model.AnnotationMocker.*;

/**
 * @author Tony Wardell
 * Date: 19/01/2017
 * Time: 14:19
 * Created with IntelliJ IDEA.
 */
public class GAFAnnotationTest {

    private static final int COL_DB = 0;
    private static final int COL_DB_OBJECT_ID = 1;
    private static final int COL_DB_OBJECT_SYMBOL = 2;
    private static final int COL_QUALIFIER = 3;
    private static final int COL_GO_ID = 4;
    private static final int COL_REFERENCE = 5;
    private static final int COL_EVIDENCE = 6;
    private static final int COL_WITH = 7;
    private static final int COL_ASPECT = 8;
    private static final int COL_DB_OBJECT_NAME = 9;
    private static final int COL_DB_OBJECT_SYNONYM = 10;
    private static final int COL_DB_OBJECT_TYPE = 11;
    private static final int COL_TAXON = 12;
    private static final int COL_DATE = 13;
    private static final int COL_ASSIGNED_BY = 14;
    private static final int COL_ANNOTATION_EXTENSION = 15;
    private static final int COL_GENE_PRODUCT = 16;

    private Annotation annotation;

    @Before
    public void setup(){
        annotation = AnnotationMocker.createValidAnnotation();
    }

    @Test
    public void createGAFStringFromAnnotationModel(){

        String converted = AnnotationToGAF.convert(annotation);

        String[] elements = converted.split("\t");
        assertThat(elements[COL_DB], is(DB));
        assertThat(elements[COL_DB_OBJECT_ID], is(ID));
        assertThat(elements[COL_DB_OBJECT_SYMBOL], is(SYMBOL));
        assertThat(elements[COL_QUALIFIER], is(QUALIFIER));
        assertThat(elements[COL_GO_ID], is(GO_ID));
        assertThat(elements[COL_REFERENCE], is(REFERENCE));
        assertThat(elements[COL_EVIDENCE], is(EVIDENCE_CODE));
        assertThat(elements[COL_WITH], equalTo(WITH_FROM_AS_STRING));
        assertThat(elements[COL_ASPECT], is("F"));
        assertThat(elements[COL_DB_OBJECT_NAME], is(""));        //name
        assertThat(elements[COL_DB_OBJECT_SYNONYM], is(""));       //synonym
        assertThat(elements[COL_DB_OBJECT_TYPE], is(PROTEIN_TYPE));
        assertThat(elements[COL_TAXON], is("taxon:"+TAXON_ID));
        assertThat(elements[COL_DATE], equalTo(DATE_AS_STRING));
        assertThat(elements[COL_ASSIGNED_BY], equalTo("IntAct"));
        assertThat(elements[COL_ANNOTATION_EXTENSION], is(DB));
        assertThat(elements[COL_GENE_PRODUCT], is(""));
    }

}

Add gene product type to Annotation.

Add gene product type to Annotation.


import java.util.stream.IntStream;

/**
 * @author David Clutter
 */
public class Problem1 {

    public static void main(final String[] args) {
        System.out.println(
                IntStream.range(1, 1000)
                        .filter(n -> n % 3 == 0 || n % 5 == 0)
                        .sum()
        );
    }
}

Add Answer to problem 1

Add Answer to problem 1


package com.github.aureliano.achmed.os.service;

import com.github.aureliano.achmed.command.CommandResponse;
import com.github.aureliano.achmed.exception.ServiceResourceException;
import com.github.aureliano.achmed.helper.StringHelper;
import com.github.aureliano.achmed.resources.properties.ServiceProperties;

public abstract class BaseService implements IService {

	private ServiceProperties properties;

	public BaseService() {
		super();
	}

	public CommandResponse start() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}

	public CommandResponse stop() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}

	public CommandResponse restart() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}

	public boolean isRunning() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}

	public void setServiceProperties(ServiceProperties properties) {
		this.properties = properties;
	}

	public ServiceProperties getServiceProperties() {
		return this.properties;
	}

	protected Integer getPid() {
		if (StringHelper.isEmpty(this.properties.getPattern())) {
			throw new ServiceResourceException("Cannot get process id. No pattern provided.");
		}

		throw new UnsupportedOperationException("Not implemented yet.");
	}
}

Create abstract base class to service implementations.


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

import javax.jms.ConnectionFactory;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jms.JmsComponent;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Ignore;
import org.junit.Test;

public class OrderRouterSimpleTest extends CamelTestSupport {

    @Override
    protected CamelContext createCamelContext() throws Exception {
        // create CamelContext
        CamelContext camelContext = super.createCamelContext();

        // connect to embedded ActiveMQ JMS broker
        ConnectionFactory connectionFactory =
            new ActiveMQConnectionFactory("vm://localhost");
        camelContext.addComponent("jms",
            JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));

        return camelContext;
    }

    @Test
    @Ignore("TODO enable when we update to Camel 2.17.1 or 2.18")
    public void testPlacingOrders() throws Exception {
        getMockEndpoint("mock:xml").expectedMessageCount(1);
        getMockEndpoint("mock:csv").expectedMessageCount(1);

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                // load file orders from src/data into the JMS queue
                from("file:src/data?noop=true").to("jms:incomingOrders");

                // content-based router
                from("jms:incomingOrders")
                .choice()
                    .when(simple("${header.CamelFileName} ends with 'xml'"))
                        .to("jms:xmlOrders")
                    .when(simple("${header.CamelFileName} ends with 'csv'"))
                        .to("jms:csvOrders");

                // test that our route is working
                from("jms:xmlOrders")
                .log("Received XML order: ${header.CamelFileName}")
                .to("mock:xml");

                from("jms:csvOrders")
                .log("Received CSV order: ${header.CamelFileName}")
                .to("mock:csv");
            }
        };
    }
}

Add cbr with simple testcase

Add cbr with simple testcase


package temportalist.esotericraft.api.galvanize;

import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTBase;
import net.minecraftforge.common.util.INBTSerializable;

/**
 * Created by TheTemportalist on 5/17/2016.
 *
 * @author TheTemportalist
 */
public interface IAbility<N extends NBTBase> extends INBTSerializable<N> {

	@interface Ability {

		String id();

	}

	String getName();

	void parseMappingArguments(Object[] args);

	String[] encodeMappingArguments();

	void onApplicationTo(EntityLivingBase entity);

	void onUpdate(EntityLivingBase entity);

	void onRemovalFrom(EntityLivingBase entity);

	void deserialize(NBTBase nbt);
}

Create ability interface and annotation

Create ability interface and annotation


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

package algorithm.boj;

import java.io.*;

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

public class Boj1924 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] inputs = br.readLine().split(" ");
        int x = Integer.parseInt(inputs[0]);
        int y = Integer.parseInt(inputs[1]);

        int[] dd = {0,3,0,1,0,1,0,0,1,0,1,0};
        int[] day = {31,28,31,30,31,30,31,31,30,31,30,31};
        String[] pr = {"SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"};
        int result = (x-1) * 31 + y;

        for(int i=0; i<x-1; i++){
            result -= dd[i];
        }

        System.out.print(pr[result%7]);
    }

}

Solve No.1924 from Baekjoon Online Judge


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

import java.lang.reflect.Method;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;

/**
 * Registry implementation for JBoss that relies on org.jboss.naming.NonSerializableFactory
 */
public class JBossRegistry implements Registry {

    /**
     * Required no-arg public constructor
     */
    public JBossRegistry() {
        // nothing
    }

    public <T> void bind(String name, T object) {
        try {
            InitialContext context = new InitialContext();

            // Now we do the equivalent of:
            //   NonSerializableFactory.rebind(context, name, object);
            // using reflection
            Class clazz = null;
            try {
                clazz = Class.forName("org.jboss.naming.NonSerializableFactory");
            } catch (ClassNotFoundException ex) {
                clazz = Class.forName("org.jboss.naming.NonSerializableFactory", true, Thread.currentThread().getContextClassLoader());
            }
            Method method = clazz.getMethod("rebind", Context.class, String.class, Object.class);
            method.invoke(null, new Object[] { context, name, object });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @SuppressWarnings("unchecked")
    public <T> T lookup(String name) {
        return (T) lookup(name, Thread.currentThread().getContextClassLoader());
    }

    @SuppressWarnings("unchecked")
    public <T> T lookup(String name, ClassLoader loader) {
        T proxiedObject = null;
        try {
            InitialContext context = new InitialContext();
            proxiedObject = (T) context.lookup(name);
            if (proxiedObject == null) return null;
            RemoteProxy<T> proxy = new RemoteProxy<T>(proxiedObject, loader, proxiedObject.getClass().getClassLoader());
            return proxy.newProxyInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @SuppressWarnings("unchecked")
    public <T> T lookupNonProxied(String name) {
        try {
            InitialContext context = new InitialContext();
            return (T) context.lookup(name);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void init(Properties props) {
        // nothing
    }

}

Add a specific JBoss Registry

Add a specific JBoss Registry

git-svn-id: bf08415a33f9c0f05ac2b054c631df0aaa894ee0@640 f54485bd-ff3a-0410-97a1-83db373c2bce


package leetcode.minimum_window_substring;

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

public class Solution {
	public static class MutableInt{
		private int val;
		public MutableInt(){
			val = 0;
		}
		public void increment(){
			val++;
		}
		public void decrement(){
			val--;
		}
		public int get(){
			return val;
		}
	}

    public String minWindow(String S, String T) {
    	if(S == null || S.length() == 0) return "";
    	if(T == null || T.length() == 0) return "";
    	Map<Character, MutableInt> outside = new HashMap<Character, MutableInt>();
    	Map<Character, MutableInt> inside = new HashMap<Character, MutableInt>();
    	char[] chars = S.toCharArray();
    	char[] chart = T.toCharArray();
    	int lens = chars.length;
    	int lent = chart.length;
    	for(char c : chart){
    		MutableInt mi = outside.get(c);
    		if(mi == null){
    			mi = new MutableInt();
    			outside.put(c, mi);
    			inside.put(c, new MutableInt());
    		}
    		mi.increment();
    	}
    	int remaining = lent;
    	int left = 0, right = 0;
    	int min = lens + 1;
    	String minString = "";
    	while(right < lens){
    		while(right < lens && remaining > 0){
    			char c = chars[right];
    			MutableInt outsideCount = outside.get(c);
    			MutableInt insideCount = inside.get(c);
    			if(outsideCount != null){
	    			if(outsideCount.get() > 0){
	    				remaining--;
	    			}
	    			insideCount.increment();
	    			outsideCount.decrement();
    			}
    			right++;
    		}
    		while(remaining == 0){
    			char c = chars[left];
    			MutableInt outsideCount = outside.get(c);
    			MutableInt insideCount = inside.get(c);
    			if(outsideCount != null){
    				if(outsideCount.get() <= 0){
    					if(right - left < min){
    						min = right - left;
    						minString = new String(chars, left, min);
    					}
    				}
    				outsideCount.increment();
    				insideCount.decrement();
    				if(outsideCount.get() > 0){
    					remaining++;
    					left++;
    					break;
    				}
    			}
    			left++;
    		}
    	}
    	return minString;
    }

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

Add java solution for 76. Minimum Window Substring

76. Minimum Window Substring: https://leetcode.com/problems/minimum-window-substring/


// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.provision;

/**
 * @author hmusum
 */
// TODO: Remove when there is no release older than 6.33 in use
@SuppressWarnings("unused")
public class Quota {

    private final int numberOfHosts;

    public Quota() {
        this(Integer.MAX_VALUE);
    }

    public Quota(int numberOfHosts) {
        this.numberOfHosts = numberOfHosts;
    }

    public int getNumberOfHosts() {
        return numberOfHosts;
    }

}

Add back to make config server work with older models * Still needed, getting NoClassDefFoundError


package javaStringReverse;

import java.util.Scanner;

public class Solution {

	public static boolean isPalindrom(String palindrom) {
		if( palindrom.length() == 1 || palindrom.length() == 0 ) return true;
		if( palindrom.charAt(0) == palindrom.charAt(palindrom.length() - 1) && palindrom.length() > 2)
			return true && isPalindrom(palindrom.substring(1, palindrom.length() - 1));
		if( palindrom.charAt(0) == palindrom.charAt(palindrom.length() - 1) ) return true;
		return false;
	}

	public static void main(String[] args) {

        Scanner scanner =new Scanner(System.in);
        String palindrom = scanner.next();
        if(isPalindrom(palindrom))
        	System.out.println("Yes");
        else
        	System.out.println("No");

        scanner.close();
    }
}

Add solution for problem Java String Reverse

Java String Reverse from HackerRank/Strings/Java String Reverse


package nl.cois;

import start.Bot;

import java.io.IOException;

public class DvbBot extends Bot {
    public static void main(String[] args) throws IOException {
        new DvbBot().readSystemInput();
    }
    @Override
    public void doTurn() {
        /* do nothing */
    }
}

Create a Bot that does nothing

Create a Bot that does nothing


package lua.value;

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

import junit.framework.TestCase;

public class LStringTest extends TestCase {
	public void testToInputStream() throws IOException {
		LString str = new LString("Hello");

		InputStream is = str.toInputStream();

		assertEquals( 'H', is.read() );
		assertEquals( 'e', is.read() );
		assertEquals( 2, is.skip( 2 ) );
		assertEquals( 'o', is.read() );
		assertEquals( -1, is.read() );

		assertTrue( is.markSupported() );

		is.reset();

		assertEquals( 'H', is.read() );
		is.mark( 4 );

		assertEquals( 'e', is.read() );
		is.reset();
		assertEquals( 'e', is.read() );

		LString substr = str.substring( 1, 4 );
		assertEquals( 3, substr.length() );

		is.close();
		is = substr.toInputStream();

		assertEquals( 'e', is.read() );
		assertEquals( 'l', is.read() );
		assertEquals( 'l', is.read() );
		assertEquals( -1, is.read() );

		is = substr.toInputStream();
		is.reset();

		assertEquals( 'e', is.read() );
	}
}

Add unit test for LString.toInputStream (meant to commit this a while ago)


package org.ensembl.healthcheck.testcase.funcgen;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

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

public class CurrentSchemaBuildUnique extends SingleDatabaseTestCase {

	protected Connection con;

	@Override
	public boolean run(DatabaseRegistryEntry dbre) {

		boolean passes = true;

		con = dbre.getConnection();
		int countCurrentCoordSystems;
		try {
			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery("select group_concat(distinct schema_build) current_schema_build, count(distinct schema_build) as c from coord_system where is_current=true");
			rs.next();
			countCurrentCoordSystems = rs.getInt("c");
			if (countCurrentCoordSystems>1) {

				String current_schema_build = rs.getString("current_schema_build");

				ReportManager.problem(this, con, "There is more than one schema_build flagged as current.");
				ReportManager.problem(this, con, "The following schema builds are marked as current: " + current_schema_build);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		passes = countCurrentCoordSystems==1;
		if (!passes) {
			ReportManager.problem(this, con, "Useful SQL: select * from coord_system where is_current=true");
		}
		return passes;
	}
}

Check that only one schema build type has been set to current in the coord_system table.


package org.jboss.weld.bootstrap.api.helpers;

import java.util.Hashtable;
import java.util.Map;

import org.jboss.weld.bootstrap.api.Singleton;
import org.jboss.weld.bootstrap.api.SingletonProvider;

/**
 *
 * @author mathieuancelin
 */
public class RegistrySingletonProvider extends SingletonProvider {
    public static final String STATIC_INSTANCE = "STATIC_INSTANCE";

    @Override
    public <T> Singleton<T> create(Class<? extends T> type) {
        return new RegistrySingleton<T>(type);
    }

    private static class RegistrySingleton<T> implements Singleton<T> {
        // use Hashtable for concurrent access
        private final Map<String, T> store = new Hashtable<String, T>();

        private final Class<? extends T> clazz;

        public RegistrySingleton(Class<? extends T> clazz) {
            this.clazz = clazz;
        }

        public T get(String id) {
            T instance = store.get(id);
            if (instance == null) {
                throw new IllegalStateException("Singleton not set for " + id + " => " + store.keySet());
            }
            return instance;
        }

        public void set(String id, T object) {
            store.put(id, object);
        }

        public void clear(String id) {
            store.remove(id);
        }

        public boolean isSet(String id) {
            return store.containsKey(id);
        }
    }
}

Add a registry singleton provider

Add a registry singleton provider


/*
 * Copyright 2016-2020 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.
 */
package nl.talsmasoftware.umldoclet.javadoc;

import jdk.javadoc.doclet.Doclet;
import net.sourceforge.plantuml.OptionFlags;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.opentest4j.AssertionFailedError;

import static java.util.Collections.emptySet;
import static java.util.Collections.singletonList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertThrows;

public class UMLOptionsTest {
    private DocletConfig config;
    private UMLOptions umlOptions;

    @BeforeEach
    void setUpUmlOptions() {
        config = new DocletConfig();
        umlOptions = new UMLOptions(config);
    }

    private Doclet.Option docletOption(String name) {
        return umlOptions.mergeWith(emptySet())
                .stream()
                .filter(o -> o.getNames().contains(name))
                .findFirst()
                .orElseThrow(() -> new AssertionFailedError("Doclet option " + name + " not found!"));
    }

    @Test
    void testUmlTimeoutOption() {
        // prepare
        Doclet.Option umlTimeoutOption = docletOption("--uml-timeout");

        // execute
        umlTimeoutOption.process("--uml-timeout", singletonList("1800"));

        // verify
        assertThat(OptionFlags.getInstance().getTimeoutMs(), is(1000L * 1800));
    }

    @Test
    void testIllegalUmlTimeoutOption() {
        // prepare
        Doclet.Option umlTimeoutOption = docletOption("--uml-timeout");

        // execute
        IllegalArgumentException expected = assertThrows(IllegalArgumentException.class, () ->
                umlTimeoutOption.process("--uml-timeout", singletonList("30 minutes")));

        // verify
        assertThat(expected.getMessage(), containsString("timeout value"));
    }
}

Add unit test for new --uml-timeout option

Signed-off-by: Sjoerd Talsma <1dafb4c4a7acdc6e1eca32ff35fda03e0e9cd976@talsma-ict.nl>


package uk.ac.ebi.quickgo.rest.cache;

import java.time.Duration;
import java.time.LocalTime;
import java.util.function.Supplier;

/**
 * This algorithm models the following situation - Start time of caching after end time. So the start time of caching
 * is occurs in one day, the end of the caching in the next. Here are the situations this class must deal with
 *
 * Before End Time: We are approaching the time of day when the data we use to populate requests is going to be
 * refreshed, therefore any subsequent requests to a RESTful service should have the following  header
 * cache-control: max-age=0
 * so User Agents or gateway caches don't cache this information (as it is likely to be out of data soon).
 *
 * After Start Time - we have high confidence data refresh will have taken place, and will not take place again until
 * after the end time the next day. Calculate the time left (in seconds) between a call to this method and Time A,
 * and set the cache-control header so this data can be cached by UAs, or gateway caches for this period. The response
 * HTTP header will be the following:
 * cache-control: max-age=36000
 * if there is exactly ten hours left between a call to this method and Time A.
 *
 * After End Time and before Start Time: We are around the indexing time. We tell all respondents not to cache - max
 * age is set to zero.
 *
 * See Caching best practices & max-age
 * gotchas,
 * Caching Tutorial for Web Authors and Webmasters,
 * Increasing Application Performance with HTTP Cache Headers | Heroku Dev Center
 *
 * @return a String that holds the number of seconds left before the cut-off time after which requests will not be
 * cached.
 *
 * @author Tony Wardell
 * Date: 10/04/2017
 * Time: 15:53
 * Created with IntelliJ IDEA.
 */
public class MaxAgeWhenStartTimeAfterEndTime implements Supplier<Duration> {

    private LocalTime start, end;

    public MaxAgeWhenStartTimeAfterEndTime(LocalTime start, LocalTime end) {
        this.start = start;
        this.end = end;
    }

    @Override public Duration get() {
        Duration remaining;
        final LocalTime now = LocalTime.now();
        if (now.isAfter(start)) {
            Duration durationLeftToday = Duration.between(now, LocalTime.MAX);
            Duration durationTomorrow = Duration.between(LocalTime.MIN, end);
            remaining = durationLeftToday.plus(durationTomorrow);
        } else {
            if (now.isBefore(end)) {
                remaining = Duration.between(now, end);
            } else {
                remaining = Duration.ZERO;
            }
        }
        assert !remaining.isNegative();
        return remaining;
    }
}

Create a class to hold max age calculation when start time for caching availability is the day before the end caching time - i.e. the caching availability period runs overnight.


import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;
import java.util.HashMap;

// Contributed by Matt Hargett, http://www.clock.org/~matt

public class NoSqlInjection {
	private static final String[] COLUMNS = new String[] {"ID", "NAME"};
	private static final String[] PREFIXES = new String[] {"GOPHER", "LLAMA"};
	private Connection connection;

	public NoSqlInjection(Connection connection) {
		this.connection = connection;
	}

	public void beSafe() throws SQLException {
		Statement query = connection.createStatement();
		query.executeQuery("select * from ANIMAL");
		ResultSet zooResults = query.getResultSet();

		String columnString = "TYPE, ANIMAL_ID";
		for (String handlerColumn : COLUMNS) {
			columnString += ", " + handlerColumn;
		}
		while (zooResults.next()) {
			for (String prefix : PREFIXES) {
				String valuesString = "";
				if (prefix.equals("GOPHER_")) {
					valuesString += "'PLATYPUS'";
				} else if (prefix.equals("LLAMA_")) {
					valuesString += "'DOLLY'";
				}

				valuesString += "," + prefix;

				for (String column : COLUMNS) {
					valuesString += "," + column;
				}

				connection.createStatement().executeUpdate("insert into HANDLER (" + columnString + ") VALUES (" + valuesString + ");");
			}
		}
	}

	public void beSafeSimple() throws SQLException {
		Statement query = connection.createStatement();
		query.executeQuery("select * from ANIMAL");
		ResultSet zooResults = query.getResultSet();

		String columnString = "TYPE, ANIMAL_ID";
		connection.createStatement().executeUpdate("insert into HANDLER (" + columnString + ") VALUES (" + PREFIXES[0] + ");");
	}
}

Add test case contributed by Matt Hargett

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@7471 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


package com.team2052.frckrawler;

public class GlobalValues {
    /**
     * SharedPreferences file name
     */
    public static final String PREFS_FILE_NAME = "FRCKrawlerPrefs";
    public static final String IS_SCOUT_PREF = "isScout";
    public static final String CURRENT_SCOUT_EVENT_ID = "currentEvent";
    public static final String PREFS_COMPILE_WEIGHT = "compileWeight";
    /**
     * The SharedPreferences key for the MAC address of the
     * most recently connected server
     */
    public static final String MAC_ADDRESS_PREF = "MACAddress";
    public static final int MAX_COMP_YEAR = 2015;
    public static final int FIRST_COMP_YEAR = 1992;
}

package com.team2052.frckrawler;

public class GlobalValues {
    /**
     * SharedPreferences file name
     */
    public static final String PREFS_FILE_NAME = "FRCKrawlerPrefs";
    public static final String IS_SCOUT_PREF = "isScout";
    public static final String CURRENT_SCOUT_EVENT_ID = "currentEvent";
    public static final String PREFS_COMPILE_WEIGHT = "compileWeight";
    /**
     * The SharedPreferences key for the MAC address of the
     * most recently connected server
     */
    public static final String MAC_ADDRESS_PREF = "MACAddress";
    public static final int MAX_COMP_YEAR = 2016;
    public static final int FIRST_COMP_YEAR = 1992;
}

Allow for import of 2016 Events

Allow for import of 2016 Events


package com.rwtema.funkylocomotion.rendering;

import cpw.mods.fml.common.ObfuscationReflectionHelper;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.client.resources.IResourceManagerReloadListener;
import net.minecraft.client.resources.SimpleReloadableResourceManager;
import net.minecraft.util.StringTranslate;

public class WordDictionary implements IResourceManagerReloadListener {
	static {
		((SimpleReloadableResourceManager) Minecraft.getMinecraft().getResourceManager()).registerReloadListener(new WordDictionary());
	}

	private static String[] words;

	public static String[] getWords() {
		if (words != null) return words;

		StringTranslate translator = ObfuscationReflectionHelper.getPrivateValue(StringTranslate.class, null, "field_74817_a", "instance");
		Map<String, String> languageList = ObfuscationReflectionHelper.getPrivateValue(StringTranslate.class, translator, "field_74816_c", "languageList");

		HashSet<String> wordSet = new HashSet<String>();

		for (char letter : chars) {
			wordSet.add(Character.toString(letter));
		}

		for (String s : languageList.values()) {
			String s1 = s.toLowerCase(Locale.US);
			for (String word : s1.split("[^{A-Za-z}]")) {
				int n = word.length();
				if (n <= 1)
					continue;

				wordSet.add(word.substring(0, 1).toUpperCase(Locale.ENGLISH) + word.substring(1).toLowerCase(Locale.ENGLISH));
			}
		}

		words = wordSet.toArray(new String[wordSet.size()]);

		return words;
	}

	@Override
	public void onResourceManagerReload(IResourceManager p_110549_1_) {
		words = null;
	}

	static final private char[] chars = new char[]{
			'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
			'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
			'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
			'Y', 'Z'
	};

}

Add 'word dictionary' for fun times

Add 'word dictionary' for fun times


/*
 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 java.util.ArrayList;
import java.util.List;

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

/**
 * Check that transcript frameshift attributes have been calculated.
 */

public class FrameshiftAttributes extends SingleDatabaseTestCase {

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

		addToGroup("post_genebuild");
		addToGroup("release");
		setDescription("Check that transcript frameshift attributes have been calculated.");

	}

	/**
	 * Only applies to core dbs.
	 */
	public void types() {

		List types = new ArrayList();

		types.add(DatabaseType.CORE);

		setAppliesToTypes(types);

	}

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

		boolean result = true;

		Connection con = dbre.getConnection();

		int rows = getRowCount(con,
				"SELECT COUNT(*) FROM attrib_type at, transcript_attrib ta WHERE at.attrib_type_id=ta.attrib_type_id AND at.code='Frameshift'");

		if (rows == 0) {

			ReportManager.problem(this, con, "No transcript frameshift attributes found");
			result = false;

		} else {

			ReportManager.correct(this, con, rows + " transcript frameshift attributes found");

		}

		return result;

	} // run

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

} // ESTStableID

Check that transcript frameshift attributes have been calculated for core databases.


package com.google.sps.servlets;

import com.google.cloud.tasks.v2.AppEngineHttpRequest;
import com.google.cloud.tasks.v2.CloudTasksClient;
import com.google.cloud.tasks.v2.HttpMethod;
import com.google.cloud.tasks.v2.QueueName;
import com.google.cloud.tasks.v2.Task;
import com.google.protobuf.ByteString;
import com.google.sps.workspace.Workspace;
import com.google.sps.workspace.WorkspaceFactory;
import java.io.IOException;
import java.nio.charset.Charset;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/workspace/queueDownload")
public class QueueDownload extends HttpServlet {
  WorkspaceFactory workspaceFactory = WorkspaceFactory.getInstance();

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    Workspace w = workspaceFactory.fromWorkspaceID(req.getParameter("workspaceID"));

    String downloadID = w.newDownloadID();

    try (CloudTasksClient client = CloudTasksClient.create()) {
      String queuePath =
          QueueName.of("fulfillment-deco-step-2020", "us-central1", "download-queue").toString();

      Task.Builder taskBuilder =
          Task.newBuilder()
              .setAppEngineHttpRequest(
                  AppEngineHttpRequest.newBuilder()
                      .setBody(
                          ByteString.copyFrom(
                              String.join(",", w.getWorkspaceID(), downloadID),
                              Charset.defaultCharset()))
                      .setRelativeUri("/tasks/prepareDownload")
                      .setHttpMethod(HttpMethod.POST)
                      .build());

      client.createTask(queuePath, taskBuilder.build());

      resp.getWriter().print(downloadID);
    }
  }
}

Add servlet to queue a download.

Add servlet to queue a download.


/*
 * 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.tomcat.util.net;

import java.util.Arrays;

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

import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.TomcatBaseTest;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.compat.TLS;

/**
 * The keys and certificates used in this file are all available in svn and were
 * generated using a test CA the files for which are in the Tomcat PMC private
 * repository since not all of them are AL2 licensed.
 *
 * The JSSE implementation of TLSv1.3 only supports authentication during the
 * initial handshake.
 */
public class TestClientCertTls13 extends TomcatBaseTest {

    @Test
    public void testClientCertGet() throws Exception {
        Assume.assumeTrue(TLS.isTlsv13Available());
        getTomcatInstance().start();
        ByteChunk res = getUrl("https://localhost:" + getPort() + "/protected");
        Assert.assertEquals("OK-" + TesterSupport.ROLE, res.toString());
    }

    @Test
    public void testClientCertPost() throws Exception {
        getTomcatInstance().start();

        int size = 32 * 1024;

        byte[] body = new byte[size];
        Arrays.fill(body, TesterSupport.DATA);

        // Protected resource
        ByteChunk res = new ByteChunk();
        int rc = postUrl(body, "https://localhost:" + getPort() + "/protected", res, null);

        Assert.assertEquals(200, rc);
        Assert.assertEquals("OK-" + size, res.toString());
    }

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

        Tomcat tomcat = getTomcatInstance();

        TesterSupport.configureClientCertContext(tomcat);
        // Need to override some of the previous settings
        tomcat.getConnector().setProperty("sslEnabledProtocols", "TLSv1.3");
        // And add force authentication to occur on the initial handshake
        tomcat.getConnector().setProperty("clientAuth", "required");

        TesterSupport.configureClientSsl();
    }
}

Add a test case for TLS 1.3 CLIENT-CERT

Add a test case for TLS 1.3 CLIENT-CERT

git-svn-id: 79cef5a5a257cc9dbe40a45ac190115b4780e2d0@1843405 13f79535-47bb-0310-9956-ffa450edef68


// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.restapi;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yahoo.container.jdisc.HttpResponse;
import com.yahoo.log.LogLevel;

import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Logger;

/**
 * A JSON response using Jackson for serialization.
 *
 * @author bjorncs
 */
public class JacksonJsonResponse<T> extends HttpResponse {

    private static final Logger log = Logger.getLogger(JacksonJsonResponse.class.getName());
    private static final ObjectMapper defaultJsonMapper = new ObjectMapper();

    private final ObjectMapper jsonMapper;
    private final T entity;

    public JacksonJsonResponse(int statusCode, T entity) {
        this(statusCode, entity, defaultJsonMapper);
    }

    public JacksonJsonResponse(int statusCode, T entity, ObjectMapper jsonMapper) {
        super(statusCode);
        this.entity = entity;
        this.jsonMapper = jsonMapper;
    }

    @Override
    public void render(OutputStream outputStream) throws IOException {
        if (log.isLoggable(LogLevel.DEBUG)) {
            String json = jsonMapper.writeValueAsString(entity);
            log.log(LogLevel.DEBUG, "Writing the following JSON to response output stream:\n" + json);
            outputStream.write(json.getBytes());
        } else {
            jsonMapper.writeValue(outputStream, entity);
        }
    }

    @Override public String getContentType() { return "application/json"; }
    public T getEntity() { return entity; }
}

Add response type for JSON serialization using Jackson


package org.wikimedia.commons.data;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import org.wikimedia.commons.contributions.Contribution;

public class DBOpenHelper  extends SQLiteOpenHelper{

    private static final String DATABASE_NAME = "commons.db";
    private static final int DATABASE_VERSION = 1;

    public DBOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        Contribution.Table.onCreate(sqLiteDatabase);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) {
        Contribution.Table.onUpdate(sqLiteDatabase);
    }
}

Add missing DbOpenHelper class (required by prev. commit)