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

package com.dmdirc.addons.ui_swing.components.vetoable;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;

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

import static javax.swing.ListSelectionModel.SINGLE_SELECTION;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class VetoableListSelectionModelTest {

    @Mock private VetoableChangeListener listener;

    @Test
    public void testInitialState() {
        final VetoableListSelectionModel instance = new VetoableListSelectionModel();
        assertEquals(instance.getLeadSelectionIndex(), -1);
        assertEquals(instance.getSelectionMode(), SINGLE_SELECTION);
        assertFalse(instance.getValueIsAdjusting());
    }

    @Test
    public void testNonVetoed() {
        final VetoableListSelectionModel instance = new VetoableListSelectionModel();
        instance.setLeadSelectionIndex(5);
        assertEquals(instance.getLeadSelectionIndex(), 5);
    }

    @Test
    public void testVetoedCalled() throws PropertyVetoException {
        final VetoableListSelectionModel instance = new VetoableListSelectionModel();
        instance.addVetoableSelectionListener(listener);
        instance.setLeadSelectionIndex(5);
        assertEquals(instance.getLeadSelectionIndex(), 5);
        verify(listener).vetoableChange(any(PropertyChangeEvent.class));
    }

    @Test
    public void testVetoedCalledAndVetoed() throws PropertyVetoException {
        doThrow(new PropertyVetoException(null, null))
                .when(listener).vetoableChange(any(PropertyChangeEvent.class));
        final VetoableListSelectionModel instance = new VetoableListSelectionModel();
        instance.addVetoableSelectionListener(listener);
        instance.setLeadSelectionIndex(5);
        assertEquals(instance.getLeadSelectionIndex(), -1);
    }

}

Add unit test for vetoablelistselectionmodel


package io.datakernel.http;

import io.datakernel.async.Promises;
import io.datakernel.eventloop.Eventloop;
import io.datakernel.test.TestUtils;
import io.datakernel.test.rules.ByteBufRule;
import io.datakernel.test.rules.EventloopRule;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

import static io.datakernel.async.TestUtils.await;
import static java.nio.charset.StandardCharsets.UTF_8;

public class AsyncHttpServerClientBreakConnectionTest {
	private final Logger logger = LoggerFactory.getLogger(AsyncHttpServerClientBreakConnectionTest.class);
	private final int FREE_PORT = TestUtils.getFreePort();

	@ClassRule
	public static final EventloopRule eventloopRule = new EventloopRule();

	@ClassRule
	public static final ByteBufRule bufRule = new ByteBufRule();

	private AsyncHttpServer server;
	private AsyncHttpClient client;
	private Eventloop eventloop = Eventloop.getCurrentEventloop();

	@Before
	public void init() throws IOException {
		server = AsyncHttpServer.create(eventloop,
				request -> {
					logger.info("Closing server...");
					eventloop.post(() ->
							server.close().whenComplete(() -> logger.info("Server Closed")));
					return Promises.delay(
							HttpResponse.ok200()
									.withBody("Hello World".getBytes()),
							100L);
				})
				.withListenPort(FREE_PORT)
				.withAcceptOnce();

		client = AsyncHttpClient.create(eventloop);
		server.listen();
	}

	@Test
	public void testBreakConnection() {
		await(client.request(
				HttpRequest.post("http://127.0.0.1:" + FREE_PORT)
						.withBody("Hello World".getBytes()))
				.map(response ->
						response.loadBody()
								.map(body -> body.getString(UTF_8))));
	}
}

Add test of concurrent closing of AsyncHttpServer


/*
 * See the file "LICENSE" for the full license governing this code.
 */
package sdp.tools;

import sdp.graph.Graph;
import sdp.io.GraphReader;
import sdp.io.GraphWriter;

/**
 *
 * @author Marco Kuhlmann <marco.kuhlmann@liu.se>
 */
public class Splitter {

    public static void main(String[] args) throws Exception {
        GraphReader reader = new GraphReader(args[0]);
        GraphWriter writerTrain = new GraphWriter(args[1]);
        GraphWriter writerDevel = new GraphWriter(args[2]);
        Graph graph;
        while ((graph = reader.readGraph()) != null) {
            if (graph.id.substring(2, 4).equals("20")) {
                writerDevel.writeGraph(graph);
            } else {
                writerTrain.writeGraph(graph);
            }
        }
        reader.close();
        writerTrain.close();
        writerDevel.close();
    }
}

Add a tool to split the training data into train/dev data according to the recommendations in our README.


package com.sunny.grokkingalgorithms.ctc.c2;

import com.sunny.grokkingalgorithms.ctc.c2.util.LinkedListUtil;
import com.sunny.grokkingalgorithms.ctc.c2.util.Node;

/**
 * Created by sundas on 3/15/2018.
 */
public class AddTwoNumbers {

  /*
  Add two numbers represented by linked list
  7->1->6  + 5->9->2
  617 + 295
  912
  stored as 2->1->9
   */

  /**
   *
   * @param numberA
   * @param numberB
   * @return
   */
  public static Node addTwoNumbers(Node numberA,Node numberB){
    Node sumRoot = null;
    int previousCarry = 0;
    Node aRunner = numberA;
    Node bRunner = numberB;
    Node previousDigitNode = null;
    /*
    Assuming that both the linked lists are of same size
     */
    while(aRunner != null && bRunner != null){
      int tempSum = aRunner.data + bRunner.data + previousCarry;
      int currentDigit = tempSum%10;
      previousCarry = tempSum/10;
      Node currentdigitNode = new Node();
      currentdigitNode.data = currentDigit;
      if(sumRoot == null){
        sumRoot = currentdigitNode;
      }
      if(previousDigitNode != null){
        previousDigitNode.next = currentdigitNode;
      }
      previousDigitNode = currentdigitNode;
      aRunner = aRunner.next;
      bRunner = bRunner.next;
    }
    if(previousCarry > 0){
      Node currentDigitNode = new Node();
      currentDigitNode.data = previousCarry;
      if(previousDigitNode != null){
        previousDigitNode.next = currentDigitNode;
      }
    }
    return sumRoot;
  }

  /**
   *
   * @param args
   */
  public static void main(String[] args) {
    int[] input = new int[]{7,1,6};
    Node numberA = LinkedListUtil.createLinkedList(input);
    LinkedListUtil.printLinkedList(numberA);
    input = new int[]{5,9,2};
    Node numberB = LinkedListUtil.createLinkedList(input);
    LinkedListUtil.printLinkedList(numberB);
    Node sumRoot = addTwoNumbers(numberA, numberB);
    LinkedListUtil.printLinkedList(sumRoot);
    System.out.println("next.......");
    input = new int[]{7,1,9};
    numberA = LinkedListUtil.createLinkedList(input);
    LinkedListUtil.printLinkedList(numberA);
    input = new int[]{5,9,9};
    numberB = LinkedListUtil.createLinkedList(input);
    LinkedListUtil.printLinkedList(numberB);
    sumRoot = addTwoNumbers(numberA,numberB);
    LinkedListUtil.printLinkedList(sumRoot);

  }

}

Add two numbers represented by linked lists stored in reverse direction.


package org.aslak.github.merge.service;

import java.util.HashSet;
import java.util.Set;

import org.aslak.github.merge.model.PullRequest;

public class PullRequestService {

    private Set<PullRequest> store;

    public PullRequestService() {
        this.store = new HashSet<>();
    }

    public PullRequest locate(String user, String repo, int pull) {
        for(PullRequest request : store) {
            if(
                    request.getSource().getUser().equals(user) &&
                    request.getSource().getRepository().equals(user) &&
                    request.getNumber() == pull) {
                return request;
            }
        }
        return null;
    }

    public void store(PullRequest pullrequest) {
        this.store.add(pullrequest);
    }
}

Add service for storing PullRequest metadata


package com.humbughq.android;

import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.widget.TextView;

class AsyncLogin extends HumbugAsyncPushTask {

    public AsyncLogin(HumbugActivity humbugActivity, String username,
            String password) {
        super(humbugActivity);
        context = humbugActivity;
        this.context.email = username;
        this.setProperty("username", username);
        this.setProperty("password", password);
    }

    public final void execute() {
        execute("api/v1/fetch_api_key");
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if (result != null) {
            this.context.api_key = result.toString();
            Log.i("login", "Logged in as " + this.context.api_key);

            Editor ed = this.context.settings.edit();
            ed.putString("email", this.context.email);
            ed.putString("api_key", this.context.api_key);

            ed.commit();

            this.context.openLogin();
        } else {
            TextView errorText = (TextView) this.context
                    .findViewById(R.id.error_text);
            errorText.setText("Login failed");
        }
    }
}

package com.humbughq.android;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.widget.TextView;

class AsyncLogin extends HumbugAsyncPushTask {

    public AsyncLogin(HumbugActivity humbugActivity, String username,
            String password) {
        super(humbugActivity);
        context = humbugActivity;
        this.context.email = username;
        this.setProperty("username", username);
        this.setProperty("password", password);
    }

