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

import static io.github.bonigarcia.BrowserBuilder.android;
import static io.github.bonigarcia.BrowserBuilder.appium;
import static io.github.bonigarcia.BrowserBuilder.chrome;
import static io.github.bonigarcia.BrowserBuilder.chromeInDocker;
import static io.github.bonigarcia.BrowserBuilder.edge;
import static io.github.bonigarcia.BrowserBuilder.firefox;
import static io.github.bonigarcia.BrowserBuilder.firefoxInDocker;
import static io.github.bonigarcia.BrowserBuilder.iexplorer;
import static io.github.bonigarcia.BrowserBuilder.opera;
import static io.github.bonigarcia.BrowserBuilder.operaInDocker;
import static io.github.bonigarcia.BrowserBuilder.phantomjs;
import static io.github.bonigarcia.BrowserBuilder.safari;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;

import java.util.stream.Stream;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

import io.github.bonigarcia.BrowserBuilder;
import io.github.bonigarcia.BrowsersTemplate.Browser;

public class BrowserBuilderTest {

    static Stream<BrowserBuilder> browserBuilderProvider() {
        return Stream.of(chrome(), firefox(), opera(), android(), appium(),
                edge(), chromeInDocker(), firefoxInDocker(), operaInDocker(),
                phantomjs(), safari(), iexplorer());
    }

    @ParameterizedTest
    @MethodSource("browserBuilderProvider")
    void templateTest(BrowserBuilder browserBuilder) {
        Browser browser = browserBuilder.version("").browserName("")
                .deviceName("").build();
        assertThat(browser, notNullValue());
    }

}

Include specific test for BrowserBuilder


package sg.ncl.adapter.deterlab.dtos.entities;

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

import static org.junit.Assert.assertEquals;

/**
 * Created by Tran Ly Vu on 10/3/2016.
 */

public class DeterLabProjectEntityTest {
    private DeterLabProjectEntity deterLabUserEntity;

    @Before
    public void setup(){
        deterLabUserEntity=new DeterLabProjectEntity();
    }

    @Test
    public void getterAndSetterTest(){
        deterLabUserEntity.setId("test1");
        deterLabUserEntity.setNclTeamId("test2");
        deterLabUserEntity.setDeterProjectId("test3");

        String actual1=deterLabUserEntity.getId();
        String actual2=deterLabUserEntity.getNclTeamId();
        String actual3=deterLabUserEntity.getDeterProjectId();

        assertEquals("test1",actual1);
        assertEquals("test2",actual2);
        assertEquals("test3",actual3);
    }

}

Update unit testing for class DeterlabProjectEntity in adapter-deterlab (SIO)


/*
 * Copyright (c) 2013 - 2017 xxyy (Philipp Nowak; xyc@l1t.li). All rights reserved.
 *
 * Any usage, including, but not limited to, compiling, running, redistributing, printing,
 *  copying and reverse-engineering is strictly prohibited without explicit written permission
 *  from the original author and may result in legal steps being taken.
 *
 * See the included LICENSE file (core/src/main/resources) for details.
 */

import li.l1t.common.util.math.WeightedDistribution;

import java.security.SecureRandom;
import java.text.MessageFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class WeightedDistributionProbabilityTestScratch {
    public static void main (String... args) {
        WeightedDistribution<Integer> dist = new WeightedDistribution<>();
        SecureRandom random = new SecureRandom();
        IntStream.range(0, 15)
                .forEach(lel -> dist.put(lel, 1));
        IntStream.range(16, 20)
                .forEach(lel -> dist.put(lel, 5));
        Stream.generate(() -> dist.next(random))
                .limit(5_000_000)
                .collect(Collectors.groupingBy(Function.identity()))
                .entrySet().stream()
                .map(e -> MessageFormat.format(" -> {0} = {1}% ^ {2}", e.getKey(), (
                        (double) e.getValue().size() / 5_000_000D) * 100D, expectedProbability(dist, e)))
                .forEach(System.out::println);
    }

    private static double expectedProbability(WeightedDistribution<Integer> dist, Map.Entry<Integer, List<Integer>> e) {
        double prob = dist.probabilities().entrySet().stream()
                .filter(e2 -> e2.getValue().equals(e.getKey()))
                .mapToDouble(Map.Entry::getKey)
                .findFirst().orElseThrow(AssertionError::new);
        Double lowerKey = Optional.ofNullable(dist.probabilities().lowerKey(prob)).orElse(0D);
        return ((prob - lowerKey) / dist.probabilitySum()) * 100;
    }
}

Add scratch file that shows how accurate WeightedDistribution is


package org.minijs.core.parser;

import org.antlr.v4.runtime.tree.ParseTree;
import org.junit.Test;
import org.minijs.core.ast.*;

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

public class TestIncDecUpdateExpression extends BaseParserTest {

    @Test
    public void testIncDecUpdateExpression() {
        String[] expressions = {
                "a++",
                "a--",
                "++a",
                "--a",
                "(a)++",
                "(a)--",
                "++(a)",
                "--(a)"
        };

        Class[] expectedSubExpressionClasses = {
                Identifier.class,
                Identifier.class,
                Identifier.class,
                Identifier.class,
                ParenthesizedExpression.class,
                ParenthesizedExpression.class,
                ParenthesizedExpression.class,
                ParenthesizedExpression.class
        };

        for (int i = 0; i < expressions.length; i++) {
            initParser(expressions[i]);
            ParseTree tree = parser.expressionList();
            Node node = visitor.visit(tree);

            assertTrue(node instanceof ExpressionList);
            ExpressionList expressionList = (ExpressionList) node;
            assertEquals(1, expressionList.size());

            Expression expr = expressionList.get(0);
            assertTrue(expr instanceof IncDecUpdateExpression);
            Expression subExpr = ((IncDecUpdateExpression)expr).getSubExpression();
            assertNotNull(subExpr);
            assertEquals(expectedSubExpressionClasses[i], subExpr.getClass());
        }
    }
}

Add unit tests for IncDecUpdateExpression, on plane PHX -> CALGARY XD


package com.github.gabrielruiu.spring.cloud.config.redis;

import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * @author Gabriel Mihai Ruiu (gabriel.ruiu@mail.com)
 */
@ConfigurationProperties(prefix = "spring.cloud.config.server.redis")
public class CloudConfigServerRedisProperties {

    /**
     * Flag to indicate whether Redis should be enabled as the storage for the configuration properties
     */
    private boolean enabled = true;

    public boolean isEnabled() {
        return this.enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("CloudConfigServerRedisProperties{");
        sb.append("enabled=").append(enabled);
        sb.append('}');
        return sb.toString();
    }
}

Prepare configuration properties class. Will be used to enable and disable the auto configuration.


import java.util.Stack;

public class MyQueue {

    private Stack<Integer> input;
    private Stack<Integer> output;

    /** Initialize your data structure here. */
    public MyQueue() {
        input = new Stack<Integer>();
        output = new Stack<Integer>();
    }

    /** Push element x to the back of queue. */
    public void push(int x) {
        input.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        peek();
        return output.pop();
    }

    /** Get the front element. */
    public int peek() {

        if (output.empty()) {

            while (!input.empty()) {
                output.push(input.pop());
            }

        }

        return output.peek();

    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
        return input.empty() && output.empty();
    }

}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */

Create : 232 Implement Queue using Stacks


/*
 * Copyright 2016 Will Knez <wbknez.dev@gmail.com>
 *
 * 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.solsticesquared.schelling;

/**
 * The main driver for the Schelling project.
 */
public final class AppEntry {

    /**
     * The application entry point.
     *
     * @param args
     *        The array of command line arguments, if any.
     */
    public static void main(final String[] args) {
    }

    /**
     * Constructor (private).
     */
    private AppEntry() {
    }
}

Add application entry point (skeleton).


public class IsPalindromeNumber {
    public boolean isPalindrome(int x) {
        int n = x;
        int digit = 0;
        int rev = 0;
        while (x > 0) {
            digit = x % 10;
            rev = rev * 10 + digit;
            x = x / 10;
        }
        return n == rev;
    }

    public static void main (String[] args) {
        IsPalindromeNumber test = new IsPalindromeNumber ();
        System.out.println (test.isPalindrome (21));
        System.out.println (test.isPalindrome (1221));
        System.out.println (test.isPalindrome (12121));
        System.out.println (test.isPalindrome (0));
    }
}

Check if number is a palindrome


package com.intellij.psi;

import com.intellij.core.CoreJavaFileManager;
import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.testFramework.PsiTestCase;
import com.intellij.testFramework.PsiTestUtil;

public class NotNullInnerClass extends PsiTestCase {

  public void testNotNullInnerClass() throws Exception {
    VirtualFile root = PsiTestUtil.createTestProjectStructure(myProject, myModule, myFilesToDelete);
    VirtualFile pkg = root.createChildDirectory(this, "foo");
    PsiDirectory dir = myPsiManager.findDirectory(pkg);
    assertNotNull(dir);
    String text = "package foo;\n\n" +
                  "public class Nested {\n" +
                  "public class InnerGeneral {}\n" +
                  "public class Inner$ {}\n" +
                  "\n" +
                  "public Inner$ inner() {\n" +
                  "   return  new Inner$();\n" +
                  "}\n" +
                  "\n" +
                  "}";
    PsiElement created = dir.add(PsiFileFactory.getInstance(getProject()).createFileFromText("Nested.java", JavaFileType.INSTANCE, text));

    GlobalSearchScope scope = GlobalSearchScope.allScope(getProject());
    CoreJavaFileManager manager = new CoreJavaFileManager(myPsiManager);
    manager.addToClasspath(root);

    PsiClass clazz = manager.findClass("foo.Nested", scope);
    assertNotNull(clazz);

    PsiClass clazzInnerGeneral = manager.findClass("foo.Nested.InnerGeneral", scope);
    assertNotNull(clazzInnerGeneral);

    PsiClass clazzInner$ = manager.findClass("foo.Nested.Inner$", scope);
    assertNotNull(clazzInner$);
  }

}

