package com.evgenii.aescrypto.test;

import android.content.Intent;
import android.test.ActivityUnitTestCase;
import android.test.suitebuilder.annotation.MediumTest;
import android.widget.ImageButton;

import com.evgenii.aescrypto.MainActivity;
import com.evgenii.aescrypto.R;

public class OpenHelpFromMainTests extends ActivityUnitTestCase<MainActivity> {
	public Intent mMainIntent;

	public OpenHelpFromMainTests() {
		super(MainActivity.class);
	}

	@Override
	protected void setUp() throws Exception {
		super.setUp();
		mMainIntent = new Intent(getInstrumentation().getTargetContext(), MainActivity.class);
	}

	@MediumTest
	public void testHelpActivityWasLaunchedWithIntent() {
		startActivity(mMainIntent, null, null);
		final ImageButton openHelpButton = (ImageButton) getActivity().findViewById(
				R.id.helpImageButton);
		openHelpButton.performClick();

		final Intent launchIntent = getStartedActivityIntent();
		assertNotNull("Intent was null", launchIntent);
		assertEquals("com.evgenii.aescrypto.HelpActivity", launchIntent.getComponent()
				.getClassName());
		assertFalse(isFinishCalled());
	}
}

Test for opening help activity


package exporter.examples;

import java.util.Date;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

// Example of application using CLI
public class DateApp {

	public static void main(String[] args) throws ParseException {

		// create Options object
		Options options = new Options();

		// add t option
		options.addOption("time", false, "displays current time");
		options.addOption("date", false, "displays current time");

		// There are several implementations to parse command line arguments,
		// the recommended one is the DefaultParser but I can't find it in the
		// library, probably outdated documentation
		BasicParser parser = new BasicParser();
		CommandLine cmd = parser.parse(options, args);

		if (cmd.hasOption("time")) {

			Date date = new Date();
			// current time
			String str = String.format("Current Time : %tT", date);
			System.out.printf(str);

		} else if (cmd.hasOption("date")) {

			Date date = new Date();
			// current date
			String str = String.format("Current Date : %tF", date);
			System.out.printf(str);

		}

	}
}

Add example using command line interface


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

import com.github.aureliano.achmed.command.CommandResponse;
import com.github.aureliano.achmed.resources.properties.PackageProperties;

public class GemPackageManager implements IPackageManager {

	private PackageProperties properties;

	public GemPackageManager() {
		super();
	}

	public CommandResponse install() {
		throw new UnsupportedOperationException("Method not implemented yet.");
	}

	public CommandResponse uninstall() {
		throw new UnsupportedOperationException("Method not implemented yet.");
	}

	public String latest() {
		throw new UnsupportedOperationException("Method not implemented yet.");
	}

	public void setPackageProperties(PackageProperties properties) {
		this.properties = properties;
	}

	public PackageProperties getPackageProperties() {
		return this.properties;
	}
}

Create template of gem package manager.


package org.spongepowered.common.effect.particle;

import org.spongepowered.api.ResourceKey;
import org.spongepowered.api.effect.particle.ParticleOption;
import org.spongepowered.api.effect.particle.ParticleType;
import org.spongepowered.common.SpongeCatalogType;

import java.util.Map;
import java.util.Optional;

public final class NumericalParticleType extends SpongeCatalogType implements ParticleType {

    private final int id;
    private final Map<ParticleOption<?>, Object> defaultOptions;

    public NumericalParticleType(int id, ResourceKey key, Map<ParticleOption<?>, Object> defaultOptions) {
        super(key);
        this.id = id;
        this.defaultOptions = defaultOptions;
    }

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

    @SuppressWarnings("unchecked")
    @Override
    public <V> Optional<V> getDefaultOption(final ParticleOption<V> option) {
        return Optional.ofNullable((V) this.defaultOptions.get(option));
    }

    @Override
    public Map<ParticleOption<?>, Object> getDefaultOptions() {
        return this.defaultOptions;
    }
}

Implement ParticleType for dumb numerical ID'd particles.


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

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.netflix.servo.Metric;

import java.util.List;

/**
 * An observer that will transform the list of metrics using a given function.
 */
public class MetricTransformObserver implements MetricObserver {
    private final Function<Metric, Metric> transformer;
    private final MetricObserver observer;

    /**
     * Create a new MetricTransformObserver using the given transfomer function
     * @param transformer The function used to transform metrics.
     * @param observer    The MetricObserver that will receive the transfomed metrics.
     */
    public MetricTransformObserver(Function<Metric, Metric> transformer, MetricObserver observer) {
        this.transformer = transformer;
        this.observer = observer;
    }

    @Override
    public void update(List<Metric> metrics) {
        final List<Metric> newMetrics = Lists.newArrayListWithCapacity(metrics.size());
        for (Metric m : metrics) {
            newMetrics.add(transformer.apply(m));
        }
        observer.update(newMetrics);
    }

    @Override
    public String getName() {
        return "MetricTransformObserver";
    }
}

Add an observer that can transfom a list of metrics before forwarding them to the underlying observer


package com.hubspot.singularity.data;

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

import com.google.inject.Inject;
import com.hubspot.singularity.SingularityTestBaseNoDb;

public class InactiveSlaveManagerTest extends SingularityTestBaseNoDb {
  @Inject
  InactiveSlaveManager inactiveSlaveManager;

  @Test
  public void itShouldContainAnInactiveHostWhenHostDeactivated() {
    inactiveSlaveManager.deactiveSlave("localhost");

    Assert.assertTrue(inactiveSlaveManager.getInactiveSlaves().contains("localhost"));
  }

  @Test
  public void itShouldNotContainHostAfterActivatingHost() {
    inactiveSlaveManager.deactiveSlave("localhost");
    inactiveSlaveManager.activateSlave("localhost");

    Assert.assertFalse(inactiveSlaveManager.getInactiveSlaves().contains("localhost"));
  }
}

Add small test suite for inactive slave manager


package tars.commons.events.storage;

import tars.commons.core.Config;
import tars.commons.events.BaseEvent;

/*
 * @@author A0124333U
 * An event where the user changes the Tars Storage Directory/File Path
 */

public class TarsStorageDirectoryChangedEvent extends BaseEvent {

    private final String newFilePath;
    private final Config newConfig;

    public TarsStorageDirectoryChangedEvent (String newFilePath, Config newConfig) {
        this.newFilePath = newFilePath;
        this.newConfig = newConfig;
    }

    public String getNewFilePath() {
        return this.newFilePath;
    }

    public Config getNewConfig() {
        return this.newConfig;
    }

    @Override
    public String toString() {
        return "File Path changed to " + this.newFilePath;
    }

}

Add event to indicate that TARS Storage Directory has changed


/*******************************************************************************
 * Copyright (c) 2017 Pivotal, Inc.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Pivotal, Inc. - initial API and implementation
 *******************************************************************************/
package org.springframework.ide.vscode.boot.java.handlers;

import java.util.Collection;

import org.springframework.ide.vscode.commons.boot.app.cli.SpringBootApp;

public class RunningAppProvider {

	public static final RunningAppProvider DEFAULT = new RunningAppProvider();

	public Collection<SpringBootApp> getAllRunningSpringApps() throws Exception {
		return SpringBootApp.getAllRunningSpringApps().values();
	}

}

Include the running app provider


package co.uk.jiveelection.campaign.output.twitter;

import co.uk.jiveelection.campaign.jive.Jive;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;

import static org.mockito.Mockito.verify;

/**
 * Unit Tests for TwitterOutput
 */
@RunWith(MockitoJUnitRunner.class)
public class TwitterOutputTest {

    @Mock
    Jive mockJiveBot;

    @Mock
    Twitter mockTwitter;

    private TwitterOutput twitterOutput;

    @Before
    public void setUp() {
        twitterOutput = new TwitterOutput(mockJiveBot, "jivebot_token", "jivebot_token_secret");
    }

    @Test
    public void should_CallJiveComplete_When_OutputCompletes() {
        // Given
        final Status status = new StatusBuilder()
                .text("tweet tweet")
                .build();

        // When
        twitterOutput.onOutputComplete(status);

        // Then
        verify(mockJiveBot).onJiveComplete(status);
    }

    @Test
    @Ignore
    public void should_UpdateStatus_When_OutputJiveCalled() throws TwitterException {
        // Given
        final String jive = "jive";

        // When
        twitterOutput.outputJive(jive);

        // Then
        verify(mockTwitter).updateStatus(jive);
        // TODO: collaborate with the Twitter object and verify
    }
}

Add unit test for TwitterOutput


package com.elmakers.mine.bukkit.action.builtin;

import com.elmakers.mine.bukkit.action.CompoundAction;
import com.elmakers.mine.bukkit.api.action.ActionHandler;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import com.elmakers.mine.bukkit.api.wand.Wand;
import org.bukkit.configuration.ConfigurationSection;

public class CheckManaAction extends CompoundAction {
    private boolean requireNotFull = false;
    private boolean requireEmpty = false;
    private double requireAmount = 0;

    @Override
    public void prepare(CastContext context, ConfigurationSection parameters) {
        super.prepare(context, parameters);
        requireAmount = parameters.getDouble("require_mana", 0);
        requireNotFull = parameters.getBoolean("require_mana_not_full", false);
        requireEmpty = parameters.getBoolean("require_mana_empty", false);
    }

