/*
 * Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
 *
 * 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.hazelcast.jet;

import com.hazelcast.jet.core.JetTestSupport;
import com.hazelcast.jet.pipeline.Pipeline;
import com.hazelcast.jet.pipeline.Sinks;
import com.hazelcast.jet.pipeline.test.TestSources;
import com.hazelcast.jet.test.SerialTest;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import static org.junit.Assert.assertEquals;

@Category(SerialTest.class)
public class JetBootstrappedStandaloneTest extends JetTestSupport {

    private static JetInstance bootstrappedInstance;

    @BeforeClass
    public static void initializeBootstrappedInstance() {
        bootstrappedInstance = Jet.bootstrappedInstance();
    }

    @AfterClass
    public static void shutdownBootstrappedInstance() {
        if (bootstrappedInstance != null) {
            bootstrappedInstance.shutdown();
        }
    }

    @Test
    public void bootstrappedInstanceIsStartedAsStandalone() {
        // start different cluster
        createJetMember();

        int size = bootstrappedInstance.getHazelcastInstance().getCluster().getMembers().size();
        assertEquals(1, size);
    }

    @Test
    public void bootstrappedInstanceCanExecuteJob() {
        Pipeline p = Pipeline.create();
        p.readFrom(TestSources.items(0, 1, 2, 3, 4))
                .writeTo(Sinks.list("sinkList"));

        bootstrappedInstance.newJob(p).join();

        List<Integer> sinkList = bootstrappedInstance.getList("sinkList");
        assertEquals(5, sinkList.size());
    }

    @Test
    public void moreBootstrappedInstanceCallReturnsTheSameInstance() {
        JetInstance bootstrappedInstance2 = Jet.bootstrappedInstance();
        assertEquals(bootstrappedInstance, bootstrappedInstance2);
    }
}

Add smoke test for standalone bootstrappedInstance


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

import com.facebook.presto.metadata.MetadataManager;
import com.facebook.presto.metadata.Signature;
import com.facebook.presto.operator.Page;
import com.facebook.presto.operator.RowPageBuilder;
import com.facebook.presto.operator.aggregation.Accumulator;
import com.facebook.presto.operator.aggregation.AggregationFunction;
import com.facebook.presto.spi.block.Block;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import org.testng.annotations.Test;

import java.util.List;

import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static com.facebook.presto.spi.type.VarcharType.VARCHAR;
import static org.testng.Assert.assertEquals;

public class TestEvaluateClassifierPredictions
{
    @Test
    public void testEvaluateClassifierPredictions()
            throws Exception
    {
        MetadataManager metadata = new MetadataManager();
        metadata.addFunctions(new MLFunctionFactory().listFunctions());
        AggregationFunction aggregation = metadata.getExactFunction(new Signature("evaluate_classifier_predictions", VARCHAR, BIGINT, BIGINT)).getAggregationFunction();
        Accumulator accumulator = aggregation.createAggregation(Optional.<Integer>absent(), Optional.<Integer>absent(), 1.0, 0, 1);
        accumulator.addInput(getPage());
        Block block = accumulator.evaluateFinal();

        String output = block.getSlice(0).toStringUtf8();
        List<String> parts = ImmutableList.copyOf(Splitter.on('\n').split(output));
        assertEquals(parts.size(), 3);
        assertEquals(parts.get(0), "Accuracy: 1/2 (50.00%)");
        assertEquals(parts.get(1), "Precision: 1/1 (100.00%)");
        assertEquals(parts.get(2), "Recall: 1/2 (50.00%)");
    }

    private static Page getPage()
            throws JsonProcessingException
    {
        return RowPageBuilder.rowPageBuilder(BIGINT, BIGINT)
                .row(1, 1)
                .row(1, 0)
                .build();
    }
}

Add unit test for evaluate_classifier_predictions


/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Yegor Bugayenko
 *
 * 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 NON-INFRINGEMENT. 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 org.cactoos.func;

import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;

/**
 * Test case for {@link True}.
 *
 * @author Vseslav Sekorin (vssekorin@gmail.com)
 * @version $Id$
 * @since 0.5
 * @checkstyle JavadocMethodCheck (500 lines)
 */
public final class TrueTest {

    @Test
    public void asValue() throws Exception {
        MatcherAssert.assertThat(
            new True().asValue(),
            Matchers.equalTo(true)
        );
    }
}

Add test case for True


/**
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
package com.codeup.console;

import com.codeup.validation.Validator;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.io.ByteArrayInputStream;
import java.io.PrintStream;
import java.util.Scanner;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class ConsoleTest {
    @Test
    public void it_accepts_a_valid_text() {
        when(validator.isValid(text)).thenReturn(true);
        console = new Console(getInput(text), output);

        assertThat(console.promptForText(message, validator), is(text));
    }

    @Test
    public void it_prompts_a_second_time_if_invalid_text_is_given() {
        when(validator.isValid(invalidText)).thenReturn(false);
        when(validator.isValid(text)).thenReturn(true);
        console = new Console(
            getInput(String.format("%s\n%s", invalidText, text)),
            output
        );

        assertThat(console.promptForText(message, validator), is(text));
        verify(validator).errorMessage();
    }

    private Scanner getInput(String text) {
        return new Scanner(new ByteArrayInputStream(text.getBytes()))
            .useDelimiter("\n")
        ;
    }

    private Console console;
    private String message = "Message";
    private String invalidText = "invalid";
    private String text = "text";

    @Mock
    private PrintStream output;

    @Mock
    private Validator validator;
}

Create first tests for Console class.


package io.github.aquerr.eaglefactions;

public abstract class PluginPermissions
{
    public static final String AllPermissions = "eaglefactions";
    public static final String AllCommands = "eaglefactions.command";

    public static final String AllyCommands = "eaglefactions.command.ally";
    public static final String AddAllyCommand = "eaglefactions.command.ally.add";
    public static final String RemoveAllyCommand = "eaglefactions.command.ally.remove";

    public static final String EnemyCommands = "eaglefactions.command.enemy";
    public static final String AddEnemyCommand = "eaglefactions.command.enemy.add";
    public static final String RemoveEnemyCommand = "eaglefactions.command.enemy.remove";

    public static final String CreateCommand = "eaglefactions.command.create";
    public static final String DisbandCommand = "eaglefactions.command.disband";
    public static final String InviteCommand = "eaglefactions.command.invite";
    public static final String JoinCommand = "eaglefactions.command.join";
    public static final String LeaveCommand = "eaglefactions.command.leave";
    public static final String ListCommand = "eaglefactions.command.list";
    public static final String KickCommand = "eaglefactions.command.kick";
    public static final String FriendlyFireCommand = "eaglefactions.command.friendlyfire";

    public static final String HelpCommand = "eaglefactions.command.help";
    public static final String PlayerCommand = "eaglefactions.command.player";
    public static final String InfoCommand = "eaglefactions.command.info";
    public static final String VersionCommand = "eaglefactions.command.version";

    public static final String ClaimCommand = "eaglefactions.command.claim";
    public static final String AutoClaimCommand = "eaglefactions.command.autoclaim";
    public static final String UnclaimCommand = "eaglefactions.command.unclaim";
    public static final String UnclaimAllCommand = "eaglefactions.command.unclaimall";

    public static final String OfficerCommand = "eaglefactions.command.officer";
    public static final String SetHomeCommand = "eaglefactions.command.sethome";
    public static final String HomeCommand = "eaglefactions.command.home";

    public static final String MapCommand = "eaglefactions.command.map";
    public static final String AutoMapCommand = "eaglefactions.command.automap";

    public static final String AdminCommand = "eaglefactions.command.admin";

    public static final String SetPowerCommand = "eaglefactions.command.setpower";
    public static final String MaxPowerCommand = "eaglefactions.command.maxpower";
}

Add file that contains all plugin permissions


package org.squiddev.plethora.integration;

import com.google.common.collect.Sets;
import dan200.computercraft.api.lua.LuaException;
import net.minecraft.util.ResourceLocation;
import org.squiddev.plethora.api.method.BasicObjectMethod;
import org.squiddev.plethora.api.method.IContext;
import org.squiddev.plethora.api.method.IUnbakedContext;
import org.squiddev.plethora.api.module.IModuleContainer;
import org.squiddev.plethora.api.reference.Reference;

import javax.annotation.Nonnull;
import java.util.Set;

import static org.squiddev.plethora.api.method.ArgumentHelper.getString;

public class MethodsModules {
	@BasicObjectMethod.Inject(
		value = IModuleContainer.class, worldThread = true,
		doc = "function():table -- Lists all modules available"
	)
	public static Object[] listModules(@Nonnull IContext<IModuleContainer> context, @Nonnull Object[] args) throws LuaException {
		return new Object[]{context.getModules().toArray()};
	}

	@BasicObjectMethod.Inject(
		value = IModuleContainer.class, worldThread = true,
		doc = "function():boolean -- Checks whether a module is available"
	)
	public static Object[] hasModules(@Nonnull IContext<IModuleContainer> context, @Nonnull Object[] args) throws LuaException {
		ResourceLocation module = new ResourceLocation(getString(args, 0));
		return new Object[]{context.hasModule(module)};
	}

	/*@BasicObjectMethod.Inject(
		value = IModuleContainer.class, worldThread = true,
		doc = "function(names:string...):table -- Gets the methods which require these modules"
	)*/
	public static Object[] filterModules(@Nonnull IContext<IModuleContainer> context, @Nonnull Object[] args) throws LuaException {
		final ResourceLocation[] modules = new ResourceLocation[args.length];
		for (int i = 0; i < args.length; i++) {
			modules[i] = new ResourceLocation(getString(args, i));
		}

		final IModuleContainer container = context.getTarget();
		IModuleContainer filteredContainer = new IModuleContainer() {
			@Nonnull
			@Override
			public Set<ResourceLocation> get() throws LuaException {
				Set<ResourceLocation> existing = container.get();
				Set<ResourceLocation> out = Sets.newHashSetWithExpectedSize(modules.length);
				for (ResourceLocation module : modules) {
					if (existing.contains(module)) out.add(module);
				}
				return out;
			}
		};

		// FIXME: This doesn't actually work, we need to pass it to the primary module reference too.
		IUnbakedContext<IModuleContainer> selected = context.makeChild(Reference.id(filteredContainer));

		return new Object[]{selected.getObject()};
	}
}