Test for pull request "CoreJavaFileManager.findClass: properly resolve $ in inner class names"


package net.floodlightcontroller.util;

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

/**
 * Utility class to get a stacktrace as a nice string
 *
 * @author gregor
 *
 */

public class StackTraceUtil {
    public static String stackTraceToString(Throwable t) {
        StringWriter sw = new StringWriter();
        t.printStackTrace(new PrintWriter(sw));
        return sw.toString();
    }
}

Add try-catch clauses around all update queues.


package org.intermine.webservice.server;

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

import java.util.Collections;
import java.util.Map;
import java.util.Properties;

import org.intermine.api.InterMineAPI;
import org.intermine.util.StringUtil;
import org.intermine.web.logic.Constants;
import org.intermine.web.logic.session.SessionMethods;
import org.intermine.webservice.server.core.JSONService;
import org.intermine.webservice.server.output.JSONFormatter;

/**
 * Service for returning the version of this service.
 * @author Alex Kalderimis
 *
 */
public class VersionService extends JSONService
{

    /**
     * Constructor
     * @param im The InterMine configuration object.
     */
    public VersionService(InterMineAPI im) {
        super(im);
    }

    @Override
    protected void execute() throws Exception {
        String version = getVersion(request.getPathInfo());
        output.addResultItem(Collections.singletonList(version));
    }

    @Override
    protected int getDefaultFormat() {
        if (hasCallback()) {
            return WebService.JSONP_FORMAT;
        } else {
            return WebService.TEXT_FORMAT;
        }
    }

    @Override
    protected Map<String, Object> getHeaderAttributes() {
        Map<String, Object> attr = super.getHeaderAttributes();
        if (formatIsJSON()) {
            attr.put(JSONFormatter.KEY_INTRO, "\"version\":");
            attr.put(JSONFormatter.KEY_QUOTE, true);
        }

        return attr;
    }

    private String getVersion(String versionType) {
        if (versionType != null) {
            versionType = StringUtil.trimSlashes(versionType).toLowerCase();

            if (versionType.startsWith("release")) {
                Properties webProperties = SessionMethods.getWebProperties(request);
                return webProperties.getProperty("project.releaseVersion");
            } else if (versionType.startsWith("ws")) {
                return "" + Constants.WEB_SERVICE_VERSION;
            }
        }
        // for backwards compatibility default is the web service version
        return "" + Constants.WEB_SERVICE_VERSION;
    }

    @Override
    protected String parseFormatFromPathInfo() {
        String pi = request.getPathInfo();
        if (pi.endsWith("json")) {
            return "json";
        } else if (pi.endsWith("jsonp")) {
            return "jsonp";
        }
        return request.getParameter(WebServiceRequestParser.OUTPUT_PARAMETER);
    }

}

Upgrade version requests to full service to get access to json processing


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

import com.facebook.presto.testing.LocalQueryRunner;
import org.testng.annotations.Test;

import static com.facebook.presto.SystemSessionProperties.DICTIONARY_AGGREGATION;
import static com.facebook.presto.testing.TestingSession.testSessionBuilder;

public class TestDictionaryAggregation
        extends AbstractTestQueryFramework
{
    public TestDictionaryAggregation()
    {
        super(() -> new LocalQueryRunner(testSessionBuilder()
                .setSystemProperty(DICTIONARY_AGGREGATION, "true")
                .build()));
    }

    @Test
    public void testMixedDistinctWithFilter()
    {
        assertQuery(
                "SELECT " +
                        "     count(DISTINCT x) FILTER (WHERE x > 0), " +
                        "     sum(x) " +
                        "FROM (VALUES 0, 1, 1, 2) t(x)",
                "VALUES (2, 4)");

        assertQuery(
                "SELECT count(DISTINCT x) FILTER (where y = 1)" +
                        "FROM (VALUES (2, 1), (1, 2), (1,1)) t(x, y)",
                "VALUES 2");
    }
}

Add basic test for dictionary aggregation


package com.indeed.proctor.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.indeed.proctor.common.model.ConsumableTestDefinition;
import com.indeed.proctor.common.model.TestDefinition;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * Simple validator to check if the input JSON file is valid format as test definition.
 */
public class TestDefinitionValidator {
    private static final ObjectMapper OBJECT_MAPPER = Serializers.strict();

    private TestDefinitionValidator() {
    }

    private static boolean isValidTestDefinition(final InputStream stream, final String testName, final String matrixSource) {
        try {
            final TestDefinition testDefinition = OBJECT_MAPPER.readValue(stream, TestDefinition.class);
            final ConsumableTestDefinition consumableTestDefinition = ProctorUtils.convertToConsumableTestDefinition(testDefinition);
            ProctorUtils.verifyInternallyConsistentDefinition(testName, matrixSource, consumableTestDefinition);
            return true;
        } catch (final Throwable e) {
            System.err.println("Error: " + e.getMessage());
            return false;
        }
    }

    public static void main(final String[] args) {
        if (args.length < 3) {
            System.err.println("Usage: java " + TestDefinitionValidator.class.getCanonicalName() + " <test_name> <matrix_source> <test_path>");
            System.exit(0);
        }

        final String testName = args[0];
        final String matrixSource = args[1];

        InputStream stream = null;
        try {
            stream = "-".equals(args[2]) ? System.in : new FileInputStream(args[2]);
        } catch (final FileNotFoundException e) {
            System.err.println("Error: " + e.getMessage());
            System.exit(1);
        }

        final boolean result = isValidTestDefinition(stream, testName, matrixSource);
        System.exit(result ? 0 : 1);
    }
}

Add simple test definition validator


package com.github.ferstl.depgraph;

import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.ResolutionScope;
import com.github.ferstl.depgraph.dot.DotBuilder;

/**
 * Creates a graph containing the group IDs of all dependencies.
 */
@Mojo(
    name = "by-groupid",
    aggregator = false,
    defaultPhase = LifecyclePhase.NONE,
    requiresDependencyCollection = ResolutionScope.TEST,
    requiresDirectInvocation = false,
    threadSafe = true)
public class DependencyGraphByGroupIdMojo extends AbstractGraphMojo {

  @Override
  protected GraphFactory createGraphFactory(ArtifactFilter artifactFilter) {
    DotBuilder dotBuilder = new DotBuilder()
        .useNodeRenderer(NodeRenderers.SCOPED_GROUP_ID)
        .useNodeLabelRenderer(NodeRenderers.GROUP_ID_LABEL);

    GraphBuilderAdapter adapter = new GraphBuilderAdapter(this.dependencyGraphBuilder);
    return new SimpleGraphFactory(adapter, artifactFilter, dotBuilder);
  }

}

Introduce a new mojo for groupId graphs


package org.apache.velocity.test.util.introspection;

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

import junit.framework.Test;
import junit.framework.TestSuite;

import org.apache.velocity.test.BaseTestCase;
import org.apache.velocity.util.introspection.ClassMap;

/**
 * Test the ClassMap Lookup
 */
public class ClassMapTestCase
        extends BaseTestCase
{
    public ClassMapTestCase(final String name)
    	throws Exception
    {
        super(name);
    }

    public static Test suite()
    {
        return new TestSuite(ClassMapTestCase.class);
    }

    public void setUp()
            throws Exception
    {
    }

    public void tearDown()
    {
    }

    public void testPrimitives()
    	throws Exception
    {
        ClassMap c = new ClassMap(TestClassMap.class);
        assertNotNull(c.findMethod("setBoolean",   new Object[] { Boolean.TRUE }));
        assertNotNull(c.findMethod("setByte",      new Object[] { new Byte((byte) 4)}));
        assertNotNull(c.findMethod("setCharacter", new Object[] { new Character('c')}));
        assertNotNull(c.findMethod("setDouble",    new Object[] { new Double(8.0) }));
        assertNotNull(c.findMethod("setFloat",     new Object[] { new Float(15.0) }));
        assertNotNull(c.findMethod("setInteger",   new Object[] { new Integer(16) }));
        assertNotNull(c.findMethod("setLong",      new Object[] { new Long(23) }));
        assertNotNull(c.findMethod("setShort",     new Object[] { new Short((short)42)}));
    }

    public static final class TestClassMap
    {
        public void setBoolean(boolean b)
        {
        }

        public void setByte(byte b)
        {
        }

        public void setCharacter(char c)
        {
        }

        public void setDouble(double d)
        {
        }

        public void setFloat(float f)
        {
        }

        public void setInteger(int i)
        {
        }

        public void setLong(long l)
        {
        }

        public void setShort(short s)
        {
        }
    }
}

Add some class map tests.


package cc.redpen.parser.markdown;

import cc.redpen.parser.LineOffset;
import org.junit.Test;

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

import static org.junit.Assert.assertEquals;