    protected boolean isAllowed(CastContext context) {
        Wand wand = context.getWand();
        if (wand == null) {
            return false;
        }
        double currentMana = wand.getMana();
        if (requireAmount > 0 && currentMana < requireAmount) {
            return false;
        }
        if (requireEmpty && currentMana > 0) {
            return false;
        }
        int manaMax = wand.getManaMax();
        if (requireNotFull && currentMana >= manaMax) {
            return false;
        }
        return true;
    }

    @Override
    public SpellResult step(CastContext context) {
        boolean allowed = isAllowed(context);
        ActionHandler actions = getHandler("actions");
        if (actions == null || actions.size() == 0) {
            return allowed ? SpellResult.CAST : SpellResult.STOP;
        }

        if (!allowed) {
            return SpellResult.NO_TARGET;
        }
        return startActions();
    }

    @Override
    public boolean requiresTarget() {
        return false;
    }
}

Add CheckMana action, for stopping a spell if mana does not meet some requirements (empty, full, certain amount)


package org.springframework.security.ui;

import org.springframework.core.Ordered;

/**
 * Stores the default order numbers of all Spring Security filters for use in configuration.
 *
 * @author luke
 * @version $Id$
 */
public class FilterChainOrderUtils {
    /**
     * The first position at which a Spring Security filter will be found. Any filter with an order less than this will
     * be guaranteed to be placed before the Spring Security filters in the stack.
     */
    public static final int FILTER_CHAIN_FIRST = Ordered.HIGHEST_PRECEDENCE + 1000;
    private static final int INTERVAL = 100;

    public static final int CHANNEL_PROCESSING_FILTER_ORDER            = FILTER_CHAIN_FIRST + INTERVAL;
    public static final int CONCURRENT_SESSION_FILTER_ORDER            = FILTER_CHAIN_FIRST + INTERVAL * 2;
    public static final int HTTP_SESSION_CONTEXT_FILTER_ORDER          = FILTER_CHAIN_FIRST + INTERVAL * 3;
    public static final int LOGOUT_FILTER_ORDER                        = FILTER_CHAIN_FIRST + INTERVAL * 4;
    public static final int AUTH_PROCESSING_FILTER_ORDER               = FILTER_CHAIN_FIRST + INTERVAL * 5;
    public static final int CAS_PROCESSING_FILTER_ORDER                = FILTER_CHAIN_FIRST + INTERVAL * 5;
    public static final int LOGIN_PAGE_FILTER_ORDER                    = FILTER_CHAIN_FIRST + INTERVAL * 6;
    public static final int BASIC_PROCESSING_FILTER_ORDER              = FILTER_CHAIN_FIRST + INTERVAL * 7;
    public static final int SECURITY_CONTEXT_HOLDER_AWARE_FILTER_ORDER = FILTER_CHAIN_FIRST + INTERVAL * 8;
    public static final int REMEMBER_ME_FILTER_ORDER                   = FILTER_CHAIN_FIRST + INTERVAL * 9;
    public static final int ANON_PROCESSING_FILTER_ORDER               = FILTER_CHAIN_FIRST + INTERVAL * 10;
    public static final int SWITCH_USER_FILTER_ORDER                   = FILTER_CHAIN_FIRST + INTERVAL * 11;
    public static final int EXCEPTION_TRANSLATION_FILTER_ORDER         = FILTER_CHAIN_FIRST + INTERVAL * 12;
    public static final int FILTER_SECURITY_INTERCEPTOR_ORDER          = FILTER_CHAIN_FIRST + INTERVAL * 13;

}

Store the default order values of security filters.


package com.example.butterknife;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;

import static org.fest.assertions.api.ANDROID.assertThat;
import static org.robolectric.Robolectric.shadowOf;

@RunWith(RobolectricTestRunner.class)
public class SimpleActivityTest {
  @Test public void verifyContentViewInjection() {
    SimpleActivity activity = new SimpleActivity();
    shadowOf(activity).callOnCreate(null);

    assertThat(activity.title).hasId(R.id.title);
    assertThat(activity.subtitle).hasId(R.id.subtitle);
    assertThat(activity.hello).hasId(R.id.hello);
    assertThat(activity.listOfThings).hasId(R.id.list_of_things);
    assertThat(activity.footer).hasId(R.id.footer);
  }
}

Add test to verify activity injection works.


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

import static org.hamcrest.Matchers.is;

public class TeamSerializationTest extends AbstractSerializationTest<Team> {

    private static final String SAMPLE_TEAM
            = "{\n"
            + "  \"name\": \"Hackers\",\n"
            + "  \"id\": 1919074,\n"
            + "  \"slug\": \"hackers\",\n"
            + "  \"description\": \"All the members\",\n"
            + "  \"permission\": \"pull\",\n"
            + "  \"privacy\": \"closed\",\n"
            + "  \"url\": \"https://api.github.com/teams/1919074\",\n"
            + "  \"members_url\": \"https://api.github.com/teams/1919074/members{/member}\",\n"
            + "  \"repositories_url\": \"https://api.github.com/teams/1919074/repos\"\n"
            + "}";

    public TeamSerializationTest() {
        super(Team.class);
    }

    @Override
    protected String getSample() {
        return SAMPLE_TEAM;
    }

    @Override
    protected void checkDeserialized(Team team) {
        errorCollector.checkThat(team.getName(), is("Hackers"));

        errorCollector.checkThat(team.getSlug(), is("hackers"));

        errorCollector.checkThat(team.getDescription(), is("All the members"));

        errorCollector.checkThat(team.getPermission(), is("pull"));
    }
}

Add serialization test for Team


package de.retest.recheck.review.workers;

import static de.retest.recheck.configuration.ProjectConfiguration.RECHECK_IGNORE;
import static de.retest.recheck.configuration.ProjectConfiguration.RECHECK_IGNORE_JSRULES;
import static de.retest.recheck.configuration.ProjectConfiguration.RETEST_PROJECT_CONFIG_FOLDER;
import static de.retest.recheck.configuration.ProjectConfiguration.RETEST_PROJECT_ROOT;
import static org.assertj.core.api.Assertions.assertThat;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import de.retest.recheck.review.GlobalIgnoreApplier;
import de.retest.recheck.review.counter.NopCounter;
import de.retest.recheck.util.junit.jupiter.SystemProperty;

class LoadShouldIgnoreWorkerTest {

	Path defaultIgnoreFile;

	@BeforeEach
	void setUp( @TempDir final Path temp ) throws Exception {
		final Path configFolder = temp.resolve( RETEST_PROJECT_CONFIG_FOLDER );
		Files.createDirectory( configFolder );

		final Path jsIgnoreFile = configFolder.resolve( RECHECK_IGNORE_JSRULES );
		Files.createFile( jsIgnoreFile );

		defaultIgnoreFile = configFolder.resolve( RECHECK_IGNORE );
		Files.copy( Paths.get( "src/main/resources/default-" + RECHECK_IGNORE ), defaultIgnoreFile );

		System.setProperty( RETEST_PROJECT_ROOT, configFolder.toString() );
	}

	@Test
	@SystemProperty( key = RETEST_PROJECT_ROOT )
	void loaded_ignore_file_should_match_default_ignore_file() throws Exception {
		final LoadShouldIgnoreWorker cut = new LoadShouldIgnoreWorker( NopCounter.getInstance() );
		final GlobalIgnoreApplier globalIgnoreApplier = cut.load();
		final List<String> loadedIgnoreFileLines = globalIgnoreApplier.persist().getIgnores().stream() //
				.map( Object::toString ) //
				.collect( Collectors.toList() );

		final List<String> defaultIgnoreFileLines = Files.readAllLines( defaultIgnoreFile );
		assertThat( loadedIgnoreFileLines ).isEqualTo( defaultIgnoreFileLines );
	}

}

Add tests that shows the problem


/*
 * Copyright 2020 Martin Winandy
 *
 * 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.tinylog.runtime;

/**
 * Representation for a defined stack trace element in the current stack trace.
 */
public interface StackTraceLocation {

	/**
	 * Adjusts the stack trace location for passing it to a method call.
	 *
	 * <p>
	 *     Whenever a stack trace location should be passed to another method, the result of this methods has to passed
	 *     instead of the original stack location object. The reason is that every method call increases the stack trace
	 *     by pushing an addition stack trace element.
	 * </p>
	 *
	 * @return Stack trace location that can be passed to another method
	 */
	StackTraceLocation push();

	/**
	 * Retrieved the fully-qualified class name of the caller.
	 *
	 * @return The fully-qualified class name of the caller
	 */
	String getCallerClassName();

	/**
	 * Retrieved the complete stack trace element of the caller.
	 *
	 * @return The complete stack trace element of the caller
	 */
	StackTraceElement getCallerStackTraceElement();

}

Add interface for stack trace locations


package com.fasterxml.jackson.databind.mixins;

import java.io.IOException;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.BaseMapTest;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TestMixinInheritance
    extends BaseMapTest
{
    // [Issue-14]
    static class Beano {
        public int ido = 42;
        public String nameo = "Bob";
    }

    static class BeanoMixinSuper {
        @JsonProperty("name")
        public String nameo;
    }

    static class BeanoMixinSub extends BeanoMixinSuper {
        @JsonProperty("id")
        public int ido;
    }

    public void testMixinInheritance() throws IOException
    {
        ObjectMapper mapper = new ObjectMapper();
        mapper.addMixInAnnotations(Beano.class, BeanoMixinSub.class);
        Map<String,Object> result;
        result = writeAndMap(mapper, new Beano());
        assertEquals(2, result.size());
        assertTrue(result.containsKey("id"));
        assertTrue(result.containsKey("name"));
    }
}