    public final void execute() {
        execute("api/v1/fetch_api_key");
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if (result != null) {
            try {
                JSONObject obj = new JSONObject(result);

                if (obj.getString("result").equals("success")) {
                    this.context.api_key = obj.getString("api_key");
                    Log.i("login", "Logged in as " + this.context.api_key);

                    Editor ed = this.context.settings.edit();
                    ed.putString("email", this.context.email);
                    ed.putString("api_key", this.context.api_key);

                    ed.commit();

                    this.context.openLogin();
                    return;
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        TextView errorText = (TextView) this.context
                .findViewById(R.id.error_text);
        errorText.setText("Login failed");
    }
}

Refactor login code to handle JSON return values for api_key method.


package com.ushahidi.android.domain.repository;

import com.ushahidi.android.domain.entity.FormAttribute;
import com.ushahidi.android.domain.entity.From;

import java.util.List;

import rx.Observable;

/**
 * @author Ushahidi Team <team@ushahidi.com>
 */
public interface FormAttributeRepository {

    /**
     * Get a list of {@link FormAttribute} from either the database or online.
     *
     * @param deploymentId An ID of {@link com.ushahidi.android.domain.entity.Deployment}
     * @param from         Where to get the formattribute from. Either from local storage or online
     * @return The retrieved form attribute.
     */
    Observable<List<FormAttribute>> getForms(Long deploymentId, From from);

    /**
     * Add/Update a {@link FormAttribute}.
     *
     * @param form The FormAttribute to be saved.
     * @return The row affected
     */
    Observable<Long> putForm(FormAttribute form);
}

Add repo for form attribute


import java.util.Scanner;

/**
 * This program will print "HIRE!" if three of five inputted values are greater than
 * 50, and "REJECT" if not.
 **/
public class Type_Test {
    public static void main(String[] args) {
        int test = 0, count = 0, z;
        Scanner m = new Scanner(System.in);

        // Both conditions must be met
        while (test < 5 && count < 2) {
            System.out.println("Enter test score");
            z = m.nextInt();

            if (z >= 50) {
                count++;
            }
            test++;
        }

        if (count == 2) {
            System.out.println("HIRE!");
        } else {
            System.out.println("REJECT");
        }
    }
}

Add problem 8 to unit 1


package test.gx.realtime.acceptance;

import gx.realtime.RealtimeLoader;
import gx.realtime.RealtimeOptions;
import org.junit.Test;

/**
 *
 */
public class LoaderTest {
    @Test
    public void testLoader() {
        RealtimeOptions options = new RealtimeOptions();
        options.setAppId("foo");
        options.setClientId("bar");

        options.setOnFileLoaded((document) -> {
            //...
        });

        RealtimeLoader rtLoader = new RealtimeLoader(options);
        rtLoader.start();
    }
}

Add acceptance test for top-level loading.


/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * 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 imagej.legacy;

import imagej.patcher.LegacyEnvironment;
import imagej.patcher.LegacyInjector;

/**
 * An interactive test for the legacy mode of ImageJ2.
 *
 * @author Johannes Schindelin
 */
public class TestDrive {

	static {
		LegacyInjector.preinit();
	}

	public static void main(String[] args) throws ClassNotFoundException,
			InterruptedException {
		System.setProperty("ij1.plugin.dirs", "/nirvana/");
		final LegacyEnvironment ij1 = new LegacyEnvironment(null, false);
		ij1.addPluginClasspath(TestDrive.class.getClassLoader());
		ij1.main();
	}
}

Add an interactive test for the legacy mode


package cucumber.eclipse.editor.editors;

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

import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.Position;
import org.junit.Test;

public class GherkinModelTest {

    @Test
    public void stepContainerFoldRangeExtendsToNextStepContainer() throws BadLocationException {
        String source = "Feature: x\n"
                + "\n"
                + "  Scenario: 1\n" // line 2
                + "    Given y\n"
                + "\n"
                + "  Scenario: 2\n" // line 5
                + "    Given z\n";
        Document document = new Document(source);
        GherkinModel model = new GherkinModel();

        model.updateFromDocument(document);
        Position range = model.getFoldRanges().get(0);

        assertThat("offset", range.getOffset(), is(document.getLineOffset(2)));
        assertThat("range", range.getLength(), is(document.getLineOffset(5) - document.getLineOffset(2)));
    }

    @Test
    public void examplesFoldRangeExtendsToNextStepContainer() throws BadLocationException {
        String source = "Feature: x\n"
                + "\n"
                + "  Scenario Outline: 1\n"
                + "    Given y\n"
                + "\n"
                + "    Examples:\n" // line 5
                + "      | a | b |\n"
                + "      | 1 | 2 |\n"
                + "\n"
                + "  Scenario: 2\n" // line 9
                + "    Given z\n";
        Document document = new Document(source);
        GherkinModel model = new GherkinModel();

        model.updateFromDocument(document);
        Position range = model.getFoldRanges().get(0);

        assertThat("offset", range.getOffset(), is(document.getLineOffset(5)));
        assertThat("range", range.getLength(), is(document.getLineOffset(9) - document.getLineOffset(5)));
    }
}

Add tests for fold range calculation.


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

package org.opendaylight.ovsdb.openstack.netvirt;

import static org.junit.Assert.*;

import java.net.HttpURLConnection;

import org.junit.Test;
import org.mockito.Mockito;
import org.opendaylight.ovsdb.plugin.api.Status;
import org.opendaylight.ovsdb.plugin.api.StatusCode;

/**
 * Unit test for {@link AbstractHandler}
 */
public class AbstractHandlerTest {

    @Test
    public void testAbstractHandler() {
        Status status = Mockito.mock(Status.class);

        Mockito.when(status.getCode())
                .thenReturn(StatusCode.BADREQUEST)
                .thenReturn(StatusCode.CONFLICT)
                .thenReturn(StatusCode.NOTACCEPTABLE)
                .thenReturn(StatusCode.NOTFOUND)
                .thenReturn(StatusCode.GONE);

        assertEquals(
                "Error, getException() did not return the correct neutron API service error",
                HttpURLConnection.HTTP_BAD_REQUEST,
                AbstractHandler.getException(status));
        assertEquals(
                "Error, getException() did not return the correct neutron API service error",
                HttpURLConnection.HTTP_CONFLICT,
                AbstractHandler.getException(status));
        assertEquals(
                "Error, getException() did not return the correct neutron API service error",
                HttpURLConnection.HTTP_NOT_ACCEPTABLE,
                AbstractHandler.getException(status));
        assertEquals(
                "Error, getException() did not return the correct neutron API service error",
                HttpURLConnection.HTTP_NOT_FOUND,
                AbstractHandler.getException(status));
        assertEquals(
                "Error, getException() did not return the correct neutron API service error",
                HttpURLConnection.HTTP_INTERNAL_ERROR,
                AbstractHandler.getException(status));
    }
}

Add JUnit testing for AbstractHandler class.


package com.denver.citiestate.utils;

import com.denver.citiestate.interfaces.Listable;
import com.denver.citiestate.pojo.ListHouse;

public class SortedList extends List {

	/**
	 *
	 * @param maxSpace
	 */
	public SortedList(int maxSpace) {
		super(maxSpace);
	}

}

Add Sorted List class with an overloaded constructor


package de.retest.recheck.ignore;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;

import java.nio.file.Paths;

import org.junit.jupiter.api.Test;

import de.retest.recheck.ui.Path;
import de.retest.recheck.ui.descriptors.Element;
import de.retest.recheck.ui.descriptors.IdentifyingAttributes;
import de.retest.recheck.ui.descriptors.MutableAttributes;
import de.retest.recheck.ui.diff.AttributeDifference;

class ContentFilterIT {

	@Test
	void should_filter_img_src_and_alt_diffs() throws Exception {
		final Filter filter = FilterLoader.load( Paths.get( "src/main/resources/filter/web/content.filter" ) ).load();

		final Element element = Element.create( "retestId", mock( Element.class ),
				IdentifyingAttributes.create( Path.fromString( "/html[1]/img[1]" ), "img" ),
				new MutableAttributes().immutable() );
		final AttributeDifference srcDiff =
				new AttributeDifference( "src", "https://old/img.jpg", "https://new/img.jpg" );
		final AttributeDifference altDiff = new AttributeDifference( "alt", "A house.", "A dog." );
		final AttributeDifference clipDiff = new AttributeDifference( "clip", "bla", "blub" );

		assertThat( filter.matches( element ) ).isFalse();
		assertThat( filter.matches( element, srcDiff ) ).isTrue();
		assertThat( filter.matches( element, altDiff ) ).isTrue();
		assertThat( filter.matches( element, clipDiff ) ).isFalse();
	}

	@Test
	void should_filter_text_diffs() throws Exception {
		final Filter filter = FilterLoader.load( Paths.get( "src/main/resources/filter/web/content.filter" ) ).load();

		final Element element = Element.create( "retestId", mock( Element.class ),
				IdentifyingAttributes.create( Path.fromString( "/html[1]/p[1]" ), "p" ),
				new MutableAttributes().immutable() );
		final AttributeDifference textDiff = new AttributeDifference( "text", "An ancient text.", "A hip new text." );
		final AttributeDifference otherDiff = new AttributeDifference( "alt", "A house.", "A dog." );

		assertThat( filter.matches( element ) ).isFalse();
		assertThat( filter.matches( element, textDiff ) ).isTrue();
		assertThat( filter.matches( element, otherDiff ) ).isFalse();
	}
}

Add some test for the filters...


/*
 * Licensed to Jasig under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Jasig 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 the following location:
 *
 *   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.jasig.cas.adaptors.ldap.lppe.ad;

import javax.security.auth.login.AccountLockedException;
import javax.security.auth.login.LoginException;

import org.jasig.cas.authentication.AccountDisabledException;
import org.jasig.cas.authentication.AccountPasswordMustChangeException;
import org.jasig.cas.authentication.InvalidLoginLocationException;
import org.jasig.cas.authentication.InvalidLoginTimeException;
import org.junit.Test;

/**
 * Unit test for {@link org.jasig.cas.adaptors.ldap.lppe.ad.ActiveDirectoryAccountState}.
 *
 * @author Misagh Moayyed
 * @since 4.0
 */
public class ActiveDirectoryAccountStateTests {

    @Test(expected=InvalidLoginTimeException.class)
    public void testAccountStateLoginTime() throws LoginException {
        final ActiveDirectoryAccountState state = new ActiveDirectoryAccountState(
                org.ldaptive.auth.ext.ActiveDirectoryAccountState.Error.INVALID_LOGON_HOURS);
        state.getError().throwSecurityException();
    }

    @Test(expected=AccountDisabledException.class)
    public void testAccountStateDisabled() throws LoginException {
        final ActiveDirectoryAccountState state = new ActiveDirectoryAccountState(
                org.ldaptive.auth.ext.ActiveDirectoryAccountState.Error.ACCOUNT_DISABLED);
        state.getError().throwSecurityException();
    }

    @Test(expected=InvalidLoginLocationException.class)
    public void testAccountStateInvalidLocation() throws LoginException {
        final ActiveDirectoryAccountState state = new ActiveDirectoryAccountState(
                org.ldaptive.auth.ext.ActiveDirectoryAccountState.Error.INVALID_WORKSTATION);
        state.getError().throwSecurityException();
    }

    @Test(expected=AccountPasswordMustChangeException.class)
    public void testAccountStatePswMustChange() throws LoginException {
        final ActiveDirectoryAccountState state = new ActiveDirectoryAccountState(
                org.ldaptive.auth.ext.ActiveDirectoryAccountState.Error.PASSWORD_MUST_CHANGE);
        state.getError().throwSecurityException();
    }

    @Test(expected=AccountLockedException.class)
    public void testAccountStateNormalException() throws LoginException {
        final ActiveDirectoryAccountState state = new ActiveDirectoryAccountState(
                org.ldaptive.auth.ext.ActiveDirectoryAccountState.Error.ACCOUNT_LOCKED_OUT);
        state.getError().throwSecurityException();
    }
}

Test case for account state detection in AD


package internal.org.springframework.content.solr;

import static com.github.paulcwarren.ginkgo4j.Ginkgo4jDSL.Describe;
import static com.github.paulcwarren.ginkgo4j.Ginkgo4jDSL.It;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.content.commons.operations.ContentOperations;
import org.springframework.content.solr.EnableFullTextSolrIndexing;
import org.springframework.content.solr.SolrConfig;
import org.springframework.content.solr.SolrIndexer;
import org.springframework.content.solr.SolrProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.convert.ConversionService;
import org.springframework.test.context.ContextConfiguration;

import com.github.paulcwarren.ginkgo4j.Ginkgo4jSpringRunner;

@RunWith(Ginkgo4jSpringRunner.class)
@ContextConfiguration(classes=EnableFullTextSolrIndexingTest.TestConfiguration.class)
public class EnableFullTextSolrIndexingTest {

	@Autowired private ApplicationContext context;

	{
		Describe("EnableFullTextSolrIndexing", () -> {
			It("should have a SolrProperties bean", () -> {
				assertThat(context.getBean(SolrProperties.class), is(not(nullValue())));
			});
			It("should have a SolrIndexer bean", () -> {
				assertThat(context.getBean(SolrIndexer.class), is(not(nullValue())));
			});
		});
	}

	@Configuration
	@EnableFullTextSolrIndexing
	@Import(ContentStoreConfiguration.class)
	public static class TestConfiguration {

		@Bean
	    public SolrClient solrClient() {
	        SolrClient sc = new HttpSolrClient("http://some/url");
	        return sc;
	    }

	}

	public static class ContentStoreConfiguration {

		// Infrastructure bean - would usually be supplied by a content store implementation
		@Bean
		public ContentOperations contentOperations() {
			return mock(ContentOperations.class);
		}

		// Developer bean - would usually be supplied by app developer
		@Bean
		public ConversionService conversionService() {
			return mock(ConversionService.class);
		}

	}

	@Test
	public void noop() {
	}

}

Add solr enablement annotation test


/**
 * @copyright
 * ====================================================================
 *    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.
 * ====================================================================
 * @endcopyright
 */

package org.apache.subversion.javahl.types;

public class Checksum implements java.io.Serializable
{
    // Update the serialVersionUID when there is a incompatible change
    // made to this class.  See any of the following, depending upon
    // the Java release.
    // http://java.sun.com/j2se/1.3/docs/guide/serialization/spec/version.doc7.html
    // http://java.sun.com/j2se/1.4/pdf/serial-spec.pdf
    // http://java.sun.com/j2se/1.5.0/docs/guide/serialization/spec/version.html#6678
    // http://java.sun.com/javase/6/docs/platform/serialization/spec/version.html#6678
    private static final long serialVersionUID = 1L;

    /**
     * Constructor to be called from the native code
     * @param digest            bytes of the digest
     * @param kind              kind of checksum
     */
    public Checksum(byte[] digest, Kind kind)
    {
        this.digest = digest;
        this.kind = kind;
    }

    /** Digest of the checksum */
    private byte[] digest;

    /** Kind of the Checksum */
    private Kind kind;

    /**
     * Retrieve the digest
     * @return  the digest
     */
    public byte[] getDigest()
    {
        return digest;
    }

    /**
     * Retrieve the kind
     * @return  the kind
     */
    public Kind getKind()
    {
        return kind;
    }

    /**
     * Kinds of checksum
     */
    public enum Kind
    {
        MD5,
        SHA1;
    }
}

Add file missed in r1098736.


package org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005;

import com.google.common.net.InetAddresses;

/**
 **/
public final class PceIdBuilder {
	private PceIdBuilder() {

	}

	/**
	 * Construct a new PCE ID, from either an IPv4 or IPv6 form.
	 *
	 * @param defaultValue Which is a PCE-ID in string form
	 * @return A PCE ID.
	 */
	public static PceId getDefaultInstance(final String defaultValue) {
		return new PceId(InetAddresses.forString(defaultValue).getAddress());
	}
}

Implement PCE ID union type builder


/*
 * Copyright 2018 B2i Healthcare Pte Ltd, http://b2i.sg
 *
 * 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.b2international.snowowl.snomed.reasoner.classification;

import java.util.Objects;

import org.eclipse.core.runtime.jobs.ISchedulingRule;

import com.b2international.snowowl.datastore.remotejobs.SerializableSchedulingRule;

/**
 * @since 7.0
 */
public final class ClassificationSchedulingRule implements SerializableSchedulingRule {

	private static int nextId = 0;

	private final int id;
	private final String repositoryId;
	private final String branch;

	public static ClassificationSchedulingRule create(final int concurrentClassifications, final String repositoryId, final String branch) {
		return new ClassificationSchedulingRule((++nextId % concurrentClassifications), repositoryId, branch);
	}

	private ClassificationSchedulingRule(final int id, final String repositoryId, final String branch) {
		this.id = id;
		this.repositoryId = repositoryId;
		this.branch = branch;
	}

	@Override
	public boolean contains(final ISchedulingRule rule) {
		return equals(rule);
	}

	@Override
	public boolean isConflicting(final ISchedulingRule rule) {
		if (getClass() != rule.getClass()) { return false; }
		final ClassificationSchedulingRule other = (ClassificationSchedulingRule) rule;

		// If the IDs are the same, the number of concurrent classifications limit has been reached
		if (id == other.id) { return true; }

		// Otherwise, both branch and repositoryId must match for a conflict
		if (!Objects.equals(branch, other.branch)) { return false; }
		if (!Objects.equals(repositoryId, other.repositoryId)) { return false; }

		return true;
	}

	@Override
	public int hashCode() {
		return Objects.hash(id, branch, repositoryId);
	}

	@Override
	public boolean equals(final Object obj) {
		if (this == obj) { return true; }
		if (obj == null) { return false; }
		if (getClass() != obj.getClass()) { return false; }

		final ClassificationSchedulingRule other = (ClassificationSchedulingRule) obj;
		if (id != other.id) { return false; }
		if (!Objects.equals(branch, other.branch)) { return false; }
		if (!Objects.equals(repositoryId, other.repositoryId)) { return false; }

		return true;
	}
}

Add scheduling rule implementation for classification jobs


/*
 * This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
 *
 * Copyright 2008-2011 Geosparc nv, http://www.geosparc.com/, Belgium.
 *
 * The program is available in open source according to the GNU Affero
 * General Public License. All contributions in this program are covered
 * by the Geomajas Contributors License Agreement. For full licensing
 * details, see LICENSE.txt in the project root.
 */
package org.geomajas.plugin.editing.jsapi.example.server.command;

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

import org.geomajas.command.Command;
import org.geomajas.geometry.Coordinate;
import org.geomajas.geometry.Geometry;
import org.geomajas.global.ExceptionCode;
import org.geomajas.global.GeomajasException;
import org.geomajas.plugin.editing.jsapi.example.dto.GetCentroidRequest;
import org.geomajas.plugin.editing.jsapi.example.dto.GetCentroidResponse;
import org.geomajas.service.DtoConverterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.vividsolutions.jts.geom.Point;

/**
 * <p>
 * This command calculates the centroid of the given geometries.
 * </p>
 *
 * @author Pieter De Graef
 */
@Component
public class GetCentroidCommand implements Command<GetCentroidRequest, GetCentroidResponse> {

	@Autowired
	private DtoConverterService converter;

	public GetCentroidResponse getEmptyCommandResponse() {
		return new GetCentroidResponse();
	}

	public void execute(GetCentroidRequest request, GetCentroidResponse response) throws Exception {
		if (request.getGeometries() == null || request.getGeometries().size() == 0) {
			throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "request");
		}

		Map<Geometry, Coordinate> centroids = new HashMap<Geometry, Coordinate>(request.getGeometries().size());
		for (Geometry geometry : request.getGeometries()) {
			com.vividsolutions.jts.geom.Geometry jtsGeom = converter.toInternal(geometry);
			Point centroid = jtsGeom.getCentroid();
			centroids.put(geometry, new Coordinate(centroid.getX(), centroid.getY()));
		}

		response.setCentroids(centroids);
	}
}

Create a showcase application that demonstrates the JavaScript API of the editing plugin.


/****************************************************************
 * 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.james.api.imap.message.request;

import org.apache.james.api.imap.ImapCommand;

public interface ImapRequest {

	/**
	 * Gets the IMAP command whose execution is requested by the client.
	 * @return ImapCommand, not null
	 */
	public abstract ImapCommand getCommand();

	/**
	 * Gets the prefix tag identifying this request.
	 * @return the tag identifying the client request, not null
	 */
	public abstract String getTag();

}

Move in other API elements.


package Reaction;

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

import static org.junit.Assert.*;

import java.util.ArrayList;

public class ReactionDBWriterTest {