public class MergedCandidateSentenceTest {
    @Test
    public void testMerge() {
        List<CandidateSentence> candidateSentences = initializeCandidateSentences(
                new CandidateSentence(1, "first ", "", 0),
                new CandidateSentence(1, "second ", "", 6),
                new CandidateSentence(1, "third", "", 13));

        MergedCandidateSentence mergedSentence = MergedCandidateSentence.merge(candidateSentences);
        assertEquals("first second third", mergedSentence.getContents());
        List<LineOffset> expectedOffsets = initializeMappingTable(
                new LineOffset(1, 0), // f
                new LineOffset(1, 1), // i
                new LineOffset(1, 2), // r
                new LineOffset(1, 3), // s
                new LineOffset(1, 4), // t
                new LineOffset(1, 5), // ' '
                new LineOffset(1, 6), // s
                new LineOffset(1, 7), // e
                new LineOffset(1, 8), // c
                new LineOffset(1, 9), // o
                new LineOffset(1, 10), // n
                new LineOffset(1, 11), // d
                new LineOffset(1, 12), // ' '
                new LineOffset(1, 13), // t
                new LineOffset(1, 14), // h
                new LineOffset(1, 15), // i
                new LineOffset(1, 16), // r
                new LineOffset(1, 17)); // d

        assertEquals(expectedOffsets.size(), mergedSentence.getOffsetMap().size());
        for (int i = 0; i < expectedOffsets.size() ; i++) {
            assertEquals(expectedOffsets.get(i),
                    mergedSentence.getOffsetMap().get(i));
        }

    }

    private static List<CandidateSentence> initializeCandidateSentences(CandidateSentence... candidateSentences) {
        List<CandidateSentence> candidateSentenceList = new ArrayList<>();
        for (CandidateSentence candidateSentence : candidateSentences) {
            candidateSentenceList.add(candidateSentence);
        }
        return candidateSentenceList;
    }

    private static List<LineOffset> initializeMappingTable(LineOffset... offsets) {
        List<LineOffset> offsetTable = new ArrayList<>();
        for (LineOffset offset : offsets) {
            offsetTable.add(offset);
        }
        return offsetTable;
    }
}

Add a test for merging sentences


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

package com.google.sps;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** */
@RunWith(JUnit4.class)
public final class MeetingRequestTest {
  // Some people that we can use in our tests.
  private static final String PERSON_A = "Person A";
  private static final String PERSON_B = "Person B";
  private static final String PERSON_C = "Person C";

  private static final int DURATION_1_HOUR = 60;

  @Test
  public void CantAddOptionalAttendeeWhoIsAlsoMandatory() {
    MeetingRequest request = new MeetingRequest(Arrays.asList(PERSON_A), DURATION_1_HOUR);
    request.addOptionalAttendee(PERSON_A);

    int actual = request.getOptionalAttendees().size();
    int expected = 0;
    Assert.assertEquals(expected, actual);
  }
}

Add a basic test for MeetingRequest.java


package com.google.ase;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class UsageTrackingConfirmation {
  private UsageTrackingConfirmation() {
    // Utility class.
  }

  public static void show(Activity activity) {
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    if (prefs.getBoolean("present_usagetracking", true)) {
      final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
      builder.setTitle("Usage Tracking");
      builder.setCancelable(true);
      builder.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
          prefs.edit().putBoolean("present_usagetracking", false).commit();
          prefs.edit().putBoolean("usagetracking", true).commit();
        }
      });
      builder.setNegativeButton("Refuse", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
          prefs.edit().putBoolean("present_usagetracking", false).commit();
          prefs.edit().putBoolean("usagetracking", false).commit();
        }
      });
      builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
        public void onCancel(DialogInterface dialog) {
          prefs.edit().putBoolean("present_usagetracking", true).commit();
          prefs.edit().putBoolean("usagetracking", false).commit();
        }
      });
      builder.setMessage("Allow collection of anonymous usage information?\n\nThis can be "
          + "changed later under preferences.");
      builder.create().show();
    }
  }
}

Add usage tracking confirmation class that was missing from the last commit.


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

import edu.usu.sdl.openstorefront.core.entity.SystemSearch;
import edu.usu.sdl.openstorefront.web.action.BaseAction;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ErrorResolution;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;

public class SavedSearchAction
		extends BaseAction
{

	private String savedSearchId;
	private SystemSearch savedSearch;
	private String searchRequest;

	@DefaultHandler
	public Resolution performSearch()
	{
		SystemSearch ss = new SystemSearch();
		ss.setSearchId(this.savedSearchId);
		this.savedSearch = (SystemSearch) ss.find();
		if (savedSearch != null) {
			setSearchRequest(savedSearch.getSearchRequest());
			return new ForwardResolution("/WEB-INF/securepages/main/searchResults.jsp");
		}
		return new ErrorResolution(404);
	}

	public String getSearchRequest()
	{
		return searchRequest;
	}

	public void setSearchRequest(String searchRequest)
	{
		this.searchRequest = searchRequest;
	}

	public SystemSearch getSavedSearch()
	{
		return savedSearch;
	}

	public void setSavedSearch(SystemSearch savedSearch)
	{
		this.savedSearch = savedSearch;
	}

	public String getSavedSearchId()
	{
		return savedSearchId;
	}

	public void setSavedSearchId(String savedSearchId)
	{
		this.savedSearchId = savedSearchId;
	}

}

Create actionBean for saved system searches


package nl.nn.adapterframework.pipes;

import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;

import nl.nn.adapterframework.configuration.ConfigurationException;
import nl.nn.adapterframework.core.IPipeLineSession;
import nl.nn.adapterframework.core.PipeRunException;

import static org.junit.Assert.*;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.json.XML;
import org.junit.Rule;

public class JsonPipeTest {
	@Mock
	private IPipeLineSession<?, ?> session;

	@Rule
	public ExpectedException exception = ExpectedException.none();

	private JsonPipe jsonPipe = new JsonPipe();

	@Test
	public void configureInputNull() throws ConfigurationException {
		exception.expect(ConfigurationException.class);
		jsonPipe.configure();
	}

	@Test
	public void configureInputWrong() throws ConfigurationException {
		jsonPipe.setDirection("foutje!");
		exception.expect(ConfigurationException.class);
		jsonPipe.configure();
	}

	@Test
	public void doPipeInputNull() throws Exception {
		exception.expect(PipeRunException.class);
		jsonPipe.doPipe(null, session);
	}

	@Test
	public void doPipeInputWrongObject() throws Exception {
		Integer input = new Integer(1);
		exception.expect(PipeRunException.class);
		jsonPipe.doPipe(input, session);
	}

	@Test
	public void doPipeInputObject() throws Exception {
		String stringResult = "{ name: Lars }";
		JSONTokener jsonTokener = new JSONTokener(stringResult);
		JSONObject jsonObject = new JSONObject(jsonTokener);
		stringResult = XML.toString(jsonObject);
		assertEquals(stringResult, "<name>Lars</name>");
	}

	@Test
	public void doPipeInputArray() throws Exception {
		String stringResult = "[ \"Wie\", \"dit leest\", \"is gek\" ]";
		JSONTokener jsonTokener = new JSONTokener(stringResult);
		JSONArray jsonArray = new JSONArray(jsonTokener);
		stringResult = XML.toString(jsonArray);
		assertEquals(stringResult,
				"<array>Wie</array><array>dit leest</array><array>is gek</array>");
	}
}

Add JUnit test for JsonPipe (by Lars)


/**
 *
 */
package org.corpus_tools.atomic.tokeneditor.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;

/**
 * TODO Description
 *
 * @author Stephan Druskat <mail@sdruskat.net>
 *
 */
public class NewTokenHandler extends AbstractHandler {

	/* (non-Javadoc)
	 * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
	 */
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		System.err.println("CREATE NEW TOKEN");
		return null;
	}

}

Create skeleton handler for the creation of new tokens


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

package org.springframework.cloud.netflix.ribbon;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration;
import org.springframework.cloud.netflix.ribbon.RibbonAutoConfigurationIntegrationTests.TestConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.netflix.client.config.CommonClientConfigKey;
import com.netflix.client.config.IClientConfig;

import static org.junit.Assert.assertEquals;

/**
 * @author Dave Syer
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestConfiguration.class)
@DirtiesContext
@IntegrationTest("ribbon.ConnectTimeout=25000")
public class RibbonAutoConfigurationIntegrationTests {

	@Autowired
	private SpringClientFactory factory;

	@Test
	public void serverListIsConfigured() throws Exception {
		IClientConfig config = this.factory.getClientConfig("client");
		assertEquals(25000,
				config.getPropertyAsInteger(CommonClientConfigKey.ConnectTimeout, 3000));
	}

	@Configuration
	@RibbonClient("client")
	@Import({ PropertyPlaceholderAutoConfiguration.class, ArchaiusAutoConfiguration.class,
			RibbonAutoConfiguration.class })
	protected static class TestConfiguration {
	}

}

Test for default ribbon client configuration


package com.kickstarter.viewmodels;

import com.kickstarter.KSRobolectricTestCase;

import org.junit.Test;

import rx.observers.TestSubscriber;

public class ResetPasswordViewModelTest extends KSRobolectricTestCase {
  @Test
  public void testResetPasswordViewModel_formValidation() {
    final ResetPasswordViewModel vm = new ResetPasswordViewModel(environment());
    final TestSubscriber<Boolean> test = new TestSubscriber<>();

    vm.outputs.isFormValid().subscribe(test);

    test.assertNoValues();

    vm.inputs.email("incorrect@kickstarter");
    test.assertValues(false);

    vm.inputs.email("hello@kickstarter.com");
    test.assertValues(false, true);
  }
}

Add form validation view model test


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

import java.util.ArrayList;
import java.util.Collection;

import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.webassembly.annotation.Export;

import de.inetsoftware.jwebassembly.ScriptEngine;
import de.inetsoftware.jwebassembly.WasmRule;

/**
 * @author Volker Berlin
 */
@RunWith(Parameterized.class)
public class CallFunctions {

    @ClassRule
    public static WasmRule rule = new WasmRule( TestClass.class );

    private final ScriptEngine script;
    private final String method;
    private final Object[] params;