Add a unit test for [Issue-14]; minor javadoc improvements


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

import org.apache.beam.sdk.transforms.ParDo;

/**
 * Category tag for validation tests which utilize stateful {@link ParDo}.
 */
public interface UsesStatefulParDo {}

Add JUnit category for stateful ParDo tests


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

package org.apache.hadoop.hive.metastore;

import org.apache.hadoop.hive.conf.HiveConf;

public class TestRemoteHiveMetaStore extends TestHiveMetaStore {
  private static final String METASTORE_PORT = "29083";
  private static boolean isServerRunning = false;

  private static class RunMS implements Runnable {

      @Override
      public void run() {
        System.out.println("Running metastore!");
        String [] args = new String [1];
        args[0] = METASTORE_PORT;
        HiveMetaStore.main(args);
      }

    }

  @Override
  protected void setUp() throws Exception {
    super.setUp();
    if(isServerRunning) {
      return;
    }
    Thread t = new Thread(new RunMS());
    t.start();

    // Wait a little bit for the metastore to start. Should probably have
    // a better way of detecting if the metastore has started?
    Thread.sleep(5000);

    // hive.metastore.local should be defined in HiveConf
    hiveConf.set("hive.metastore.local", "false");
    hiveConf.setVar(HiveConf.ConfVars.METASTOREURIS, "thrift://localhost:" + METASTORE_PORT);
    hiveConf.setIntVar(HiveConf.ConfVars.METATORETHRIFTRETRIES, 3);

    client = new HiveMetaStoreClient(hiveConf);
    isThriftClient = true;

    // Now you have the client - run necessary tests.
    isServerRunning = true;
  }

}

Add TestRemoteHiveMetastor removed by mistake


package leetcode.maximal_square;

public class Solution {
    public int maximalSquare(char[][] matrix) {
        if(matrix.length == 0 || matrix[0].length == 0) return 0;
        int h = matrix.length, w = matrix[0].length;
        int[][] maxSqrSize = new int[h][w];
        int max = 0;
        for(int i = 0; i < h; i++){
            for(int j = 0; j < w; j++){
                if(matrix[i][j] == '1'){
                    int m = 1;
                    if(i > 0 && j > 0){
                        m = Math.min(maxSqrSize[i - 1][j], maxSqrSize[i][j - 1]);
                        if(matrix[i - m][j - m] == '1'){
                            m++;
                        }
                    }
                    maxSqrSize[i][j] = m;
                    max = Math.max(m, max);
                }
            }
        }
        return max * max;
    }
}

Add java solution for 221. Maximal Square


// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package com.android.webview.chromium;

/**
 * Helper class used to fix up resource ids.
 * This is mostly a copy of the code in frameworks/base/core/java/android/app/LoadedApk.java.
 * TODO: Remove if a cleaner mechanism is provided (either public API or AAPT is changed to generate
 * this code).
 */
class ResourceRewriter {
    /**
     * Rewrite the R 'constants' for the WebView library apk.
     */
    public static void rewriteRValues(final int packageId) {
        // TODO: We should use jarjar to remove the redundant R classes here, but due
        // to a bug in jarjar it's not possible to rename classes with '$' in their name.
        // See b/15684775.
        com.android.webview.chromium.R.onResourcesLoaded(packageId);
        org.chromium.android_webview.R.onResourcesLoaded(packageId);
        org.chromium.content.R.onResourcesLoaded(packageId);
        org.chromium.ui.R.onResourcesLoaded(packageId);
    }
}

// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package com.android.webview.chromium;

/**
 * Helper class used to fix up resource ids.
 */
class ResourceRewriter {
    /**
     * Rewrite the R 'constants' for the WebView library apk.
     */
    public static void rewriteRValues(final int packageId) {
        // This list must be kept up to date to include all R classes depended on directly or
        // indirectly by android_webview_java.
        // TODO(torne): find a better way to do this, http://crbug.com/492166.
        com.android.webview.chromium.R.onResourcesLoaded(packageId);
        org.chromium.android_webview.R.onResourcesLoaded(packageId);
        org.chromium.components.web_contents_delegate_android.R.onResourcesLoaded(packageId);
        org.chromium.content.R.onResourcesLoaded(packageId);
        org.chromium.ui.R.onResourcesLoaded(packageId);
    }
}

Add missing R class to WebView resource rewriting.


package net.robobalasko.dfa.core;

import net.robobalasko.dfa.core.exceptions.MultipleStartNodesException;
import net.robobalasko.dfa.core.exceptions.NodeConnectionException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.LinkedList;

import static org.junit.Assert.*;

public class NodeConnectionStateTest {

    private NodeConnectionState nodeConnectionState;

    @Before
    public void setUp() {
        nodeConnectionState = new NodeConnectionState();
    }

    @Test
    public void testResetConnectionStateSucceeds() {
        nodeConnectionState.resetConnectionState();
        assertNull(nodeConnectionState.getStartNode());
        assertNull(nodeConnectionState.getEndNode());
        assertFalse(nodeConnectionState.isConnecting());
    }

    @Test(expected = NodeConnectionException.class)
    public void testConnectNodesFails() throws MultipleStartNodesException, NodeConnectionException {
        nodeConnectionState.connectNodes();
    }

    @Test
    public void testConnectNodesSucceeds() throws MultipleStartNodesException, NodeConnectionException {
        StateNode firstNode = new StateNode('a', false, false, new LinkedList<StateNode>(), null);
        StateNode secondNode = new StateNode('b', false, false, new LinkedList<StateNode>(), null);
        nodeConnectionState.setStartNode(firstNode);
        nodeConnectionState.setEndNode(secondNode);
        nodeConnectionState.connectNodes();
        assertEquals('a', nodeConnectionState.getStartNode().getName());
        assertEquals('b', nodeConnectionState.getEndNode().getName());
    }

    @Test
    public void testSetStartNode() {
        StateNode startNode = new StateNode('a', false, false, null, null);
        nodeConnectionState.setStartNode(startNode);
        assertEquals('a', nodeConnectionState.getStartNode().getName());
        assertTrue(nodeConnectionState.getStartNode().isActive());
        assertTrue(nodeConnectionState.isConnecting());
    }

    @Test
    public void testSetEndNode() {
        StateNode endNode = new StateNode('b', false, false, null, null);
        nodeConnectionState.setEndNode(endNode);
        assertEquals('b', nodeConnectionState.getEndNode().getName());
        assertTrue(nodeConnectionState.getEndNode().isActive());
    }

    @After
    public void tearDown() {
        nodeConnectionState = null;
    }

}

Add tests for NodeConnectionState class.


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

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import junit.framework.TestCase;

public class TikaInputStreamTest extends TestCase {

    public void testFileBased() throws IOException {
        File file = createTempFile("Hello, World!");
        InputStream stream = new TikaInputStream(file);

        assertEquals(
                "The file returned by the getFile() method should"
                + " be the file used to instantiate a TikaInputStream",
                file, TikaInputStream.get(stream).getFile());

        assertEquals(
                "The contents of the TikaInputStream should equal the"
                + " contents of the underlying file",
                "Hello, World!", readStream(stream));

        stream.close();
        assertTrue(
                "The close() method must not remove the file used to"
                + " instantiate a TikaInputStream",
                file.exists());

        file.delete();
    }

    public void testStreamBased() throws IOException {
        InputStream input =
            new ByteArrayInputStream("Hello, World!".getBytes("UTF-8"));
        InputStream stream = new TikaInputStream(input);

        File file = TikaInputStream.get(stream).getFile();
        assertTrue(file != null && file.isFile());

        assertEquals(
                "The contents of the file returned by the getFile method"
                + " should equal the contents of the TikaInputStream",
                "Hello, World!", readFile(file));

        assertEquals(
                "The contents of the TikaInputStream should not get modified"
                + " by reading the file first",
                "Hello, World!", readStream(stream));

        stream.close();
        assertFalse(
                "The close() method must remove the temporary file created"
                + " by a TikaInputStream",
                file.exists());
    }

    private File createTempFile(String data) throws IOException {
        File file = File.createTempFile("tika-", ".tmp");
        OutputStream stream = new FileOutputStream(file);
        try {
            stream.write(data.getBytes("UTF-8"));
        } finally {
            stream.close();
        }
        return file;
    }

    private String readFile(File file) throws IOException {
        InputStream stream = new FileInputStream(file);
        try {
            return readStream(stream);
        } finally {
            stream.close();
        }
    }

    private String readStream(InputStream stream) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        IOUtils.copy(stream, buffer);
        return buffer.toString("UTF-8");
    }

}

Allow passing of files or memory buffers to parsers


package info.u_team.u_team_test.init;

import net.minecraftforge.event.world.BiomeLoadingEvent;
import net.minecraftforge.eventbus.api.*;

public class TestBiomeLoadingFeatures {

	private static void biomeLoadingAddition(BiomeLoadingEvent event) {
	}

	public static void registerForge(IEventBus bus) {
		bus.addListener(EventPriority.HIGH, TestBiomeLoadingFeatures::biomeLoadingAddition);
	}

}

Add test biome loading features


package org.spoofax.interpreter.library.ssl;

import io.usethesource.capsule.Map;
import io.usethesource.capsule.Set;