Add some basic methods to list modules


package com.github.fge.grappa.examples.recursiveparens;

import com.github.parboiled1.grappa.parsers.EventBusParser;
import org.parboiled.Parboiled;
import org.parboiled.Rule;
import org.parboiled.parserunners.BasicParseRunner;
import org.parboiled.parserunners.ParseRunner;

public class RecursiveParensParser
    extends EventBusParser<Void>
{
    Rule exprContent()
    {
        return oneOrMore(noneOf("()"));
    }

    Rule expression()
    {
        return sequence(
            '(',
            exprContent(),
            zeroOrMore(expression()),
            optional(exprContent()),
            ')'
        );
    }

    public static void main(final String... args)
    {
        final RecursiveParensParser parser
            = Parboiled.createParser(RecursiveParensParser.class);
        final ParseRunner<Void> runner =
            new BasicParseRunner<>(parser.expression());
        System.out.println(runner.run("(a(b(c))d)").isSuccess());
    }
}

Add a parser for recursive parens plus contents


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

package com.google.gerrit.acceptance.git;

import com.google.gerrit.acceptance.AbstractDaemonTest;
import org.eclipse.jgit.api.errors.TransportException;
import org.eclipse.jgit.junit.TestRepository;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.transport.RefSpec;
import org.junit.Test;

public class GitmodulesIT extends AbstractDaemonTest {
  @Test
  public void invalidSubmoduleURLIsRejected() throws Exception {
    pushGitmodules("name", "-invalid-url", "path", "Invalid submodule URL");
  }

  @Test
  public void invalidSubmodulePathIsRejected() throws Exception {
    pushGitmodules("name", "http://somewhere", "-invalid-path", "Invalid submodule path");
  }

  @Test
  public void invalidSubmoduleNameIsRejected() throws Exception {
    pushGitmodules("-invalid-name", "http://somewhere", "path", "Invalid submodule name");
  }

  private void pushGitmodules(String name, String url, String path, String expectedErrorMessage)
      throws Exception {
    Config config = new Config();
    config.setString("submodule", name, "url", url);
    config.setString("submodule", name, "path", path);
    TestRepository<?> repo = cloneProject(project);
    repo.branch("HEAD")
        .commit()
        .insertChangeId()
        .message("subject: adding new subscription")
        .add(".gitmodules", config.toText().toString())
        .create();

    exception.expectMessage(expectedErrorMessage);
    exception.expect(TransportException.class);
    repo.git().push().setRemote("origin").setRefSpecs(new RefSpec("HEAD:refs/for/master")).call();
  }
}

Add tests for .gitmodules validation


package de.philipphager.disclosure.database.version.mapper;

import android.content.pm.PackageInfo;
import de.philipphager.disclosure.database.version.model.Version;
import de.philipphager.disclosure.util.Mapper;
import org.threeten.bp.LocalDateTime;

public class ToVersionMapper implements Mapper<PackageInfo, Version> {
  private final long appId;

  public ToVersionMapper(long appId) {
    this.appId = appId;
  }

  @Override public Version map(PackageInfo from) {
    return Version.create(appId, from.versionCode, from.versionName, LocalDateTime.now());
  }
}

Add mapper for Version model


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

import java.util.List;

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

/**
 *
 * @author Julian Mendez
 *
 */
public class ExampleLoaderTest {

	@Test
	public void testGetExampleConfigurations() {
		ExampleLoader loader = new ExampleLoader();
		List<ExampleConfiguration> list = loader.getExampleConfigurations();
		Assert.assertEquals(2, list.size());

		{
			ExampleConfiguration conf0 = list.get(0);
			Assert.assertEquals("example-0", conf0.getOntologyName());
			Assert.assertTrue(conf0.getOntologyFileName().endsWith("/examples/example-0.owl"));
			Assert.assertEquals(
					"query(sub('http://lat.inf.tu-dresden.de/systems/born/born-example#a', 'http://lat.inf.tu-dresden.de/systems/born/born-example#e')).\n\n",
					conf0.getQuery());
		}

		{
			ExampleConfiguration conf1 = list.get(1);
			Assert.assertEquals("example-1", conf1.getOntologyName());
			Assert.assertTrue(conf1.getOntologyFileName().endsWith("/examples/example-1.owl"));
			Assert.assertEquals(
					"query(sub('http://lat.inf.tu-dresden.de/systems/born/born-example#a', 'http://lat.inf.tu-dresden.de/systems/born/born-example#e')).\n\n",
					conf1.getQuery());
		}

	}

}

Create test for example loader


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

package org.eclipse.birt.report.tests.model.regression;

import java.util.List;

import org.eclipse.birt.report.model.api.DesignFileException;
import org.eclipse.birt.report.model.api.ScriptDataSetHandle;
import org.eclipse.birt.report.tests.model.BaseTestCase;

/**
 * Regression description:
 *

 * BIRT 2.0 Scripted Data Set converted incorrectly in 2.1
 *

 * First attachment in this file is a report design created in 2.0.1, which
 * defines a Scripted Data Set. Open the design in 2.1RC5, the BIRT designer
 * converts the design to 2.1 format. (Attachment 2 [edit] is the converted
 * design file). However visual inspection of the XML source reveals that the
 * data set definition contains both a "resultSet" structure and an identical
 * "resultSetHints" structure. The "resultSet" structure here is wrong - it
 * should have been removed during the conversion.
 *

 * As it stands the extranueous "resultSet" does not stop the data set from
 * working so this is not a critical issue. But it should be removed.
 *

 * Test description:
 *

 * Open the 2.1 report, make sure that the resultSet list property is removed
 * after convertion.
 *

 */
public class Regression_148548 extends BaseTestCase
{

	private final static String REPORT = "ScriptTest2.0.1.rptdesign"; //$NON-NLS-1$

	/**
	 * @throws DesignFileException
	 */

	public void test_regression_148548( ) throws DesignFileException
	{
		openDesign( REPORT );
		ScriptDataSetHandle ds = (ScriptDataSetHandle) designHandle
				.findDataSet( "Data Set" ); //$NON-NLS-1$
		List resultSets = ds
				.getListProperty( ScriptDataSetHandle.RESULT_SET_PROP );

		assertNull( resultSets );
	}
}

Add one regression test case


package seedu.address.model;

import static org.junit.Assert.*;

import org.junit.Test;

import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.model.person.Person;
import seedu.address.testutil.PersonBuilder;
import seedu.address.testutil.TestPerson;

/**
 * Test classes for Person
 */
public class PersonTest {
    @Test
    public void person_hashCodeShouldMatch_returnTrue() {
        TestPerson pb;
        try {
            pb = (new PersonBuilder()).withAddress("Singapore").withLabels("testLabel").withName("Name").withPhone("12345678").withEmail("email@email.com").build();
            Person p = new Person(pb);
            int hashcode = 1027801006;
            assert(p.hashCode() == hashcode);
        } catch (IllegalValueException e) {
            e.printStackTrace();
            fail("Person fail Illegal value");
        }

    }
}

Add Testcase for Person's hashcode


package io.quarkus.smallrye.graphql.deployment;

import static io.restassured.RestAssured.get;
import static org.hamcrest.Matchers.containsString;

import javax.validation.Valid;
import javax.validation.constraints.Size;

import org.eclipse.microprofile.graphql.GraphQLApi;
import org.eclipse.microprofile.graphql.Query;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.test.QuarkusUnitTest;

/**
 * Basic test to verify that bean validation constraints on input fields are transformed into GraphQL directives when
 * the option to include directives in the schema is enabled.
 */
public class BeanValidationGraphQLDirectivesTest extends AbstractGraphQLTest {