    public CallFunctions( ScriptEngine script, String method, Object[] params ) {
        this.script = script;
        this.method = method;
        this.params = params;
    }

    @Parameters(name="{0}-{1}")
    public static Collection<Object[]> data() {
        ArrayList<Object[]> list = new ArrayList<>();
        for( Object[] val : ScriptEngine.testParams() ) {
            ScriptEngine script = (ScriptEngine)val[0];
            addParam( list, script, "intCall" );
        }
        return list;
    }

    private static void addParam( ArrayList<Object[]> list, ScriptEngine script, String method, Object ...params ) {
        list.add( new Object[]{script, method, params} );
    }

    @Test
    public void test() {
        rule.test( script, method, params );
    }

    static class TestClass {

        @Export
        static int intCall() {
            return intConst();
        }

        static int intConst() {
            return -42;
        }

    }
}

Add support for invoke static method calls


package org.xwiki.extension.repository.xwiki;

public class Paths
{
    public final static String EXTENSIONS = "/extensions/";

    public final static String EXTENSIONSDESCRIPTORS_SIMPLESEARCH = "/extensions/simplesearch/{pattern}";

    public final static String EXTENSIONSDESCRIPTORS_ID = "/extensions/{extensionId}";

    public final static String EXTENSIONDESCRIPTOR = "/extensions/{extensionId}/{extensionVersion}";

    public final static String EXTENSIONFILE = "/extensions/{extensionId}/{extensionVersion}/file";
}

Make XWiki Repository protocol more restfull


package kapil.voiceassistedweatherapp;

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

import javax.inject.Scope;

/**
 * Custom scope intended to match the scope of the activity.
 */

@Scope
@Retention(RetentionPolicy.RUNTIME)
@interface ActivityScope {
}

Create custom scope to match that of the activity


package leetcode.add_binary;

public class Solution {
    public String addBinary(String a, String b) {
    	if(a == null) a = "";
    	if(b == null) b = "";
        char[] ca = a.toCharArray();
        char[] cb = b.toCharArray();
        char[] ans = new char[Math.max(ca.length, cb.length) + 1];
        int l_ca = ca.length;
        int l_cb = cb.length;
        int l_ans = ans.length;
        int carry = 0;
        for(int i = 0; i < l_ans; i++){
        	int va = 0, vb = 0;
        	if(i < l_ca){
        		va = ca[l_ca - 1 - i] == '1' ? 1 : 0;
        	}
        	if(i < l_cb){
        		vb = cb[l_cb - 1 - i] == '1' ? 1 : 0;
        	}
        	ans[l_ans - 1 - i] = (carry + va + vb) % 2 == 0 ? '0' : '1';
        	carry = (va + vb + carry) / 2;
        }
        int start;
        for(start = 0; start < l_ans - 1 && ans[start] == '0'; start++) System.err.println(ans[start]);
        return new String(ans, start, l_ans - start);
    }

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

Add java solution for 67. Add Binary


package uk.ac.ox.oucs.oauth.dao;

import uk.ac.ox.oucs.oauth.domain.Accessor;
import uk.ac.ox.oucs.oauth.domain.Consumer;

import java.util.Collection;

/**
 * Delegate method to access the OAuthDAO.
 *

 * As the DAO might work with Hibernate, and everything Hibernate related has to be in Shared, the DAO interface is in the API.
 * Even so, the DAO shouldn't be used (except in here), so the interface is package-visible, and the only way to access to it
 * is by creating a delegate class to do every call.
 *

 *

 * This shouldn't be used anywhere else for obvious security reasons!
 *

 *
 * @author Colin Hebert
 */
public class OAuthProvider {
    private AccessorDao accessorDao;
    private ConsumerDao consumerDao;

    public void setAccessorDao(AccessorDao accessorDao) {
        this.accessorDao = accessorDao;
    }

    public void setConsumerDao(ConsumerDao consumerDao) {
        this.consumerDao = consumerDao;
    }

    public void createAccessor(Accessor accessor) {
        accessorDao.create(accessor);
    }

    public Accessor getAccessor(String accessorId) {
        return accessorDao.get(accessorId);
    }

    public Collection<Accessor> getAccessorsByUser(String userId) {
        return accessorDao.getByUser(userId);
    }

    public Accessor updateAccessor(Accessor accessor) {
        return accessorDao.update(accessor);
    }

    public void removeAccessor(Accessor accessor) {
        accessorDao.remove(accessor);
    }

    public void markExpiredAccessors() {
        accessorDao.markExpiredAccessors();
    }

    public void createConsumer(Consumer consumer) {
        consumerDao.create(consumer);
    }

    public Consumer getConsumer(String consumerId) {
        return consumerDao.get(consumerId);
    }

    public Consumer updateConsumer(Consumer consumer) {
        return consumerDao.update(consumer);
    }

    public void removeConsumer(String consumerId) {
        consumerDao.remove(consumerId);
    }
}

Create a delegate class to access DAO from within the impl


package co.kr.godo.test.driver;

import static org.junit.Assert.*;

import org.junit.Test;
import static org.hamcrest.CoreMatchers.*;

public class TestObjectTest {

	@Test
	public final void testAppend() {
		TestObject testObject = new TestObject();

		testObject.setAppender("Test");
		testObject.setAppendee("Driver");

		assertThat(testObject.append(), is("TestDriver"));
	}

}

Test Sample : Test Driver (1) Junit으로 만든 Test Driver


package goplaces.resources;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;

import org.json.JSONObject;

import goplaces.models.CustomizeRouteQuery;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.memcache.ErrorHandlers;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.appengine.api.taskqueue.*;

@Path("/place_details")
public class PlaceDetailsResource {

	@Context UriInfo uriInfo;
	@Context Request request;

	DatastoreService datastore;
	MemcacheService syncCache;

	private static final Logger log = Logger.getLogger(SelectWaypointsResource.class.getName());

	public PlaceDetailsResource(){
		datastore = DatastoreServiceFactory.getDatastoreService();
		syncCache = MemcacheServiceFactory.getMemcacheService();

		syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
	}
}
	// @POST
	// @Produces(MediaType.APPLICATION_JSON)
	// //public String selectWaypointsForRoute(CustomizeRouteQuery customizeRouteQuery, @Context HttpServletResponse servletResponse) {

Create empty class for URL /place_details


package com.cocoahero.android.essentials.media;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.location.Location;
import android.location.LocationManager;

public class ExifInterface extends android.media.ExifInterface {

    // ------------------------------------------------------------------------
    // Constructors
    // ------------------------------------------------------------------------

    public ExifInterface(File file) throws IOException {
        super(file.getAbsolutePath());
    }

    // ------------------------------------------------------------------------
    // Public Methods
    // ------------------------------------------------------------------------

    public Location getLocation() {
        float[] latlon = new float[2];
        if (this.getLatLong(latlon)) {
            Location location = new Location(LocationManager.GPS_PROVIDER);
            location.setLatitude(latlon[0]);
            location.setLongitude(latlon[1]);
            return location;
        }
        return null;
    }

    public void setLocation(Location location) {
        this.setLatitude(location.getLatitude());
        this.setLongitude(location.getLongitude());

        if (location.hasAltitude()) {
            this.setAltitude(location.getAltitude());
        }

        Date date = new Date(location.getTime());

        String dateStamp = new SimpleDateFormat("y:M:d").format(date);
        String timeStamp = new SimpleDateFormat("H:m:s").format(date);

        this.setAttribute(TAG_GPS_DATESTAMP, dateStamp);
        this.setAttribute(TAG_GPS_TIMESTAMP, timeStamp);
    }

    public void setAltitude(double altitude) {
        this.setAttribute(TAG_GPS_ALTITUDE_REF, (altitude > 0 ? "0" : "1"));
        this.setAttribute(TAG_GPS_ALTITUDE, String.valueOf(Math.abs(altitude)));
    }

    public void setLatitude(double latitude) {
        int latDeg = (int) Math.abs(latitude);
        int latMin = (int) Math.abs(((latitude % 1) * 60));
        int latSec = (int) Math.abs(((((latitude % 1) * 60) % 1) * 60));

        String latStr = String.format("%d/1,%d/1,%d/1", latDeg, latMin, latSec);

        this.setAttribute(TAG_GPS_LATITUDE, latStr);
        this.setAttribute(TAG_GPS_LATITUDE_REF, ((latitude > 0) ? "N" : "S"));
    }

    public void setLongitude(double longitude) {
        int lonDeg = (int) Math.abs(longitude);
        int lonMin = (int) Math.abs(((longitude % 1) * 60));
        int lonSec = (int) Math.abs(((((longitude % 1) * 60) % 1) * 60));

        String lonStr = String.format("%d/1,%d/1,%d/1", lonDeg, lonMin, lonSec);

        this.setAttribute(TAG_GPS_LONGITUDE, lonStr);
        this.setAttribute(TAG_GPS_LONGITUDE_REF, ((longitude > 0) ? "E" : "W"));
    }
}

Add helper class for working EXIF headers


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

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

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

/**
 * Function returning minimum of two values.
 * For example, min(1, 3) = 1.
 */
public class Min extends Function
{
	/**
	 * @see org.mapyrus.function.Function#evaluate(org.mapyrus.ContextStack, org.mapyrus.Argument, org.mapyrus.Argument)
	 */
	public Argument evaluate(ContextStack context, Argument arg1, Argument arg2)
		throws MapyrusException
	{
		double d1 = arg1.getNumericValue();
		double d2 = arg2.getNumericValue();
		Argument retval = (d1 < d2) ? arg1 : arg2;
		return(retval);
	}

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

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

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

Split functions out from Expression.java into separate classes.


package org.javamoney.moneta.spi;

import java.util.Objects;

import javax.money.CurrencyUnit;
import javax.money.MonetaryAmount;

import org.javamoney.moneta.FastMoney;

public class FastMoneyProducer implements MonetaryAmountProducer {