import org.spoofax.interpreter.core.IContext;
import org.spoofax.interpreter.core.InterpreterException;
import org.spoofax.interpreter.library.AbstractPrimitive;
import org.spoofax.interpreter.stratego.Strategy;
import org.spoofax.interpreter.terms.IStrategoTerm;
import java.util.Iterator;

public class SSL_immutable_map_intersect_set extends AbstractPrimitive {

    protected SSL_immutable_map_intersect_set() {
        super("SSL_immutable_map_intersect_set", 1, 1);
    }

    @Override
    public boolean call(IContext env, Strategy[] sargs, IStrategoTerm[] targs)
            throws InterpreterException {
        if(!(env.current() instanceof StrategoImmutableMap)) {
            return false;
        }
        if(!(targs[0] instanceof StrategoImmutableSet)) {
            return false;
        }

        final Map.Transient<IStrategoTerm, IStrategoTerm> one = ((StrategoImmutableMap) env.current()).backingMap.asTransient();
        final Set.Immutable<IStrategoTerm> other = ((StrategoImmutableSet) targs[0]).backingSet;
        for(Iterator<IStrategoTerm> iterator = one.keyIterator(); iterator.hasNext(); ) {
            IStrategoTerm key = iterator.next();
            if(!other.contains(key)) {
                iterator.remove();
            }
        }

        env.setCurrent(new StrategoImmutableMap(one.freeze()));
        return true;
    }
}

Add map masking operation: intersecting with a set


import java.util.*;
class CoxeterElement {
    private int[] expression;
    private int rank = 0;
    private int length;

    public CoxeterElement(int[] input, int rank) {
	boolean validElement = true;

	// Check all generators are legal
	for(int i = 0; i < input.length; i++) {
	    if ((input[i] > rank) | (input[i] < 1)) {
		validElement = false;
	    }
	}

	if (validElement) {
	    this.rank = rank;
	    this.length = input.length;
	    this.expression = new int[length];
	    for(int i = 0; i < input.length; i++) {
		expression[i] = input[i];
	    }
	}
	else {
	    System.out.println("Invalid element");
	}
    }

    public Element toPermutation() {
	int[] permutation = new int[rank];
	int temp;
	int generator;
	Element answer;

	for (int i = 0; i < rank; i++) {
	    permutation[i] = i + 1;
	}
	for (int i = 0; i < length; i++) {
	    generator = expression[i];
	    if (generator > 1) {
		temp = permutation[generator - 2];
		permutation[generator - 2] = permutation[generator - 1];
		permutation[generator - 1] = temp;
	    }
	    else {
		temp = permutation[0];
		permutation[0] = -1*permutation[1];
		permutation[1] = -1*temp;
	    }
	}
	answer = new Element(permutation);
	return answer;
    }

}

Add class to deal with expressions in terms of generators


/*
 * Java Genetic Algorithm Library (@__identifier__@).
 * Copyright (c) @__year__@ Franz Wilhelmstötter
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Author:
 *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
 */
package org.jenetics.example;

/**
 * @author Franz Wilhelmstötter
 * @version !__version__!
 * @since !__version__!
 */
public class Springsteen {
}

Implement a variation of the Knapsack problem.


package com.papier.jurani;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/**
 * Created by Angellica on 3/23/2016.
 */
public class ChosenTargetActivity extends AppCompatActivity {

    private String chosenPlayer;
    private String chosenTask;
    private String chosenTarget;
    private TextView thePlayer;
    private TextView theTask;
    private TextView theTarget;
    private Button repeatGame;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chosen_target);
        Toolbar toolbar = (Toolbar) findViewById(R.id.chosen_target_toolbar);
        setSupportActionBar(toolbar);

        chosenPlayer = getIntent().getExtras().getString("player");
        chosenTask = getIntent().getExtras().getString("task");
        chosenTarget = getIntent().getExtras().getString("target");

        thePlayer = (TextView) findViewById(R.id.player_text);
        thePlayer.setText(chosenPlayer);

        theTask = (TextView) findViewById(R.id.task_text);
        theTask.setText(chosenTask);

        theTarget = (TextView) findViewById(R.id.chosen_target);
        theTarget.setText(chosenTarget);

        repeatGame = (Button) findViewById(R.id.repeat_game_button);
        repeatGame.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
}

Add new activity: chosen target activity.


package imagej.core.tools.global;

import imagej.ImageJ;
import imagej.ext.display.event.input.KyPressedEvent;
import imagej.ext.module.ModuleInfo;
import imagej.ext.module.ModuleService;
import imagej.ext.tool.AbstractTool;
import imagej.ext.tool.Tool;
import imagej.util.Log;

@Tool(name = "Keyboard Shortcuts", global = true, priority = Integer.MIN_VALUE)
public class AcceleratorHandler extends AbstractTool {

	private final ModuleService moduleService;

	public AcceleratorHandler() {
		moduleService = ImageJ.get(ModuleService.class);
	}

	@Override
	public boolean onKeyDown(final KyPressedEvent evt) {
		// TODO: enquire the OptionService whether the Control modifier should be
		// forced
		final ModuleInfo moduleInfo =
			moduleService.getModuleForAccelerator(evt.getAcceleratorString(true));
		if (moduleInfo == null) return false;
		moduleService.run(moduleInfo);
		return true;
	}
}

Add a global tool that handles accelerators in image windows


/*******************************************************************************
 * This file is part of OpenNMS(R).
 *
 * Copyright (C) 2012-2016 The OpenNMS Group, Inc.
 * OpenNMS(R) is Copyright (C) 1999-2016 The OpenNMS Group, Inc.
 *
 * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
 *
 * OpenNMS(R) is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * OpenNMS(R) is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with OpenNMS(R).  If not, see:
 *      http://www.gnu.org/licenses/
 *
 * For more information contact:
 *     OpenNMS(R) Licensing <license@opennms.org>
 *     http://www.opennms.org/
 *     http://www.opennms.com/
 *******************************************************************************/

package org.opennms.features.topology.plugins.topo.bsm;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class ReductionKeyVertexTest {

    @Test
    public void canGetLabelFromReductionKey() {
        assertEquals("nodeDown:10", ReductionKeyVertex.getLabelFromReductionKey("uei.opennms.org/nodes/nodeDown::10"));
        assertEquals("nodeLostService:DNS", ReductionKeyVertex.getLabelFromReductionKey("uei.opennms.org/nodes/nodeLostService::9:2600:5800:f2a2:0000:02d0:b7ff:fe25:3e1c:DNS"));
        assertEquals("dataCollectionFailed:48", ReductionKeyVertex.getLabelFromReductionKey("uei.opennms.org/nodes/dataCollectionFailed::48"));
        assertEquals("this_is_a_really_long_re", ReductionKeyVertex.getLabelFromReductionKey("this_is_a_really_long_reduction_key_that_shouldnt_match_the_know_pattern"));
    }
}

Add test to validate the getLabelFromReductionKey() function.


/*
 * Copyright (c) 2017 3TUSK, Seraph-JACK, yesterday17, et al.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

package info.tritusk.mooncakecraft.crafting;

import com.google.gson.JsonObject;
import net.minecraft.init.Items;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.item.crafting.ShapelessRecipes;
import net.minecraft.util.NonNullList;
import net.minecraftforge.common.crafting.IRecipeFactory;
import net.minecraftforge.common.crafting.JsonContext;
import net.minecraftforge.oredict.ShapelessOreRecipe;

public class RemainBottleRecipeFactory implements IRecipeFactory{

    @Override
    public IRecipe parse(JsonContext context, JsonObject json) {
        ShapelessOreRecipe recipe = ShapelessOreRecipe.factory(context, json);

        return new RemainBottleRecipe("mooncakecraft:remain_bottle", recipe.getRecipeOutput(), recipe.getIngredients());
    }

    public static class RemainBottleRecipe extends ShapelessRecipes {
        public RemainBottleRecipe(String group, ItemStack output, NonNullList<Ingredient> ingredients) {
            super(group, output, ingredients);
        }

        @Override
        public NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv)
        {
            NonNullList<ItemStack> nonnulllist = NonNullList.<ItemStack>withSize(inv.getSizeInventory(), ItemStack.EMPTY);

            for (int i = 0; i < nonnulllist.size(); ++i)
            {
                ItemStack itemstack = inv.getStackInSlot(i);

                if(itemstack.isItemEqual(new ItemStack(Items.POTIONITEM))) {
                    nonnulllist.set(i, new ItemStack(Items.GLASS_BOTTLE, 1));
                    continue;
                }

                nonnulllist.set(i, net.minecraftforge.common.ForgeHooks.getContainerItem(itemstack));
            }

            return nonnulllist;
        }
    }
}

Remove IRecipe and uses IRecipeFactory & Recipe files instead.


package org.apache.logging.log4j.core.config;

import java.util.Comparator;

import org.apache.logging.log4j.core.util.Assert;

/**
 * Comparator for classes annotated with {@link Order}.
 *
 * @since 2.1
 */
public class OrderComparator implements Comparator<Class<?>> {
    @Override
    public int compare(final Class<?> lhs, final Class<?> rhs) {
        final Order lhsOrder = Assert.requireNonNull(lhs, "lhs").getAnnotation(Order.class);
        final Order rhsOrder = Assert.requireNonNull(rhs, "rhs").getAnnotation(Order.class);
        if (lhsOrder == null && rhsOrder == null) {
            // both unannotated means we can't really compare them
            return 0;
        }
        // if only one class is @Order-annotated, then prefer that one
        if (rhsOrder == null) {
            return -1;
        }
        if (lhsOrder == null) {
            return 1;
        }
        // larger value means higher priority
        return Integer.signum(rhsOrder.value() - lhsOrder.value());
    }
}