    @RegisterExtension
    static QuarkusUnitTest test = new QuarkusUnitTest()
            .withApplicationRoot((jar) -> jar
                    .addClasses(Person.class)
                    .addAsResource(new StringAsset("quarkus.smallrye-graphql.schema-include-directives=true"),
                            "application.properties")
                    .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"));

    @Test
    public void validateDirectivesPresentInSchema() {
        get("/graphql/schema.graphql")
                .then()
                .body(containsString("input PersonInput {\n" +
                        "  name: String @constraint(maxLength : 20, minLength : 5)\n" +
                        "}\n"))
                .body(containsString(
                        "queryWithConstrainedArgument(constrained: String @constraint(maxLength : 123)): String"));
    }

    @GraphQLApi
    public static class ValidationApi {

        @Query
        public String query(@Valid Person person) {
            return null;
        }

        @Query
        public String queryWithConstrainedArgument(@Size(max = 123) String constrained) {
            return null;
        }

    }

    public static class Person {

        @Size(min = 5, max = 20)
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

}

Test for bean validation directives


package swing;

import java.awt.BorderLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JSplitPane;

public class TestJSplitPane {
  private void init() {
    JFrame frame = new JFrame();
    frame.setLayout(new BorderLayout());
    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    splitPane.setRightComponent(new JButton("Here I Am"));
    splitPane.setLeftComponent(new JButton("Me Too"));
    splitPane.setResizeWeight(0.8);
    frame.add(splitPane, BorderLayout.CENTER);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }

  public static void main(String[] args) {
    new TestJSplitPane().init();
  }
}

Add example about usage of the JSplitPane used by buttons.


package edu.java.cosc111.samples;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;

/**
 *
 * @author russel
 */
public class PathTest {

    private static final Scanner cin = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        manageFile();
    }

    private static void getFileInformationFromPath(Path p) throws IOException{

        System.out.println("\n---------------File Information------------------");
        System.out.printf("Is absolute path? %s%n",p.isAbsolute());
        System.out.printf("Absolute Path: %s%n",p.toAbsolutePath());
        System.out.printf("Filename: %s%n",p.getFileName());
        System.out.printf("Parent: %s%n",p.getParent());

        System.out.printf("Kind: %s%n",Files.isDirectory(p)?"Directory":"File");
        System.out.printf("Size (in bytes): %d%n",Files.size(p));

        System.out.printf("Existing: %b%n",Files.exists(p));
        System.out.printf("Readable: %b%n",Files.isReadable(p));
        System.out.printf("Writable: %b%n",Files.isWritable(p));
        System.out.printf("Executable: %b%n",Files.isExecutable(p));
        System.out.printf("Hidden: %b%n",Files.isHidden(p));
        System.out.println("-------------------------------------------------\n");
    }

    private static void manageFile() throws IOException{

        while(true){
            System.out.print("Enter file path: ");
            String path = cin.nextLine();
            Path p = Paths.get(path);
            System.out.println("What do you want to do:");
            System.out.println("   [0] Exit");
            System.out.println("   [1] Create File");
            System.out.println("   [2] Create Directory");
            System.out.println("   [3] Delete File/Directory");
            System.out.println("   [4] Get File/Directory Information");
            System.out.print("Choice: ");
            int choice;
            switch((choice = cin.nextInt())){
                case 0:return;
                case 1:
                case 2:
                    if(Files.exists(p)){
                        System.out.printf("%s already exists.%n",p.toAbsolutePath());
                    }else{
                        if(choice == 1){
                            Files.createFile(p);
                        }else{
                            Files.createDirectories(p);
                        }
                        System.out.printf("%s is created successfully.%n",p.toAbsolutePath());
                    }
                    break;
                case 3:
                    if(Files.deleteIfExists(p)){
                        System.out.printf("%s is deleted successfully.%n",p.toAbsolutePath());
                    }else{
                        System.out.printf("%s does not exists.%n",p.toAbsolutePath());
                    }
                    break;
                case 4:
                    getFileInformationFromPath(p);
                default:
                    break;
            }
            cin.nextLine();
            System.out.println();
        }
    }
}

Add sample to test basic Path and Files methods


package com.millross.blog.async;

import org.junit.Test;

import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.atomic.AtomicReference;

/**
 *
 */
public class ExceptionalThenComposeTest extends CompletableFutureTestBase {

    @Test(expected = IntentionalException.class)
    public void exceptionCallingThenApplyAsSeenFromNextStage() throws Throwable {
        final AtomicReference<Throwable> thrownException = new AtomicReference<>(null);
        final CompletableFuture<Object> future = CompletableFuture.supplyAsync(delayedValueSupplier(1), executor)
                .thenCompose(i -> {
                    throw new IntentionalException();
                })
                .whenComplete((v, t) -> {
                    if (t != null) {
                        thrownException.set(t);
                    }
                });
        try {
            future.join();
        } catch (CompletionException ex) {
            throw (Optional.ofNullable(thrownException.get().getCause()).orElse(new RuntimeException("No thrown exception")));
        }
    }

}

Add exception propagation demo for thenCompose


package org.opennms.netmgt.dao;

import java.util.Collection;

import org.hibernate.criterion.Restrictions;
import org.opennms.netmgt.model.OnmsCriteria;
import org.opennms.netmgt.model.OnmsNode;

public class CriteriaTestCase extends AbstractDaoTestCase {

    public void testSimple() {
        OnmsCriteria crit = new OnmsCriteria(OnmsNode.class);
        crit.add(Restrictions.eq("label", "node1"));

        Collection<OnmsNode> matching = getNodeDao().findMatching(crit);

        assertEquals("Expect a single node with label node1", 1, matching.size());

        OnmsNode node = matching.iterator().next();
        assertEquals("node1", node.getLabel());
        assertEquals(3, node.getIpInterfaces().size());
    }

    public void testComplicated() {
        OnmsCriteria crit =
            new OnmsCriteria(OnmsNode.class)
            .createAlias("ipInterfaces", "iface")
            .add(Restrictions.eq("iface.ipAddress", "192.168.2.1"));

        Collection<OnmsNode> matching = getNodeDao().findMatching(crit);

        assertEquals("Expect a single node with an interface 192.168.2.1", 1, matching.size());

        OnmsNode node = matching.iterator().next();
        assertEquals("node2", node.getLabel());
        assertEquals(3, node.getIpInterfaces().size());

    }
}

Test case for new OnmsCriteria


package leetcode101_110;

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

/**Given a singly linked list where elements are sorted in ascending order,
 convert it to a height balanced BST.
 * Created by eugene on 16/1/28.
 */
public class ConvertSortedListToBinarySearchTree {

    //Definition for a binary tree node.
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }

    // Definition for singly-linked list.
    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }

    //获取链表长度后,自底向上(中序顺序)递归建树
    private ListNode node = null;
    public TreeNode sortedListToBST(ListNode head) {
        if (head==null) return null;
        node = head;
        int len = 0;
        while (node!=null){
            len++;
            node = node.next;
        }
        node = head;
        return sortedListToBST(0, len-1);
    }
    private TreeNode sortedListToBST(int l, int r){
        if (l>r) return null;
        int m = (l+r)/2;
        TreeNode left = sortedListToBST(l, m-1);
        TreeNode root = new TreeNode(node.val);
        node = node.next;
        TreeNode right = sortedListToBST(m+1, r);
        root.left = left;
        root.right = right;
        return root;
    }

    //先将链表转为数组,再自顶向下(先根再左右子树)递归建树
    public TreeNode sortedListToBST1(ListNode head) {
        if (head==null) return null;
        ListNode node = head;
        List<Integer> list = new ArrayList<>();
        while (node!=null){
            list.add(node.val);
            node = node.next;
        }
        return sortedArrayToBST(list, 0, list.size()-1);
    }
    private TreeNode sortedArrayToBST(List<Integer> nums, int l, int r){
        if (l>r) return null;
        int m = (l+r)/2;
        TreeNode root = new TreeNode(nums.get(m));
        root.left = sortedArrayToBST(nums, l, m-1);
        root.right = sortedArrayToBST(nums, m+1, r);
        return root;
    }

}

Convert Sorted List to Binary Search Tree


package com.test.graphs;

import com.graphs.DetectCycle;
import com.graphs.GraphAdjacencyListRepresentation;

import junit.framework.TestCase;

public class TestDetectCycle extends TestCase {

    public void testConnectedComponentsInDirectedGraph() {
        GraphAdjacencyListRepresentation graph = new GraphAdjacencyListRepresentation(13, true);

        graph.addEdge(0, 5);
        graph.addEdge(0, 1);

        graph.addEdge(2, 0);
        graph.addEdge(2, 3);

        graph.addEdge(3, 5);
        graph.addEdge(3, 2);

        graph.addEdge(4, 3);
        graph.addEdge(4, 2);

        graph.addEdge(5, 4);

        graph.addEdge(6, 9);
        graph.addEdge(6, 4);
        graph.addEdge(6, 8);
        graph.addEdge(6, 0);

        graph.addEdge(7, 6);
        graph.addEdge(7, 9);

        graph.addEdge(8, 6);

        graph.addEdge(9, 11);
        graph.addEdge(9, 10);

        graph.addEdge(10, 12);

        graph.addEdge(11, 4);
        graph.addEdge(11, 12);

        graph.addEdge(12, 9);

        assertEquals(true, DetectCycle.haveCycle(graph));

        graph = new GraphAdjacencyListRepresentation(13, true);

        graph.addEdge(0, 5);
        graph.addEdge(0, 1);
        graph.addEdge(0, 6);

        graph.addEdge(2, 0);
        graph.addEdge(2, 3);

        graph.addEdge(3, 5);

        graph.addEdge(5, 4);

        graph.addEdge(6, 9);
        graph.addEdge(6, 4);

        graph.addEdge(7, 6);

        graph.addEdge(8, 7);

        graph.addEdge(9, 11);
        graph.addEdge(9, 10);
        graph.addEdge(9, 12);

        graph.addEdge(11, 12);

        assertEquals(false, DetectCycle.haveCycle(graph));

    }

}

Add JUnit test for DetectCycle


/*
 * Copyright 2019, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package io.spine.core;

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

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

/**
 * Filters events delivered to the {@linkplain Subscribe subscriber method} the first
 * parameter of which has this annotation.
 *
 *
For example, the following method would be invoked only if the owner of the created
 * project is {@code mary@ackme.net}:
 *
{@code
 * \@Subscribe
 * void on(@Where(field = "owner.email" equals = "mary@ackme.net") ProjectCreated e) { ... }
 * }

 *
 *
NOTE: This syntax applies only to events. Filtering state subscriptions
 * is not supported.
 */
@Retention(RUNTIME)
@Target(PARAMETER)
@Documented
public @interface Where {

    /**
     * The {@linkplain io.spine.base.FieldPath path to the field} of the event message to filter by.
     */
    String field();

    /**
     * The expected value of the field.
     *
     *
The value converted with help of {@link io.spine.string.Stringifier Stringifier}s into
     * the type of the actual value of the message field.
     */
    String equals();
}

Introduce new argument filter annotation


package org.jetbrains.plugins.javaFX.sceneBuilder;

import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorPolicy;
import com.intellij.openapi.fileEditor.FileEditorProvider;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.javaFX.fxml.JavaFxFileTypeFactory;

/**
 * @author Alexander Lobas
 */
public class SceneBuilderEditorProvider implements FileEditorProvider, DumbAware{
  @Override
  public boolean accept(@NotNull Project project, @NotNull VirtualFile file) {
    return JavaFxFileTypeFactory.FXML_EXTENSION.equalsIgnoreCase(file.getExtension()) &&
           SystemInfo.isJavaVersionAtLeast("1.8") &&
           Registry.is("embed.scene.builder");
  }