	@Override
	public MonetaryAmount create(CurrencyUnit currency, Number number) {
		return FastMoney.of(Objects.requireNonNull(number), Objects.requireNonNull(currency));
	}

}

Create an interface to be producer of MonetaryAmount


package com.gitblit.tests;

import java.security.KeyPair;

import org.eclipse.jgit.transport.JschConfigSessionFactory;
import org.eclipse.jgit.transport.OpenSshConfig;
import org.eclipse.jgit.util.FS;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class JschConfigTestSessionFactory extends JschConfigSessionFactory {

	final KeyPair keyPair;

	public JschConfigTestSessionFactory(KeyPair keyPair) {
		this.keyPair = keyPair;
	}

    @Override
    protected void configure(OpenSshConfig.Host host, Session session) {
        session.setConfig("StrictHostKeyChecking", "no");
    }

    @Override
	protected JSch getJSch(final OpenSshConfig.Host hc, FS fs) throws JSchException {
    	JSch jsch = super.getJSch(hc, fs);
//    	jsch.removeAllIdentity();
//    	jsch.addIdentity("unittest", keyPair.getPrivate().getEncoded(), keyPair.getPublic().getEncoded(), null);
    	return jsch;
    }
}

Add missing unit test utility class


package hudson.plugins.git.browser;

import hudson.plugins.git.GitChangeSet;
import java.io.IOException;
import java.net.URL;
import org.junit.Test;
import static org.junit.Assert.*;

public class PhabricatorTest {

    private final String repoName = "phabricatorRepo";
    private final String repoUrl = "http://phabricator.example.com/";
    private final Phabricator phabricator;

    private final GitChangeSetSample sample;

    public PhabricatorTest() {
        phabricator = new Phabricator(repoUrl, repoName);
        sample = new GitChangeSetSample(true);
    }

    @Test
    public void testGetRepo() throws IOException {
        assertEquals(repoName, phabricator.getRepo());
    }

    @Test
    public void testGetChangeSetLink() throws Exception {
        URL result = phabricator.getChangeSetLink(sample.changeSet);
        assertEquals(new URL(repoUrl + "r" + repoName + sample.id), result);
    }

    @Test
    public void testGetDiffLink() throws Exception {
        for (GitChangeSet.Path path : sample.changeSet.getPaths()) {
            URL diffLink = phabricator.getDiffLink(path);
            URL expectedDiffLink = new URL(repoUrl + "diffusion/" + repoName + "/change/master/" + path.getPath() + ";" + sample.id);
            String msg = "Wrong link for path: " + path.getPath();
            assertEquals(msg, expectedDiffLink, diffLink);
        }
    }

    @Test
    public void testGetFileLink() throws Exception {
        for (GitChangeSet.Path path : sample.changeSet.getPaths()) {
            URL fileLink = phabricator.getDiffLink(path);
            URL expectedFileLink = new URL(repoUrl + "diffusion/" + repoName + "/change/master/" + path.getPath() + ";" + sample.id);
            String msg = "Wrong link for path: " + path.getPath();
            assertEquals(msg, expectedFileLink, fileLink);
        }
    }

}

Add test for Phabricator repo browser


package in.co.sdslabs.cognizance;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class EventCategoryFragment extends Fragment{

	public EventCategoryFragment() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		// Retrieving the currently selected item number
        int position = getArguments().getInt("position");

        // List of rivers
        String[] countries = getResources().getStringArray(R.array.eventCategories);

        // Creating view correspoding to the fragment
        View v = inflater.inflate(R.layout.eventfragment_layout, container, false);

        // Getting reference to the TextView of the Fragment
        TextView tv = (TextView) v.findViewById(R.id.tv_content);

        // Setting currently selected river name in the TextView
        tv.setText(countries[position]);
		return v;
	}

}

Add fragment class for EventCategory


package io.mandrel.data.export;

import io.mandrel.data.content.FieldExtractor;
import io.mandrel.gateway.Document;

import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class DelimiterSeparatedValuesExporterTest {

	@Test
	public void export_documents_default() throws Exception {

		// Arrange
		DelimiterSeparatedValuesExporter exporter = new DelimiterSeparatedValuesExporter();

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		Writer writer = new OutputStreamWriter(out);

		List<Document> documents = new ArrayList<>();

		Document document1 = new Document();
		document1.put("key1", Arrays.asList("value1"));
		document1.put("key2", Arrays.asList("value2", "value2b"));
		documents.add(document1);

		Document document2 = new Document();
		document2.put("key1", Arrays.asList("value11111"));
		document2.put("key2", Arrays.asList("value22222", "value22222b"));
		documents.add(document2);

		List<FieldExtractor> fields = new ArrayList<>();
		fields.add(new FieldExtractor().setName("key1"));
		fields.add(new FieldExtractor().setName("key2"));

		// Actions
		exporter.init(writer);
		exporter.export(documents, fields);
		exporter.close();

		// Asserts
		String result = new String(out.toByteArray());
		Assertions.assertThat(result).contains("key1,key2").contains("value1,value2|value2b").contains("value11111,value22222|value22222b");
	}
}

Add tests for csv exporter


package leetcode.jump_game_ii;

public class Solution {
	public int jump(int[] A) {
		if(A == null || A.length == 0) return -1;
        int size = A.length;
        int[] jumps = new int[size];
        jumps[0] = 1;
        int cur = 0;
        int R = 0;
        while(cur < size && jumps[cur] > 0 && jumps[size - 1] == 0){
        	if(cur + A[cur] > R){
        		for(int i = R + 1; i <= cur + A[cur] && i < size; i++){
        			jumps[i] = jumps[cur] + 1;
        			R = i;
        		}

        	}
        	cur++;
        }
        return jumps[A.length - 1] - 1;
    }

	public static void main(String[] args){
		System.err.println(new Solution().jump(new int[]{1, 3, 0, 2, 0, 1}));
	}
}

Add java solution for 45. Jump Game II


package net.silentchaos512.gems.guide;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import com.google.common.collect.Lists;

/**
 * A custom hash map that returns a reversed, sorted list of values when values() is called. Basically, this is just to
 * fight the random ordering of entries in the latest version of Guide-API (2.0.0-31).
 *
 * @author Silent
 */
public class CategoryMap<K, V> extends HashMap<K, V> {

  List<V> sortedValues = Lists.newArrayList();

  @Override
  public V put(K key, V value) {

    // Guide-API reverses the list, so we append to the front end.
    sortedValues.add(0, value);
    return super.put(key, value);
  }

  @Override
  public Collection<V> values() {

    return sortedValues;
  }
}

package net.silentchaos512.gems.guide;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import com.google.common.collect.Lists;

/**
 * A custom hash map that returns a reversed, sorted list of values when values() is called. Basically, this is just to
 * fight the random ordering of entries in the latest version of Guide-API (2.0.0-31).
 *
 * @author Silent
 */
public class CategoryMap<K, V> extends HashMap<K, V> {

  List<V> sortedValues = Lists.newArrayList();

  @Override
  public V put(K key, V value) {

    // Guide-API no longer reverses the list, so append to the end.
    sortedValues.add(value);
    return super.put(key, value);
  }

  @Override
  public Collection<V> values() {

    return sortedValues;
  }
}

Fix guide book entry order.


package io.jasonsparc.chemistry.util;

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

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.SOURCE;

/**
 * Denotes that the annotated type is a utility class.
 *

 * A utility class is a class that is just a namespace for functions. No instances of it can exist,
 * and all its members are static. For example, {@link java.lang.Math java.lang.Math} and
 * {@link java.util.Collections java.util.Collections} are well known utility classes.
 *

 * Created by jason on 05/08/2016.
 */
@Documented
@Retention(SOURCE)
@Target(TYPE)
public @interface UtilityClass {
}

Add annotation to mark utility classes


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

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

import static org.junit.Assert.assertEquals;

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

  private RemoveComments removeComments;

  @Before public void setUp() {
    this.removeComments = new RemoveComments();
  }

  @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullFiles() {
    removeComments.remove(null);
  }

  @Test public void shouldReturnEmptyStringIfFileIsNull() {
    FakeFile file = new FakeFile();

    String result = removeComments.remove(file);

    assertEquals("", result);
  }

  @Test public void shouldReturnFileContentWithoutComments() {
    FakeFile file =
        new FakeFile("Hello world ", "this is the content /* of a fake file */", "of a real file");

    String result = removeComments.remove(file);

    assertEquals("Hello world this is the content of a real file", result);
  }
}

Add some tests to problem 23


/*
 * Copyright 2020 DiffPlug
 *
 * 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.diffplug.gradle.spotless;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermissions;

import org.assertj.core.api.AbstractStringAssert;
import org.assertj.core.api.Assertions;
import org.junit.Test;

import com.diffplug.spotless.FileSignature;

public class FilePermissionsTest extends GradleIntegrationHarness {
	@Test
	public void spotlessApplyShouldPreservePermissions() throws IOException {
		if (FileSignature.machineIsWin()) {
			// need unix filesystem
			return;
		}
		setFile("build.gradle").toLines(
				"buildscript { repositories { mavenCentral() } }",
				"plugins {",
				"    id 'com.diffplug.spotless'",
				"}",
				"",
				"spotless {",
				"    java {",
				"        target file('test.java')",
				"        googleJavaFormat('1.2')",
				"    }",
				"}");
		setFile("test.java").toResource("java/googlejavaformat/JavaCodeUnformatted.test");

		Path path = rootFolder().toPath().resolve("test.java");
		Files.setPosixFilePermissions(path, PosixFilePermissions.fromString("rwxr--r--"));
		assertPermissions(path).isEqualTo("rwxr--r--");

		gradleRunner().withArguments("spotlessApply").build();
		assertFile("test.java").sameAsResource("java/googlejavaformat/JavaCodeFormatted.test");
		assertPermissions(path).isEqualTo("rwxr--r--");
	}

	private AbstractStringAssert<?> assertPermissions(Path path) throws IOException {
		return Assertions.assertThat(PosixFilePermissions.toString(Files.getPosixFilePermissions(path)));
	}
}

Fix the failing test with @tglaeser's PR.


package com.datastax.driver.core;

import java.nio.ByteBuffer;
import java.util.Set;

import org.testng.annotations.*;

import static org.testng.Assert.assertFalse;

import com.datastax.driver.core.CCMBridge.CCMCluster;

/**
 * Tests that the token map is correctly initialized at startup (JAVA-415).
 */