Add Comparator for @Order-annotated classes.


package de.asw.courses.web2016.demo.backend.servlet.introspect;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/introspect/*")
public class HttpRequestIntrospectionServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		String httpMethod = req.getMethod();
		String requestUri = req.getRequestURI();

		String queryString = req.getQueryString();

		PrintWriter out = resp.getWriter();

		out.println("Request");
		out.printf("%s %s?%s%n", httpMethod, requestUri, queryString);
		out.println();

		out.println("Headers");
		for (String headerName : Collections.list(req.getHeaderNames())) {
			String headerValue = req.getHeader(headerName);
			out.printf("%s %s%n", headerName, headerValue);
		}
		out.println();

		out.println("Parameters");
		for (String parameterName : Collections.list(req.getParameterNames())) { // req.getParameterMap()
			String parameterValue = Arrays.toString(req.getParameterValues(parameterName));
			out.printf("%s %s%n", parameterName, parameterValue);
		}
		out.println();

		out.println("Request Body");
		try (Scanner scanner = new Scanner(req.getReader())) {
			while (scanner.hasNextLine()) {
				System.out.println(scanner.nextLine());
			}
		}
	}
}

Add example for http servlet request introspection


package at.ac.tuwien.inso.method_security_tests;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import at.ac.tuwien.inso.service.TagService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@SpringBootTest
@ActiveProfiles("test")
@Transactional
public class TagServiceSecurityTests {

    @Autowired
    private TagService tagService;

    @Test(expected = AuthenticationCredentialsNotFoundException.class)
    public void searchForSubjectsNotAuthenticated() {
        tagService.findAll();
    }

    @Test
    @WithMockUser
    public void searchForSubjectsAuthenticated() {
        tagService.findAll();
    }
}

Add tests for TagService method security


/* ********************************************************************
    Licensed to Jasig under one or more contributor license
    agreements. See the NOTICE file distributed with this work
    for additional information regarding copyright ownership.
    Jasig licenses this file to you under the Apache License,
    Version 2.0 (the "License"); you may not use this file
    except in compliance with the License. You may obtain a
    copy of the License at:

    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.bedework.util.elasticsearch;

import org.bedework.util.jmx.ConfBaseMBean;

/** Parameters for interactiosn with elastic search
 *
 * @author douglm
 *
 */
public interface EsCtlMBean extends ConfBaseMBean, IndexProperties {
  String serviceName = "org.bedework:service=esctl";

  /**
   * @return list of indexes maintained by indexer.
   */
  String listIndexes();
}

Fix up case of name


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

/* $Id$ */

package org.apache.xmlgraphics.ps.dsc.events;

import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;

import junit.framework.TestCase;

import org.apache.xmlgraphics.ps.dsc.DSCCommentFactory;

public class DSCCommentBoundingBoxTestCase extends TestCase {

    public void testBoundingBox() throws Exception {
        DSCComment comment = DSCCommentFactory.createDSCCommentFor("BoundingBox");
        DSCCommentBoundingBox bbox = (DSCCommentBoundingBox)comment;
        bbox.parseValue("289 412 306 429");
        Rectangle refRect = new Rectangle(289, 412, 306 - 289, 429 - 412);
        assertEquals(refRect, bbox.getBoundingBox());

        comment = DSCCommentFactory.createDSCCommentFor("BoundingBox");
        bbox = (DSCCommentBoundingBox)comment;
        bbox.parseValue("289.12 412.2 306.777 429.11");
        Rectangle2D refRect2D = new Rectangle2D.Double(
                289.12, 412.2, 306.777 - 289.12, 429.11 - 412.2);
        assertEquals(refRect2D, bbox.getBoundingBox());

        comment = DSCCommentFactory.createDSCCommentFor("HiResBoundingBox");
        bbox = (DSCCommentHiResBoundingBox)comment;
        bbox.parseValue("289.12 412.2 306.777 429.11");
        refRect2D = new Rectangle2D.Double(
                289.12, 412.2, 306.777 - 289.12, 429.11 - 412.2);
        assertEquals(refRect2D, bbox.getBoundingBox());
    }

}

Test case for the BoundingBox implementation.


package dev.codefoundry.string;

public class DeleteCharsToEqualizeStrings {
	public int solve(String a, String b) {
        int[][] dp = new int[a.length() + 1][b.length() + 1];

        for (int i = 0; i <= a.length(); i++) {
            for (int j = 0; j <= b.length(); j++) {
                if (i == 0 || j == 0) {
                    dp[i][j] = i + j;
                } else if (a.charAt(i - 1) == b.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    dp[i][j] = 1 + Math.min(dp[i][j - 1], dp[i - 1][j]);
                }
            }
        }

        return dp[a.length()][b.length()];
    }

	public static void main(String[] args) {
		System.out.println(new DeleteCharsToEqualizeStrings().solve("a", "bb"));
	}
}

Delete Chars to equalize strings


/*
 * $Id$
 */

/*

 Copyright (c) 2000-2016 Board of Trustees of Leland Stanford Jr. University,
 all rights reserved.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 STANFORD UNIVERSITY 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.

 Except as contained in this notice, the name of Stanford University shall not
 be used in advertising or otherwise to promote the sale, use or other dealings
 in this Software without prior written authorization from Stanford University.

 */

package org.lockss.plugin.highwire;

import org.lockss.filter.pdf.ExtractingPdfFilterFactory;
import org.lockss.pdf.*;
import org.lockss.plugin.ArchivalUnit;
import org.lockss.util.Logger;

/**
 * A pdf filter that handles the more challenging PDFs of child plugins where pdfplus
 * files have non-substantive changes (annotation uris, ordering, etc). In this
 * case scrape out the content text for comparison.
 * This code modified from BaseAtyponScrapingPdfFilterFactory  @author alexohlson
 *
 */
public class HighWireDrupalScrapingPdfFilterFactory extends ExtractingPdfFilterFactory {

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

  /*
   * Many pdf files have the CreationDate and ModDate and the two ID numbers in the trailer
   * vary from collection to collection. Filter them out to avoid incorrect hash failures.
   * This is a scraping filter to it also returns just the actual pdf content and not the layout.
   */
  @Override
  public void transform(ArchivalUnit au, PdfDocument pdfDocument)
      throws PdfException {

    pdfDocument.unsetCreationDate();
    pdfDocument.unsetModificationDate();
    pdfDocument.unsetMetadata();
    pdfDocument.unsetCreator();
    pdfDocument.unsetProducer();
    pdfDocument.unsetAuthor();
    pdfDocument.unsetTitle();
    pdfDocument.unsetSubject();
    pdfDocument.unsetKeywords();
    PdfUtil.normalizeTrailerId(pdfDocument);
    PdfUtil.normalizeAllTokenStreams(pdfDocument);
  }
}

Use Drupal PDF hash filter


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

package info.avalon566.shardingscaling.sync.mysql.binlog.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import org.junit.Before;
import org.junit.Test;
import java.math.BigDecimal;

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

public class DecimalValueDecoderTest {

    private int meta;

    @Before
    public void setUp() {
        meta = 14 << 8;
        meta += 4;
    }

    @Test
    public void assertDecodePositiveNewDecimal() {
        byte[] newDecimalBytes = ByteBufUtil.decodeHexDump("810DFB38D204D2");
        ByteBuf newDecimalByteBuf = Unpooled.buffer(newDecimalBytes.length);
        newDecimalByteBuf.writeBytes(newDecimalBytes);
        BigDecimal actual = (BigDecimal) DecimalValueDecoder.decodeNewDecimal(meta, newDecimalByteBuf);
        assertThat(actual.toString(), is("1234567890.1234"));
    }

    @Test
    public void assertDecodeNegativeNewDecimal() {
        byte[] newDecimalBytes = ByteBufUtil.decodeHexDump("7EF204C72DFB2D");
        ByteBuf newDecimalByteBuf = Unpooled.buffer(newDecimalBytes.length);
        newDecimalByteBuf.writeBytes(newDecimalBytes);
        BigDecimal actual = (BigDecimal) DecimalValueDecoder.decodeNewDecimal(meta, newDecimalByteBuf);
        assertThat(actual.toString(), is("-1234567890.1234"));
    }
}

Add unit test for DecimalValueDecoder


/**
 *
 * Copyright 2021 Florian Schmaus
 *
 * 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.jivesoftware.smackx.jingle.element;

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

import org.jivesoftware.smack.packet.StreamOpen;

import org.junit.jupiter.api.Test;

public class JingleTest {

    @Test
    public void noRedundantNamespaceTest() {
        Jingle.Builder jingleBuilder = Jingle.builder("test-id");
        jingleBuilder.setSessionId("MySession");
        jingleBuilder.setAction(JingleAction.content_accept);

        JingleContent.Builder jingleContentBuilder = JingleContent.getBuilder();
        jingleContentBuilder.setName("Hello world");
        jingleContentBuilder.setCreator(JingleContent.Creator.initiator);

        jingleBuilder.addJingleContent(jingleContentBuilder.build());
        Jingle iq = jingleBuilder.build();

        String actualXml = iq.toXML(StreamOpen.CLIENT_NAMESPACE).toString();
        String expectedXml
                        = "<iq id='test-id' type='set'>"
                        + "<jingle xmlns='urn:xmpp:jingle:1' action='content-accept' sid='MySession'>"
                        + "<content creator='initiator' name='Hello world'/>"
                        + "</jingle></iq>";
        assertEquals(expectedXml, actualXml);
    }
}

Add unit test to check that there are no redundant namespaces


package de.fu_berlin.agdb.crepe.rest.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * A REST controller to serve data about the available locations
 * and allow the user to add new ones.
 */