    Pair pair0 = createPair("UNIQUE-ID", "ANDELA-FELLOW");
    Pair pair1 = createPair("TYPES", "OMOTOSO");
    Pair pair2 = createPair("COMMON-NAME", "FEMALE");
    Pair pair3 = createPair("ATOM-MAPPINGS", "ANDELA");
    Pair pair4 = createPair("IN-PATHWAY", "10");

    ReactionDBWriter reactionDBWriter;
    Reaction reaction;

    public Pair<String, ArrayList<String>> createPair(String key, String value) {
        ArrayList<String> values = new ArrayList<>();
        values.add(value);
        return new Pair<>(key, values);
    }

    public void populatePairList(){
        reaction.add(pair0);
        reaction.add(pair1);
        reaction.add(pair2);
        reaction.add(pair3);
        reaction.add(pair4);
    }

    @Before
    public void setUp() throws Exception {
        reactionDBWriter = new ReactionDBWriter();
        reaction = new Reaction();
        populatePairList();
    }

    @After
    public void tearDown() throws Exception {

    }

    @Test
    public void testConnectToReactionDatabase() throws Exception {
        reactionDBWriter.connectToReactionDatabase();
        assertTrue(reactionDBWriter.isConnected());
    }

    @Test
    public void testCreateReactionTable() throws Exception {
        testConnectToReactionDatabase();
        reactionDBWriter.createReactionTable();
    }