  @NotNull
  @Override
  public FileEditor createEditor(@NotNull Project project, @NotNull VirtualFile file) {
    return new SceneBuilderEditor(project, file);
  }

  @NotNull
  @Override
  public String getEditorTypeId() {
    return "JavaFX-Scene-Builder";
  }

  @NotNull
  @Override
  public FileEditorPolicy getPolicy() {
    return FileEditorPolicy.PLACE_AFTER_DEFAULT_EDITOR;
  }
}

package org.jetbrains.plugins.javaFX.sceneBuilder;

import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorPolicy;
import com.intellij.openapi.fileEditor.FileEditorProvider;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.javaFX.fxml.JavaFxFileTypeFactory;

/**
 * @author Alexander Lobas
 */
public class SceneBuilderEditorProvider implements FileEditorProvider, DumbAware{
  static {
    ClassLoader pluginClassLoader = SceneBuilderEditorProvider.class.getClassLoader();
    pluginClassLoader.setPackageAssertionStatus("com.oracle.javafx.scenebuilder.kit", false);
  }

  @Override
  public boolean accept(@NotNull Project project, @NotNull VirtualFile file) {
    return JavaFxFileTypeFactory.FXML_EXTENSION.equalsIgnoreCase(file.getExtension()) &&
           SystemInfo.isJavaVersionAtLeast("1.8") &&
           Registry.is("embed.scene.builder");
  }

  @NotNull
  @Override
  public FileEditor createEditor(@NotNull Project project, @NotNull VirtualFile file) {
    return new SceneBuilderEditor(project, file);
  }

  @NotNull
  @Override
  public String getEditorTypeId() {
    return "JavaFX-Scene-Builder";
  }

  @NotNull
  @Override
  public FileEditorPolicy getPolicy() {
    return FileEditorPolicy.PLACE_AFTER_DEFAULT_EDITOR;
  }
}

Disable assertions in Scene Builder because of false positives (IDEA-162542)


package com.alexstyl.specialdates.events;

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

import static org.fest.assertions.api.Assertions.assertThat;

@RunWith(MockitoJUnitRunner.class)
public class EventTypeTest {

    @Test
    public void mapsTypeBirthdayIdToBirthdayEvent() {
        EventType eventType = EventType.fromId(EventColumns.TYPE_BIRTHDAY);
        assertThat(eventType).isEqualTo(EventType.BIRTHDAY);
    }

    @Test
    public void mapsTypeNamedayIdToNamedayEvent() {
        EventType eventType = EventType.fromId(EventColumns.TYPE_NAMEDAY);
        assertThat(eventType).isEqualTo(EventType.NAMEDAY);
    }

    @Test(expected = IllegalArgumentException.class)
    public void throwExceptionOnInvalidId() {
        EventType.fromId(3);
    }
}

Add test to ensure correct creation of EventType


package net.glowstone.block;

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

import org.junit.jupiter.api.Test;

class MaterialUtilTest {
    @Test
    public void testSanityChecks() {
        assertTrue(MaterialUtil.SLABS.containsAll(MaterialUtil.WOODEN_SLABS));
        assertTrue(MaterialUtil.STAIRS.containsAll(MaterialUtil.WOODEN_STAIRS));
        assertTrue(MaterialUtil.BUTTONS.containsAll(MaterialUtil.WOODEN_BUTTONS));
    }
}

Add sanity checks for reflectively-generated sets in MaterialUtil


package com.stripe.model;

import com.stripe.BaseStripeTest;
import com.stripe.model.Event;

import java.io.IOException;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class EventTest extends BaseStripeTest {
	@Test
	public void nestedObjectDeserializesToModel() throws IOException {
		String json = resource("account_event.json");
		Event event = StripeObject.PRETTY_PRINT_GSON.fromJson(json, Event.class);

		// Thanks to some GSON magic, the object nested within the event can be
		// typecast to its expected type.
		Account account = (com.stripe.model.Account)event.getData().getObject();

		assertEquals(account.getEmail(), "test@stripe.com");
	}
}

Add test to demonstrate event deserialization


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

package org.springframework.session.data.mongo;

import org.junit.Test;

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

/**
 * @author Rob Winch
 */
public class MongoExpiringSessionTests {

	@Test
	public void isExpiredWhenIntervalNegativeThenFalse() {
		MongoExpiringSession session = new MongoExpiringSession();
		session.setMaxInactiveIntervalInSeconds(-1);
		session.setLastAccessedTime(0L);

		assertThat(session.isExpired()).isFalse();
	}
}

Add MongoSession.isExpired interval < 0 Test


package leetcode.invert_binary_tree;

import common.TreeNode;

public class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root != null){
            TreeNode tmp = root.left;
            root.left = root.right;
            root.right = tmp;
            invertTree(root.left);
            invertTree(root.right);
        }
        return root;
    }
}

Add java solution for 226. Invert Binary Tree


package net.vexelon.bgrates.ui;

import java.util.Map;

import com.google.common.collect.Maps;

import net.vexelon.bgrates.R;

public class UIFlags {

	private static final Map<String, Integer> flagsMap = Maps.newHashMap();

	static {
		flagsMap.put("au", R.drawable.au);
		flagsMap.put("bg", R.drawable.bg);
		flagsMap.put("br", R.drawable.br);
		flagsMap.put("ca", R.drawable.ca);
		flagsMap.put("ch", R.drawable.ch);
		flagsMap.put("ca", R.drawable.ca);
		flagsMap.put("cn", R.drawable.cn);
		flagsMap.put("cz", R.drawable.cz);
		flagsMap.put("dk", R.drawable.dk);
		flagsMap.put("ee", R.drawable.ee);
		flagsMap.put("gb", R.drawable.gb);
		flagsMap.put("hk", R.drawable.hk);
		flagsMap.put("hr", R.drawable.hr);
		flagsMap.put("hu", R.drawable.hu);
		flagsMap.put("id", R.drawable.id);
		flagsMap.put("in", R.drawable.in);
		flagsMap.put("is", R.drawable.is);
		flagsMap.put("jp", R.drawable.jp);
		flagsMap.put("kr", R.drawable.kr);
		flagsMap.put("lt", R.drawable.lt);
		flagsMap.put("lv", R.drawable.lv);
		flagsMap.put("mx", R.drawable.mx);
		flagsMap.put("my", R.drawable.my);
		flagsMap.put("no", R.drawable.no);
		flagsMap.put("nz", R.drawable.nz);
		flagsMap.put("ph", R.drawable.ph);
		flagsMap.put("pl", R.drawable.pl);
		flagsMap.put("ro", R.drawable.ro);
		flagsMap.put("ru", R.drawable.ru);
		flagsMap.put("se", R.drawable.se);
		flagsMap.put("sg", R.drawable.sg);
		flagsMap.put("th", R.drawable.th);
		flagsMap.put("tr", R.drawable.tr);
		flagsMap.put("us", R.drawable.us);
		flagsMap.put("xa", R.drawable.xa);
		flagsMap.put("za", R.drawable.za);
		flagsMap.put("eu", R.drawable.eu);
	}

	public static int getResourceFromCode(String code) {
		Integer resId = R.drawable.unknown;
		if (!code.isEmpty()) {
			String lower = code.substring(0, 2).toLowerCase();
			if (flagsMap.containsKey(lower)) {
				resId = flagsMap.get(lower);
			}
		}
		return resId;
	}
}

Add currency flags UI handler


package guitests;

import static org.junit.Assert.assertTrue;

import java.io.File;

import org.junit.Test;

//@@author A0164440M
public class PathCommandTest extends TaskBookGuiTest {

    @Test
    public void saveToCorrectPath() {
        assertCorrectPathResult("path", "a.xml");
        assertCorrectPathResult("path", "a.txt");
    }

    @Test
    public void saveToInvalidPath() {
        assertWrongPathResult("path", "data/C:");

        commandBox.runCommand("path");
        assertResultMessage("Invalid command format! \npath: Change save path. "
                + "Parameters: path [filename] \nExample: path taskbook.xml");
    }

    private void assertCorrectPathResult(String command, String path) {
        commandBox.runCommand(command + " " + path);
        assertTrue(fileExist(path));
        assertResultMessage("Save path has been successfully updated \n");
    }

    private void assertWrongPathResult(String command, String path) {
        commandBox.runCommand(command + " " + path);
        assertTrue(!fileExist(path));
        assertResultMessage("This path is invalid");
    }

    private boolean fileExist(String path) {
        File f = new File(path);
        if (f.exists() && !f.isDirectory()) {
            return true;
        }
        return false;
    }
}

Add test case for path command


package com.consol.citrus.simulator.http;

import java.io.IOException;
import java.nio.charset.Charset;

import com.consol.citrus.http.controller.HttpMessageController;
import org.springframework.http.MediaType;
import org.springframework.mock.http.MockHttpInputMessage;
import org.springframework.mock.http.MockHttpOutputMessage;
import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * @author Christoph Deppisch
 */
public class SimulatorHttpMessageConverterTest {

    private SimulatorHttpMessageConverter converter = new SimulatorHttpMessageConverter();

    @Test
    public void testSimulatorMessageConverter() throws IOException {
        Assert.assertFalse(converter.canRead(Object.class, Object.class, MediaType.ALL));
        Assert.assertFalse(converter.canRead(Object.class, MediaType.ALL));
        Assert.assertFalse(converter.canWrite(Object.class, Object.class, MediaType.ALL));
        Assert.assertFalse(converter.canWrite(Object.class, MediaType.ALL));

        Assert.assertEquals(converter.read(String.class, HttpMessageController.class, new MockHttpInputMessage("Hello".getBytes(Charset.forName("UTF-8")))), "Hello");
    }

    @Test(expectedExceptions = IllegalStateException.class)
    public void testUnsupportedRead() throws IOException {
        converter.read(Object.class, new MockHttpInputMessage("Hello".getBytes(Charset.forName("UTF-8"))));
    }