public class TokenMapTest {
    CCMCluster ccmCluster = null;
    Cluster cluster = null;

    @BeforeMethod(groups = "short")
    public void setup() {
        ccmCluster = CCMBridge.buildCluster(1, Cluster.builder());
        cluster = ccmCluster.cluster;
    }

    @Test(groups = "short")
    public void initTest() {
        // If the token map is initialized correctly, we should get replicas for any partition key
        ByteBuffer anyKey = ByteBuffer.wrap(new byte[]{});
        Set<Host> replicas = cluster.getMetadata().getReplicas("system", anyKey);
        assertFalse(replicas.isEmpty());
    }

    @AfterMethod(groups = "short")
    public void teardown() {
        ccmCluster.discard();
    }
}

Add test for token map initialization at startup (JAVA-415).


/*
 * Copyright 2015 Red Hat, Inc. and/or its affiliates
 * and other contributors as indicated by the @author tags.
 *
 * 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.hawkular.alerts.api.model.data;

/**
 * Severity set for a {@link org.hawkular.alerts.api.model.trigger.Trigger} and assigned to an
 * {@link Alert} it generates.
 *
 * @author jay shaughnessy
 * @author lucas ponce
 */
public enum AvailabilityType {
    UP, DOWN, UNAVAILABLE
}

Move Alert into events package


package no.uio.ifi.trackfind.frontend;

import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.annotations.Widgetset;
import com.vaadin.data.HasValue;
import com.vaadin.data.provider.AbstractBackEndDataProvider;
import com.vaadin.data.provider.Query;
import com.vaadin.server.ExternalResource;
import com.vaadin.server.VaadinRequest;
import com.vaadin.spring.annotation.SpringUI;
import com.vaadin.ui.*;
import com.vaadin.ui.renderers.ButtonRenderer;
import com.vaadin.ui.renderers.ClickableRenderer;
import elemental.json.JsonValue;
import lombok.extern.slf4j.Slf4j;
import no.uio.ifi.trackfind.backend.pojo.TfHub;
import no.uio.ifi.trackfind.backend.pojo.TfObjectType;
import no.uio.ifi.trackfind.backend.pojo.TfReference;
import no.uio.ifi.trackfind.backend.services.MetamodelService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.stream.Stream;

/**
 * Hystrix Vaadin UI of the application.
 * Uses custom theme (VAADIN/themes/trackfind/trackfind.scss).
 * Uses custom WidgetSet (TrackFindWidgetSet.gwt.xml).
 *
 * @author Dmytro Titov
 */
@SpringUI(path = "/monitor")
@Widgetset("TrackFindWidgetSet")
@Title("Hystryx Dashboard")
@Theme("trackfind")
@Slf4j
public class TrackFindMonitorUI extends AbstractUI {

    @Override
    protected void init(VaadinRequest vaadinRequest) {
        HorizontalLayout headerLayout = buildHeaderLayout();
        VerticalLayout referencesLayout = buildReferencesLayout();
        HorizontalLayout mainLayout = buildMainLayout(referencesLayout);
        HorizontalLayout footerLayout = buildFooterLayout();
        VerticalLayout outerLayout = buildOuterLayout(headerLayout, mainLayout, footerLayout);
        setContent(outerLayout);
    }

    private VerticalLayout buildReferencesLayout() {
        VerticalLayout layout = new VerticalLayout();
        layout.setSizeFull();
        BrowserFrame browser = new BrowserFrame("Browser", new ExternalResource("http://localhost/hystrix/monitor?stream=http%3A%2F%2Flocalhost%2Factuator%2Fhystrix.stream&title=TrackFind"));
        browser.setSizeFull();
        layout.addComponent(browser);
        Panel panel = new Panel("Circuits status", browser);
        panel.setSizeFull();
        layout.addComponents(panel);
        layout.setExpandRatio(panel, 1f);
        return layout;
    }

    private HorizontalLayout buildMainLayout(VerticalLayout leftLayout) {
        HorizontalLayout mainLayout = new HorizontalLayout(leftLayout);
        mainLayout.setExpandRatio(leftLayout, 0.66f);
        mainLayout.setSizeFull();
        return mainLayout;
    }

}

Create Vaadin view with BrowserFrame with Hystrix dashboard


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

package com.google.sps.servlets;

import com.google.sps.classes.DSACampaign;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Query;
import org.junit.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import static com.google.appengine.api.datastore.FetchOptions.Builder.withLimit;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;

/*
 * Tests the doGet() and doPost() functions in DSACampaignsServlet.java.
 */
@RunWith(JUnit4.class)
public final class PresetServletTest {

  @Mock
  HttpServletRequest request;

  @Mock
  HttpServletResponse response;

  private final LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());

  @Before
  public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    helper.setUp();
  }

  @After
  public void tearDown() {
    helper.tearDown();
  }

  @Test
  public void PresetServletDoGetTest() throws IOException, ServletException {

  }

  @Test
  public void PresetServletdoPostTest() throws IOException, ServletException {

  }
}

Add preset GET and POST tests (Not implemented)


package leetcode;

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

/**
 * https://leetcode.com/problems/different-ways-to-add-parentheses/
 */
public class Problem241 {
    public List<Integer> diffWaysToCompute(String input) {
        List<Integer> result = new ArrayList<>();

        return result;
    }

    public static void main(String[] args) {
        Problem241 prob = new Problem241();
        System.out.println(prob.diffWaysToCompute("2-1-1"));
        System.out.println(prob.diffWaysToCompute("2*3-4*5"));
    }
}

Add skeleton for problem 241


@XmlSchema(namespace="http://xml.opendap.org/ns/WCS/2.0/LocalFileCatalog#",
         elementFormDefault = XmlNsForm.QUALIFIED)
package opendap.wcs.v2_0;

import javax.xml.bind.annotation.*;

Add Package Info File: most elegant place to specify LFC namespace


package scratch;

import com.bradmcevoy.http.Resource;
import com.ettrema.http.caldav.demo.TResourceFactory;

/**
 *
 * @author alex
 */
public class TResourceFactoryFindTest {
  public static void main(String[] args)
  {
    TResourceFactory factory = new TResourceFactory();
    Resource resource = factory.getResource(null, "http://localhost:9080/calendarHome/calendarOne/");
    System.out.println("FOUND : "+resource);
  }
}

Test case for TResourceFactory find method


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

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

import org.jsmpp.PDUStringException;
import org.testng.annotations.Test;

/**
 * @author uudashr
 *
 */
public class OctetStringValidationTest {
    private static final String FULL_LENGTH_TEXT = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor";
    private static final int MAX_SHORT_MESSAGE_LENGTH = 254;

    @Test
    public void zeroLength() throws Exception {
        String shortMessage = "";
        assertEquals(shortMessage.length(), 0);
        StringValidator.validateString(shortMessage.getBytes(), StringParameter.SHORT_MESSAGE);
    }

    @Test
    public void nonZeroBelow255Length() throws Exception {
        String shortMessage = "This is a simple message";
        assertTrue(shortMessage.length() > 0);
        assertTrue(shortMessage.length() <= MAX_SHORT_MESSAGE_LENGTH);
        StringValidator.validateString(shortMessage.getBytes(), StringParameter.SHORT_MESSAGE);
    }

    @Test
    public void fullLegth() throws Exception {
        assertEquals(FULL_LENGTH_TEXT.length(), MAX_SHORT_MESSAGE_LENGTH);
        StringValidator.validateString(FULL_LENGTH_TEXT.getBytes(), StringParameter.SHORT_MESSAGE);
    }

    @Test(expectedExceptions = PDUStringException.class)
    public void overLengthText() throws Exception {
        String shortMessage = FULL_LENGTH_TEXT + " ";
        assertTrue(shortMessage.length() > MAX_SHORT_MESSAGE_LENGTH);
        StringValidator.validateString(shortMessage.getBytes(), StringParameter.SHORT_MESSAGE);
    }
}

Add new test case for OctetString validation


package org.swcraft.javase.collections.puzzle;

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

import org.junit.Test;

public class PersonTest {

	@Test
	public void testReflexive() throws Exception {
		Person x = new Person("A", "B");
		assertTrue(x.equals(x));
	}

	@Test
	public void testSymmetric() throws Exception {
		Person x = new Person("A", "B");
		Person y = new Person("A", "B");
		assertTrue(x.equals(y) && y.equals(x));
	}

	@Test
	public void testDifferentPeople() throws Exception {
		Person x = new Person("A", "B");
		Person y = new Person("C", "B");
		assertFalse(x.equals(y));
	}

	@Test
	public void testTransitive() throws Exception {
		Person x = new Person("A", "B");
		Person y = new Person("A", "B");
		Person z = new Person("A", "B");
		assertTrue(x.equals(y) && y.equals(z) && x.equals(y));
	}