    @Test
    public void testWriteReactionToDatabase() throws Exception {
        testConnectToReactionDatabase();
        testCreateReactionTable();
        reactionDBWriter.writeReactionToDatabase(reaction);
        reactionDBWriter.disconnect();
        assertFalse(reactionDBWriter.isConnected());
    }
}

Add Test to fail ReactionDBWriter class


package com.github.aureliano.verbum_domini.helper;

import com.github.aureliano.verbum_domini.core.bean.IBean;
import com.github.aureliano.verbum_domini.core.impl.dao.DaoFactory;

public final class ServiceHelper {

	private ServiceHelper() {
		super();
	}

	public static boolean exist(Class<? extends IBean> type, String id) {
		if (!id.matches("\\d+")) {
			return false;
		}

		return DaoFactory.createDao(type).exist(Integer.parseInt(id));
	}
}

Use fast method to verify entity existence.


package nl.next35.logic;

import nl.next35.domain.Post;
import nl.next35.domain.User;

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

/**
 * @author Lesley
 */
public final class ResolverChain {

    private final List<Resolver> resolvers = new ArrayList<>();

    public List<Post> resolve(User user) {
        List<Post> posts = new ArrayList<>();

        resolvers.stream().map(r -> r.getPosts(user)).forEach(posts::addAll);

        return posts;
    }

    public void add(Resolver resolver) {
        resolvers.add(resolver);
    }

    public void remove(Resolver resolver) {
        resolvers.remove(resolver);
    }

}

Add class that can take up multiple resolvers.


package com.google.sps;

import javax.servlet.http.HttpServletRequest;

import com.google.gson.JsonObject;
import com.google.sps.util.BodyParser;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import static org.mockito.Mockito.*;

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

@RunWith(JUnit4.class)
public class BodyParserTest {
  private static final String JSON_EXAMPLE = "{\"prop1\":12345, \"prop2\":asdf}";
  private HttpServletRequest request;

  @Before
  public void setUp() throws IOException {
    request = mock(HttpServletRequest.class);
    when(request.getReader()).thenReturn(new BufferedReader(new StringReader(JSON_EXAMPLE)));
  }

  @Test
  public void testSerializedJsonParse() throws IOException {
    JsonObject obj = BodyParser.parseJsonObjectFromRequest(request);
    Assert.assertEquals(obj.getAsJsonPrimitive("prop1").getAsInt(), 12345);
    Assert.assertEquals(obj.getAsJsonPrimitive("prop2").getAsString(), "asdf");
  }
}

Add unit test for BodyParser


package oasis.model.i18n;

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

import java.util.Locale;

import org.junit.Test;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class LocaleJsonSerializationTest {
  public static class Foo {
    @JsonProperty Locale locale;
  }

  @Test public void testSerialization() throws Exception {
    Foo foo = new Foo();
    foo.locale = Locale.FRANCE;

    ObjectMapper mapper = new ObjectMapper()
        .registerModule(new LocalizableModule());
    ObjectNode node = mapper.convertValue(foo, ObjectNode.class);

    assertThat(node.get("locale"))
        .describedAs(mapper.writeValueAsString(foo))
        .isEqualTo(mapper.getNodeFactory().textNode(Locale.FRANCE.toLanguageTag()));
  }

  @Test public void testDeserialization() throws Exception {
    ObjectMapper mapper = new ObjectMapper()
        .registerModule(new LocalizableModule());
    Foo foo = mapper.readValue("{\"locale\": \"en-GB\"}", Foo.class);

    assertThat(foo.locale).isEqualTo(Locale.UK);
  }
}

Add unit test for java.util.Locale ser-/deser-ialization to/from JSON.


package javaStdinAndStdout2;

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int x = sc.nextInt();
            double y = sc.nextDouble();
            String s = sc.nextLine();
            if( s.length() == 0 ) s += sc.nextLine();

            System.out.println("String: " + s);
            System.out.println("Double: " + y);
            System.out.println("Int: " + x);
            sc.close();
    }
}

Add solution for problem Java Stdin And Stdout 2


package main.algorithm.leetcode;

import main.algorithm.leetcode.structure.ListNode;
import org.junit.Test;

/**
 * Description :
 *   <i>https://leetcode.com/problems/delete-node-in-a-linked-list/</i>
 *   Runtime: 0 ms, faster than 100.00% of Java online submissions for Delete Node in a Linked List.
 *   Memory Usage: 38.2 MB, less than 74.67% of Java online submissions for Delete Node in a Linked List.
 *
 * @author chile
 * @version 1.0
 * @date 2021/8/4 10:31
 */
public class DeleteNodeInALinkedList {

    class Solution {

        public void deleteNode(ListNode node) {
            ListNode temp = node.next;
            node.val = node.next.val;
            node.next = node.next.next;
            temp = null;
        }

    }

    @Test
    public void test1() {
        ListNode head = new ListNode(1);
        head.addNext(2).addNext(3);
        new Solution().deleteNode(head.next);
        while (head != null) {
            System.out.println(head.val);
            head = head.next;
        }
    }

}

Delete Node in a Linked List


package com.phonegap.demo;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.net.*;
import android.webkit.WebView;

public class NetworkManager {

	Context mCtx;
	WebView mView;
	ConnectivityManager sockMan;

	NetworkManager(Context ctx, WebView view)
	{
		mCtx = ctx;
		mView = view;
		sockMan = (ConnectivityManager) mCtx.getSystemService(Context.CONNECTIVITY_SERVICE);
	}

	public boolean isAvailable()
	{
		NetworkInfo info = sockMan.getActiveNetworkInfo();
		return info.isConnected();
	}

	public boolean isReachable(String uri)
	{
		boolean reached = true;
		try {
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpGet httpget = new HttpGet(uri);
			httpclient.execute(httpget);
		} catch (Exception e) { reached = false;}
		return reached;
	}

}

package com.phonegap.demo;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.net.*;
import android.webkit.WebView;

public class NetworkManager {

	Context mCtx;
	WebView mView;
	ConnectivityManager sockMan;

	NetworkManager(Context ctx, WebView view)
	{
		mCtx = ctx;
		mView = view;
		sockMan = (ConnectivityManager) mCtx.getSystemService(Context.CONNECTIVITY_SERVICE);
	}

	public boolean isAvailable()
	{
		NetworkInfo info = sockMan.getActiveNetworkInfo();
		return info.isConnected();
	}

	public boolean isReachable(String uri)
	{
		boolean reached = isAvailable();
		try {
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpGet httpget = new HttpGet(uri);
			httpclient.execute(httpget);
		} catch (Exception e) { reached = false;}
		return reached;
	}

}

Make reachable depend on availability


package info.u_team.u_team_core.util.annotation;

import org.apache.logging.log4j.*;
import org.objectweb.asm.Type;

import info.u_team.u_team_core.api.construct.*;
import info.u_team.u_team_core.api.integration.*;
import info.u_team.u_team_core.util.AnnotationUtil;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.loading.FMLEnvironment;
import net.minecraftforge.forgespi.language.ModFileScanData.AnnotationData;

public class AnnotationManager {

	private static final Logger LOGGER = LogManager.getLogger("AnnotationManager");

	public static void constructConstructs(String modid) {
		for (AnnotationData data : AnnotationUtil.getAnnotations(modid, Type.getType(Construct.class))) {
			final String annotationModid = (String) data.getAnnotationData().get("modid");
			final Boolean client = (Boolean) data.getAnnotationData().get("client");
			if (modid.equals(annotationModid)) {
				if (client == null || !client || client && FMLEnvironment.dist == Dist.CLIENT) {
					LOGGER.info("Try to load construct for mod " + modid);
					try {
						Class.forName(data.getMemberName()).asSubclass(IModConstruct.class).newInstance().construct();
					} catch (LinkageError | ClassNotFoundException | InstantiationException | IllegalAccessException | ClassCastException ex) {
						LOGGER.error("Failed to load and construct mod construct : {}", data.getMemberName(), ex);
						throw new RuntimeException(ex);
					}
				}
			}
		}
	}