    @Test(expectedExceptions = IllegalStateException.class)
    public void testUnsupportedWrite() {
        converter.write("Hello", MediaType.TEXT_PLAIN, new MockHttpOutputMessage());
    }

    @Test(expectedExceptions = IllegalStateException.class)
    public void testUnsupportedGenericWrite() {
        converter.write("Hello", String.class, MediaType.TEXT_PLAIN, new MockHttpOutputMessage());
    }

}

Add unit test for new classes


package de.fu_berlin.cdv.chasingpictures.api;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.test.AndroidTestCase;
import android.util.Log;

import org.springframework.http.ResponseEntity;

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

import de.fu_berlin.cdv.chasingpictures.R;

/**
 * @author Simon Kalt
 */
public class PhotoUploadRequestTest extends AndroidTestCase {

    private static final String TAG = "PhotoUploadRequestTest";

    public void setUp() throws Exception {
        super.setUp();
    }

    public void testPhotoUpload() throws Exception {
        // Register user so we have a valid access token
        LoginRequestTest.registerUser(
                getContext(),
                "Tom",
                LoginRequestTest.getUniqueEmail(),
                "12345678"
        );

        Place place = new Place();
        place.setId(6);

        //region Save picture
        Bitmap bitmap = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.upload_image);
        File tempFile = null;
        try {
            tempFile = File.createTempFile("UPLOAD_TEST", ".jpg", getContext().getCacheDir());
            FileOutputStream out = new FileOutputStream(tempFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.close();
        } catch (IOException e) {
            Log.e(TAG, "Image file could not be written.", e);
        }
        //endregion

        PhotoUploadRequest request = new PhotoUploadRequest(getContext(), place, tempFile);
        ResponseEntity<Picture> pictureResponseEntity = request.sendRequest();
        assertNotNull("No response entity received", pictureResponseEntity);
        Picture picture = pictureResponseEntity.getBody();
        assertNotNull("Response entity has empty body", picture);
    }
}

Add test for photo upload


package gov.nih.nci.calab.dto.common;

/**
 * This class includes properties for User Authentication and Authorization .
 *
 *
 * @author doswellj
 *
 */

public class UserBean
{

	private String loginId;
	private String fullName;
	private String firstName;
	private String lastName;

	public UserBean() {}

	public UserBean(String strLoginId, String firstName, String lastName)
	{
		this.loginId = strLoginId;
		this.firstName= firstName;
		this.lastName= lastName;
		this.fullName = firstName + " " + lastName;
	}

	public String getLoginId()
	{
		return loginId;
	}
	public void setLoginId(String loginId)
	{
		this.loginId = loginId;
	}

	public String getFirstName()
	{
		return firstName;
	}
	public void setFirstName(String firstName)
	{
		this.firstName = firstName;
	}

	public String getLastName()
	{
		return lastName;
	}
	public void setLastName(String lastName)
	{
		this.lastName = lastName;
	}

	public String getFullName() {
		return fullName;
	}

	public void setFullName(String fullName) {
		this.fullName =fullName;
	}
}

Move the package. Container user info


/*
 * Copyright (C) 2017 Joao Paulo Fernandes Ventura, Udi Cohen
 *
 * 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.udinic.accounts_authenticator_example.authentication;

import android.os.Bundle;
import android.support.annotation.NonNull;

import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.GetTokenResult;

import static android.accounts.AccountManager.KEY_ACCOUNT_NAME;
import static android.accounts.AccountManager.KEY_AUTHTOKEN;
import static android.accounts.AccountManager.KEY_PASSWORD;
import static com.google.common.base.Preconditions.checkNotNull;

class SignUpTask implements Continuation<Bundle, Task<Bundle>> {

    private Bundle mAuthData;

    @Override
    public Task<Bundle> then(@NonNull Task<Bundle> task) throws Exception {
        mAuthData = checkNotNull(task.getResult());
        return signUp().continueWithTask(getAuthToken()).continueWith(getResult());
    }

    private Task<AuthResult> signUp() {
        return FirebaseAuth.getInstance().createUserWithEmailAndPassword(
                checkNotNull(mAuthData.getString(KEY_ACCOUNT_NAME)),
                checkNotNull(mAuthData.getString(KEY_PASSWORD))
        );
    }

    private Continuation<AuthResult, Task<GetTokenResult>> getAuthToken() {
        return new Continuation<AuthResult, Task<GetTokenResult>>() {
            @Override
            public Task<GetTokenResult> then(@NonNull Task<AuthResult> task) throws Exception {
                return task.getResult().getUser().getToken(true);
            }
        };
    }

    private Continuation<GetTokenResult, Bundle> getResult() {
        return new Continuation<GetTokenResult, Bundle> () {
            @Override
            public Bundle then(@NonNull Task<GetTokenResult> task) throws Exception {
                mAuthData.putString(KEY_AUTHTOKEN, checkNotNull(task.getResult().getToken()));
                return mAuthData;
            }
        };
    }

}

Create Firebase sign up task


package com.bdt.kiradb;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

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

@RunWith(Parameterized.class)
public class IterableTest {

    private final Integer integer;

    public IterableTest(Integer integer) {
        this.integer = integer;
    }

    @Parameterized.Parameters
    public static Collection<Object[]> theData() {
        Object[][] data = new Object[][]{
                {1}, {2}, {3}, {4}
        };

        return Arrays.asList(data);
    }

    @Test
    public void testMe() {
//        System.out.printf("i: %d\n", integer);
    }

}

Add an example of a JUnit test where JUnit itself iterates over some user provided set of data.


package problems;

import java.util.Stack;

public class BinaryTreeUpsideDown {

    class TreeNode {
        int val;
        TreeNode left, right;

        public TreeNode(int value) {
            this.val = value;
        }
    }

    public final TreeNode upsideDownBinaryTree(TreeNode root) {
        // recursive solution
        if (root == null || root.left == null)
            return root;

        final TreeNode parent = root.left;
        final TreeNode head = upsideDownBinaryTree(parent);
        parent.left = root.right;
        parent.right = root;
        root.left = root.right = null;
        return head;
    }

    public final TreeNode upsideDownBinaryTree2(TreeNode root) {
        // iterative solution using stack
        Stack<TreeNode> st = new Stack<TreeNode>();
        TreeNode left = root;
        while (left != null) {
            st.push(left);
            left = left.left;
        }
        TreeNode head = st.isEmpty() ? null : st.pop();
        TreeNode parent = head;
        while (st.size() > 0) {
            TreeNode t = st.pop();
            parent.right = t;
            parent.left = t.right;
            t.left = t.right = null;
            parent = t;
        }
        return head;
    }

    void PreorderPrintTree(TreeNode root) {
        if (root == null)
            System.out.print("#,");
        else {
            System.out.print(root.val + ",");
            PreorderPrintTree(root.left);
            PreorderPrintTree(root.right);
        }
    }

    public static void main(String[] args) {
        BinaryTreeUpsideDown ud = new BinaryTreeUpsideDown();

        TreeNode root = ud.new TreeNode(1);
        root.left = ud.new TreeNode(2);
        root.right = ud.new TreeNode(3);
        root.left.left = ud.new TreeNode(4);
        root.left.right = ud.new TreeNode(5);

        TreeNode head = ud.upsideDownBinaryTree2(root);
        ud.PreorderPrintTree(head);
    }
}

Add Binary Tree Upside Down


package simple.xml.load;

import java.io.FileOutputStream;
import java.io.StringWriter;

import simple.xml.ValidationTestCase;
import simple.xml.ElementArray;
import simple.xml.Element;
import simple.xml.Attribute;
import simple.xml.Text;
import simple.xml.Root;

public class TextTest extends ValidationTestCase {

   private static final String SOURCE =
   "<test>\n"+
   "   <array>\n"+
   "     <text name='a' version='ONE'>Example 1</text>\r\n"+
   "     <text name='b' version='TWO'>Example 2</text>\r\n"+
   "     <text name='c' version='THREE'>Example 3</text>\r\n"+
   "   </array>\n\r"+
   "</test>";

   @Root(name="test")
   private static class TextList {

      @ElementArray(name="array")
      private TextEntry[] array;
   }

   @Root(name="text")
   private static class TextEntry {

      @Attribute(name="name")
      private String name;

      @Attribute(name="version")
      private Version version;

      @Text
      private String text;
   }

   private enum Version {

      ONE,
      TWO,
      THREE
   }

   private Persister persister;

   public void setUp() throws Exception {
      persister = new Persister();
   }

   public void testText() throws Exception {
      TextList list = persister.read(TextList.class, SOURCE);

      assertEquals(list.array[0].version, Version.ONE);
      assertEquals(list.array[0].name, "a");
      assertEquals(list.array[0].text, "Example 1");
      assertEquals(list.array[1].version, Version.TWO);
      assertEquals(list.array[1].name, "b");
      assertEquals(list.array[1].text, "Example 2");
      assertEquals(list.array[2].version, Version.THREE);
      assertEquals(list.array[2].name, "c");
      assertEquals(list.array[2].text, "Example 3");

      StringWriter buffer = new StringWriter();
      persister.write(list, buffer);
      validate(list, persister);

      list = persister.read(TextList.class, buffer.toString());

      assertEquals(list.array[0].version, Version.ONE);
      assertEquals(list.array[0].name, "a");
      assertEquals(list.array[0].text, "Example 1");
      assertEquals(list.array[1].version, Version.TWO);
      assertEquals(list.array[1].name, "b");
      assertEquals(list.array[1].text, "Example 2");
      assertEquals(list.array[2].version, Version.THREE);
      assertEquals(list.array[2].name, "c");
      assertEquals(list.array[2].text, "Example 3");

      validate(list, persister);
   }
}

Add unit testing for text annotations


/*******************************************************************************
 * Copyright (c) 2017 Eurotech and/or its affiliates 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
 *
 * Contributors:
 *     Eurotech - initial API and implementation
 *******************************************************************************/
package org.eclipse.kapua.service.certificate;