	@Test
	public void testNull() throws Exception {
		Person x = new Person("A", "B");
		assertFalse(x.equals(null));
	}
}

Test for person class (without 1 import test case)


/**
 *
 */
package test.api.service.impl.retrofit;

import static org.junit.Assert.assertTrue;
import javastrava.api.v3.service.impl.retrofit.StravaServiceImpl;
import javastrava.config.StravaConfig;

import org.junit.Test;

/**
 * @author Dan Shannon
 *
 */
public class StravaServiceImplTest {
	@Test
	public void testRequestRatePercentageWarning() {
		StravaServiceImpl.requestRate = StravaConfig.RATE_LIMIT;
		assertTrue(100f == StravaServiceImpl.requestRatePercentage());
	}

	@Test
	public void testRequestRateDailyPercentageWarning() {
		StravaServiceImpl.requestRateDaily = StravaConfig.RATE_LIMIT_DAILY;
		assertTrue(100f == StravaServiceImpl.requestRateDailyPercentage());
	}

	@Test
	public void testRequestRatePercentageExceeded() {
		StravaServiceImpl.requestRate = StravaConfig.RATE_LIMIT + 1;
		assertTrue(100f < StravaServiceImpl.requestRatePercentage());
	}

	@Test
	public void testRequestRateDailyPercentageExceeded() {
		StravaServiceImpl.requestRateDaily = StravaConfig.RATE_LIMIT_DAILY + 1;
		assertTrue(100f < StravaServiceImpl.requestRateDailyPercentage());
	}
}

Add tests to validate string formatting for warnings on rate limits


package leetcode.reorder_list;

import java.util.ArrayList;

import common.ListNode;

public class Solution {
	public void reorderList(ListNode head) {
		if(head == null || head.next == null) return;
		ListNode cur = head;
		ListNode tail = null;
		int cnt = 0;
		while(cur != null){
			cnt++;
			cur = cur.next;
		}
		cnt = (cnt + 1) / 2;

		cur = head;
		while(cnt > 1){
			cur = cur.next;
			cnt--;
		}

		ListNode prev = cur;
		ListNode nxt = prev.next;
		prev.next = null;
		prev = null;
		while(nxt != null){
			ListNode tmp = nxt.next;
			nxt.next = prev;
			prev = nxt;
			nxt = tmp;
		}
		tail = prev;
		ListNode back = tail, forward = head;
		while(back != null && forward != null){
			ListNode ff = forward.next;
			ListNode bb = back.next;
			forward.next = back;
			back.next = ff;
			back = bb;
			forward = ff;
		}
	}

	public static void dumpList(ListNode head){
		ListNode cur = head;
		while(cur != null){
			System.err.print("" + cur.val + ", ");
			cur = cur.next;
		}
		System.err.println("");
	}

	public static void main(String[] args){
		final int N = 9;
		ArrayList<ListNode> nodeAry = new ArrayList<ListNode>();
		for(int i = 0; i < N; i++){
			nodeAry.add(new ListNode(i));
			if(i > 0) nodeAry.get(i - 1).next = nodeAry.get(i);
		}
		new Solution().reorderList(nodeAry.get(0));
		dumpList(nodeAry.get(0));
	}
}

Add java solution for 143. Reorder List


package com.google.common.base;

public final class Stopwatch{
	private long start;
	private long duration;

	public Stopwatch() {
	}

	public Stopwatch start() {
		start = System.nanoTime();
		duration = 0;
		return this;
	}

	public Stopwatch stop() {
		duration = System.nanoTime() - start;
		start = 0;
		return this;
	}

	public Stopwatch reset() {
		start = 0;
		duration = 0;
		return this;
	}

	public long elapsedNanos() {
		return (start == 0) ? duration : (System.nanoTime() - start);
	}

	public long elapsedMillis() {
		return elapsedNanos() / 1000000;
	}
}

package com.google.common.base;

//HBase requires an old version of Guava, and Twitter requires a new one.
//HBase only needs the Stopwatch class from guava, so it's simplest to add this class before the actual Guava in the classpath, so HBase sees this old shim.
public final class Stopwatch{
	private long start;
	private long duration;

	public Stopwatch() {
	}

	public Stopwatch start() {
		start = System.nanoTime();
		duration = 0;
		return this;
	}

	public Stopwatch stop() {
		duration = System.nanoTime() - start;
		start = 0;
		return this;
	}

	public Stopwatch reset() {
		start = 0;
		duration = 0;
		return this;
	}

	public long elapsedNanos() {
		return (start == 0) ? duration : (System.nanoTime() - start);
	}

	public long elapsedMillis() {
		return elapsedNanos() / 1000000;
	}
}

Add comment explaining why there is a shim


package com.antew.redditinpictures.library.interfaces;

import java.util.List;

public interface RedditPostFilter<PostData> {
    public List<PostData> filterPosts(boolean includeNsfwImages);
}

Add interface for filtering reddit posts.


package org.monospark.spongematchers.parser.element;

import static org.junit.Assert.assertTrue;

import org.junit.Test;
import org.monospark.spongematchers.parser.SpongeMatcherParseException;

public class EmptyElementParserTest {

    @Test
    public void parseElements_EmptyElementLowerCase_ReturnsCorrectStringElement()
            throws SpongeMatcherParseException {
        String input = "empty";

        StringElement element = StringElementParser.parseStringElement(input);

        assertTrue(element instanceof EmptyElement);
    }

    @Test
    public void parseElements_EmptyElementUpperCase_ReturnsCorrectStringElement()
            throws SpongeMatcherParseException {
        String input = "Empty";

        StringElement element = StringElementParser.parseStringElement(input);

        assertTrue(element instanceof EmptyElement);
    }
}

Add unit tests for empty element parsing


package ruby.ninja.experiments.zahlenpuzzle.board;

import org.junit.Test;
import rubys.ninja.experiments.zahlenpuzzle.board.BoardSize;
import rubys.ninja.experiments.zahlenpuzzle.board.HardcodedInitializer;
import rubys.ninja.experiments.zahlenpuzzle.token.EmptyToken;
import rubys.ninja.experiments.zahlenpuzzle.token.NumericalToken;
import rubys.ninja.experiments.zahlenpuzzle.token.Token;

import java.util.List;

import static org.junit.Assert.*;

/**
 * @author Ruben Schmidmeister (bash)
 */
public class HardcodedInitializerTest {
    @Test
    public void testInitializer() throws Exception {
        HardcodedInitializer initializer = new HardcodedInitializer();

        List<Token> tokens = initializer.getTokens();

        assertNumericalToken(tokens.get(0), 15);
        assertNumericalToken(tokens.get(1), 4);
        assertNumericalToken(tokens.get(2), 1);
        assertNumericalToken(tokens.get(3), 6);
        assertNumericalToken(tokens.get(4), 3);
        assertNumericalToken(tokens.get(5), 8);
        assertNumericalToken(tokens.get(6), 5);
        assertNumericalToken(tokens.get(7), 10);
        assertNumericalToken(tokens.get(8), 7);
        assertNumericalToken(tokens.get(9), 12);
        assertNumericalToken(tokens.get(10), 9);
        assertNumericalToken(tokens.get(11), 14);
        assertNumericalToken(tokens.get(12), 11);
        assertTrue(tokens.get(13) instanceof EmptyToken);
        assertNumericalToken(tokens.get(14), 13);
        assertNumericalToken(tokens.get(15), 2);

        assertEquals(new BoardSize(4, 4), initializer.getBoardSize());
    }

    private void assertNumericalToken(Token token, Integer value) {
        assertTrue(token instanceof NumericalToken);
        assertSame(value, ((NumericalToken) token).getValue());
    }
}

Add test for hardcoded initializer


package org.lemurproject.galago.contrib.parse;

import org.lemurproject.galago.core.parse.Document;
import org.lemurproject.galago.core.parse.DocumentStreamParser;
import org.lemurproject.galago.core.types.DocumentSplit;
import org.lemurproject.galago.utility.Parameters;

import java.io.BufferedReader;
import java.io.IOException;

/**
 * Simple {@link DocumentStreamParser} to consume the Signal Media Dataset from the NewsIR'16 workshop.
 * Add --filetype=org.lemurproject.galago.contrib.parse.SignalMediaJSONParser to your command line.
 * Also add --tokenizer/field=title to your "galago build" command if you want to index the title field.
 * @author jfoley
 */
public class SignalMediaJSONParser extends DocumentStreamParser {
  private final BufferedReader reader;

  /**
   * This is the constructor expected by UniversalParser
   * It must be implemented in each implementing class
   *
   * @param split
   * @param p
   */
  public SignalMediaJSONParser(DocumentSplit split, Parameters p) throws IOException {
    super(split, p);
    this.reader = DocumentStreamParser.getBufferedReader(split);
  }

  @Override
  public Document nextDocument() throws IOException {
    String line = reader.readLine();
    if(line == null) return null;

    Document doc = new Document();
    Parameters jdoc = Parameters.parseString(line);
    doc.metadata.put("source", jdoc.getString("source"));
    doc.metadata.put("title", jdoc.getString("title"));
    doc.metadata.put("media-type", jdoc.getString("media-type")); // News or Blog
    doc.metadata.put("published", jdoc.getString("published"));

    doc.name = jdoc.getString("id");
    doc.text = "<title>"+jdoc.getString("title")+"</title>"+jdoc.getString("content");
    return doc;
  }

  @Override
  public void close() throws IOException {
    reader.close();
  }
}

Add parser for NewsIR JSON document collection.


/*
 * Copyright (C) 2016 Black Duck Software Inc.
 * http://www.blackducksoftware.com/
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Black Duck Software ("Confidential Information"). You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Black Duck Software.
 */