	public static void constructIntegrations(String modid) {
		for (AnnotationData data : AnnotationUtil.getAnnotations(modid, Type.getType(Integration.class))) {
			final String annotationModid = (String) data.getAnnotationData().get("modid");
			final String integrationModid = (String) data.getAnnotationData().get("integration");
			if (modid.equals(annotationModid)) {
				if (ModList.get().isLoaded(integrationModid)) {
					LOGGER.info("Try to load " + integrationModid + " integration for mod " + modid);
					try {
						Class.forName(data.getMemberName()).asSubclass(IModIntegration.class).newInstance().construct();
					} catch (LinkageError | ClassNotFoundException | InstantiationException | IllegalAccessException | ClassCastException ex) {
						LOGGER.error("Failed to load and construct integration : {}", data.getMemberName(), ex);
						throw new RuntimeException(ex);
					}
				}
			}
		}
	}

}

Make new annotation manager class that bundles the construct manager and the integration manager


import java.util.Scanner;

public class CountBitPairs {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        System.out.println(countBitPairs(n));
    }

    public static int countBitPairs(int n) {
        int count = 0;
        int previous = n & 1;
        int i;
        n >>= 1;

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

        return count;
    }
}

Solve homework2-problem8: Count of Equal Bit Pairs


/*
 *  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 dk.ekot.misc;

import org.junit.Assert;

import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Is isReadable reliable?
 */
public class IsReadableTest {
    public static void main(String[] args) throws URISyntaxException {
        final String RESOURCE = "log4j.xml";
        URL resource = Thread.currentThread().getContextClassLoader().getResource(RESOURCE);
        Assert.assertNotNull("Resource '" + RESOURCE + "' should exist", resource);

        Path resourcePath = Paths.get(resource.toURI());
        Assert.assertTrue("Resource '" + RESOURCE + "' should be readable", Files.isReadable(resourcePath));
    }
}

Add basic test of Files.isReadable


package dea.monitor.tools;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashSet;
import java.util.Set;

public class EncodeString {
	public Set<String> vaildTypes = new HashSet<String>();

	public EncodeString() {
		vaildTypes.add("MD5");
		vaildTypes.add("SHA1");
	}

	public String genResponse(String encodeType, String txt) throws NoSuchAlgorithmException {

		MessageDigest md = MessageDigest.getInstance(encodeType);
		byte[] arr = txt.getBytes();
		arr = md.digest(arr);
		StringBuilder sb = new StringBuilder();
		for (byte b : arr) {
			sb.append(String.format("%02x", b));
		}
		return sb.toString();
	}

	public void usage() {
		System.err.println("Usage: EncodeString encodeType textToEncode");
		System.err.println("Where encodeType is one of:");
		for (String encodeType : vaildTypes) {
			System.err.println(encodeType);
		}
	}

	public static void main(String[] args) {
		EncodeString item = new EncodeString();
		try {
			if (args.length < 2)
				item.usage();
			else if (!item.vaildTypes.contains(args[0]))
				item.usage();
			else {
				System.out.println(item.genResponse(args[0], args[1]));
			}
		} catch (Exception e) {
			System.err.println(e.getMessage());
			item.usage();
		}
	}

}

Add tool to gen MD5 or SHA hash of string


package com.rox.emu;

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

import static junit.framework.TestCase.assertEquals;

public class SimpleMemoryTest {
    private Memory memory;

    @Before
    public void setup(){
        memory = new SimpleMemory(65534);
    }

    @Test
    public void testGetAndSetByte(){
        memory.setByte(0, 99);
        memory.setByte(0x10, 101);
        memory.setByte(0b00000001, 1);

        assertEquals(99, memory.getByte(0));
        assertEquals(101, memory.getByte(16));
        assertEquals(1, memory.getByte(1));
    }

    @Test
    public void testSetMemory(){
        int[] values = new int[] {1,22,33,44,55};
        memory.setMemory(0, values);

        assertEquals(1, memory.getByte(0));
        assertEquals(22, memory.getByte(1));
        assertEquals(33, memory.getByte(2));
        assertEquals(44, memory.getByte(3));
        assertEquals(55, memory.getByte(4));
    }

}

Test cases for memory abstraction class


package org.xblackcat.sjpu.storage.ann;

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

/**
 * Mark with the annotation a method parameter to substitute in runtime a value into SQL. It helpfull to pass the same value to a different
 * places of SQL. Value of the annotation represent an indexed argument in SQL query. Indexed argument represented with
 * '{<index>}' construction. Argument should be String type.
 *

 * Example:
 *

 *     interface ITestAH extends IAH {
 *         {@linkplain Sql @SQL}("INSERT INTO `duplicate`(`id`, `name`, `name_copy`) VALUES (?, {1}, {1})")
 *         void addName(int id, @SqlArg(1) String name) throws {@linkplain org.xblackcat.sjpu.storage.StorageException StorageException};
 *     }
 *

 *

 * 17.02.14 11:21
 *
 * @author xBlackCat
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
public @interface SqlArg {
    int value();
}

Introduce a new annotation for substituting repeatable value in to query


package sfBugs;

import java.lang.reflect.Method;

public class Bug1912994 {
	public String foo() throws Exception {
		String s = null;
		try {
			Method m = this.getClass().getMethod("foo");
			m.invoke(this);
			char[] t = new char[0];
			t[1] = 'a';
			s = "foo";
			s += "bar";
			// Thread.sleep(100);
			return s;
		} catch (Exception e) { // Should yield "L D REC"
			throw new Exception(e);
		}
	}

	// If you comment out the following method, no "L D REC" warning is
	// emitted for line 17
	public String foo2() throws Exception {
		String s = null;
		try {
			Method m = this.getClass().getMethod("foo2");
			m.invoke(this);
			char[] t = new char[0];
			t[1] = 'a';
			s = "foo";
			s += "bar";
			// Thread.sleep(100);
			return s;
		} catch (RuntimeException re) {
			throw re;
		} catch (Exception e) {
			throw new Exception(e);
		}
	}
}

Test case for [ 1912994 ] REC_CATCH_EXCEPTION broken with JDT in 3.3.1


package sfBugs;

public class Bug2984602 {

	int itemID;

	public int hashCode() {
		return itemID;
	}

	public boolean equals(Object object) {
		if (!(Bug2984602.class.isInstance(object))) {
			return false;
		}

		boolean equals = false;
		Bug2984602 compareTo = (Bug2984602) object;

		if (this.itemID == compareTo.itemID) {
			equals = true;
		}

		return equals;
	}

}

Add test case for false positive on Class.isInstance for equals() che - ID: 2984602


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

package org.scijava.log;

import static org.junit.Assert.assertTrue;
import static org.scijava.log.LogService.INFO;

import org.junit.Test;

/**
 * Tests {@link LogService}.
 *
 * @author Johannes Schindelin
 */
public class LogServiceTest {
	@Test
	public void testDefaultLevel() {
		final LogService log = new StderrLogService();
		int level = log.getLevel();
		assertTrue("default level (" + level + ") is at least INFO(" + INFO + ")", level >= INFO);
	}
}

Test the default level with StderrLogService


package com.opera.core.systems;

import junit.framework.TestCase;

import org.junit.Test;

import com.opera.core.systems.util.VersionUtil;

public class VersionUtilsTest extends TestCase {

	private final String version = "2.0";
	private final String[] biggerVersions = {"2.0.0", "2.0.1", "2.1", "2.1.0", "3.0", "3.0.1"};
	private final String[] smallerVersions = {"1.0.0", "1.0.1", "1.1", "1.1.0", "1.0", "1.9.9"};

	@Test
	public void testShouldSupportSmallerThan() {
		traverseVersions(biggerVersions, 1, ">");
	}

	@Test
	public void testShouldSupportBiggerThan() {
		traverseVersions(smallerVersions, -1, "<");
	}

	@Test
	public void testShouldSupportEquals() {

		for(int i = 0; i < biggerVersions.length; ++i) {
			int result = VersionUtil.compare(biggerVersions[i], biggerVersions[i]);
			assertTrue("Expected equals on " + biggerVersions[i]  , result == 0 );
		}

		for(int i = 0; i < smallerVersions.length; ++i) {
			int result = VersionUtil.compare(smallerVersions[i], smallerVersions[i]);
			assertTrue("Expected equals on " + smallerVersions[i]  , result == 0 );
		}
	}

	private void traverseVersions(String[] arr, int expected, String sign) {
		for(int i = 0; i < arr.length; ++i) {
			int result = VersionUtil.compare(arr[i], version);
			assertTrue("Expected " + arr[i] + " " + sign + " " + version, result == expected );
		}
	}

}

Add tests for Version Utils comparison


/* ============================================================================
 * Copyright (c) 2015 Imagic Bildverarbeitung AG, CH-8152 Glattbrugg.
 * All rights reserved.
 *
 * http://www.imagic.ch/
 * ============================================================================
 */
package algorithm.string;

import java.util.Scanner;

/**
 *
 * @version $Revision$
 * @version $Date$
 * @author $Author$
 * @owner Sandro Mario Zbinden
 */
public class AlternatingCharacters {
    public static class Solution {

        private static int alternatingCharacters(String input) {
            int deleteCount = 0;
            for (int i = 0; i < input.length() - 1; i++) {
                if (input.charAt(i) == input.charAt(i + 1)) {
                    deleteCount = deleteCount + 1;
                }
            }
            return deleteCount;
        }

        public static void main(String[] args) {
            try (Scanner in = new Scanner(System.in)) {
                int testCases = in.nextInt();
                for (int i = 0; i < testCases; i++) {
                    System.out.println(alternatingCharacters(in.next()));
                }
            }
        }

    }

    public static void main(String[] args) {
        Solution.main(null);
    }
}

Add solution for Alternating Characters problem