import org.eclipse.kapua.model.KapuaUpdatableEntityPredicates;

public interface CertificatePredicates extends KapuaUpdatableEntityPredicates {

    /**
     * Certificate name
     */
    public static final String NAME = "name";

    public static final String USAGE = "certificateUsages";

    public static final String USAGE_NAME = USAGE + ".name";

}

/*******************************************************************************
 * Copyright (c) 2017 Eurotech and/or its affiliates 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
 *
 * Contributors:
 *     Eurotech - initial API and implementation
 *******************************************************************************/
package org.eclipse.kapua.service.certificate;

import org.eclipse.kapua.model.KapuaUpdatableEntityPredicates;

public interface CertificatePredicates extends KapuaUpdatableEntityPredicates {

    /**
     * Certificate name
     */
    public static final String NAME = "name";

    public static final String USAGE = "certificateUsages";

    public static final String USAGE_NAME = USAGE + ".name";

    public static final String STATUS = "status";

}

Add Status in Certificate Predicates


package org.jboss.forge.addons.envers.commands;

import org.jboss.forge.addon.configuration.Configuration;
import org.jboss.forge.addon.configuration.facets.ConfigurationFacet;
import org.jboss.forge.addon.projects.ProjectFactory;
import org.jboss.forge.addon.projects.Projects;
import org.jboss.forge.addon.ui.command.CommandExecutionListener;
import org.jboss.forge.addon.ui.command.UICommand;
import org.jboss.forge.addon.ui.context.UIExecutionContext;
import org.jboss.forge.addon.ui.context.UISelection;
import org.jboss.forge.addon.ui.result.Result;

import javax.inject.Inject;

/**
 * @author Ivan St. Ivanov
 */
public class JpaEntityCreationListener implements CommandExecutionListener
{
   @Override public void preCommandExecuted(UICommand uiCommand, UIExecutionContext uiExecutionContext)
   {

   }

   @Inject
   private ProjectFactory projectFactory;

   @Override public void postCommandExecuted(UICommand uiCommand, UIExecutionContext uiExecutionContext, Result result)
   {
      String commandName = uiCommand
               .getMetadata(uiExecutionContext.getUIContext())
               .getName();
      if (commandName.equals("JPA: New Entity") && projectFactory != null)
      {

         Configuration configuration = Projects
                  .getSelectedProject(projectFactory, uiExecutionContext.getUIContext())
                  .getFacet(ConfigurationFacet.class)
                  .getConfiguration();
         if ((Boolean) configuration.getProperty(Constants.AUTO_AUDIT_CONFIG_ENTRY))
         {
            uiExecutionContext.getUIContext().getSelection();
         }

      }
   }

   @Override public void postCommandFailure(UICommand uiCommand, UIExecutionContext uiExecutionContext,
            Throwable throwable)
   {

   }
}

Add the command listener showcase


/*
 *  Copyright 2011 Couchbase, 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.
 *  under the License.
 */
package org.couchbase.mock.memcached.protocol;

import java.nio.ByteBuffer;
import org.couchbase.mock.memcached.Item;

/**
 *
 * @author Trond Norbye <trond.norbye@gmail.com>
 */
public class BinaryGetResponse extends BinaryResponse {
    public BinaryGetResponse(BinaryCommand command, ErrorCode error) {
        super(command, error);
    }

    public BinaryGetResponse(BinaryCommand command, Item item) {
        super(create(command, item));
    }

    private static ByteBuffer create(BinaryCommand command, Item item) {
        final ByteBuffer message = BinaryResponse.create(command, ErrorCode.SUCCESS,
                4 /* flags */, 0, item.getValue().length, 0);
        message.putInt(item.getFlags());
        message.put(item.getValue());
        message.rewind();
        return message;
    }

}

/*
 *  Copyright 2011 Couchbase, 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.
 *  under the License.
 */
package org.couchbase.mock.memcached.protocol;

import java.nio.ByteBuffer;
import org.couchbase.mock.memcached.Item;

/**
 *
 * @author Trond Norbye <trond.norbye@gmail.com>
 */
public class BinaryGetResponse extends BinaryResponse {
    public BinaryGetResponse(BinaryCommand command, ErrorCode error) {
        super(command, error);
    }

    public BinaryGetResponse(BinaryCommand command, Item item) {
        super(create(command, item));
    }

    private static ByteBuffer create(BinaryCommand command, Item item) {
        final ByteBuffer message = BinaryResponse.create(command, ErrorCode.SUCCESS,
                4 /* flags */, 0, item.getValue().length, item.getCas());
        message.putInt(item.getFlags());
        message.put(item.getValue());
        message.rewind();
        return message;
    }

}

Return CAS for get operation


package org.jsmpp.util;

import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;

public class HexUtilTest {

	@Test
	public void testEncode()
	{
		String res = HexUtil.convertStringToHexString("hello world");

		assertEquals("68656c6c6f20776f726c64", res);
	}
}

Add minor unit tests for HexUtil


/*
 * Licensed to the University of California, Berkeley 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 tachyon.hadoop.contract;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.contract.AbstractFSContract;
import org.apache.hadoop.fs.contract.AbstractFSContractTestBase;
import org.junit.Test;

import java.net.URL;

public class TestTachyonFSContractLoaded extends AbstractFSContractTestBase {

  @Override
  protected AbstractFSContract createContract(Configuration conf) {
    return new TachyonFSContract(conf);
  }

  @Test
  public void testContractWorks() throws Throwable {
    String key = getContract().getConfKey(SUPPORTS_ATOMIC_RENAME);
    assertNotNull("not set: " + key, getContract().getConf().get(key));
    assertFalse("true: " + key, getContract().isSupported(SUPPORTS_ATOMIC_RENAME, false));
  }

  @Test
  public void testContractResourceOnClasspath() throws Throwable {
    URL url = this.getClass().getClassLoader().getResource(TachyonFSContract.CONTRACT_XML);
    assertNotNull("could not find contract resource", url);
  }
}

Add test for contract xml loading.


package com.madisp.bad;

import com.madisp.bad.eval.BadConverter;
import com.madisp.bad.eval.BadScope;
import com.madisp.bad.expr.Expression;
import com.madisp.bad.expr.ExpressionFactory;

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

/**
 * Created with IntelliJ IDEA.
 * User: madis
 * Date: 5/18/13
 * Time: 6:25 PM
 */