package com.blackducksoftware.integration.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

public class HostnameHelper {

    public static String getMyHostname() {
        String hostName = null;

        try {
            hostName = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            try {
                // Get the network interfaces for this machine
                Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

                while (interfaces.hasMoreElements()) {
                    NetworkInterface nic = interfaces.nextElement();
                    // Get the addresses for this network interface
                    Enumeration<InetAddress> addresses = nic.getInetAddresses();
                    // will loop through the addresses until it finds a non loop back address that has a host name
                    while (hostName == null && addresses.hasMoreElements()) {
                        InetAddress address = addresses.nextElement();
                        // if the address is not a loopback address then get the host name
                        if (!address.isLoopbackAddress()) {
                            hostName = address.getHostName();
                            break;
                        }
                    }
                    if (hostName != null) {
                        break;
                    }
                }
            } catch (SocketException se) {
                // ignore this
            }
        }
        return hostName;
    }
}

Add class to handle getHostname


package de.interseroh.report.server.birt;

public enum BirtDataType {

    SCALAR_PARAMETER(0),
    FILTER_PARAMETER(1),
    LIST_PARAMETER(2),
    TABLE_PARAMETER(3),
    PARAMETER_GROUP(4),
    CASCADING_PARAMETER_GROUP(5);

    private int parameterType;

    BirtDataType(int parameterType) {
        this.parameterType = parameterType;
    }

    public int getType() {
        return parameterType;
    }

    public static BirtDataType valueOf(int parameterType) {
        for (BirtDataType type : BirtDataType.values()) {
            if (type.parameterType == parameterType)
                return type;

        }
        return null; // FIXME - Throw UnkknownParameterType Exception
    }

}

Add Enum for Birt Parameter Types


package org.jctools.sets;

import org.openjdk.jcstress.annotations.Actor;
import org.openjdk.jcstress.annotations.JCStressTest;
import org.openjdk.jcstress.annotations.Outcome;
import org.openjdk.jcstress.annotations.State;
import org.openjdk.jcstress.infra.results.IntResult1;

import static org.openjdk.jcstress.annotations.Expect.ACCEPTABLE;
import static org.openjdk.jcstress.annotations.Expect.FORBIDDEN;

/**
 * @author Tolstopyatov Vsevolod
 * @since 13/05/17
 */
@JCStressTest
@Outcome(id = "0", expect = FORBIDDEN, desc = "Missing read")
@Outcome(id = "1", expect = ACCEPTABLE, desc = "Ok")
@Outcome(id = "2", expect = FORBIDDEN, desc = "Duplicate reads")
@Outcome(expect = FORBIDDEN, desc = "Can't happen")
@State
public class SingleWriterHashSetDuplicateReadsTest {

    private final SingleWriterHashSet<Integer> set = new SingleWriterHashSet<>(16);

    public SingleWriterHashSetDuplicateReadsTest() {
        // Collide elements so removal of 1 will shift 17
        set.add(1);
        set.add(17);
    }

    @Actor
    public void actor1() {
        set.remove(1);
    }

    @Actor
    public void actor2(IntResult1 result) {
        int counter = 0;
        for (Integer integer : set) {
            if (integer == 17) {
                ++counter;
            }
        }

        result.r1 = counter;
    }
}

Add jcstress test which reveals issue in SingleWriterHashSet with removal + iterator reads


/**
 * 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.camel.itest.karaf;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.junit.PaxExam;

@RunWith(PaxExam.class)
public class CamelAwsSesTest extends BaseKarafTest {

    public static final String COMPONENT = extractName(CamelAwsSesTest.class);

    @Test
    public void test() throws Exception {
    	testComponent(COMPONENT);
    }

}

Create single Karaf feature tests for single components, aws-ses test


package org.jboss.loom.test.jaxb;

import java.io.StringReader;
import java.util.List;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import org.eclipse.persistence.oxm.annotations.XmlDiscriminatorNode;
import org.eclipse.persistence.oxm.annotations.XmlDiscriminatorValue;
import org.jboss.loom.utils.XmlUtils;
import org.junit.Assert;
import org.junit.Test;

/**
 *
 * @author Ondrej Zizka, ozizka at redhat.com
 */
public class JaxbInheritance2Test {
    @Test
    public void testUnmarshall() throws JAXBException{
        final Unmarshaller marshaller = XmlUtils.createJaxbContext(Root.class).createUnmarshaller();
        Root root = (Root) marshaller.unmarshal( new StringReader(
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root></root>") );

        boolean rightClass = (DiscFoo.class.isAssignableFrom( root.subs.get(0).getClass() ));
        Assert.assertTrue( "base elements go into subclasses", rightClass );

        rightClass = (DiscBar.class.isAssignableFrom( root.subs.get(1).getClass() ));
        Assert.assertTrue( "base elements go into subclasses", rightClass );
    }

    @XmlRootElement
    public static class Root {
        @XmlElement(name = "sub")
        List<Base> subs;
    }

    @XmlDiscriminatorNode("@disc")
    @XmlSeeAlso({DiscFoo.class, DiscBar.class})
    public static abstract class Base {}

    @XmlRootElement @XmlDiscriminatorValue("foo")
    public static class DiscFoo {}

    @XmlRootElement @XmlDiscriminatorValue("bar")
    public static class DiscBar {}

}

Add 2nd JAXB inheritance test


package com.intellij.rt.execution.junit2;

import junit.framework.TestResult;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.framework.Test;

import java.util.Hashtable;
import java.util.Enumeration;

public class RunOnce extends TestResult {
  private Hashtable myPeformedTests = new Hashtable();
  private static final String NOT_ALLOWED_IN_ID = ":";

  protected void run(TestCase test) {
    if (test.getClass().getName().startsWith(TestSuite.class.getName())) {
      super.run(test);
    } else {
      String testKey = keyOf(test);
      if (!myPeformedTests.containsKey(testKey)) {
        super.run(test);
        myPeformedTests.put(testKey, test);
      } else {
        fireTestSkipped(test, (Test)myPeformedTests.get(testKey));
      }
    }
  }

  private void fireTestSkipped(TestCase test, Test peformedTest) {
    for (Enumeration each = fListeners.elements(); each.hasMoreElements();) {
      Object listener = each.nextElement();
      if (listener instanceof TestSkippingListener)
        ((TestSkippingListener)listener).onTestSkipped(test, peformedTest);
    }
  }

  private String keyOf(TestCase test) {
    return test.getClass().getName() + NOT_ALLOWED_IN_ID +
        test.getName() + NOT_ALLOWED_IN_ID +
        test.toString();
  }
}

package com.intellij.rt.execution.junit2;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestResult;
import junit.framework.TestSuite;

import java.util.Hashtable;

public class RunOnce extends TestResult {
  private Hashtable myPeformedTests = new Hashtable();
  private static final String NOT_ALLOWED_IN_ID = ":";

  protected void run(TestCase test) {
    if (test.getClass().getName().startsWith(TestSuite.class.getName())) {
      super.run(test);
    } else {
      String testKey = keyOf(test);
      if (!myPeformedTests.containsKey(testKey)) {
        super.run(test);
        myPeformedTests.put(testKey, test);
      } else {
        fireTestSkipped(test, (Test)myPeformedTests.get(testKey));
      }
    }
  }

  private void fireTestSkipped(TestCase test, Test peformedTest) {
    for (int i = 0; i < fListeners.size(); i++) {
      Object listener = fListeners.get(i);
      if (listener instanceof TestSkippingListener) {
        ((TestSkippingListener)listener).onTestSkipped(test, peformedTest);
      }
    }
  }

  private String keyOf(TestCase test) {
    return test.getClass().getName() + NOT_ALLOWED_IN_ID +
           test.getName() + NOT_ALLOWED_IN_ID +
           test.toString();
  }
}

Upgrade to JUnit 4.0: Fixing Vector -> List update consequences.


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

package org.scijava;

/**
 * Interface for things that have names.
 *
 * @author Lee Kamentsky
 */
public interface Named {

	/** Gets the name of the object. */
	String getName();

	/** Sets the name of the object. */
	void setName(String name);

}

Add interface for named things


// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.requests.extensions;

import com.microsoft.graph.concurrency.*;
import com.microsoft.graph.core.*;
import com.microsoft.graph.models.extensions.*;
import com.microsoft.graph.models.generated.*;
import com.microsoft.graph.http.*;
import com.microsoft.graph.requests.extensions.*;
import com.microsoft.graph.requests.generated.*;
import com.microsoft.graph.options.*;
import com.microsoft.graph.serializer.*;

import java.util.Arrays;
import java.util.EnumSet;

// This file is available for extending, afterwards please submit a pull request.

/**
 * The class for the Workbook Chart Collection Page.
 */
public class WorkbookChartCollectionPage extends BaseWorkbookChartCollectionPage implements IWorkbookChartCollectionPage {

    /**
     * A collection page for WorkbookWorksheet.
     *
     * @param response The serialized BaseWorkbookChartCollectionResponse from the service
     * @param builder The request builder for the next collection page
     */
    public WorkbookChartCollectionPage(final BaseWorkbookChartCollectionResponse response, final IWorkbookChartCollectionRequestBuilder builder) {
        super(response, builder);
    }
}

Move collections to requests folder


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

package org.apache.tapestry5.ioc.annotations;

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.CLASS)
@Documented
public @interface IncompatibleChange
{
    /**
     * Identifies the release in which this signature of the method.
     *
     * @return a release number, e.g., "5.4"
     */
    String release();

    /**
     * Short string describing what changed.
     */
    String details();
}

Add an annotation to clearly identify incompatible changes to method signatures