@RestController
@RequestMapping("/locations")
public class LocationMetaDataController {

}

Add REST controller for new database schema


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

import org.apache.jackrabbit.oak.plugins.document.util.Utils;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;

import static org.junit.Assert.assertNull;

@Ignore
public class UpdateLimitTest {

    @Rule
    public DocumentMKBuilderProvider builderProvider = new DocumentMKBuilderProvider();

    private DocumentNodeStore ns;
    private DocumentStore store;
    private String testId;

    @Before
    public void before() {
        ns = builderProvider.newBuilder().getNodeStore();
        store = ns.getDocumentStore();
        testId = Utils.getIdFromPath("/test");
    }

    @Test
    public void rebase() throws Exception {
        NodeBuilder builder = someChanges(ns.getRoot().builder());
        for (int i = 0; i < 20; i++) {
            ns.rebase(builder);
            assertNull(store.find(Collection.NODES, testId));
        }
    }

    @Test
    public void reset() {
        NodeBuilder builder = someChanges(ns.getRoot().builder());
        for (int i = 0; i < 20; i++) {
            ns.reset(builder);
            someChanges(builder);
            assertNull(store.find(Collection.NODES, testId));
        }
    }

    private NodeBuilder someChanges(NodeBuilder root) {
        NodeBuilder test = root.child("test");
        for (int i = 0; i < 23; i++) {
            test.child("node-" + i);
        }
        return root;
    }
}

Update count increases with rebase


package de.terrestris.shogun2.service;

import de.terrestris.shogun2.dao.UserGroupDao;
import de.terrestris.shogun2.model.UserGroup;

public class UserGroupServiceTest extends
		AbstractSecuredPersistentObjectServiceTest<UserGroup, UserGroupDao<UserGroup>, UserGroupService<UserGroup, UserGroupDao<UserGroup>>> {

	/**
	 *
	 * @throws Exception
	 */
	public void setUpImplToTest() throws Exception {
		implToTest = new UserGroup();
	}

	@Override
	protected UserGroupService<UserGroup, UserGroupDao<UserGroup>> getCrudService() {
		return new UserGroupService<UserGroup, UserGroupDao<UserGroup>>();
	}

	@SuppressWarnings("unchecked")
	@Override
	protected Class<UserGroupDao<UserGroup>> getDaoClass() {
		return (Class<UserGroupDao<UserGroup>>) new UserGroupDao<UserGroup>().getClass();
	}

}

Add a test class for the UserGroupService


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

package org.opendaylight.ovsdb.openstack.netvirt;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

import java.net.HttpURLConnection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.opendaylight.neutron.spi.NeutronFloatingIP;
import org.opendaylight.ovsdb.openstack.netvirt.api.Action;
import org.opendaylight.ovsdb.openstack.netvirt.impl.NeutronL3Adapter;

/**
 * Unit test for {@link FloatingIPHandler}
 */
@RunWith(MockitoJUnitRunner.class)
public class FloatingIPHandlerTest {

    @InjectMocks private FloatingIPHandler floatingHandler = mock(FloatingIPHandler.class, Mockito.CALLS_REAL_METHODS);
    @InjectMocks private NeutronL3Adapter neutronL3Adapter = mock(NeutronL3Adapter.class);

    @Test
    public void testCanCreateFloatingIP(){
        assertEquals("Error, did not return the correct HTTP status code", HttpURLConnection.HTTP_OK, floatingHandler.canCreateFloatingIP(mock(NeutronFloatingIP.class)));
    }

    @Test
    public void testCanUpdateFloatingIP(){
        assertEquals("Error, did not return the correct HTTP status code", HttpURLConnection.HTTP_OK, floatingHandler.canUpdateFloatingIP(mock(NeutronFloatingIP.class), mock(NeutronFloatingIP.class)));
    }

    @Test
    public void testCanDeleteFloatingIP(){
        assertEquals("Error, did not return the correct HTTP status code", HttpURLConnection.HTTP_OK, floatingHandler.canDeleteFloatingIP(mock(NeutronFloatingIP.class)));
    }

    @Test
    public void testProcessEvent(){
        NorthboundEvent ev = mock(NorthboundEvent.class);

        when(ev.getNeutronFloatingIP()).thenReturn(mock(NeutronFloatingIP.class));
        when(ev.getAction()).thenReturn(Action.UPDATE);

        verifyNoMoreInteractions(neutronL3Adapter);

        floatingHandler.processEvent((AbstractEvent) ev);

        verify(neutronL3Adapter, times(1)).handleNeutronFloatingIPEvent(ev.getNeutronFloatingIP(), ev.getAction());;

        when(ev.getAction()).thenReturn(Action.ADD);
        verify(neutronL3Adapter, times(0)).handleNeutronFloatingIPEvent(ev.getNeutronFloatingIP(), ev.getAction());;

        when(ev.getAction()).thenReturn(Action.DELETE);
        verify(neutronL3Adapter, times(0)).handleNeutronFloatingIPEvent(ev.getNeutronFloatingIP(), ev.getAction());;
    }
}

Add JUnit testing for FloatingIPHandler class.


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

package io.michaelrocks.libphonenumber.android;

import java.io.InputStream;

class ResourceMetadataLoader implements MetadataLoader {
  private final Class<?> loaderClass;

  public ResourceMetadataLoader() {
    this(ResourceMetadataLoader.class);
  }

  public ResourceMetadataLoader(Class<?> loaderClass) {
    this.loaderClass = loaderClass;
  }

  @Override
  public InputStream loadMetadata(String metadataFileName) {
    return loaderClass.getResourceAsStream(metadataFileName);
  }
}

Implement a metadata loader that loads data from resources


package org.metaborg.core.project;

import java.util.Map;
import java.util.concurrent.ConcurrentMap;

import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.metaborg.core.config.ConfigRequest;
import org.metaborg.core.config.IProjectConfig;
import org.metaborg.core.config.IProjectConfigService;
import org.metaborg.core.messages.StreamMessagePrinter;
import org.metaborg.core.source.ISourceTextService;
import org.metaborg.util.log.ILogger;
import org.metaborg.util.log.LoggerUtils;

import com.google.common.collect.Maps;
import com.google.inject.Inject;

public class ConfigBasedProjectService implements IProjectService {
    private static final ILogger logger = LoggerUtils.logger(ConfigBasedProjectService.class);

    private final ConcurrentMap<FileName, IProject> projects = Maps.newConcurrentMap();

    private final ISourceTextService sourceTextService;
    private final IProjectConfigService projectConfigService;

    @Inject public ConfigBasedProjectService(ISourceTextService sourceTextService,
        IProjectConfigService projectConfigService) {
        this.sourceTextService = sourceTextService;
        this.projectConfigService = projectConfigService;
    }

    @Override public IProject get(FileObject resource) {
        IProject project = getProject(resource);
        if(project == null) {
            project = findProject(resource);
        }
        return project;
    }

    private IProject getProject(FileObject resource) {
        for(Map.Entry<FileName,IProject> entry : projects.entrySet()) {
            if(resource.getName().isAncestor(entry.getKey())) {
                return entry.getValue();
            }
        }
        return null;
    }

    private IProject findProject(FileObject resource) {
        try {
            FileObject dir = (resource.isFolder() ? resource : resource.getParent());
            while(dir != null) {
                FileName name = dir.getName();
                if(projectConfigService.available(dir)) {
                    final ConfigRequest<IProjectConfig> configRequest = projectConfigService.get(dir);
                    if(!configRequest.valid()) {
                        logger.error("Errors occurred when retrieving project configuration from project directory {}", dir);
                        configRequest.reportErrors(new StreamMessagePrinter(sourceTextService, false, false, logger));
                    }

                    final IProject project = new Project(dir, configRequest.config());
                    IProject prevProject;
                    if((prevProject = projects.putIfAbsent(name, project)) != null) {
                        logger.warn("Project with location {} already exists", name);
                        return prevProject;
                    }
                    return project;
                }
                dir = dir.getParent();
            }
        } catch(FileSystemException e) {
            logger.error("Error while searching for project configuration.",e);
        }
        logger.warn("No project configuration file was found for {}.",resource);
        return null;
    }
}

Add project service that searches for config file.


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.


import java.util.concurrent.TimeUnit;

import model.Model;

public class GameLoop {
	private Model model;
	public GameLoop(Model model){
		this.model = model;
	}
	public void startLoop(){
		this.gameLoop();
	}
	private void gameLoop(){
		while(true){
			model.update();
			try{
			TimeUnit.MILLISECONDS.sleep(18);
			}catch(Exception e){

			}
		}
	}
}

Put the gameloop class up


/**
 * 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.
 *
 * Copyright 2012-2014 the original author or authors.
 */
package org.assertj.core.api.iterable;

import static org.assertj.core.util.Arrays.array;

import org.assertj.core.api.AbstractIterableAssert;
import org.assertj.core.api.ConcreteIterableAssert;
import org.assertj.core.api.IterableAssertBaseTest;