public class ConsoleRepl {
	public static void main(String[] args) throws IOException {
		ExpressionFactory factory = new ExpressionFactory();
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		System.out.println("Repl running, type 'exit' to quit.");
		BadScope scope = new BadScope(null, new Object());
		String s;
		while (!(s = getLine(reader)).equals("exit")) {
			if (s.isEmpty()) {
				continue;
			}
			try {
				Expression expr = factory.buildExpression(s);
				System.out.println(BadConverter.string(expr.value(scope)));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private static String getLine(BufferedReader reader) throws IOException {
		System.out.print("> ");
		System.out.flush();
		return reader.readLine().trim();
	}
}

Add plain old Java main class with a script REPL


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

import fs.App;
import fs.Disk;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Leo
 */
public class CopyVirtualToVirtualCommand extends Command{

    public static final String COMMAND = "copyVtoV";

    @Override
    public void execute(String[] args)
    {
        try
        {
            if (args.length != 4)
            {
                reportSyntaxError();
                return;
            }
            String virtualOriginPath = args[1];
            String virtualDestinationPath = args[3];
            App app = App.getInstance();
            Disk disk = app.getDisk();
            disk.copyVirtualToVirtual(virtualOriginPath, virtualDestinationPath);
        }
        catch (Exception ex)
        {
            Logger.getLogger(CopyRealToVirtualCommand.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    protected String getName()
    {
        return COMMAND;
    }

    @Override
    protected String getDescription()
    {
        return "Copies a content from a virtual node to another virtual node of the File System";
    }

    @Override
    protected String getSyntax()
    {
        return getName() + "VirtualOriginPath /to/ VirtualDestinationPath";
    }

}

Copy virtual to virtual command implemented.


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

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

class TestProjectTests {

  private final Path projects = Path.of("src/test-project");

  @Nested
  class Empty {

    @Test
    void build(@TempDir Path work) {
      assertThrows(AssertionError.class, () -> new Probe(projects.resolve("empty"), work));
    }
  }

  @Nested
  class MissingModule {

    @Test
    void build(@TempDir Path work) {
      var probe = new Probe(projects.resolve("missing-module"), work);
      assertEquals(1, probe.bach.main(List.of("build")), probe.toString());
      assertLinesMatch(
          List.of(">> INIT >>", ">> build(<empty>)", ">> BUILD >>", "Bach::compile"),
          probe.lines());
      assertLinesMatch(
          List.of(
              "project.modules=[a]",
              "project.requires=[b]",
              "found in library=[]",
              "Missing module(s) are: b",
              "Compilation failed."),
          probe.errors());
    }
  }
}

Build all test projects as part of the integration tests


/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2013 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.undertow.server.security;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * A test case to test the SPNEGO authentication mechanism.
 *
 * @author Darran Lofthouse
 */
public class SpnegoAuthenticationTestCase {

    @BeforeClass
    public static void startServers() {

    }

    @AfterClass
    public static void stopServers() {

    }

    @Test
    public void test() {

    }

}

Test for SPNEGO authentication in issolation.


public class QuickSelect
{
    /**
     * @param nums Unsorted array
     * @param k k-th smallest element to return
     * @return k-th smallest element
     */
    public int quickSelect(int[] nums, int k)
    {
        // Boundary check omitted

        int i = 0;
        int j = nums.length-1;

        while (true)
        {
            int pos = partition(nums, i, j);

            if (pos == k-1) return nums[pos];
            else if (pos < k-1) i = pos+1;
            else j = pos-1;
        }
    }

    private int partition(int[] nums, int i, int j)
    {
        int pivot = nums[j];

        int k = j-1;
        while (i <= k)
        {
            if (nums[i] <= pivot) i++;
            else
            {
                swap(nums, i, k);
                k--;
            }
        }

        swap(nums, i, j);
        return i;
    }

    private void swap(int[] nums, int i, int j)
    {
        int t = nums[j];
        nums[j] = nums[i];
        nums[i] = t;
    }
}

Add implementation for quick select


// Use length variable to help copy an array.
class ACopy {
	public static void main(String args[]) {
		int i;
		int nums1[] = new int[10];
		int nums2[] = new int[10];

		for(i=0; i < nums1.length; i++)
			nums1[i] = i;

		// copy nums1 to nums2
		if(nums2.length == nums1.length)
			for(i = 0; i < nums2.length; i++)
				nums2[i] = nums1[i];

		for(i=0; i < nums2.length; i++)
			System.out.print(nums2[i] + " ");
	}
}


import static de.retest.recheck.ignore.FilterLoader.load;
import static java.nio.file.Paths.get;
import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import de.retest.recheck.review.ignore.io.ErrorHandlingLoader;
import io.github.netmikey.logunit.api.LogCapturer;

class DefaultRecheckIgnoreTest {

	@RegisterExtension
	LogCapturer warningAndErrorLogs = LogCapturer.create() //
			.captureForType( ErrorHandlingLoader.class );

	@Test
	void default_recheck_ignore_should_load_without_exception() throws Exception {
		load( get( getClass().getResource( "default-recheck.ignore" ).toURI() ) ).load();

		// Assert that no error was logged...
		assertThat( warningAndErrorLogs.size() ).isEqualTo( 0 );
	}

}

Add a test that checks that the default-recheck.ignore is not faulty


package com.bert.pixels.models;

/**
 * Possible colors for a pixel
 */
public enum Color {
  /**
   * Red pixels can only more right.
   */
  RED,
  /**
   * Yellow pixels can only more left.
   */
  YELLOW
}

Add enum for pixel colors


package seedu.tasklist.model;

import static org.junit.Assert.assertEquals;

import java.util.Date;

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

import seedu.tasklist.commons.exceptions.IllegalValueException;

import seedu.tasklist.model.tag.UniqueTagList;
import seedu.tasklist.model.task.Comment;
import seedu.tasklist.model.task.DeadlineTask;
import seedu.tasklist.model.task.EventTask;
import seedu.tasklist.model.task.FloatingTask;
import seedu.tasklist.model.task.Name;
import seedu.tasklist.model.task.Priority;
import seedu.tasklist.model.task.Status;
import seedu.tasklist.model.task.Task;

public class TaskTest {
    private Task task;
    private TaskTestHelper helper;

    @Before
    public void initialize() {
        helper = new TaskTestHelper();
    }

    @Test
    public void create_FloatingTask_returnsTrue() throws Exception {
        task = helper.createFloatingTask();
        assertEquals(task.getType(), FloatingTask.TYPE);
    }

    @Test
    public void create_EventTask_returnsTrue() throws Exception {
        task = helper.createEventTask();
        assertEquals(task.getType(), EventTask.TYPE);
    }

    @Test
    public void create_DeadlineTask_returnsTrue() throws Exception {
        task = helper.createDeadlineTask();
        assertEquals(task.getType(), DeadlineTask.TYPE);
    }

    class TaskTestHelper {

        /**
         * Creates floating task
         */
        public Task createFloatingTask() throws IllegalValueException {
            return new FloatingTask(new Name("testFloatingTask1"), new Comment("test"),
                                     new Priority("medium"), new Status(), new UniqueTagList());
        }

        /**
         * Creates an event task
         */
        public Task createEventTask() throws IllegalValueException {
            return new EventTask(new Name("testEventTask1"), new Comment("test"),
                                    new Priority("low"), new Status(), new Date(), new Date(), new UniqueTagList());
        }

        /**
         * Creates a deadline task
         */
        public Task createDeadlineTask() throws IllegalValueException {
            return new DeadlineTask(new Name("testDeadlineTask1"), new Comment("test"),
                                    new Priority("high"), new Status(), new Date(), new UniqueTagList());
        }
    }
}

Create TaskTesk.java to test for 3 types of task


// Use commas in a for statement.
class Comma {
	public static void main(String args[]) {
		int i, j;

		for(i=0, j=10; i < j; i++, j--)
			System.out.println("i and j: " + i + " " + j);
	}
}

Use commas in a for statement


package org.projectodd.nodej;

import static org.fest.assertions.Assertions.assertThat;

import java.io.IOException;

import org.dynjs.runtime.DynObject;
import org.dynjs.runtime.Types;
import org.junit.Before;
import org.junit.Test;

public class PathTest extends NodejTestSupport {

    @Before
    public void beforeTests() {
        assertThat(eval("path = require('path'); path").getClass()).isEqualTo(DynObject.class);
    }

    @Test
    public void testNormalize() {
        assertThat(eval("path.normalize('/foo/bar//baz/asdf/quux/..')")).isEqualTo("/foo/bar/baz/asdf");
    }

    @Test
    public void testJoin() {
        assertThat(eval("path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')")).isEqualTo("/foo/bar/baz/asdf");
        assertThat(eval("path.join('foo', {}, 'bar')")).isEqualTo("foo/bar");
    }

    @Test
    public void testResolve() {
        assertThat(eval("path.resolve('/foo/bar', './baz')")).isEqualTo("/foo/bar/baz");
    }

    @Test
    public void testRelative() {
        assertThat(eval("path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')")).isEqualTo("../../impl/bbb");
    }

    @Test
    public void testDirname() {
        assertThat(eval("path.dirname('/foo/bar/baz/asdf/quux')")).isEqualTo("/foo/bar/baz/asdf");
    }

    @Test
    public void testBasename() {
        assertThat(eval("path.basename('/foo/bar/baz/asdf/quux.html')")).isEqualTo("quux.html");
        // TODO: Not clear why this is failing
//        assertThat(eval("path.basename('/foo/bar/baz/asdf/quux.html', '.html')")).isEqualTo("quux");
    }

    @Test
    public void testExtname() {
        assertThat(eval("path.extname('index.html')")).isEqualTo(".html");
    }

    @Test
    public void testPathSep() {
        assertThat(eval("path.sep")).isEqualTo(System.getProperty("file.separator"));
    }
}

Add tests for node.js require('path')


package tc.oc.projectares.api;

import javax.annotation.Nullable;

public class PlayerManager {
    public static @Nullable Player getPlayer(org.bukkit.entity.Player bukkit) {
        throw new UnsupportedOperationException();
    }
}

Add an example of a static method that would need to be overwritten using reflection.


package org.realityforge.gwt.appcache.server.mgwt;

import org.realityforge.gwt.appcache.server.propertyprovider.UserAgentPropertyProvider;

public class MgwtManifestServlet
  extends AbstractMgwtManifestServlet
{
  public MgwtManifestServlet()
  {
    addPropertyProvider( new MgwtOsPropertyProvider() );
    addPropertyProvider( new UserAgentPropertyProvider() );
    addPropertyProvider( new MobileUserAgentProvider() );
  }
}

Add a concrete mgwt servlet


package org.jdesktop.swingx.painter;

import org.jdesktop.beans.AbstractBeanInfoTest;

public class AlphaPainterBeanInfoTest extends AbstractBeanInfoTest<AlphaPainter<Object>> {
    /**
     * {@inheritDoc}
     */
    @Override
    protected AlphaPainter<Object> createInstance() {
        return new AlphaPainter<Object>();
    }
}

Add bean test for AlphaPainter.


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

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Helper class that parses JavaScript files for special
 * Sprockets comments
 * like these:
 *

 * //= require library_name
 * //= require ./file_name

 *

 * Note that paths can also be surrounded by quotes, but they are completely optional:
 *

 * //= require "library_name"
 * //= require "./file_name"

 *
 * @since 4.0
 */
public class SprocketsParserImplV4 implements SprocketsParser
{
    private static final Logger LOGGER = LoggerFactory.getLogger(
        SprocketsParserImplV4.class
    );

    static final Pattern REQ = Pattern.compile("^\\s*//=\\s*require\\s+(\\S.*\\S)\\s*$");

    public List<Sprocket> parseSprockets(BufferedReader javascript)
        throws IOException
    {
        List<Sprocket> sprockets = new ArrayList<Sprocket>();

        while(true)
        {
            String line = javascript.readLine();
            if(null == line) break;

            Matcher require = REQ.matcher(line);
            if(!require.find()) continue;

            String path = stripQuotes(require.group(1));
            boolean isLibrary = !(path.startsWith("./") || path.startsWith("../"));
            sprockets.add(new Sprocket(isLibrary, path));
        }
        return sprockets;
    }

    private String stripQuotes(String path)
    {
        String[] quotes = new String[] { "\"", "'" };
        for(String q : quotes)
        {
            if(path.startsWith(q) && path.endsWith(q))
            {
                path = path.substring(1, path.length() - 1);
                break;
            }
        }
        return path;
    }
}

Introduce parse logic for new sprockets syntax


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

package org.scijava.io;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

/**
 * {@link Location} backed by a {@link URL}.
 *
 * @author Curtis Rueden
 */
public class URLLocation extends AbstractLocation {

	/** The URL backing this location. */
	private final URL url;

	public URLLocation(final URL url) {
		this.url = url;
	}

	// -- URLLocation methods --

	/** Gets the associated {@link URL}. */
	public URL getURL() {
		return url;
	}

	// -- Location methods --

	/**
	 * Gets the associated {@link URI}, or null if this URL is not formatted
	 * strictly according to to RFC2396 and cannot be converted to a URI.
	 */
	@Override
	public URI getURI() {
		try {
			return getURL().toURI();
		}
		catch (final URISyntaxException exc) {
			return null;
		}
	}

}

Add a location type backed by a remote URL


package ch.hevs.aislab.magpie.broker.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import ch.hevs.aislab.magpie.broker.model.MobileClient;

@Repository
public interface MobileClientRepo extends CrudRepository<MobileClient, Long>{

	MobileClient findByUsername(String username);

}

Add repo for the mobile users


package com.example.storm;

import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.IRichBolt;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import com.example.Marker;
import java.util.Arrays;
import java.util.Map;

public class MarkerBolt implements IRichBolt {

	private Marker marker;
	private OutputCollector collector;

	@Override
	public void prepare(Map stormConf, TopologyContext topologyContext, OutputCollector outputCollector) {
		collector = outputCollector;
		marker = new Marker();
	}

	@Override
	public void execute(Tuple tuple) {
		Long number = tuple.getLongByField("number");
		String heading = tuple.getStringByField("heading");
		Marker.Attributes bean = marker.mark(number);
		collector.emit(tuple, Arrays.<Object>asList(heading, bean.getIsEven(), bean.getSource()));
		collector.ack(tuple);
	}

	@Override
	public void cleanup() {
	}

	@Override
	public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) {
		outputFieldsDeclarer.declare(new Fields("heading", "isEven", "source"));
	}

	@Override
	public Map<String, Object> getComponentConfiguration() {
		return null;
	}

}

Simplify demo + bean output fields.


package symbolTable.entries;

public class LocalVariableEntry extends AVariableEntry {

    /**
     * LocalVariableEntry Constructor
     *
     * @param name
     * @param scope
     */
    public LocalVariableEntry(String name, int scope) {
        super(name, scope);

    }
}

Add class to prepresent local variables.


package net.acomputerdog.TerrainEdit.main;

import net.acomputerdog.BlazeLoader.main.Version;
import net.acomputerdog.BlazeLoader.mod.Mod;

public class ModTerrainEdit extends Mod {
    /**
     * Returns ID used to identify this mod internally, even among different versions of the same mod.  Mods should override.
     * --This should never be changed after the mod has been released!--
     *
     * @return Returns the id of the mod.
     */
    @Override
    public String getModId() {
        return "acomputerdog.terrainedit";
    }

    /**
     * Returns the user-friendly name of the mod.  Mods should override.
     * --Can be changed among versions, so this should not be used to ID mods!--
     *
     * @return Returns user-friendly name of the mod.
     */
    @Override
    public String getModName() {
        return "Terrain Edit";
    }

    /**
     * Gets the version of the mod as an integer for choosing the newer version.
     *
     * @return Return the version of the mod as an integer.
     */
    @Override
    public int getIntModVersion() {
        return 0;
    }

    /**
     * Gets the version of the mod as a String for display.
     *
     * @return Returns the version of the mod as an integer.
     */
    @Override
    public String getStringModVersion() {
        return "0.0";
    }

    /**
     * Returns true if this mod is compatible with the installed version of BlazeLoader.  This should be checked using Version.class.
     * -Called before mod is loaded!  Do not depend on Mod.load()!-
     *
     * @return Returns true if the mod is compatible with the installed version of BlazeLoader.
     */
    @Override
    public boolean isCompatibleWithBLVersion() {
        if(Version.getMinecraftVersion().equals("1.6.4") && Version.getGlobalVersion() == 0 && Version.getApiVersion() <= 2){
            return true;
        }else{
            System.out.println("TerrainEdit - Incorrect version, aborting launch!");
            return false;
        }
    }

    /**
     * Gets a user-friendly description of the mod.
     *
     * @return Return a String representing a user-friendly version of the mod.
     */
    @Override
    public String getModDescription() {
        return "A command-line terrain editor";
    }

    /**
     * Called when mod is loaded.  Called before game is loaded.
     */
    @Override
    public void load() {
        super.load();
    }

    /**
     * Called when mod is started.  Game is fully loaded and can be interacted with.
     */
    @Override
    public void start() {
        super.start();
    }

    /**
     * Called when mod is stopped.  Game is about to begin shutting down, so mod should release system resources, close streams, etc.
     */
    @Override
    public void stop() {
        super.stop();
    }
}

Correct method description in Mod


package leetcode.number_of_1_bits;

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        n = n - ((n >> 1) & 0x55555555);
        n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
        return (((n + (n >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
    }

    public static void main(String[] args){
        System.err.println(new Solution().hammingWeight(-1));
    }
}

Add java solution for 191. Number of 1 Bits


package org.gozer.services;

import org.junit.Test;
import org.kevoree.kcl.KevoreeJarClassLoader;
import org.kevoree.resolver.MavenResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.MalformedURLException;
import java.util.Arrays;

public class KCLTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(KCLTest.class);

    @Test
    public void should_load_classe() throws MalformedURLException, IllegalAccessException, InstantiationException, NoSuchMethodException {
        KevoreeJarClassLoader kclScope1 = new KevoreeJarClassLoader();
        kclScope1.isolateFromSystem();

        KevoreeJarClassLoader kclScope = new KevoreeJarClassLoader();

        MavenResolver resolver = new MavenResolver();
        resolver.setBasePath("target/repository");

        File dependencyPath = resolver.resolve("mvn:org.springframework:spring-core:3.2.4.RELEASE:jar", Arrays.asList("http://repo1.maven.org/maven2"));

        kclScope.addJarFromURL(dependencyPath.toURI().toURL());
        LOGGER.info("deploiement jar path : {}", dependencyPath.toURI().toURL());
        kclScope1.addChild(kclScope);

        Class cl1 = kclScope.loadClass("org.springframework.core.io.Resource");
        Object objOfCl1 = cl1.newInstance();

//        KevoreeJarClassLoader kclScope2 = new KevoreeJarClassLoader();
//
//        //can be call dynamicallly at anytime
//        //removeChild also available
//        kclScope2.addChild(kclScope1);
//
//        Class clMain = kclScope2.loadClass("yourMain");
//        //slf4j classes will be resolved transitively
//        clMain.getMethod("main").invoke();
    }
}

Add an unit test to have simple example of KCL


package us.crast.mondochest;

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

import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;

public class DirectionalStrings {
	private static Map<String, BlockFace> dirs = new HashMap<String, BlockFace>();

	public static Block parseDirectional(Block context, String directioninfo) throws MondoMessage {
		String[] directional = directioninfo.split(" ");
		if ((directional.length % 2) != 0) {
			throw new MondoMessage("Directional info specification is invalid");
		}
		for (int i = 0; i < directional.length; i+=2) {
			BlockFace desired_face = dirs.get(directional[i].toUpperCase());
			if (desired_face == null) {
				throw new MondoMessage(String.format("Direction must be one of up/down/north/south/east/west, got '{0}'", directional[i]));
			}
			int distance = Integer.parseInt(directional[i+1]);
			if (distance < 0) {
				distance = -distance;
				desired_face = desired_face.getOppositeFace();
			}
			context = context.getRelative(desired_face, distance);
		}
		return context;
	}

	static {
		dirs.put("UP", BlockFace.UP);
		dirs.put("DOWN", BlockFace.DOWN);
		dirs.put("EAST", BlockFace.EAST);
		dirs.put("WEST", BlockFace.WEST);
		dirs.put("NORTH", BlockFace.NORTH);
		dirs.put("SOUTH", BlockFace.SOUTH);
	}
}

Add in support for parsing directional strings like 'up 7 east 12'


package jenkins.plugins.git;

import hudson.model.Item;
import hudson.model.TopLevelItem;
import hudson.plugins.git.GitStatus;
import jenkins.scm.api.SCMSource;
import jenkins.scm.api.SCMSourceOwner;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Collections;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

/**
 * @author Robin Müller
 */
public class GitSCMSourceTest {

    public static final String REMOTE = "git@remote:test/project.git";

    @Rule
    public JenkinsRule jenkins = new JenkinsRule();

    private GitStatus gitStatus;

    @Before
    public void setup() {
        gitStatus = new GitStatus();
    }

    @Test
    public void testSourceOwnerTriggeredByDoNotifyCommit() throws ServletException, IOException {
        GitSCMSource gitSCMSource = new GitSCMSource("id", REMOTE, "", "*", "", false);
        GitSCMSourceOwner scmSourceOwner = setupGitSCMSourceOwner(gitSCMSource);
        jenkins.getInstance().add(scmSourceOwner, "gitSourceOwner");

        gitStatus.doNotifyCommit(mock(HttpServletRequest.class), REMOTE, "master", "");

        verify(scmSourceOwner).onSCMSourceUpdated(gitSCMSource);
    }

    private GitSCMSourceOwner setupGitSCMSourceOwner(GitSCMSource gitSCMSource) {
        GitSCMSourceOwner owner = mock(GitSCMSourceOwner.class);
        when(owner.getSCMSources()).thenReturn(Collections.<SCMSource>singletonList(gitSCMSource));
        when(owner.hasPermission(Item.READ)).thenReturn(true);
        return owner;
    }

    private interface GitSCMSourceOwner extends TopLevelItem, SCMSourceOwner {}
}

Add test of GitStatus.Listener onNotifyCommit method


package com.google.sps.servlets;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Transaction;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.UserRecord;
import com.google.sps.firebase.FirebaseAppManager;
import java.io.IOException;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Once class owner submits a TA email, retrieve that user and add them as a TA to the class
@WebServlet("/create-user")
public class CreateUser extends HttpServlet {

  private FirebaseAuth authInstance;

  // Get the current session
  @Override
  public void init(ServletConfig config) throws ServletException {
    try {
      authInstance = FirebaseAuth.getInstance(FirebaseAppManager.getApp());
    } catch (IOException e) {
      throw new ServletException(e);
    }
  }

}

Create servlet for adding user entity.


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

package ticket25;

import org.junit.Test;
import org.sablecc.sablecc.automaton.graph.State;
import org.sablecc.sablecc.automaton.graph.Transition;

public class TransitionBug {

    @Test
    public void bug() {

        State<Integer> state = new State<Integer>("state");
        Transition<Integer> transition = new Transition<Integer>(state, state,
                null);

        // Line that causes the bug.
        transition.equals(transition);
    }
}

Add regression test. See ticket:25.