/*
 * Copyright 2012-2014 TORCH GmbH
 *
 * This file is part of Graylog2.
 *
 * Graylog2 is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Graylog2 is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Graylog2.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.graylog2.gelfclient.encoder;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel;
import org.graylog2.gelfclient.GelfConfiguration;
import org.testng.annotations.Test;

import java.util.Random;

import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;

public class GelfMessageChunkEncoderTest {
    @Test
    public void testChunkedEncode() throws Exception {
        GelfConfiguration config = new GelfConfiguration();
        EmbeddedChannel channel = new EmbeddedChannel(new GelfMessageChunkEncoder(config));
        String largeMessage = largeMessage(1500);

        channel.writeOutbound(Unpooled.wrappedBuffer(largeMessage.getBytes()));

        ByteBuf chunk1 = (ByteBuf) channel.readOutbound();
        ByteBuf chunk2 = (ByteBuf) channel.readOutbound();

        // Generates two messages
        assertNull(channel.readOutbound());

        // Check for GELF chunked magic bytes
        assertEquals((byte) 0x1e, chunk1.readByte());
        assertEquals((byte) 0x0f, chunk1.readByte());
        assertEquals((byte) 0x1e, chunk2.readByte());
        assertEquals((byte) 0x0f, chunk2.readByte());

        // 8 bytes for the message ID
        assertEquals(8, chunk1.readBytes(8).array().length);
        assertEquals(8, chunk2.readBytes(8).array().length);

        // 1 byte sequence number
        assertEquals((byte) 0, chunk1.readByte());
        assertEquals((byte) 1, chunk2.readByte());

        // 1 byte sequence count
        assertEquals((byte) 2, chunk1.readByte());
        assertEquals((byte) 2, chunk2.readByte());

        // data bytes
        assertEquals(1420, chunk1.readableBytes());
        assertEquals(largeMessage.length() - 1420, chunk2.readableBytes());
    }

    private String largeMessage(int limit) {
        Random r = new Random();
        String largeMessage = "";

        while (largeMessage.length() < limit) {
            largeMessage += r.nextInt();
        }

        return largeMessage;
    }
}

Add test for the message chunk encoder.


package devopsdistilled.operp.server.data.entities;

import javax.inject.Inject;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import devopsdistilled.operp.server.context.JpaH2TestContext;
import devopsdistilled.operp.server.data.repo.ProductRepository;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = JpaH2TestContext.class)
@Transactional
public class ProductTest {

	@Inject
	private ProductRepository productRepository;

	@Test
	public void test() {
		Assert.assertNotNull(productRepository);

	}

}

Add Test to test Product


// 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 com.google.cloud.secretmanager.v1.AccessSecretVersionResponse;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretVersionName;
import java.io.IOException;

public class SecretHandler {
  private static final String PROJECT_ID = "unitebystep";
  private static final String API_KEY_ID = "api-key";
  private static final String VERSION_ID = "1";

  public static String getApiKey() throws IOException {
    try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) {
      SecretVersionName secretVersionName =
          SecretVersionName.of(PROJECT_ID, "your-secret-id-1", VERSION_ID);

      AccessSecretVersionResponse response = client.accessSecretVersion(secretVersionName);
      String result = response.getPayload().getData().toStringUtf8();
      client.close();

      return result;
    }
  }
}

Add handler for accessing secrets


/**
 * Illustrates loading a sequence file of people and how many pandas they have seen
 */
package com.oreilly.learningsparkexamples.java;

import java.util.List;
import scala.Tuple2;

import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;

public class BasicLoadSequenceFile {

  public static class ConvertToNativeTypes implements PairFunction<Tuple2<Text, IntWritable>, String, Integer> {
    public Tuple2<String, Integer> call(Tuple2<Text, IntWritable> record) {
      return new Tuple2(record._1.toString(), record._2.get());
    }
  }

  public static void main(String[] args) throws Exception {
		if (args.length != 2) {
      throw new Exception("Usage BasicLoadSequenceFile [sparkMaster] [input]");
		}
    String master = args[0];
    String fileName = args[1];

		JavaSparkContext sc = new JavaSparkContext(
      master, "basicloadjson", System.getenv("SPARK_HOME"), System.getenv("JARS"));
    JavaPairRDD<Text, IntWritable> input = sc.sequenceFile(fileName, Text.class, IntWritable.class);
    JavaPairRDD<String, Integer> result = input.mapToPair(new ConvertToNativeTypes());
    List<Tuple2<String, Integer>> resultList = result.collect();
    for (Tuple2<String, Integer> record : resultList) {
      System.out.println(record);
    }
	}
}

Add a basic load sequence file example for Java


// SMSLib for Java v3
// A Java API library for sending and receiving SMS via a GSM modem
// or other supported gateways.
// Web Site: http://www.smslib.org
//
// Copyright (C) 2002-2012, Thanasis Delenikas, Athens/GREECE.
// SMSLib is distributed under the terms of the Apache License version 2.0
//
// 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.smslib.modem.athandler;

import java.io.IOException;
import org.smslib.GatewayException;
import org.smslib.TimeoutException;
import org.smslib.modem.ModemGateway;

/**
 * AT Handler for Huawei E220 modems.
 */

public class ATHandler_Huawei_E220 extends ATHandler_Huawei {

	public ATHandler_Huawei_E220(ModemGateway myGateway) {
		super(myGateway);
	}

	@Override
	public void init() throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		super.init();
		getModemDriver().write("AT+CSCA?\r");
		String smsc = getModemDriver().getResponse();
		getModemDriver().write("AT+CSCA=" + smsc + "\r");
		getModemDriver().getResponse();
	}
}

Add Huawei E220 AT Handler


package no.ssb.vtl.script.error;

/*
 * ========================LICENSE_START=================================
 * Java VTL
 * %%
 * Copyright (C) 2016 - 2017 Hadrien Kohl
 * %%
 * 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.
 * =========================LICENSE_END==================================
 */

import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.Token;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class VTLScriptExceptionTest {

    @Test
    public void testContextWithStartStop() throws Exception {

        ParserRuleContext context = mock(ParserRuleContext.class);
        Token start = mock(Token.class);
        Token stop = mock(Token.class);

        when(start.getCharPositionInLine()).thenReturn(1);
        when(stop.getCharPositionInLine()).thenReturn(2);

        when(start.getLine()).thenReturn(3);
        when(stop.getLine()).thenReturn(4);

        when(context.getStart()).thenReturn(start);
        when(context.getStop()).thenReturn(stop);

        VTLScriptException exception = new VTLScriptException("user defined message", context);

        assertThat(exception.getStartColumn()).isEqualTo(1);
        assertThat(exception.getStopColumn()).isEqualTo(2);
        assertThat(exception.getStartLine()).isEqualTo(3);
        assertThat(exception.getStopLine()).isEqualTo(4);

    }

    @Test
    public void testContextWithSameStartStop() throws Exception {

        ParserRuleContext context = mock(ParserRuleContext.class);
        Token token = mock(Token.class);

        when(token.getCharPositionInLine()).thenReturn(0);
        when(token.getLine()).thenReturn(0);

        when(context.getStart()).thenReturn(token);
        when(context.getStop()).thenReturn(token);

        when(token.getText()).thenReturn("token");

        VTLScriptException exception = new VTLScriptException("user defined message", context);

        assertThat(exception.getStartColumn()).isEqualTo(0);
        assertThat(exception.getStopColumn()).isEqualTo(5);
        assertThat(exception.getStartLine()).isEqualTo(0);
        assertThat(exception.getStopLine()).isEqualTo(0);

    }
}

Add test for the different start and stop tokens context can return


package org.jpos.ee;

import org.junit.jupiter.api.Test;

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

public class SysConfigEnvironmentProviderTest {

    @SuppressWarnings("unchecked")
    SysConfigEnvironmentProvider getProvider() {
        return new SysConfigEnvironmentProvider() {
            @Override
            protected <T> T exec(DBAction<T> action) throws Exception {
                return (T) "someValue";
            }
        };
    }

    @Test
    void testGetValue() {
        SysConfigEnvironmentProvider p = getProvider();
        String value = p.get("someKey");
        assertEquals("someValue", value);
    }

    @Test
    void testKeyIsNull() {
        assertThrows(NullPointerException.class, () -> getProvider().get(null));
    }
}

Add unit tests for SysConfigEnvironmentProvider.


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

package com.google.instrumentation.common;

/**
 * Interface for getting the current time.
 */
public abstract class Clock {

  /**
   * Obtains the current instant from this clock.
   *
   * @return the current instant.
   */
  public abstract Timestamp now();

  /**
   * Returns a time measurement with nanosecond precision that can only be used to calculate elapsed
   * time.
   *
   * @return a time measurement with nanosecond precision that can only be used to calculate elapsed
   *     time.
   */
  public abstract long nowNanos();
}

Add an interface for getting the time throughout the Instrumentation library.


package com.tutorialspoint.documentation;

import java.io.IOException;

/**
 *
Add Two Numbers!
 The AddNum program implements an application that simply adds two given
 * integer numbers and Prints the output on the screen.
 *

 * Note: Giving proper comments in your program makes it more user friendly and it is assumed
 * as a high quality code.
 *
 * @author Peter
 * @version 1.0
 * @since 2015-07-18
 */
public class AddNum {
  /**
   * This method is used to add two integers. This is a the simplest form of a class method, just to
   * show the usage of various javadoc Tags.
   *
   * @param numA This is the first parameter to addNum method
   * @param numB This is the second parameter to addNum method
   * @return int This returns sum of numA and numB.
   */
  public int addNum(int numA, int numB) {
    return numA + numB;
  }

  /**
   * This is the main method which makes use of addNum method.
   *
   * @param args Unused.
   * @return Nothing.
   * @exception IOException On input error.
   * @see IOException
   */
  public static void main(String args[]) throws IOException {

    AddNum obj = new AddNum();
    int sum = obj.addNum(10, 20);

    System.out.println("Sum of 10 and 20 is :" + sum);
  }
}

Add example about the usage of <h1>, <p>, <b>, @author, @version, @since, @param, @return, @exception and @see tags.


package codeu.chat.server;

import java.util.Collection;
import java.util.Map;