import static org.mockito.Mockito.verify;

/**
 * Tests for <code>{@link AbstractIterableAssert#containsSubsequence(Object[])}</code>.
 *
 * @author Harry Cummings
 */
public class IterableAssert_containsSubsequence_Test extends IterableAssertBaseTest {

  @Override
  protected ConcreteIterableAssert<Object> invoke_api_method() {
	return assertions.containsSubsequence("Luke", "Leia");
  }

  @Override
  protected void verify_internal_effects() {
	verify(iterables).assertContainsSubsequence(getInfo(assertions), getActual(assertions), array("Luke", "Leia"));
  }
}

Add tests for containsSubsequence public API method.


package com.github.ivbaranov.rxbluetooth;

import android.bluetooth.BluetoothProfile;

/**
 * Event container class.  Contains state (whether the service was just connected or
 * disconnected), profile type and {@link BluetoothProfile}. When service state is {@link
 * State#DISCONNECTED} the mBluetoothProfile is null.
 */
public class ServiceEvent {

  public enum State {
    CONNECTED,
    DISCONNECTED
  }

  private State mState;
  private int mProfileType;
  private BluetoothProfile mBluetoothProfile;

  public ServiceEvent(State state, int profileType, BluetoothProfile bluetoothProfile) {
    mState = state;
    mProfileType = profileType;
    mBluetoothProfile = bluetoothProfile;
  }

  public State getState() {
    return mState;
  }

  public int getProfileType() {
    return mProfileType;
  }

  public BluetoothProfile getBluetoothProfile() {
    return mBluetoothProfile;
  }

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

    ServiceEvent that = (ServiceEvent) o;

    if (mProfileType != that.mProfileType) return false;
    if (mState != that.mState) return false;
    return !(mBluetoothProfile != null ? !mBluetoothProfile.equals(that.mBluetoothProfile)
        : that.mBluetoothProfile != null);
  }

  @Override public int hashCode() {
    int result = mState.hashCode();
    result = 31 * result + mProfileType;
    result = 31 * result + (mBluetoothProfile != null ? mBluetoothProfile.hashCode() : 0);
    return result;
  }

  @Override public String toString() {
    return "ServiceEvent{" +
        "mState=" + mState +
        ", mProfileType=" + mProfileType +
        ", mBluetoothProfile=" + mBluetoothProfile +
        '}';
  }
}

Add service event class. It contains state, profile type and profile proxy object.


/*
  Copyright 2016, Google, Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package com.example.translate;

// [START translate_quickstart]
// Imports the Google Cloud client library
import com.google.cloud.translate.Translate;
import com.google.cloud.translate.Translate.TranslateOption;
import com.google.cloud.translate.TranslateOptions;
import com.google.cloud.translate.Translation;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    Translate translate = TranslateOptions.builder().apiKey("YOUR_API_KEY").build().service();
    // The text to translate
    String text = "Hello, world!";
    // Translates some text into Russian
    Translation translation = translate.translate(
      text,
      TranslateOption.sourceLanguage("en"),
      TranslateOption.targetLanguage("ru")
    );
    System.out.printf("Text: %s%n", text);
    System.out.printf("Translation: %s%n", translation.translatedText());
  }
}
// [END translate_quickstart]

Add Translate API quickstart sample.


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

public class Solution {

    public ListNode reverseList(ListNode head) {

        ListNode reversedList = null;

        while (head != null) {

            ListNode next = head.next;
            head.next = reversedList;
            reversedList = head;
            head = next;

        }

        return reversedList;

    }

}

Create : 206 Reverse Linked List


package leetcode.construct_binary_tree_from_preorder_and_inorder_traversal;

import common.TreeNode;

public class Solution {
	public TreeNode buildTree(int[] preorder, int[] inorder, int pre_from, int pre_to, int in_from, int in_to){
		if(in_from == in_to || pre_from == pre_to) return null;
		int rootval = preorder[pre_from];
		TreeNode root = new TreeNode(rootval);
		int rootidx;
		for(rootidx = in_from; rootidx < in_to && inorder[rootidx] != rootval; rootidx++);
		System.err.println(rootidx);
		root.left = buildTree(preorder, inorder, pre_from + 1, pre_from + 1 + (rootidx - in_from), in_from, rootidx);
		root.right = buildTree(preorder, inorder, pre_to + 1 - (in_to - rootidx), pre_to, rootidx + 1, in_to);
		return root;
	}
	public TreeNode buildTree(int[] preorder, int[] inorder) {
		if(inorder == null || preorder == null) return null;
    	return buildTree(preorder, inorder, 0, inorder.length, 0, preorder.length);
    }

    public static void inOrder(TreeNode cur){
    	if(cur != null){
    		inOrder(cur.left);
    		System.err.print(cur.val + "->");
    		inOrder(cur.right);
    	}
    }

    public static void preOrder(TreeNode cur){
    	if(cur != null){
    		System.err.print(cur.val + "->");
    		preOrder(cur.left);
    		preOrder(cur.right);
    	}
    }

    public static void main(String[] args){
    	int[] preorder = new int[]{1, 5, 4, 9, 3, 8, 6, 7};
    	int[] inorder = new int[]{4, 9, 5, 1, 8, 3, 7, 6};
    	TreeNode ret = new Solution().buildTree(preorder, inorder);
    	preOrder(ret);
    	System.err.println("");
    	inOrder(ret);
    	System.err.println("");
    }
}

Add java solution for 105. Construct Binary Tree from Preorder and Inorder Traversal


package com.thinkaurelius.titan.hadoop;

import com.thinkaurelius.titan.HBaseStorageSetup;
import com.thinkaurelius.titan.diskstorage.configuration.WriteConfiguration;
import org.apache.hadoop.hbase.util.VersionInfo;
import org.junit.AfterClass;
import org.junit.BeforeClass;

import java.io.IOException;

public class HBaseIndexManagementIT extends AbstractIndexManagementIT {

    @Override
    public WriteConfiguration getConfiguration() {
        return HBaseStorageSetup.getHBaseGraphConfiguration();
    }

    @BeforeClass
    public static void startHBase() throws IOException {
        HBaseStorageSetup.startHBase();
    }

    @AfterClass
    public static void stopHBase() {
        // Workaround for https://issues.apache.org/jira/browse/HBASE-10312
        if (VersionInfo.getVersion().startsWith("0.96"))
            HBaseStorageSetup.killIfRunning();
    }
}

Add HBase-backend MapReduce re(move)index tests


/**
 * Copyright (c) 2015-present Jorge Díaz All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */

package jorgediazest.indexchecker.model;

import jorgediazest.util.data.Data;

/**
 * @author Jorge Díaz
 */
public class DDLRecordPermissionsHelper extends IndexCheckerPermissionsHelper {

	@Override
	protected String getPermissionsClassName(Data data) {
		return "com.liferay.dynamic.data.lists.model.DDLRecordSet";
	}

	@Override
	protected long getPermissionsClassPK(Data data) {
		return data.get("recordSetId", -1L);
	}
}

Fix DDLRecord issues: due some Liferay 7 changes, all records are detected as outdated


/*******************************************************************************
 * Copyright (c) 2016 IBM Corp.
 *
 * 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.ibm.liberty.starter.it.api.v1;

import static org.junit.Assert.assertTrue;

import java.io.File;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;

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

public class MicroProfileAPIJarDownloadTest {

    @Test
    public void testRepoUrl() throws Exception {
        String url = "http://localhost:" + System.getProperty("liberty.test.port") + "/start/api/v1/repo/net/wasdev/wlp/starters/ms-builder/config/0.0.1/config-0.0.1.jar";
        Client client = ClientBuilder.newClient();
        Response response = client.target(url).request("application/zip").get();
        try {
            int responseStatus = response.getStatus();
            if (responseStatus != 200) {
                Assert.fail("Expected response status 200, instead found " + responseStatus + ". Response was " + response.readEntity(String.class));
            }
            assertTrue("Config class not found", findConfig(response));
        } finally {
            response.close();
        }

    }

    private boolean findConfig(Response resp) throws Exception {
        // Read the response into an InputStream
        InputStream entityInputStream = resp.readEntity(InputStream.class);
        // Create a new ZipInputStream from the response InputStream
        ZipInputStream zipIn = new ZipInputStream(entityInputStream);
        // This system property is being set in the liberty-starter-application/build.gradle file
        String tempDir = System.getProperty("liberty.temp.dir");
        File file = new File(tempDir + "/config.jar");
        System.out.println("Creating zip file: " + file.toString());
        file.getParentFile().mkdirs();
        ZipEntry inputEntry = null;
        boolean found = false;
        while ((inputEntry = zipIn.getNextEntry()) != null) {
            String entryName = inputEntry.getName();
            System.out.println("File: "+entryName);
            if ("org/eclipse/microprofile/config/Config.class".equals(entryName)) {
                System.out.println("Found Config.class file.");
                found = true;
            }
            zipIn.closeEntry();
        }
        zipIn.close();
        return found;
    }
}

Add integration test for jar files.


package com.test.graphs;

import com.graphs.GraphEdgeListRepresentation;

import junit.framework.TestCase;

public class TestGraphEdgeListRepresentation extends TestCase{

    public void testGraphEdgeListRepresentationOperations() {

        //Undirected graph
        GraphEdgeListRepresentation graph = new GraphEdgeListRepresentation(10, false);
        graph.addEdge(0, 1);
        graph.addEdge(0, 6);
        graph.addEdge(0, 8);
        graph.addEdge(1, 4);
        graph.addEdge(1, 6);
        graph.addEdge(1, 9);
        graph.addEdge(2, 4);
        graph.addEdge(2, 6);
        graph.addEdge(3, 4);
        graph.addEdge(3, 5);
        graph.addEdge(3, 8);
        graph.addEdge(4, 5);
        graph.addEdge(4, 9);
        graph.addEdge(7, 8);
        graph.addEdge(7, 9);
        assertEquals(15, graph.getE_Size());
        assertEquals(10, graph.getV_Size());
        assertEquals(true, graph.hasEdge(7, 8));
        assertEquals(true, graph.hasEdge(8, 7));
        assertEquals(false, graph.hasEdge(0, 5));
//        System.out.println(graph.toString());

      //Directed graph
        graph = new GraphEdgeListRepresentation(10, true);
        graph.addEdge(0, 1);
        graph.addEdge(0, 6);
        graph.addEdge(0, 8);
        graph.addEdge(1, 4);
        graph.addEdge(1, 6);
        graph.addEdge(1, 9);
        graph.addEdge(2, 4);
        graph.addEdge(2, 6);
        graph.addEdge(3, 4);
        graph.addEdge(3, 5);
        graph.addEdge(3, 8);
        graph.addEdge(4, 5);
        graph.addEdge(4, 9);
        graph.addEdge(7, 8);
        graph.addEdge(7, 9);
        assertEquals(15, graph.getE_Size());
        assertEquals(10, graph.getV_Size());
        assertEquals(true, graph.hasEdge(7, 8));
        assertEquals(false, graph.hasEdge(8, 7));
        assertEquals(false, graph.hasEdge(0, 5));
        System.out.println(graph.toString());
    }

}

Add JUnit to test the Edge list representation of graph


/*
 * Copyright 2015 Open Networking Laboratory
 *
 * 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.onosproject.vtnrsc.virtualport;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable;

import org.junit.Test;
import org.onosproject.vtnrsc.VirtualPortId;

import com.google.common.testing.EqualsTester;

/**
 * Unit tests for VirtualPortId class.
 */