import codeu.chat.common.ConversationHeader;
import codeu.chat.common.ConversationPayload;
import codeu.chat.common.Message;
import codeu.chat.common.Secret;
import codeu.chat.common.User;
import codeu.chat.util.Uuid;

public interface PersistenceFileSkeleton {
  public interface ServerInfo {
    Uuid id();
    Secret secret();
    Uuid lastSeen();
  }

  ServerInfo serverInfo();

  Map<Uuid, User> users();

  Map<Uuid, ConversationHeader> conversationHeaders();
  Map<Uuid, ConversationPayload> conversationPayloads();

  Map<Uuid, Message> messages();

}

Create persistence file's skeleton with an interface


import org.junit.Test;

public class isogramtest {

    @Test
    public void whenStringHasRepeatingCharactersThenItIsNotAnIsogram() {
        assert (!isogram.isIsogram("abcdefb"));
    }

    @Test
    public void whenStringHasNoRepeatingCharactersThenItIsAnIsogram(){
        assert (isogram.isIsogram("bacdefg"));
    }

    @Test
    public void whenStringIsEmptyThenItIsAnIsogram(){
        assert (isogram.isIsogram(""));
    }

    @Test
    public void whenStringIsOneLetterThenItIsAnIsogram(){
        assert (isogram.isIsogram("A"));
    }
}

Add string isogram test for Java implementation


package org.zstack.utils;

import org.apache.commons.io.ByteOrderMark;
import org.apache.commons.io.input.BOMInputStream;

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

import static java.util.Arrays.asList;

/**
 * Created by kayo on 2018/10/9.
 */
public class BOMUtils {
    public static void skipBOM(InputStream inputStream) throws IOException {
        BOMInputStream bomi = new BOMInputStream(inputStream,
                ByteOrderMark.UTF_16BE,
                ByteOrderMark.UTF_16LE,
                ByteOrderMark.UTF_32BE,
                ByteOrderMark.UTF_32LE);
        if (bomi.hasBOM()) {
            inputStream.skip(bomi.getBOM().length());
        }
    }
}

Add BOM utils to support skip bom


package bdv;

import bdv.export.ProgressWriterConsole;
import bdv.img.imaris.Imaris;
import bdv.spimdata.SpimDataMinimal;
import bdv.spimdata.XmlIoSpimDataMinimal;
import bdv.viewer.ViewerOptions;
import java.io.IOException;
import mpicbg.spim.data.SpimDataException;

public class ImarisExample
{
	static void createXmlForIms( String imsFilename, String xmlFilename ) throws IOException, SpimDataException
	{
		final SpimDataMinimal spimData = Imaris.openIms( imsFilename );
		new XmlIoSpimDataMinimal().save( spimData, xmlFilename );
	}

	public static void main( String[] args ) throws IOException, SpimDataException
	{
		System.setProperty( "apple.laf.useScreenMenuBar", "true" );

		final String imsFilename = "/Users/pietzsch/Desktop/OvernightClaritySmall.ims";
		final String xmlFilename = "/Users/pietzsch/Desktop/OvernightClaritySmall.xml";

//		final String imsFilename = "/Users/pietzsch/Imaris Demo Images/DrosophilaEggChamber_with_objects.ims";
//		final String xmlFilename = "/Users/pietzsch/Imaris Demo Images/DrosophilaEggChamber_with_objects.xml";

		// write xml file for ims
		createXmlForIms( imsFilename, xmlFilename );

		// open xml file in BigDataViewer
		BigDataViewer.open( xmlFilename, "BigDataViewer", new ProgressWriterConsole(), ViewerOptions.options() );
	}
}

Add example of creating a XML file corresponding to a .ims file


package com.daksh.tmdbsample.data.model;

import org.junit.Test;

import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;

/**
 * Created by daksh on 12-Sep-16.
 */
public class MovieTest {

    @Test
    public void testGetFormattedUserRating() throws Exception {
        assertEquals("10".concat(Movie.USER_RATING_APPEND),
                Movie.getFormattedUserRating(9.999999));

        assertNotEquals("1".concat(Movie.USER_RATING_APPEND),
                Movie.getFormattedUserRating(0.99));

        assertEquals("1".concat(Movie.USER_RATING_APPEND),
                Movie.getFormattedUserRating(0.999));

        assertEquals("9.45".concat(Movie.USER_RATING_APPEND),
                Movie.getFormattedUserRating(9.450001));

        assertEquals("0".concat(Movie.USER_RATING_APPEND),
                Movie.getFormattedUserRating(0.0000000001));

        assertEquals("8.46".concat(Movie.USER_RATING_APPEND),
                Movie.getFormattedUserRating(8.455));
    }
}

Add Unit Test for Movie.getFormattedUserRating() function


package leetcode.next_permutation;

import java.util.Arrays;

public class Solution {
    public void nextPermutation(int[] num) {
    	if(num == null || num.length == 0) return;
    	int idx;
    	for(idx = num.length - 2; idx >= 0 && num[idx + 1] <= num[idx]; idx--);
    	if(idx < 0){
    		Arrays.sort(num);
    	}else{
    		int nextIdx = idx + 1;
    		for(int i = idx + 1; i < num.length && num[i] > num[idx]; i++){
    			nextIdx = i;
    		}
    		int tmp = num[idx];
    		num[idx] = num[nextIdx];
    		num[nextIdx] = tmp;
    		for(int i = 0; i < (num.length - (idx + 1)) / 2; i++){
    			tmp = num[idx + 1 + i];
    			num[idx + 1 + i] = num[num.length - 1 - i];
    			num[num.length - 1 - i] = tmp;
    		}
    	}
    }

    public static void main(String[] args){
    	int[] ary = new int[]{};
    	for(int i = 0; i < 120; i++){
    		new Solution().nextPermutation(ary);
    		for(int j = 0; j < ary.length; j++){
    			System.err.print(ary[j] + ", ");
    		}
    		System.err.println("");
    	}
    }
}

Add java solution for 31. Next Permutation


package hudson.slaves;

import static org.junit.Assert.fail;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;

public class NodeParallelTest {

    @Rule
    public JenkinsRule r = new JenkinsRule();

    private static final Logger LOGGER = Logger.getLogger(NodeParallelTest.class.getName());

    private final AtomicInteger count = new AtomicInteger();

    @Test
    @Issue("JENKINS-53401")
    public void createNodesWithParallelThreads() throws InterruptedException, ExecutionException {
        int n = 50;
        List<Callable<Void>> tasks = Collections.nCopies(n, () -> {
            try {
                int i = count.incrementAndGet();
                LOGGER.log(Level.INFO, "Creating slave " + i);
                // JenkinsRule sync on Jenkins singleton, so this doesn't work
                // r.createSlave();
                DumbSlave agent = new DumbSlave("agent-"+i, "/tmp", new JNLPLauncher(true));
                r.jenkins.addNode(agent);
                agent.setNodeProperties(Collections.singletonList(new EnvironmentVariablesNodeProperty(new EnvironmentVariablesNodeProperty.Entry("foo", "" + i))));
                return null;
            } catch (Exception e1) {
                throw new RuntimeException(e1);
            }
        });
        ExecutorService executorService = Executors.newFixedThreadPool(n);
        List<Future<Void>> futures = executorService.invokeAll(tasks);
        List<Void> resultList = new ArrayList<>(futures.size());
        // Check for exceptions
        try {
            for (Future<Void> future : futures) {
                // Throws an exception if an exception was thrown by the task.
                resultList.add(future.get());
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            fail(e.getMessage());
        }
    }
}

Add a test failing without the patch


package com.averi.worldscribe.views;

import android.content.Context;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;

import java.lang.reflect.Field;

/**
 * A Marquee-able Android Toolbar.
 *
 *

 *     Credit to InsanityOnABun. The Gist for this class can be found
 *     here.
 *

 */
public class MarqueeToolbar extends Toolbar {

    TextView title;

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

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

    public MarqueeToolbar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setTitle(CharSequence title) {
        if (!reflected) {
            reflected = reflectTitle();
        }
        super.setTitle(title);
        selectTitle();
    }

    @Override
    public void setTitle(int resId) {
        if (!reflected) {
            reflected = reflectTitle();
        }
        super.setTitle(resId);
        selectTitle();
    }

    boolean reflected = false;
    private boolean reflectTitle() {
        try {
            Field field = Toolbar.class.getDeclaredField("mTitleTextView");
            field.setAccessible(true);
            title = (TextView) field.get(this);
            title.setEllipsize(TextUtils.TruncateAt.MARQUEE);
            title.setMarqueeRepeatLimit(-1);
            return true;
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            return false;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return false;
        } catch (NullPointerException e) {
            e.printStackTrace();
            return false;
        }
    }

    public void selectTitle() {
        if (title != null)
            title.setSelected(true);
    }
}

Add custom view class for Marquee-able Toolbar


package techreborn.compat.ic2;

import ic2.api.item.IC2Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import reborncore.common.util.CraftingHelper;
import techreborn.compat.ICompatModule;
import techreborn.init.ModBlocks;

/**
 * Created by Mark on 06/06/2016.
 */
public class RecipesIC2 implements ICompatModule {
    @Override
    public void preInit(FMLPreInitializationEvent event) {

    }

    @Override
    public void init(FMLInitializationEvent event) {
        CraftingHelper.addShapelessRecipe(new ItemStack(ModBlocks.machineframe, 0, 1), IC2Items.getItem("resource","machine"));
        CraftingHelper.addShapelessRecipe( IC2Items.getItem("resource","machine"), new ItemStack(ModBlocks.machineframe, 0, 1));
    }

    @Override
    public void postInit(FMLPostInitializationEvent event) {

    }

    @Override
    public void serverStarting(FMLServerStartingEvent event) {

    }
}

package techreborn.compat.ic2;

import ic2.api.item.IC2Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import reborncore.common.util.CraftingHelper;
import techreborn.compat.ICompatModule;
import techreborn.init.ModBlocks;

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

/**
 * Created by Mark on 06/06/2016.
 */
public class RecipesIC2 implements ICompatModule {