public class VirtualPortIdTest {

    final VirtualPortId virtualPortId1 = VirtualPortId.portId("1");
    final VirtualPortId sameAsVirtualPortId1 = VirtualPortId.portId("1");
    final VirtualPortId virtualPortId2 = VirtualPortId.portId("2");

    /**
     * Checks that the VirtualPortId class is immutable.
     */
    @Test
    public void testImmutability() {
        assertThatClassIsImmutable(VirtualPortId.class);
    }

    /**
     * Checks the operation of equals().
     */
    @Test
    public void testEquals() {
        new EqualsTester().addEqualityGroup(virtualPortId1, sameAsVirtualPortId1)
                .addEqualityGroup(virtualPortId2).testEquals();
    }

    /**
     * Checks the construction of a VirtualPortId object.
     */
    @Test
    public void testConstruction() {
        final String vPortIdValue = "aaa";
        final VirtualPortId virtualPortId = VirtualPortId.portId(vPortIdValue);
        assertThat(virtualPortId, is(notNullValue()));
        assertThat(virtualPortId.portId(), is(vPortIdValue));

    }
}

Add the junit test code of VirtualPortId


package learntocode.javaapi.io_and_nio.nio;

import java.nio.file.Files;
import java.nio.file.Path;

/**
 * Show some methods
 */
public class FileParameters {
    public static void main(String[] args) {
        Path path = FilesCreatorNIO.createFiles()[0];

        checkAndPrint("Writable", Files::isWritable, path);
        checkAndPrint("Readable", Files::isReadable, path);
        checkAndPrint("Executable", Files::isExecutable, path);
        checkAndPrint("Symbolic Link", Files::isSymbolicLink, path);
        checkAndPrint("Regular file", Files::isRegularFile, path);
        checkAndPrint("Directory", Files::isDirectory, path);
    }

    private static void checkAndPrint(String checkName, BooleanByPathFuncInterface function, Path p) {
        if (function.check(p))
            System.out.println("File IS " + checkName );
        else
            System.out.println("File IS NOT " + checkName);
    }

    private interface BooleanByPathFuncInterface {
        boolean check(Path p);
    }
}

Add file parameters checker to show, what you can get with NIO


package org.verapdf.model.impl.pb.pd;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.verapdf.model.baselayer.Object;
import org.verapdf.model.impl.BaseTest;
import org.verapdf.model.pdlayer.PDAcroForm;

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

/**
 * @author Evgeniy Muravitskiy
 */
public class PBoxPDAcroFormTest extends BaseTest {

	public static final String FILE_RELATIVE_PATH = "pd/InteractiveObjects.pdf";

	@BeforeClass
	public static void setUp() throws URISyntaxException, IOException {
		expectedType = PBoxPDAcroForm.ACRO_FORM_TYPE;
		expectedID = null;

		setUp(FILE_RELATIVE_PATH);
		actual = new PBoxPDAcroForm(document.getDocumentCatalog().getAcroForm());
	}

	@Test
	public void testNeedAppearancesMethod() {
		Assert.assertFalse(((PDAcroForm) actual).getNeedAppearances());
	}

	@Test
	public void testFormFieldLink() {
		List<? extends Object> formFields = actual.getLinkedObjects(PBoxPDAcroForm.FORM_FIELDS);
		Assert.assertEquals(1, formFields.size());
		for (Object object : formFields) {
			Assert.assertEquals(PBoxPDFormField.FORM_FIELD_TYPE, object.getType());
		}
	}

	@AfterClass
	public static void tearDown() throws IOException {
		expectedType = null;
		expectedID = null;
		actual = null;

		document.close();
	}
}

Add test for acro forms


/*
 Copyright (C) 2010 EBI, GRL

 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package org.ensembl.healthcheck.testcase.generic;

import java.sql.Connection;

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

/**
 * Check that only genes have projected xrefs.
 */

public class ProjectedXrefGenes extends SingleDatabaseTestCase {

    /**
     * Constructor.
     */
    public ProjectedXrefGenes() {

        addToGroup("post_genebuild");
        addToGroup("release");
        setDescription("Check that only genes have projected xrefs");
        setTeamResponsible("Core");

    }

    /**
     * Run the test for each database.
     * @param dbre The database to check.
     * @return Result.
     */
    public boolean run(DatabaseRegistryEntry dbre) {

        boolean result = true;

        Connection con = dbre.getConnection();

    			String sql = "SELECT COUNT(*) FROM external_db e, xref x, object_xref ox, transcript t WHERE e.external_db_id=x.external_db_id AND x.xref_id=ox.xref_id AND ox.ensembl_object_type='Transcript' AND ox.ensembl_id=t.transcript_id AND x.info_type='PROJECTION'";

    			int rows = getRowCount(con, sql);

    			if (rows > 0) {

    				ReportManager.problem(this, con, "There are " + rows + " projected xrefs linked to transcripts however only genes and translations should have them.");
    				result = false;

    			} else {

    				ReportManager.correct(this, con, "No projected xrefs associated with transcripts");

    			}

        return result;
    }

} // ProjectedXrefGenes


/**
 * IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
 *
 * http://izpack.org/
 * http://izpack.codehaus.org/
 *
 * Copyright 2003 Jonathan Halliday
 *
 * 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.izforge.izpack.panels.imgpacks;

import com.izforge.izpack.panels.packs.PacksPanelConsole;

/**
 * A Console implementation for ImgPacksPanel. Behaves exactly like the
 * {@link PacksPanelConsole}
 *
 * @author Polane Ramothea
 *
 */
public final class ImgPacksPanelConsole extends PacksPanelConsole {

	/**
	 *
	 */
	public ImgPacksPanelConsole() {
		super();
	}

}

Create a Console for Img Packs Panel


package com.codenvy.ide.ext.datasource.client.explorer;

import com.google.gwt.i18n.client.Constants;

public interface DatasourceExplorerConstants extends Constants {

    @DefaultStringValue("Explore")
    String exploreButtonLabel();
}

Add constants interface for the explorer


package edu.northwestern.bioinformatics.studycalendar.dao;

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

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

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

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


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

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;

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

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {RefreshScopeNullBeanIntegrationTests.TestConfiguration.class})
public class RefreshScopeNullBeanIntegrationTests {

	@Autowired
	private MyCustomComponent myCustomComponent;

	@Autowired
	private org.springframework.cloud.context.scope.refresh.RefreshScope scope;

	@Test
	@DirtiesContext
	public void testRefreshBean() {
		assertThat(this.myCustomComponent).isNotNull();
		// ...and then refresh, so the bean is re-initialized:
		// this.scope.refreshAll();
	}

	protected static class OptionalService { }

	public static class MyCustomComponent {

		private final OptionalService optionalService;

		public MyCustomComponent(OptionalService optionalService) {
			this.optionalService = optionalService;
		}
	}

	@Configuration
	protected static class OptionalConfiguration {

		@Bean
		@RefreshScope
		public OptionalService service() {
			return null;
		}
	}

	@Configuration
	@Import({ RefreshAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, OptionalConfiguration.class })
	protected static class TestConfiguration {

		@Autowired(required = false)
		private OptionalService optionalService;

		@Bean
		public MyCustomComponent myCustomComponent() {
			return new MyCustomComponent(optionalService);
		}
	}

}

Test for NPE when calling getClass() in RefreshScope