    List<RecipeDuplicate> recipeDuplicateList = new ArrayList<>();

    @Override
    public void preInit(FMLPreInitializationEvent event) {

    }

    @Override
    public void init(FMLInitializationEvent event) {
        recipeDuplicateList.add(new RecipeDuplicate(new ItemStack(ModBlocks.machineframe, 0, 1), IC2Items.getItem("resource","machine")));

        for(RecipeDuplicate duplicate : recipeDuplicateList){
            duplicate.add();
        }
    }

    @Override
    public void postInit(FMLPostInitializationEvent event) {

    }

    @Override
    public void serverStarting(FMLServerStartingEvent event) {

    }

    public class RecipeDuplicate {

        ItemStack stack1;

        ItemStack stack2;

        public RecipeDuplicate(ItemStack stack1, ItemStack stack2) {
            this.stack1 = stack1;
            this.stack2 = stack2;
        }

        public void add(){

            CraftingHelper.addShapelessRecipe(stack2, stack1);
            CraftingHelper.addShapelessRecipe(stack1, stack2);

        }

    }

}

Clean up ic2 recipes a little


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

/**
 * @author Volker Berlin
 */
public enum ScriptEngine {
    NodeJS,
    SpiderMonkey,
}

Add a list of script engines


package leetcode.contains_duplicate_ii;

import java.util.HashSet;
import java.util.Set;

public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Set<Integer> window = new HashSet<Integer>(k);
        for(int i = 0; i < k && i < nums.length; i++){
            if(window.contains(nums[i])){
                return true;
            }else{
                window.add(nums[i]);
            }
        }
        for(int i = k; i < nums.length; i++){
            if(window.contains(nums[i])){
                return true;
            }else{
                window.add(nums[i]);
                window.remove(nums[i - k]);
            }
        }
        return false;
    }
}

Add java solution for 219. Contains Duplicate II


package leetcode.factorial_trailing_zeroes;

public class Solution {
    public int trailingZeroes(int n) {
        int ret = 0;
        while(n > 0){
        	ret += n / 5;
        	n /= 5;
        }
        return ret;
    }
    public static void main(String[] args){
    	System.err.println(new Solution().trailingZeroes(100));
    }
}

Add java solution for 172. Factorial Trailing Zeroes


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

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

import org.junit.Test;

import jp.ac.shibaura_it.se.tslab.aaextractor.predicate.SVMScaleFile;

public class RLSSVMScaleFileTest {

	@Test
	public void 正しいAttrIndexMinMaxLineに真を返す() {
		SVMScaleFile scaleFile = new SVMScaleFile();
		String line = "1 -2 3.1";
		boolean actual = scaleFile.isValidAttrIndexMinMaxLine(line);
		boolean expected = true;

		assertThat(actual, is(expected));
	}

	@Test
	public void 正しいAttrIndexMinMaxLineの最小値を認識する() {
		SVMScaleFile scaleFile = new SVMScaleFile();
		String line = "1 -2 3.1";
		scaleFile.isValidAttrIndexMinMaxLine(line);
		double actual = scaleFile.minAttr.get(1);
		double expected = -2;

		assertThat(actual, is(expected));
	}

	@Test
	public void 正しいAttrIndexMinMaxLineの最大値を認識する() {
		SVMScaleFile scaleFile = new SVMScaleFile();
		String line = "1 -2 3.1";
		scaleFile.isValidAttrIndexMinMaxLine(line);
		double actual = scaleFile.maxAttr.get(1);
		double expected = 3.1;

		assertThat(actual, is(expected));
	}

	@Test
	public void 正しくないAttrIndexMinMaxLineに偽を返す() {
		SVMScaleFile scaleFile = new SVMScaleFile();
		String line = "1 2.3";
		boolean actual = scaleFile.isValidAttrIndexMinMaxLine(line);
		boolean expected = false;

		assertThat(actual, is(expected));
	}
}

Add a test for scalers


package controllers;

import org.junit.*;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

import com.gargoylesoftware.htmlunit.BrowserVersion;

import play.test.*;
import play.libs.F.*;
import static play.test.Helpers.*;
import static org.fest.assertions.Assertions.*;

public class ApplicationIntegrationTest {

  @Test
  public void test() {
    running(testServer(3333, fakeApplication(inMemoryDatabase())), new HtmlUnitDriver(BrowserVersion.CHROME), new Callback<TestBrowser>() {
      public void invoke(TestBrowser browser) {
        browser.goTo("http://localhost:3333");
        assertThat(browser.pageSource()).contains("CDEX");
      }
    });
  }

}

Add a passing integration test


package sfBugs;

import edu.umd.cs.findbugs.annotations.NonNull;

public class Bug1924512 {
    @NonNull
    public static String nonNullLoop(String[] args) {
        String ret = null;
        for (String s : args) {
            ret = s;
        }
        return ret; // no warning reported here
    }

    @NonNull
    public static String nonNullIf(String[] args) {
        String ret = null;
    	if(args.length > 0) {
    		ret = args[0];
    	}
    	return ret; // warning correctly reported here
    }
}

Test case for [ 1924512 ] Null check fooled by zero-iteration loop


package leetcode.generate_parentheses;

import java.util.ArrayList;

public class Solution {
	public static void dfs(int n, int depth, int stack, StringBuilder sb, ArrayList<String> ary){
		if(depth == 2 * n){
			ary.add(sb.toString());
		}else{
			if(stack > 0){
				sb.append(')');
				dfs(n, depth + 1, stack - 1, sb, ary);
				sb.setLength(sb.length() - 1);
			}
			if(depth + stack < n * 2){
				sb.append('(');
				dfs(n, depth + 1, stack + 1, sb, ary);
				sb.setLength(sb.length() - 1);
			}
		}
	}

    public ArrayList<String> generateParenthesis(int n) {
    	ArrayList<String> ary = new ArrayList<String>();
        dfs(n, 0, 0, new StringBuilder(), ary);
        return ary;
    }

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

Add java solution for 22. Generate Parentheses


package com.vrg.rapid;

import com.google.common.collect.ImmutableList;
import com.vrg.rapid.pb.Endpoint;
import com.vrg.rapid.pb.Phase1bMessage;
import com.vrg.rapid.pb.Rank;
import org.junit.Test;

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

import static junit.framework.Assert.assertTrue;

/**
 * Tests for loggable wrapper around protobuf objects
 */
public class LoggableTests {
    @Test
    public void testToString() throws IOException, InterruptedException {
        final String logString = ("" + Utils.loggable(getMessage()));
        assertTrue(!logString.contains("\n"));
    }

    @Test
    public void testCollectionToString() throws IOException, InterruptedException {
        final List<Phase1bMessage> messages = ImmutableList.of(getMessage(), getMessage());
        final String logString = ("" + Utils.loggable(messages));
        assertTrue(!logString.contains("\n"));
    }

    private Phase1bMessage getMessage() {
        final Rank rank = Rank.newBuilder().setRound(1).setNodeIndex(2).build();
        final List<Endpoint> endpoints =
                ImmutableList.of(Endpoint.newBuilder().setHostname("127.0.0.1").setPort(50).build(),
                        Endpoint.newBuilder().setHostname("127.0.0.2").setPort(51).build());
        return Phase1bMessage.newBuilder()
                .setRnd(rank)
                .addAllVval(endpoints)
                .build();
    }
}

Test case for logging utilities


package com.tutorialspoint.documentation;

/**
 * The HelloWorld program implements an application that simply displays "Hello World!" to the
 * standard output.
 *
 * @author Peter
 * @version 1.0
 * @since 2015-07-18
 */
public class HelloWorld {
  public static void main(String[] args) {
    // Prints Hello, World! on standard output.
    System.out.println("Hello World!");
  }
}

Add example about the usage of @author, @version and @since tags.


package org.dynmap.common;

public enum DynmapChatColor {
    BLACK(0x0),
    DARK_BLUE(0x1),
    DARK_GREEN(0x2),
    DARK_AQUA(0x3),
    DARK_RED(0x4),
    DARK_PURPLE(0x5),
    GOLD(0x6),
    GRAY(0x7),
    DARK_GRAY(0x8),
    BLUE(0x9),
    GREEN(0xA),
    AQUA(0xB),
    RED(0xC),
    LIGHT_PURPLE(0xD),
    YELLOW(0xE),
    WHITE(0xF);

    private final String str;

    private DynmapChatColor(final int code) {
        this.str = String.format("\u00A7%x", code);
    }
    @Override
    public String toString() {
        return str;
    }
    public static String stripColor(final String input) {
        if (input == null) {
            return null;
        }
        return input.replaceAll("(?i)\u00A7[0-9A-F]", "");
    }
}

package org.dynmap.common;

public enum DynmapChatColor {
    BLACK(0x0),
    DARK_BLUE(0x1),
    DARK_GREEN(0x2),
    DARK_AQUA(0x3),
    DARK_RED(0x4),
    DARK_PURPLE(0x5),
    GOLD(0x6),
    GRAY(0x7),
    DARK_GRAY(0x8),
    BLUE(0x9),
    GREEN(0xA),
    AQUA(0xB),
    RED(0xC),
    LIGHT_PURPLE(0xD),
    YELLOW(0xE),
    WHITE(0xF);

    private final String str;

    private DynmapChatColor(final int code) {
        this.str = String.format("\u00A7%x", code);
    }
    @Override
    public String toString() {
        return str;
    }
    public static String stripColor(final String input) {
        if (input == null) {
            return null;
        }
        return input.replaceAll("(?i)\u00A7[0-9A-Za-z]", "");
    }
}

Fix chat color stripping - deal with non-color escapes


/*
 * Copyright 2015 MovingBlocks
 *
 * 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.
 */

@API package org.terasology.logic.spawner;

import org.terasology.module.sandbox.API;

Allow modules to customize spawning logic.