/*
 * Copyright 2017 Open mHealth
 *
 * 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.openmhealth.shim.googlefit.mapper;

import com.fasterxml.jackson.databind.JsonNode;
import org.openmhealth.schema.domain.omh.DataPoint;
import org.openmhealth.schema.domain.omh.Geoposition;

import java.util.Optional;

import static org.openmhealth.schema.domain.omh.LengthUnit.METER;
import static org.openmhealth.schema.domain.omh.PlaneAngleUnit.DEGREE_OF_ARC;
import static org.openmhealth.shim.common.mapper.JsonNodeMappingSupport.*;

/**
 * A mapper from Google Fit "merged location samples" endpoint responses (derived:com.google.location.sample:com.google.android.gms:merge_location_samples)
 * to {@link Geoposition} objects.
 *
 * @author Emerson Farrugia
 * @see Google Fit Data Type Documentation
 */
public class GoogleFitGeopositionDataPointMapper extends GoogleFitDataPointMapper<Geoposition> {

    @Override
    protected Optional<DataPoint<Geoposition>> asDataPoint(JsonNode listNode) {

        JsonNode listValueNode = asRequiredNode(listNode, "value");
        double latitude = asRequiredDouble(listValueNode.get(0), "fpVal");
        double longitude = asRequiredDouble(listValueNode.get(1), "fpVal");
        // TODO add accuracy to geoposition
        Optional<Double> accuracyInM = asOptionalDouble(listValueNode.get(2), "fpVal");
        Optional<Double> altitudeInM = asOptionalDouble(listValueNode.get(3), "fpVal");

        Geoposition.Builder measureBuilder =
                new Geoposition.Builder(
                        DEGREE_OF_ARC.newUnitValue(latitude),
                        DEGREE_OF_ARC.newUnitValue(longitude),
                        getTimeFrame(listNode));

        altitudeInM.ifPresent((a) -> measureBuilder.setElevation(METER.newUnitValue(a)));

        Geoposition geoposition = measureBuilder.build();

        Optional<String> originDataSourceId = asOptionalString(listNode, "originDataSourceId");

        return Optional.of(newDataPoint(geoposition, originDataSourceId.orElse(null)));
    }
}

Add Google Fit geoposition mapper


/*
 Copyright (C) 2003 EBI, GRL

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

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

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

import java.sql.Connection;

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

/**
 * Check for any xref.info_type that are blank ('') - they should be NULL for various other things to work.
 */

public class BlankInfoType extends SingleDatabaseTestCase {

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

		addToGroup("post_genebuild");
		addToGroup("release");
		setDescription("Check for any xref.info_type that are blank ('') - they should be NULL for various other things to work.");

	}

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

		boolean result = true;

		Connection con = dbre.getConnection();

		int rows = getRowCount(con, "SELECT COUNT(*) FROM xref WHERE info_type = ''");

		if (rows > 0) {

			ReportManager.problem(this, con, rows + " rows in xref have a blank info_type - should be set to null");
			result = false;

		} else {

			ReportManager.correct(this, con, "No blank info_types in xref");

		}

		return result;

	} // run

} // BlankInfoType


package org.springframework.data.datastore.repository;

import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
import static org.junit.Assert.assertThat;

import java.util.Arrays;

import org.junit.Test;

import com.google.cloud.datastore.PathElement;

public class ContextTest {
    @Test
    public void testWith1() {
        // Exercise
        try (Context ctx = Context.with(Arrays.asList(
                PathElement.of("Kind", 1)))) {
            // Verify
            assertThat(Context.getAncestors(), contains(
                PathElement.of("Kind", 1)));
        }
    }

    @Test
    public void testWith2() {
        // Exercise
        try (Context ctx = Context.with(Arrays.asList(
                PathElement.of("Kind", 1),
                PathElement.of("Kind", 2)))) {
            // Verify
            assertThat(Context.getAncestors(), contains(
                PathElement.of("Kind", 1),
                PathElement.of("Kind", 2)));
        }
    }

    @Test
    public void testWithVararg1() {
        // Exercise
        try (Context ctx = Context.with(
                PathElement.of("Kind", 1))) {
            // Verify
            assertThat(Context.getAncestors(), contains(
                PathElement.of("Kind", 1)));
        }
    }

    @Test
    public void testWithVararg2() {
        // Exercise
        try (Context ctx = Context.with(
                PathElement.of("Kind", 1),
                PathElement.of("Kind", 2))) {
            // Verify
            assertThat(Context.getAncestors(), contains(
                PathElement.of("Kind", 1),
                PathElement.of("Kind", 2)));
        }
    }

    @Test
    public void testClose1() {
        // Setup, Exercise
        try (Context ctx = Context.with(
                PathElement.of("Kind", 1))) {
        }

        // Verify
        assertThat(Context.getAncestors(), empty());
    }

    @Test
    public void testClose2() {
        // Setup, Exercise
        try (Context ctx = Context.with(
                PathElement.of("Kind", 1),
                PathElement.of("Kind", 1))) {
        }

        // Verify
        assertThat(Context.getAncestors(), empty());
    }
}

Add tests for Context class


package org.knowm.xchange.service.trade.params;

import org.knowm.xchange.currency.CurrencyPair;

public class DefaultCancelOrderByPairAndIfParams implements CancelOrderByIdParams, CancelOrderByCurrencyPair {

	private CurrencyPair currencyPair;
	private String orderId;

	public DefaultCancelOrderByPairAndIfParams(CurrencyPair currencyPair, String orderId) {
		this.currencyPair = currencyPair;
		this.orderId = orderId;
	}

	public void setCurrencyPair(CurrencyPair pair) {
		this.currencyPair = pair;
	}

	public void setOrderId(String orderId) {
		this.orderId = orderId;
	}

	@Override
	public CurrencyPair getCurrencyPair() {
		return currencyPair;
	}

	@Override
	public String getOrderId() {
		return orderId;
	}
}

Add DefaultCancelOrder with pair and id params


package npe;

public class CheckATHROW {
	public void doNotReport(Throwable obj) throws Throwable {
		throw obj;
	}

	public void throwNullValueReport(boolean b) throws Throwable {

		Throwable t = null;

		if (b) {
			System.out.println("Yeah");
		}

		throw t;
	}

	public void throwPossiblyNullReport(Throwable t) throws Throwable {
		if (t != null) {
			System.out.println("ok");
		}

		throw t;
	}
}

Test that ATHROW instructions are assumed to have a null check.


package com.oriordank;

import com.oriordank.plist.MapDbPListStore;
import org.apache.activemq.broker.Broker;
import org.apache.activemq.broker.BrokerPlugin;

public class MapDbBrokerPlugin implements BrokerPlugin {
    @Override
    public Broker installPlugin(Broker broker) throws Exception {
        broker.getBrokerService().setTempDataStore(new MapDbPListStore());
        return broker;
    }
}

Add option of configuring using <plugins>


/*
 * Copyright (C) 2011 0xlab - http://0xlab.org/
 *
 * 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.
 *
 * Authored by Kan-Ru Chen <kanru@0xlab.org>
 */

package org.zeroxlab.aster;

import java.util.*;
import javax.swing.event.*;

public class DefaultActionListModel implements ActionListModel {
    /** The listeners waiting for model changes. */
    protected EventListenerList listenerList = new EventListenerList();

    public void addChangeListener(ChangeListener l) {
        listenerList.add(ChangeListener.class, l);
    }

    public void removeChangeListener(ChangeListener l) {
        listenerList.remove(ChangeListener.class, l);
    }

    /**
     * Run each ChangeListener's stateChanged
     * method.
     */
    protected void fireStateChanged() {
        ChangeEvent ev = null;
        Object[] listeners = listenerList.getListenerList();
        for (int i = listeners.length-2; i >= 0; i -= 2) {
            if (listeners[i] == ChangeListener.class) {
                // Lazily create the event:
                if (ev == null)
                    ev = new ChangeEvent(this);
                ((ChangeListener)listeners[i+1]).stateChanged(ev);
            }
        }
    }

    /**
     * Returns an array of all the change listeners registered on this
     * DefaultActionListModel.
     *
     * @return all of this model's ChangeListeners or an empty
     *         arrary if no change listeners are currently registered
     *
     * @see #addchangeListener
     * @see #removeChangeListener
     */
    public ChangeListener[] getChangeListeners() {
        return (ChangeListener[]) listenerList.getListeners(ChangeListener.class);
    }

    /** The command stack */
    Deque actionList = new ArrayDeque<AsterCommand>();
    /** The recall command */
    AsterCommand recall;

    public DefaultActionListModel() {
    }

    public void setRecall(AsterCommand cmd) {
        recall = cmd;
        fireStateChanged();
    }

    public void pushCmd(AsterCommand cmd) {
        actionList.addFirst(cmd);
        fireStateChanged();
    }

    public void popCmd() {
        try {
            actionList.removeFirst();
            fireStateChanged();
        } catch (NoSuchElementException e) {
            // log.w("try to pop empty command list");
        }
    }
}

Add default action list model implementation.


/*
 * Copyright 2014 Open mHealth
 *
 * 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.openmhealth.data.generator.service;

import org.joda.time.DateTime;
import org.openmhealth.data.generator.domain.MeasureGroup;
import org.openmhealth.schema.pojos.Activity;
import org.openmhealth.schema.pojos.DataPoint;
import org.openmhealth.schema.pojos.HeartRate;
import org.openmhealth.schema.pojos.Metadata;
import org.openmhealth.schema.pojos.builder.ActivityBuilder;
import org.openmhealth.schema.pojos.builder.HeartRateBuilder;
import org.openmhealth.schema.pojos.generic.DurationUnitValue;
import org.openmhealth.schema.pojos.generic.LengthUnitValue;
import org.springframework.stereotype.Service;

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

import static org.openmhealth.schema.pojos.generic.DurationUnitValue.DurationUnit.min;
import static org.openmhealth.schema.pojos.generic.LengthUnitValue.LengthUnit.m;

/**
 * @author Emerson Farrugia
 */
@Service
public class PhysicalActivityDataPointGenerationServiceImpl extends AbstractDataPointGenerationServiceImpl
        implements DataPointGenerationService {

    @Override
    public Iterable<DataPoint> generateDataPoints(Iterable<MeasureGroup> measureGroups) {

        List<DataPoint> dataPoints = new ArrayList<>();

        for (MeasureGroup measureGroup : measureGroups) {

            ActivityBuilder builder = new ActivityBuilder();

            double duration = measureGroup.getMeasureValue("duration");
            builder.withStartAndDuration(convert(measureGroup.getEffectiveDateTime()), duration, min);
            builder.setDistance(measureGroup.getMeasureValue("distance"), m);

            Metadata metadata = new Metadata();
            metadata.setTimestamp(DateTime.now());

            Activity dataPoint = builder.build();
            dataPoint.setMetadata(metadata);

            dataPoints.add(dataPoint);
        }

        return dataPoints;
    }
}

Add physical activity data generation service.


package ca.corefacility.bioinformatics.irida.web.controller.test.integration;

import com.google.common.net.HttpHeaders;
import com.jayway.restassured.response.Response;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

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

import static com.jayway.restassured.RestAssured.get;
import static com.jayway.restassured.RestAssured.given;
import static com.jayway.restassured.path.json.JsonPath.from;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

/**
 * Integration tests for project samples.
 *
 * @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>
 */
public class ProjectSamplesIntegrationTest {
    private static final Logger logger = LoggerFactory.getLogger(ProjectSamplesIntegrationTest.class);

    @Test
    public void testAddSampleToProject() {
        Map<String, String> sample = new HashMap<>();
        sample.put("sampleName", "sample 1");

        // load a project
        String projectsJson = get("/projects").asString();
        String projectUri = from(projectsJson).get("resource.resources[0].links[0].href");
        // get the uri for creating samples associated with the project.
        String projectJson = get(projectUri).asString();
        String samplesUri = from(projectJson).get("resource.links.find{it.rel == 'project/samples'}.href");

        // post that uri
        Response r = given().body(sample).expect().response().statusCode(HttpStatus.CREATED.value()).when().post(samplesUri);

        // check that the locations are set appropriately.
        String location = r.getHeader(HttpHeaders.LOCATION);
        String linkLocation = r.getHeader(HttpHeaders.LINK);

        assertNotNull(location);
        assertTrue(location.matches("^http://localhost:8080/api/samples/[a-f0-9\\-]+$"));

        assertNotNull(linkLocation);
        assertTrue(linkLocation.matches("^<http://localhost:8080/api/projects/[a-f0-9\\-]+/samples/[a-f0-9\\-]+>; rel=relationship$"));
    }
}

Test that samples can be added to a project without previously being persisted.


package org.apache.markt;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

class NoopFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // NO-OP
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        // NO-OP
    }

    @Override
    public void destroy() {
        // NO-OP
    }
}

Package private no-op filter for testing with.


package com.sequenceiq.environment.environment.repository.converter;

import java.util.Optional;

import com.sequenceiq.cloudbreak.converter.DefaultEnumConverter;
import com.sequenceiq.environment.environment.flow.deletion.event.EnvDeleteStateSelectors;

public class EnvDeleteStateSelectorsConverter extends DefaultEnumConverter<EnvDeleteStateSelectors> {
    @Override
    public EnvDeleteStateSelectors getDefault() {
        return EnvDeleteStateSelectors.FINALIZE_ENV_DELETE_EVENT;
    }

    @Override
    public Optional<EnvDeleteStateSelectors> tryConvertUnknownField(String attribute) {
        if ("START_PREREQUISITES_DELETE_EVENT".equals(attribute)) {
            return Optional.of(EnvDeleteStateSelectors.FINISH_ENV_DELETE_EVENT);
        }
        return Optional.empty();
    }
}

Implement resource group termination step - backward compatibility


/**
 * 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.db.api.assertions.impl.constructor;

import org.assertj.db.api.assertions.impl.AssertionsOnColumnOfChangeType;
import org.junit.Test;

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

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

/**
 * Tests on {@link AssertionsOnColumnOfChangeType} class :
 * {@link AssertionsOnColumnOfChangeType#AssertionsOnColumnOfChangeType()} private constructor.
 *
 * @author Régis Pouiller
 *
 */
public class AssertionsOnColumnOfChangeType_Constructor_Test {

  /**
   * This method tests the private constructor of {@code Assertions} for the tests coverage..
   * @throws NoSuchMethodException
   * @throws SecurityException
   * @throws java.lang.reflect.InvocationTargetException
   * @throws IllegalAccessException
   * @throws InstantiationException
   * @throws IllegalArgumentException
   */
  @Test
  public void test_private_constructor_for_the_tests_coverage()
          throws SecurityException, NoSuchMethodException, IllegalArgumentException,
          InstantiationException, IllegalAccessException, InvocationTargetException {

    Constructor<AssertionsOnColumnOfChangeType> constructor = AssertionsOnColumnOfChangeType.class.getDeclaredConstructor();
    assertThat(Modifier.isPrivate(constructor.getModifiers())).isTrue();
    constructor.setAccessible(true);
    constructor.newInstance();
    constructor.setAccessible(false);
  }
}

Add test on constructor of AssertionsOnColumnOfChangeType


package com.codemelon.graph.vertex.interfaces;

import com.codemelon.graph.common.Color;

/**
 * Vertex that supports colored edges
 * @author Marshall Farrier
 * @version Dec 10, 2012
 */
public interface ColoredEdgeVertex extends Vertex {
	/**
	 * Set the color of the given edge
	 * @param to head of the edge whose color is to be set
	 * @param color value to which to set the edge's color
	 */
	public void setEdgeColor(ColoredEdgeVertex to, Color color);
	/**
	 * Retrieve the color of the given edge
	 * @param to head of the edge whose color is to be retrieved
	 * @return the edge's color
	 */
	public Color getEdgeColor(ColoredEdgeVertex to);
}

Add vertex interface to support colored edges


package me.izstas.rfs.server.service;

import java.io.IOException;
import java.nio.file.*;

import me.izstas.rfs.server.RfsException;

class PathUtils {
    static RfsException wrapException(IOException e, String message) {
        if (e instanceof AccessDeniedException) {
            return new InaccessiblePathException(e);
        }

        if (e instanceof NoSuchFileException) {
            return new NonexistentPathException(e);
        }

        return new RfsException(message, e);
    }

    static void createDirectories(Path path, boolean parent) {
        try {
            Files.createDirectories(parent ? path.getParent() : path);
        }
        catch (FileAlreadyExistsException | NoSuchFileException e) { // While combination of these two may look weird,
                                                                     // on Windows we seem to get the latter one
                                                                     // if the problem is caused not by the immediate parent
                                                                     // but a further ascendant
            throw new NonexistentPathException("The path contains a file (not a directory) as one of the ascendants", e);
        }
        catch (IOException e) {
            throw wrapException(e, parent ? "Can't create ascendant directories" : "Can't create directories");
        }
    }

    private PathUtils() {
        throw new AssertionError();
    }
}

Add a class with some utility methods


package org.jboss.jandex.test;

import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.Index;
import org.jboss.jandex.Indexer;
import org.jboss.jandex.Type;
import org.junit.Test;

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

import static org.junit.Assert.assertNotNull;

public class BoundedWildcardTestCase {

  public static class TestSubject<T extends Number> implements Comparable<T> {
    @Override
    public int compareTo(T o) {
      return 0;
    }
  }

  @Test
  public void testIndexer() throws IOException {
    Indexer indexer = new Indexer();
    InputStream stream = getClass().getClassLoader().getResourceAsStream(TestSubject.class.getName().replace('.', '/') + ".class");
    indexer.index(stream);
    Index index = indexer.complete();
    verifyMethodTypeVariable(index);
  }

  private void verifyMethodTypeVariable(Index index) {
    ClassInfo classInfo = index.getClassByName(DotName.createSimple(TestSubject.class.getName()));
    assertNotNull(classInfo.method("compareTo", Type.create(DotName.createSimple(Number.class.getName()), Type.Kind.CLASS)));
  }
}

Add test for method type variables that reference a class-level bounded wildcard generic


package com.dreamchain.skeleton.WS;

import com.dreamchain.skeleton.model.Customer;
import com.dreamchain.skeleton.model.User;
import com.dreamchain.skeleton.service.CustomerService;
import com.dreamchain.skeleton.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.jws.WebMethod;
import javax.jws.WebService;

/**
 * Created by LAPTOP DREAM on 11/4/2016.
 */

@WebService
public class CustomerWebService {

    @Autowired(required = true)
    private CustomerService customerService;

//    @WebMethod(exclude = true)
//    public void setCustomerService(CustomerService customerService) {
//        this.customerService = customerService;
//    }
    @WebMethod(operationName = "getCustomerById")
    public Customer getCustomerById(long id) {
        Customer customer = customerService.get(id);
        return customer;
    }

}

Add Customer soap web service


/* Covers test cases for use cases:
 * 2
 *
 * http://stackoverflow.com/questions/10845937/how-to-do-junit-testing-in-android
 * Referenced Oct 23, 2013 for general format of Test class
 *
 */

import android.test.ActivityInstrumentationTestCase2;
import android.widget.TextView;

public class ChooseStoryActivityTestCases extends ActivityInstrumentationTestCase2<ChooseStoryActivity> {
	//declare activity and widgets
	private ChooseStoryActivity myChooseStoryActivity;
	private TextView myView;

	//Constructor
	public ChooseStoryActivityTestCases(){
		super("ualberta.g12.adventurecreator.ChooseStoryActivity", ChooseStoryActivity.class);
	}

	//initializes things you want to be set for all tests (not necessary)
	@Override
    protected void setUp() throws Exception {
        super.setUp();
        mActivity = this.getActivity();
        mView = (TextView) mActivity.findViewById(ualberta.g12.adventurecreator.ChooseStoryActivity.R.id.textviewID);
    }

	/* Test Cases - all start with "test" */

	//Use Case 2, test 1/3
	public void testBrowseStoryList {
		addMultiStory();
		assertTrue(scrollable(mView.getText()));
	}

	//Use Case 2, test 2/3
	public void testBrowseNoScrollList {
		addOneStory();
		assertFalse(scrollable(mView.getText()));
	}

	//Use Case 2, test 3/3
	public void testBrowseEmptyStoryList {
		String Story = myView.getText();
		assertEquals(Story, null);
	}

}

Put both test cases for use case 2 in here and changed the name so that it would potentially compile


package fr.tvbarthel.apps.simpleweatherforcast.fragments;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.widget.ArrayAdapter;

import java.security.InvalidParameterException;

public class TemperatureUnitPickerDialogFragment extends DialogFragment {

	private static final String BUNDLE_TEMPERATURE_UNIT_NAMES = "BundleTemperatureUnitNames";
	private static final String BUNDLE_TEMPERATURE_UNIT_SYMBOLS = "BundleTemperatureUnitSymbols";

	public static TemperatureUnitPickerDialogFragment newInstance(String[] temperatureUnitNames, String[] temperatureUnitSymbols) {
		final TemperatureUnitPickerDialogFragment instance = new TemperatureUnitPickerDialogFragment();
		final Bundle arguments = new Bundle();
		arguments.putStringArray(BUNDLE_TEMPERATURE_UNIT_NAMES, temperatureUnitNames);
		arguments.putStringArray(BUNDLE_TEMPERATURE_UNIT_SYMBOLS, temperatureUnitSymbols);
		instance.setArguments(arguments);
		return instance;
	}

	private TemperatureUnitPickerDialogFragment() {
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		final Bundle arguments = getArguments();

		final String[] temperatureUnitNames = arguments.getStringArray(BUNDLE_TEMPERATURE_UNIT_NAMES);
		final String[] temperatureUnitSymbols = arguments.getStringArray(BUNDLE_TEMPERATURE_UNIT_SYMBOLS);

		final ArrayAdapter<String> temperatureUnitNameAdapter = new ArrayAdapter<String>(getActivity(),
				android.R.layout.simple_expandable_list_item_1, temperatureUnitNames);

		final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		//TODO don't use a hard coded string
		builder.setTitle("Select a unit");
		builder.setAdapter(temperatureUnitNameAdapter, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Log.d("argonne",  temperatureUnitNames[which] + " -> " + temperatureUnitSymbols[which]);
				//TODO store the temperature unit chosen
			}
		});
		builder.setCancelable(true);
		//TODO don't use a hard coded string
		builder.setNegativeButton("Cancel", null);
		return builder.create();
	}
}

Add a dialog fragment skeleton for the temperature unit selection


package sfBugs;

public class Bug1908621 {
	public static Boolean get_bool() {
		Boolean test;

		if (1 == (int)Math.round(Math.random())) {
			test = null;
		} else {
			test = true;
		}

		return test;
	}

	/*
	 * Both alternatives do exactly the same. Alternative 1 gets the possible Null-Pointer-Dereference from the method "get_bool()",
	 * Alternative 2 gets the possible Null-Pointer-Dereference directly in the same method.
	 * FindBugs sends the alert only in alternative 2. It should also send the alert in alternative 1.
	 *
	 */

	public static void main (String[] args) {
		/**
		 * Alternative 1: Doesn't create a Null-Pointer-Dereference alert
		 */

		Boolean test = get_bool();

		if (test) {
			System.out.println("TRUE");
		}

		/**
		 * Alternative 2: Creates a Null-Pointer-Dereference alert
		 */

		//BEGIN: get_bool()
		Boolean test2;

		if (1 == (int)Math.round(Math.random())) {
			test2 = null;
		} else {
			test2 = true;
		}
		//END: get_bool()

		if (test2) {
			System.out.println("TRUE");
		}
	}
}

Test case for [ 1908621 ] Null Pointer Dereference


package cpw.mods.fml.common.functions;

import java.util.Collection;
import java.util.List;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;

public class CollectionWrapperFactory {
    /**
     * Return a read only cast view of the supplied ungeneric collection, based on the element type given
     * @param coll The collection to cast
     * @param elementType the supertype contained in the collection
     * @return a collection asserting that type relationship
     */
    public static <T> Collection<T> wrap(@SuppressWarnings("rawtypes") Collection coll, Class<T> elementType)
    {
        Collection<?> asGeneric = coll;
        return Collections2.transform(asGeneric, new TypeCastFunction<T>(elementType));
    }

    /**
     * Return a read only cast view of the supplied ungeneric list, based on the element type given
     * @param list The list to cast
     * @param elementType the supertype contained in the list
     * @return a list asserting that type relationship
     */
    public static <T> List<T> wrap(@SuppressWarnings("rawtypes") List list, Class<T> elementType)
    {
        List<?> asGeneric = list;
        return Lists.transform(asGeneric, new TypeCastFunction<T>(elementType));
    }
}

Add a helper for casting some common collection types into generic form


package mesosphere.marathon.client.model.v2;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import mesosphere.marathon.client.Marathon;
import mesosphere.marathon.client.MarathonClient;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.Test;

import java.util.ArrayList;

import static org.junit.Assert.*;

public class ExternalVolumeTest {

    @Test
    public void testExternalVolumes() throws Exception {
        final MockWebServer server = new MockWebServer();
        final String mockResponse = "{\"container\": {\"volumes\": [" +
                "{\"containerPath\":\"/data/db\",\"mode\":\"RW\",\"external\":" +
                "{\"name\":\"mongodb-testvol\",\"provider\":\"dvdi\",\"options\":" +
                "{\"dvdi/driver\":\"rexray\"}}}]}}";

        try {
            server.enqueue(new MockResponse().setBody(mockResponse));
            server.start();
            Marathon client = MarathonClient.getInstance(server.url("/").toString());

            App app = new App();
            app.setId("mongo");
            app.setCpus(1.0);
            app.setMem(256.0);
            app.setContainer(new Container());
            app.getContainer().setDocker(new Docker());
            app.getContainer().getDocker().setImage("mongo");
            app.getContainer().setVolumes(new ArrayList<Volume>());

            ExternalVolume externalVolume = new ExternalVolume();
            externalVolume.setName("mongodb-testvol");
            externalVolume.setMode("RW");
            externalVolume.setContainerPath("/data/db");
            externalVolume.setProvider("dvdi");
            externalVolume.setDriver("rexray");

            app.getContainer().getVolumes().add(externalVolume);

            final App appRes = client.createApp(app);
            assertFalse(appRes.getContainer().getVolumes().isEmpty());

            ExternalVolume responseVolume = (ExternalVolume) appRes.getContainer().getVolumes().iterator().next();
            assertEquals("mongodb-testvol", responseVolume.getExternalVolumeInfo().getName());

            RecordedRequest request = server.takeRequest();
            assertNotNull(request);

            final String requestBody = request.getBody().readUtf8();
            assertNotNull(requestBody);

            // request to JSON
            JsonObject requestPayload = new Gson().fromJson(requestBody, JsonObject.class);
            assertNotNull(requestPayload);
            JsonObject requestVolume = requestPayload.getAsJsonObject("container").getAsJsonArray("volumes").get(0).getAsJsonObject();
            assertNotNull(requestVolume);
            assertEquals("RW", requestVolume.get("mode").getAsString());
            assertEquals("/data/db", requestVolume.get("containerPath").getAsString());
        } finally {
            server.shutdown();
        }
    }

}

Add Test for External Volumes


package de.timroes;

import static org.junit.Assert.*;

import de.timroes.axmlrpc.ResponseParser;
import de.timroes.axmlrpc.XMLRPCClient;
import de.timroes.axmlrpc.XMLRPCServerException;
import de.timroes.axmlrpc.serializer.SerializerHandler;
import org.junit.Test;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

public class TestResponseParser {
    public final static String xmlDecl = "<?xml version=\"1.0\"?>";
    public final static SerializerHandler sh = new SerializerHandler(XMLRPCClient.FLAGS_NONE);

    @Test
    public void testSimpleResponse() throws Exception {
        ResponseParser sut = new ResponseParser();
        Object actual = sut.parse(sh, strToStream(xmlDecl +
                "<methodResponse>" +
                "  <params>" +
                "    <param>" +
                "      <value><string>toto</string></value>" +
                "    </param>" +
                "  </params>" +
                "</methodResponse>"), false);
        assertEquals("toto", actual);
    }

    @Test
    /**
     * I'm not sure it really makes sense to support this case. But since I'm adding tests on code which existed
     * for years, I guess it's better to avoid breaking retro compatibility.
     */
    public void testAcceptMissingHeader() throws Exception {
        ResponseParser sut = new ResponseParser();
        Object actual = sut.parse(sh, strToStream("<methodResponse>" +
                "  <params>" +
                "    <param>" +
                "      <value><string>toto</string></value>" +
                "    </param>" +
                "  </params>" +
                "</methodResponse>"), false);
        assertEquals("toto", actual);
    }

    @Test
    public void testXmlrpcError() throws Exception {
        ResponseParser sut = new ResponseParser();
        try {
            sut.parse(sh, strToStream("<methodResponse>" +
                    "  <fault>" +
                    "    <value>" +
                    "      <struct>" +
                    "        <member>" +
                    "          <name>faultCode</name>" +
                    "          <value><int>4</int></value>" +
                    "        </member>" +
                    "        <member>" +
                    "          <name>faultString</name>" +
                    "          <value><string>error X occurred</string></value>" +
                    "        </member>" +
                    "      </struct>" +
                    "    </value>" +
                    "  </fault>" +
                    "</methodResponse>"), false);
            fail("The previous call should have thrown");
        } catch (XMLRPCServerException e){
            assertEquals("error X occurred [4]", e.getMessage());
            assertEquals(4, e.getErrorNr());
        }
}

    private static InputStream strToStream(String str){
        return new ByteArrayInputStream(str.getBytes());
    }
}

Add basic tests on the parser


package com.test.graphs;

import java.util.LinkedList;

import com.graphs.GraphAdjacencyListRepresentation;
import com.graphs.MostDirectPath;

import junit.framework.TestCase;

public class TestMostDirectPath extends TestCase {

    public void testMostDirectPath() {

        GraphAdjacencyListRepresentation graph = new GraphAdjacencyListRepresentation(13, true);
        graph.addEdge(0, 5);
        graph.addEdge(0, 1);

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

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

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

        graph.addEdge(5, 4);

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

        graph.addEdge(7, 6);

        graph.addEdge(8, 6);

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

        graph.addEdge(10, 12);

        graph.addEdge(11, 12);

        graph.addEdge(12, 9);

        MostDirectPath dp = new MostDirectPath(graph, 6);
        assertEquals(0, dp.getDistance(6));
        assertEquals(-1, dp.getDistance(7));
        assertEquals(2, dp.getDistance(2));
        assertEquals(2, dp.getDistance(5));

        LinkedList<Integer> pathTo3 = new LinkedList<>();
        pathTo3.add(6);
        pathTo3.add(4);
        pathTo3.add(3);

        System.out.println(dp.getMostDirectPath(3));

        assertEquals(true, pathTo3.equals(dp.getMostDirectPath(3)));

    }

}

Add JUnit test for MostDirectPath


package net.grinder.util;

import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;

import org.junit.Test;

public class NetworkUtilTest {
	@Test
	public void testLocalHostName() {
		String localHostAddress = NetworkUtil.getLocalHostAddress("www.google.com", 80);
		assertThat(localHostAddress, notNullValue());
		assertThat(localHostAddress, not("127.0.0.1"));
		localHostAddress = NetworkUtil.getLocalHostAddress("122.132.22.11", 80);
		assertThat(localHostAddress, notNullValue());
		assertThat(localHostAddress, not("127.0.0.1"));

	}
}

Add agent which is used for specific user.


/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This 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 software 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 software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.xwiki.refactoring.job;

import org.xwiki.job.Request;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.stability.Unstable;

/**
 * Define a request that can be processed by a user.
 *
 * @version $Id$
 * @since 10.10RC1
 */
@Unstable
public interface UserOrientedRequest extends Request
{
    /**
     * @return {@code true} in case the job should check if the user specified by {@link #getUserReference()} is
     *         authorized to perform the actions implied by this request, {@code false} otherwise
     */
    boolean isCheckRights();

    /**
     * Sets whether the job should check or not if the user specified by {@link #getUserReference()} is authorized to
     * perform the actions implied by this request.
     *
     * @param checkRights {@code true} to check if {@link #getUserReference()} is authorized to perform this request,
     *            {@code false} to perform this request without checking rights
     */
    void setCheckRights(boolean checkRights);

    /**
     * @return the user that should be used to perform this request; this user must be authorized to perform the actions
     *         implied by this request if {@link #isCheckRights()} is {@code true}.
     */
    DocumentReference getUserReference();

    /**
     * Sets the user that should be used to perform this request. This user must be authorized to perform the actions
     * implied by this request if {@link #isCheckRights()} is {@code true}.
     *
     * @param userReference the user reference
     */
    void setUserReference(DocumentReference userReference);
}

Add a "Delete all" button on the recycle bin


/*
 *    Copyright 2013 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.mybatis.cdi;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({METHOD, FIELD, TYPE, PARAMETER})
public @interface MySpecialManager {
}

Test case for Mapper injection (fail)


package no.ssb.vtl.test;

import com.google.common.collect.ForwardingObject;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import no.ssb.vtl.model.Component;
import no.ssb.vtl.model.DataPoint;
import no.ssb.vtl.model.DataStructure;
import no.ssb.vtl.model.Dataset;
import no.ssb.vtl.model.StaticDataset;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 *
 */
public class TestDataset extends ForwardingObject implements Dataset {

    private final Random random;
    private final StaticDataset delegate;

    private boolean variableSize;
    private boolean shuffleData;
    private boolean shuffleStructure;

    public TestDataset(Random random, StaticDataset dataset) {
        this.delegate = checkNotNull(dataset);
        this.random = checkNotNull(random);
    }

    @Override
    public Stream<DataPoint> getData() {
        Stream<DataPoint> stream = delegate().getData();

        if (shuffleStructure)
            // TODO

        if (!shuffleData)
            return stream;

        List<DataPoint> collect = stream.collect(Collectors.toList());
        Collections.shuffle(collect, this.random);
        return collect.stream();

    }

    @Override
    public Optional<Map<String, Integer>> getDistinctValuesCount() {
        return Optional.empty();
    }

    @Override
    public Optional<Long> getSize() {
        return Optional.empty();
    }

    @Override
    public DataStructure getDataStructure() {
        DataStructure structure = delegate().getDataStructure();
        if (!shuffleStructure)
            return structure;

        ArrayList<Map.Entry<String, Component>> entries = Lists.newArrayList(structure.entrySet());
        Collections.shuffle(entries, this.random);
        return DataStructure.copyOf(ImmutableMap.copyOf(entries)).build();
    }

    @Override
    protected StaticDataset delegate() {
        return this.delegate;
    }
}

Add a test utility that randomize datasets


package com.exp.tracker.services.impl;

import java.util.List;

import javax.faces.model.SelectItem;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import com.exp.tracker.services.api.RoleService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/root-applicationContext.xml")
@ActiveProfiles("demo")
@WebAppConfiguration
public class JpaRoleServiceTests {

	@Autowired
	private RoleService roleService;

	@Test
	public void roleServiceTests() {
		List<SelectItem> rsi = roleService.getRolesSelectItems();
		Assert.assertNotNull("Failed to get roles",rsi);
		Assert.assertTrue("Expected exactly 3 roles", rsi.size() == 3);
	}
}

Fix strage test failure in Travis environment


package com.xqbase.bn.schema;

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

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

@RunWith(Parameterized.class)
public class TestSchemaFullName {

    @Parameterized.Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
                new Object[]{"a", "o.a.h", "o.a.h.a"}
        });
    }

    private final String name;
    private final String namespace;
    private final String fullName;

    public TestSchemaFullName(String name, String namespace, String fullName) {
        this.name = name;
        this.namespace = namespace;
        this.fullName = fullName;
    }

    @Test
    public void testFullName() {
        SchemaName schemaName = new SchemaName(name, namespace);
        Assert.assertEquals(fullName, schemaName.getFullName());
    }
}

Add full name test case......


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

/**
 * Write code to remove duplicates from an unsorted linked list. How would you solve this problem
 * if
 * a temporary buffer is not allowed?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class RemoveListDuplicatedElements {

}

Add statement to problem 57


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

import hudson.model.FreeStyleProject;
import org.jvnet.hudson.test.HudsonTestCase;

import java.util.concurrent.Future;
import java.util.Collections;

/**
 * Tests for {@link RevisionParameterAction}
 *
 * @author Chris Johnson
 */
public class RevisionParameterActionTest extends HudsonTestCase {

    /**
     * Test covering the behaviour until 1.1.25 where passing different revision
     * actions to a job in the queue combines them and ignores the later revisions.
     */
    public void testCombiningScheduling() throws Exception {

        FreeStyleProject fs = createFreeStyleProject("freestyle");

        // scheduleBuild2 returns null if request is combined into an existing item. (no new item added to queue)
        Future b1 = fs.scheduleBuild2(20, null, Collections.singletonList(new RevisionParameterAction("DEADBEEF")));
        Future b2 = fs.scheduleBuild2(20, null, Collections.singletonList(new RevisionParameterAction("FREED456")));

        //System.out.println(b1);
        //System.out.println(b2);

        // Check that we have the correct futures.
        assertNotNull(b1);
        assertNull(b2);

        // Check that only one build occured
        waitUntilNoActivity();
        assertEquals(fs.getBuilds().size(),1);
    }

}

Create testcase for starting builds with RevisionParameterAction


package com.itmill.toolkit.tests.components.tabsheet;

import com.itmill.toolkit.terminal.ThemeResource;
import com.itmill.toolkit.tests.components.TestBase;
import com.itmill.toolkit.ui.Component;
import com.itmill.toolkit.ui.Label;
import com.itmill.toolkit.ui.TabSheet;
import com.itmill.toolkit.ui.TextField;

public class TabSheetIcons extends TestBase {

    @Override
    protected String getDescription() {
        return "Tests rendering of a Tabsheet with fixed/dynamic width when the TabSheet contains icons";
    }

    @Override
    protected Integer getTicketNumber() {
        return null;
    }

    @Override
    protected void setup() {
        TabSheet ts1 = createTabsheet();
        ts1.setHeight("100px");
        TabSheet ts2 = createTabsheet();
        ts2.setHeight("100px");
        ts2.setWidth("400px");

        addComponent(ts1);
        addComponent(ts2);
    }

    private TabSheet createTabsheet() {
        TabSheet tabsheet = new TabSheet();
        tabsheet.setSizeUndefined();

        Component[] tab = new Component[3];
        tab[0] = new Label("This is tab 1");
        tab[0].setIcon(new ThemeResource("icons/32/folder-add.png"));
        tab[0].setCaption("tab number 1");
        tab[1] = new TextField("This is tab 2", "Contents of tab 2 textfield");
        tab[2] = new Label("This is tab 3");
        tab[2].setIcon(new ThemeResource("icons/16/folder-add.png"));
        tab[2].setCaption("tab number 3");

        for (Component c : tab) {
            tabsheet.addTab(c);
        }

        return tabsheet;
    }

}

Test case for a TabSheet containing icons


/**
 * Sample file using the RiakClient#store(RiakObject, ...) API
 */

package com.trifork.riak_http;

import java.io.IOException;

import com.basho.riak.client.RiakClient;
import com.basho.riak.client.RiakObject;

public class HTTPPushLotsOfData {

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

		RiakClient riak = new RiakClient("http://127.0.0.1:8098/riak");

		long before = System.currentTimeMillis();

		byte[] val = new byte[419];

		for (int i = 0; i < 100; i++) {

			long before2 = System.currentTimeMillis();

			String cpr = "" + (1000000000+i);
			String cpr_key = cpr;

			for (int rid = 0; rid < 1000; rid++)  {

				String rid_key = "" + (200000+i);

				RiakObject ro = new RiakObject(riak, cpr_key, rid_key, val);
				riak.store(ro);

			}

			long after2 = System.currentTimeMillis();

			System.out.println(""+i+" x 1000 INSERTS: "+(after2-before2)+"ms");

		}

		long after = System.currentTimeMillis();

		System.out.println("TOTAL TIME: "+(1.0*(after-before)/1000.0)+"s");
	}

}

Test similar to push-lots-of-data but using the HTTP-based java client.


/*
 * This is a special marker class used to differentiate our special
 * version of BCEL used for running Daikon/Chicory from any other
 * version that may be on the classpath. (markro)
 */

package org.apache.commons.bcel6;

public class PLSEMarker
{
  public static final String marker = "PLSE version of BCEL6";
}

Add a marker class to identify our version of bcel6.


package fi.vincit.mutrproject.service;

import static fi.vincit.multiusertest.rule.expection.Expectations.call;
import static fi.vincit.multiusertest.util.UserIdentifiers.ifAnyOf;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import fi.vincit.multiusertest.annotation.TestUsers;
import fi.vincit.multiusertest.util.LoginRole;
import fi.vincit.mutrproject.AbstractConfiguredIT;

@TestUsers(
        creators = {"role:ROLE_SUPER_ADMIN", "role:ROLE_ADMIN", "role:ROLE_USER", "role:ROLE_USER"},
        users = {"role:ROLE_SUPER_ADMIN", "role:ROLE_ADMIN", "role:ROLE_USER", "role:ROLE_ANONYMOUS", TestUsers.CREATOR}
)
public class TodoServiceJava8IT extends AbstractConfiguredIT {

    @Autowired
    private TodoService todoService;

    @Test
    public void getPrivateTodoList() throws Throwable {
        long id = todoService.createTodoList("Test list", false);
        logInAs(LoginRole.USER);
        authorization().expect(
                call(() -> todoService.getTodoList(id))
                        .toFail(ifAnyOf("role:ROLE_USER", "role:ROLE_ANONYMOUS"))
        );
    }

    @Test
    public void getPublicTodoList() throws Throwable {
        long id = todoService.createTodoList("Test list", true);
        logInAs(LoginRole.USER);
        todoService.getTodoList(id);
    }

    @Test
    public void addTodoItem() throws Throwable {
        long listId = todoService.createTodoList("Test list", false);
        logInAs(LoginRole.USER);

        authorization().expect(
                call(() -> todoService.addItemToList(listId, "Write tests"))
                        .notToFail(ifAnyOf("role:ROLE_ADMIN", "role:ROLE_SUPER_ADMIN", TestUsers.CREATOR))
        );
    }

}

Add example test for Java8 style assertions


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

package com.dmdirc.parser.irc.outputqueue;

import com.dmdirc.parser.common.QueuePriority;
import org.junit.Before;
import org.junit.Test;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

import static org.junit.Assert.assertEquals;

public class PriorityOutputQueueTest {

    private BufferedReader reader;
    private BufferedOutputStream outputStream;
    private PriorityOutputQueue outputQueue;

    @Before
    public void setup() throws IOException {
        PipedInputStream pipeInput = new PipedInputStream();
        reader = new BufferedReader(new InputStreamReader(pipeInput));
        outputStream = new BufferedOutputStream(new PipedOutputStream(pipeInput));
        outputQueue = new PriorityOutputQueue();
    }

    @Test(expected = IllegalStateException.class)
    public void testThrowsIfOutputStreamNotSet() {
        outputQueue.sendLine("testing", QueuePriority.IMMEDIATE);
    }

    @Test
    public void testSendsLinesToOutput() throws IOException {
        outputQueue.setOutputStream(outputStream);
        outputQueue.sendLine("test 123");
        outputQueue.sendLine("456...");
        assertEquals("test 123", reader.readLine());
        assertEquals("456...", reader.readLine());
    }

    @Test
    public void testDiscarding() throws IOException {
        outputQueue.setOutputStream(outputStream);
        outputQueue.setDiscarding(true);
        outputQueue.sendLine("test 123");
        outputQueue.setDiscarding(false);
        outputQueue.sendLine("456...");
        assertEquals("456...", reader.readLine());
    }

}

Add some super basic OutputQueue tests.


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

package org.spine3.string;

import com.google.protobuf.Duration;
import org.junit.Test;
import org.spine3.time.Durations2;

import static org.junit.Assert.assertEquals;

/**
 * @author Alexander Yevsyukov
 */
public class DurationStringifierShould {

    private static final Stringifier<Duration> stringifier = TimeStringifiers.forDuration();

    @Test
    public void convert_back_and_forth() {
        final Duration positive = Durations2.hoursAndMinutes(5, 37);
        final Duration negative = Durations2.hoursAndMinutes(-4, -31);

        assertEquals(positive, stringifier.reverse()
                                          .convert(stringifier.convert(positive)));
        assertEquals(negative, stringifier.reverse()
                                          .convert(stringifier.convert(negative)));
    }
}

Add test for duration stringifier


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

import java.util.Map;

import org.ensembl.healthcheck.DatabaseRegistryEntry;

/**
 * Compare the RepeatTypes in the current database with those from the equivalent
 * database on the secondary server.
 */

public class ComparePreviousVersionRepeatTypes extends ComparePreviousVersionBase {

	/**
	 * Create a new XrefTypes testcase.
	 */
	public ComparePreviousVersionRepeatTypes() {

		addToGroup("post_genebuild");
		addToGroup("release");
		setDescription("Compare the types of repeat features in the current database with those from the equivalent database on the secondary server");

	}

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

	protected Map getCounts(DatabaseRegistryEntry dbre) {

		return getCountsBySQL(dbre, "SELECT DISTINCT(rc.repeat_type), COUNT(*) FROM repeat_feature rf, repeat_consensus rc WHERE rf.repeat_consensus_id=rc.repeat_consensus_id GROUP BY rc.repeat_type");

	}

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

	protected String entityDescription() {

		return "Repeats of repeat consensus type";

	}

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

	protected double threshold() {

		return 0.75;

	}

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

} // ComparePreviousVersionRepeatTypes

Check types of repeat features against previous release.


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

package org.voltdb.sysprocs.saverestore;

import org.voltcore.utils.DBBPool;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

/**
 * A helper class to encapsulate the serialization of snapshot output buffers
 */
public class SnapshotOutputBuffers {
    private final List<DBBPool.BBContainer> m_containers = new ArrayList<DBBPool.BBContainer>();

    public void addContainer(DBBPool.BBContainer container)
    {
        m_containers.add(container);
    }

    public List<DBBPool.BBContainer> getContainers()
    {
        return m_containers;
    }

    public byte[] toBytes()
    {
        ByteBuffer buf = ByteBuffer.allocate(4 + // buffer count
                                             (8 + 4 + 4) * m_containers.size()); // buffer info

        buf.putInt(m_containers.size());
        for (DBBPool.BBContainer container : m_containers) {
            buf.putLong(container.address);
            buf.putInt(container.b.position());
            buf.putInt(container.b.remaining());
        }

        return buf.array();
    }
}

Add a helper class to encapsulate serialization of multiple snapshot buffers to EE.


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

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

public class AptPackageManager implements IPackageManager {

	private PackageProperties properties;

	public AptPackageManager() {
		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 apt package manager.


package com.jraska.vsb.or1.schedule;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Random;

import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;

public class SelfAdaptiveStrategyTest {
  //region Test Methods

  @Test
  public void testFillListAtStart() throws Exception {
    IObjectiveFunction objectiveFunction = mock(IObjectiveFunction.class);

    int size = 111;
    SelfAdaptiveSearchStrategy strategy = new SelfAdaptiveSearchStrategy(new Random(), objectiveFunction, size);

    strategy.getNext(new int[2]);

    assertThat(strategy.getNeighboursStrategies().size(), equalTo(size - 1)); //-1 because one is used
  }

  @Test
  public void testFillsWiningList() throws Exception {
    SelfAdaptiveSearchStrategy strategy = new SelfAdaptiveSearchStrategy(new GettingBetterFunction());

    for (int i = 0, size = strategy.getSize(); i < size; i++) {
      strategy.getNext(new int[2]);
    }

    assertThat(strategy.getWinningNeighbourStrategies().size(), equalTo(strategy.getSize())); //all should succeed
  }

  @Test
  public void testUsesWinningList() throws Exception {
    SelfAdaptiveSearchStrategy strategy = new SelfAdaptiveSearchStrategy(new GettingBetterFunction());

    for (int i = 0, size = strategy.getSize(); i < size; i++) {
      strategy.getNext(new int[2]);
    }

    ArrayList<ILocalSearchStrategy> winningStrategies = new ArrayList<ILocalSearchStrategy>(strategy.getWinningNeighbourStrategies());

    strategy.fillNeighboursList();

    assertThat(strategy.getWinningNeighbourStrategies().size(), equalTo(0));

    ArrayList<ILocalSearchStrategy> refilledStrategies = new ArrayList<ILocalSearchStrategy>(strategy.getNeighboursStrategies());
    for (int i = 0, size = strategy.getSize() / 2; i < size; i++) { // / 2 because only first part should fit
      assertThat(refilledStrategies.get(i), equalTo(winningStrategies.get(i)));
    }
  }

  //endregion

  //region Nested classes

  static class GettingBetterFunction implements IObjectiveFunction {
    private int _counter = Integer.MAX_VALUE;

    @Override
    public int evaluate(int[] solution) {
      return --_counter;
    }
  }

  //endregion
}

Add Self adaptive strategy test


package peergos.server.tests;

import org.junit.*;
import peergos.server.*;
import peergos.server.storage.*;
import peergos.shared.*;
import peergos.shared.crypto.*;
import peergos.shared.crypto.symmetric.*;
import peergos.shared.user.fs.*;
import peergos.shared.user.fs.cryptree.*;

import java.time.*;
import java.util.*;
import java.util.stream.*;

public class BlockSizeTests {
    private static Crypto crypto = Main.initCrypto();

    @Test
    public void largeDirectoryCryptreeNode() {
        SymmetricKey rBase = SymmetricKey.random();
        SymmetricKey wBase = SymmetricKey.random();
        SymmetricKey parent = SymmetricKey.random();
        SymmetricKey parentParent = SymmetricKey.random();
        FileProperties props = new FileProperties("a-directory", true, false, "", 0, 0,
                LocalDateTime.now(), false, Optional.empty(), Optional.empty());
        SigningPrivateKeyAndPublicHash signingPair = ChampTests.createUser(new RAMStorage(), crypto);

        Optional<RelativeCapability> parentCap = Optional.of(new RelativeCapability(Optional.empty(), crypto.random.randomBytes(32), parentParent, Optional.empty()));
        RelativeCapability nextChunk = new RelativeCapability(Optional.empty(), crypto.random.randomBytes(32), parentParent, Optional.empty());

        String nameBase = IntStream.range(0, 252).mapToObj(i -> "A").collect(Collectors.joining());
        List<NamedRelativeCapability> children = IntStream.range(0, 500)
                .mapToObj(i -> new NamedRelativeCapability(nameBase + String.format("%03d", i), nextChunk))
                .collect(Collectors.toList());
        CryptreeNode.ChildrenLinks childrenLinks = new CryptreeNode.ChildrenLinks(children);
        CryptreeNode.DirAndChildren dir = CryptreeNode.createDir(MaybeMultihash.empty(), rBase,
                wBase, Optional.of(signingPair), props, parentCap, parent, nextChunk, childrenLinks, crypto.hasher).join();

        byte[] raw = dir.dir.serialize();
        Assert.assertTrue(raw.length < Fragment.MAX_LENGTH);
    }
}

Add test for large directory raw cryptree size


/*
 * Copyright 2002-2021 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
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.test.context.testng;

import org.junit.platform.suite.api.IncludeEngines;
import org.junit.platform.suite.api.SelectPackages;
import org.junit.platform.suite.api.Suite;

/**
 * JUnit Platform based test suite for tests written in TestNG that involve the
 * Spring TestContext Framework.
 *
 *
This suite is only intended to be used manually within an IDE.
 *
 *
Logging Configuration

 *
 *
In order for our log4j2 configuration to be used in an IDE, you must set the
 * following system property before running any tests — for example, in
 * Run Configurations in Eclipse.
 *
 *

 * -Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager
 *

 *
 * @author Sam Brannen
 * @since 5.3.11
 */
@Suite
@IncludeEngines("testng")
@SelectPackages("org.springframework.test.context.testng")
class TestNGTestSuite {
}

Introduce @Suite for TestNG tests


package tachyon.client.table;

import tachyon.annotation.PublicApi;

@PublicApi
public class TachyonRawTables {
  private static TachyonRawTables sTachyonRawTables;

  public static class TachyonRawTablesFactory {
    private TachyonRawTablesFactory() {} // prevent init

    public static synchronized TachyonRawTables get() {
      if (sTachyonRawTables == null) {
        sTachyonRawTables = new TachyonRawTables();
      }
      return sTachyonRawTables;
    }
  }

  private TachyonRawTables() {}
}

Add raw table client skeleton.


package fillingjars;

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    private static Scanner stdin = new Scanner(System.in);

    public static void main(String[] args) {
        long numJars = stdin.nextLong();
        long numOperations = stdin.nextLong();
        long sum = 0;
        for(int i = 0; i < numOperations; i++){
        	long firstJarIndex = stdin.nextLong();
        	long lastJarIndex = stdin.nextLong();
        	long numCandies = stdin.nextLong();
            sum += (lastJarIndex-firstJarIndex+1) * numCandies;
        }
        long average = (long)Math.floor(sum / numJars);
        System.out.println(average);
    }
}

Add solution to "Filling Jars" problem


package util;

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

/**
 * Small helper functions that don't need their own class.
 */
public class Util {

    /**
     * Loads version string from properties file in resources folder.
     *
     * @return Version string
     */
    public static String getVersion() {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        InputStream inputStream = loader.getResourceAsStream("version.properties");
        Properties prop = new Properties();
        String version = "";

        try {
            prop.load(inputStream);
        } catch (IOException e) {
            version = "x.y.z";
        }

        version = prop.getProperty("version");
        return version;
    }
}

Add util function to get version string in Java code


// 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 org.chromium.chrome.test.util;

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

/**
 * This annotation can be used to mark a test that should be enabled only in Document mode.
 */
@Retention(RetentionPolicy.RUNTIME)
public @interface DisableInTabbedMode {
}

Add annotation to stop tests from running in tabbed mode


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

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

/**
 * Annotate fields that contain a {@link com.cloudbees.plugins.credentials.common.IdCredentials#getId()}.
 *
 * In future this annotation may be used to allow more credentials lookup over the remote channel layer by
 * ensuring that only those credential ids that were sent across to the remote side of the channel can be
 * retrieved by the remote side.
 *
 * @since 1.11
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CredentialsId {
}

Add an annotation to allow marking fields that hold credential ids


/*
 * Copyright 2008 The Kuali Foundation.
 *
 * Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
 *
 * 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.kuali.kra.s2s;

import java.sql.Connection;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.kuali.kra.KraTestBase;
/**
 *
 * This class is to test the database connectivity for coeus s2s engine.
 */
public class KualiDataSourceConnectionManagerTest extends KraTestBase {
    @Before
	public void setUp() throws Exception{
		super.setUp();
	}
    @After
	public void tearDown() throws Exception {
		super.tearDown();
	}
    @Test
	public final void getDatabaseConnectionTest() throws Exception{
        KualiDataSourceConnectionManager cnnMgr = new KualiDataSourceConnectionManager();
        assertNotNull(cnnMgr.getDatabaseConnection());
    }
    @Test
    public final void freeDatabaseConnectionTest() throws Exception{
        KualiDataSourceConnectionManager cnnMgr = new KualiDataSourceConnectionManager();
        Connection conn = cnnMgr.getDatabaseConnection();
        cnnMgr.freeDatabaseConnection(conn);
        assertTrue(conn.isClosed());
    }
}

Test class for coeus-s2s engine


/***
 This is free and unencumbered software released into the public domain.

 Anyone is free to copy, modify, publish, use, compile, sell, or
 distribute this software, either in source code form or as a compiled
 binary, for any purpose, commercial or non-commercial, and by any
 means.

 For more information, please refer to <http://unlicense.org/>
 */

package com.path.android.jobqueue;

import android.util.Log;

import nl.changer.enhancedpriorityjobqueue.BuildConfig;

/**
 * @author Mustafa Ferhan Akman
 *         <p/>
 *         Create a simple and more understandable Android logs.
 * @date 21.06.2012
 */

public class DebugLog {

    static String className;
    static String methodName;

    public static boolean isDebuggable() {
        return BuildConfig.DEBUG;
    }

    private static String createLog(String log) {

        StringBuffer buffer = new StringBuffer();
        buffer.append("[");
        buffer.append(methodName);
        buffer.append("] ");
        buffer.append(log);

        return buffer.toString();
    }

    private static void getMethodNames(StackTraceElement[] sElements) {
        className = sElements[1].getFileName();
        methodName = sElements[1].getMethodName();
    }

    public static void e(String message) {
        if (!isDebuggable())
            return;

        // Throwable instance must be created before any methods
        getMethodNames(new Throwable().getStackTrace());
        Log.e(className, createLog(message));
    }

    public static void i(String message) {
        if (!isDebuggable())
            return;

        getMethodNames(new Throwable().getStackTrace());
        Log.i(className, createLog(message));
    }

    public static void d(String message) {
        if (!isDebuggable())
            return;

        getMethodNames(new Throwable().getStackTrace());
        Log.d(className, createLog(message));
    }

    public static void v(String message) {
        if (!isDebuggable())
            return;

        getMethodNames(new Throwable().getStackTrace());
        Log.v(className, createLog(message));
    }

    public static void w(String message) {
        if (!isDebuggable())
            return;

        getMethodNames(new Throwable().getStackTrace());
        Log.w(className, createLog(message));
    }

    public static void wtf(String message) {
        if (!isDebuggable())
            return;

        getMethodNames(new Throwable().getStackTrace());
        Log.wtf(className, createLog(message));
    }

}

Remove non-persistant job queue from the library. All that we intend to do from now should be persistant on disk


package cs437.som.visualization;

import java.awt.Color;

/**
 * Interface for accessing color progressions.
 */
public interface ColorProgression {

    /**
     * Provide a Color object corresponding to this progression and based on a
     * scale of 0-100 (inclusive).
     *
     * @param intensity    The intensity the color should correspond to.
     * @return              The appropriate color to heat map {@code intensity}.
     */
    Color getColor(int intensity);
}

Add a color progression interface.


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

import junit.framework.TestCase;
import org.junit.Test;

import java.util.ArrayList;

/**
 * Test for ProcessingStepConfiguration.
 */
public class ProcessingStepConfigurationTest extends TestCase {

    /** Test the format getter/setter. */
    @Test
    public void testFormatType() {
        ProcessingStepConfiguration procStepConf
            = new ProcessingStepConfiguration();
        procStepConf.setFormatType("a format type");
        assertEquals("a format type", procStepConf.getFormatType());
    }

    /** Test the title getter/setter. */
    @Test
    public void testTitle() {
        ProcessingStepConfiguration procStepConf
            = new ProcessingStepConfiguration();
        procStepConf.setTitle("a title");
        assertEquals("a title", procStepConf.getTitle());
    }

    /** Test the description getter/setter. */
    @Test
    public void testDescription() {
        ProcessingStepConfiguration procStepConf
            = new ProcessingStepConfiguration();
        procStepConf.setDescription("a description");
        assertEquals("a description", procStepConf.getDescription());
    }

    /** Test the command getter/setter. */
    @Test
    public void testCommand() {
        ProcessingStepConfiguration procStepConf
            = new ProcessingStepConfiguration();
        procStepConf.setCommand("a command");
        assertEquals("a command", procStepConf.getCommand());
    }

    /** Test the parameter getter/setter. */
    @Test
    public void testParameters() {
        ProcessingStepConfiguration procStepConf
            = new ProcessingStepConfiguration();

        ArrayList<ConfigurationParameter> cp
            = new ArrayList<ConfigurationParameter>();

        ArrayList<ConfigurationParameter> emptyList
            = new ArrayList<ConfigurationParameter>();

        procStepConf.setParameters(cp);
        assertEquals(emptyList, procStepConf.getParameters());
    }

}

Add Unit Test for ProcessStepConfigurations


package leetcode.move_zeroes;

public class Solution {
    public void moveZeroes(int[] nums) {
        if(nums == null) return;
        int size = nums.length;
        if(size <= 1) return;
        int last0 = 0;
        for(int i = 0; i < size; i++){
            if(nums[i] != 0){
                if(i != last0){
                    nums[last0] = nums[i];
                    nums[i] = 0;
                }
                last0++;
            }
        }
    }
}

Add solution for 283. Move Zeroes


/*
 Copyright (C) 2003 EBI, GRL

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

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

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

import java.sql.Connection;

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

/**
 * Check for any coord_system.versions that are blank ('') - they should be NULL for various other things to work.
 */

public class BlankCoordSystemVersions extends SingleDatabaseTestCase {

	/**
	 * Create a new BlankCoordSystem testcase.
	 */
	public BlankCoordSystemVersions() {

		addToGroup("post_genebuild");
		addToGroup("release");
		setDescription("Check for any coord_system.version that are blank ('') - they should be NULL.");
		setTeamResponsible("Genebuilders");

	}

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

		boolean result = true;

		Connection con = dbre.getConnection();

		int rows = getRowCount(con, "SELECT COUNT(*) FROM coord_system WHERE version = ''");

		if (rows > 0) {

			ReportManager.problem(this, con, rows + " rows in coord_system have a blank versions - should be set to null");
			result = false;

		} else {

			ReportManager.correct(this, con, "No blank versions in coord_system");

		}

		return result;

	} // run

} // BlankCoordSystemVersions


package jeranvier.math.dsp.filters;

import jeranvier.math.linearAlgebra.Vector;
import jeranvier.math.util.Complex;

public class MovingAverage {

	public static Vector SimpleMovingAverage(Vector data, int windowRadius){
		Vector.Builder vb = new Vector.Builder(data.size());

		for(int i = 1; i <= windowRadius; i++){
			Complex sum = new Complex();
			for(int j=1; j<=i+windowRadius; j++){
				sum = sum.add(data.get(j));
			}
			vb.set(i, sum.divideBy(i+windowRadius));
		}

		for(int i = windowRadius+1; i < data.size()-windowRadius; i++){
			Complex sum = new Complex();
			for(int j=i-windowRadius; j<i+windowRadius; j++){
				sum = sum.add(data.get(j));
			}
			vb.set(i, sum.divideBy(2*windowRadius));
		}

		for(int i = data.size()-windowRadius; i <= data.size(); i++){
			Complex sum = new Complex();
			for(int j =i; j<=data.size(); j++){
				sum = sum.add(data.get(j));
			}
			vb.set(i, sum.divideBy(data.size()-i+1));
		}
		return vb.build();
	}

}

ADD simple implementation of a moving average


package org.linkeddatafragments.datasource;

import com.hp.hpl.jena.rdf.model.Model;

/**
 * Base implementation of a Basic Linked Data Fragment.
 * @author Ruben Verborgh
 */
public class BasicLinkedDataFragmentImpl implements BasicLinkedDataFragment {
	private final Model triples;
	private final long totalSize;

	/**
	 * Create a new Basic Linked Data Fragment.
	 * @param triples the triples (possibly partial)
	 * @param totalSize the total size
	 */
	public BasicLinkedDataFragmentImpl(Model triples, long totalSize) {
		this.triples = triples;
		this.totalSize = totalSize;
	}

	@Override
	public Model getTriples() {
		return triples;
	}

	@Override
	public long getTotalSize() {
		return totalSize;
	}
}

Add base implementation of BasicLinkedDataFragment.


package com.github.aureliano.verbum_domini.web.ui;

import java.io.IOException;

import javax.faces.component.FacesComponent;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;

import com.github.aureliano.verbum_domini.helper.UrlHelper;

@FacesComponent(
		value = "com.github.aureliano.verbum_domini.web.ui.HtmlStyleSheet",
		tagName = "styleSheet", createTag = true
	)
public class HtmlStyleSheet extends UIComponentBase {

	public HtmlStyleSheet() {
		super();
	}

	@Override
	public String getFamily() {
		return "custom.ui.verbum_domini";
	}

	@Override
	public void encodeBegin(FacesContext facesContext) throws IOException {
		StringBuilder tag = new StringBuilder();

		tag.append("<link rel=\"stylesheet\" type=\"text/css\"");

		String source = (String) super.getAttributes().get("source");
		if (source != null) {
			String url = UrlHelper.buildWebAppUrl("css/" + source + ".css");
			tag.append(" href=\"" + url + "\"");
		}

		String media = (String) super.getAttributes().get("media");
		if (media != null) {
			tag.append(" media=\"" + media + "\"");
		}

		tag.append("/>");

		facesContext.getResponseWriter().write(tag.toString());
	}
}

Create style sheet tag component.


package com.skraylabs.poker.model;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;

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

public class InvalidCardFormatExceptionTest {

  @Before
  public void setUp() throws Exception {}

  @After
  public void tearDown() throws Exception {}

  @Test
  public void testDefaultConstructor() {
    // Exercise
    InvalidCardFormatException exception = new InvalidCardFormatException();
    // Verify
    String message = exception.getMessage();
    String invalidString = exception.getInvalidString();
    assertThat(message, equalTo(InvalidCardFormatException.MSG_DEFAULT));
    assertThat(invalidString, is(nullValue()));
  }

  @Test
  public void testInitializingConstructor() {
    // Exercise
    InvalidCardFormatException exception = new InvalidCardFormatException("5x");
    // Verify
    String message = exception.getMessage();
    String invalidString = exception.getInvalidString();
    String expectedMessage = String.format(InvalidCardFormatException.MSG_WITH_SAMPLE, "5x");
    assertThat(message, equalTo(expectedMessage));
    assertThat(invalidString, equalTo("5x"));
  }
}

Define some constructor tests for InvalidCardFormatException.


package org.xdi.oxauth.service;

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

import javax.ws.rs.core.Application;
import javax.ws.rs.ext.Provider;

import org.xdi.oxauth.gluu.ws.rs.GluuConfigurationWS;

/**
 * Integration with Resteasy
 *
 * @author Yuriy Movchan
 * @version 0.1, 03/28/2017
 */
@Provider
public class TestResteasyInitializer extends Application {

	@Override
	public Set<Class<?>> getClasses() {
		HashSet<Class<?>> classes = new HashSet<Class<?>>();
		classes.add(GluuConfigurationWS.class);
		return classes;
	}

}

Add RS Test Application provider


package org.aslak.github.merge.rest.jaxrs;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class CatchAllExceptionMapper implements ExceptionMapper<Throwable> {

    @Override
    public Response toResponse(Throwable exception) {
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
            .header("Content-Type", MediaType.APPLICATION_JSON)
            .entity(
                    new StringBuilder()
                        .append("{\n")
                            .append("\"message\": ").append(exception.getMessage()).append("\",")
                        .append("}\n")
                    )
            .build();
    }
}

Add catch all Exception maper


package com.souptitlemobile;

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

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import com.facebook.react.uimanager.events.EventDispatcher;

public class TableView extends RecyclerView {
    private List<View> mRecycleViews = null;
    private int mRowHeight;
    private int mHoldItems;
    private EventDispatcher mEventDiscpatcher;

    private final MyAdapter mMyAdapter;

    public TableView(Context context) {
        super(context);
        setLayoutManager(new LinearLayoutManager(getContext()));
        mMyAdapter = new MyAdapter(); // TODO: what is it Adapter???
        setAdapter(mMyAdapter);
    }

    protected void onMeasure(int widthSpec, int heightSpec) {
        final int w =
            MeasureSpec.getSize(
              MeasureSpec.makeMeasureSpec(widthSpec, MeasureSpec.AT_MOST)
            );
        final int h =
            MeasureSpec.getSize(
              MeasureSpec.makeMeasureSpec(heightSpec, MeasureSpec.AT_MOST)
            );
        setMeasuredDimension(w, h);
    }
}

Make initial android table view realisation


/*
 * FindBugs - Find bugs in Java programs
 * Copyright (C) 2003, University of Maryland
 *
 * 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 edu.umd.cs.findbugs.detect;
import edu.umd.cs.findbugs.*;
import java.util.*;
import java.io.PrintStream;
import org.apache.bcel.classfile.*;
import java.util.zip.*;
import java.io.*;

import edu.umd.cs.pugh.visitclass.DismantleBytecode;
import edu.umd.cs.pugh.visitclass.Constants2;

public class PreferZeroLengthArrays extends BytecodeScanningDetector implements   Constants2 {
    boolean nullOnTOS = false;
    private BugReporter bugReporter;

  public PreferZeroLengthArrays(BugReporter bugReporter) {
	this.bugReporter = bugReporter;
  }

   public void visit(Code obj) {
	String returnType = methodSig.substring(methodSig.indexOf(")")+1);
	if (returnType.startsWith("[")) {
		nullOnTOS = false;
		super.visit(obj);
		}
	}

    public void sawOpcode(int seen) {

	switch (seen) {
	case ACONST_NULL:
		nullOnTOS = true;
		return;
	case ARETURN:
		if (nullOnTOS)
                  bugReporter.reportBug(new BugInstance("PZLA_PREFER_ZERO_LENGTH_ARRAYS", LOW_PRIORITY)
                        .addClassAndMethod(this)
                        .addSourceLine(this, PC));
		break;
	}
	nullOnTOS = false;
	}
}

Check for methods with array return type that return null


/*
 * Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
 */

package org.jsimpledb;

import java.util.UUID;

import org.jsimpledb.annotation.JSimpleClass;
import org.jsimpledb.annotation.OnChange;
import org.jsimpledb.change.SimpleFieldChange;
import org.jsimpledb.test.TestSupport;
import org.testng.Assert;
import org.testng.annotations.Test;

public class OnChangeNestedGetterTest extends TestSupport {

    @Test
    public void testSimpleFieldChange() {

        final JSimpleDB jdb = BasicTest.getJSimpleDB(Person.class);
        final JTransaction tx = jdb.createTransaction(true, ValidationMode.AUTOMATIC);
        JTransaction.setCurrent(tx);
        try {

            final Person p = tx.create(Person.class);
            p.setId(UUID.randomUUID());
            p.setId(null);
            tx.commit();

        } finally {
            JTransaction.setCurrent(null);
        }
    }

// Model Classes

    @JSimpleClass(storageId = 100)
    public abstract static class Person implements JObject {

        @org.jsimpledb.annotation.JField(storageId = 101)
        public abstract UUID getId();
        public abstract void setId(UUID id);

        @OnChange("id")
        private void change(SimpleFieldChange<Person, ?> change) {
            Assert.assertEquals(this.getId(), change.getNewValue());
        }
    }
}

Add unit test exposing @OnChange bug.


package prope.metrics.adaptability.elements;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.List;

public class ElementSerializer {

	private final String fileName;

	private final String ROW_COLOR = "\\myrowcolour";

	private final String TABLE_NEWLINE = "\\\\";

	private final boolean useRowColor;

	private PrintWriter writer;

	public static void main(String[] args) throws FileNotFoundException {
		new ElementSerializer(true, args[0]).serializeToLatexTable();
	}

	ElementSerializer(boolean useColor, String fileName) {
		this.useRowColor = useColor;
		this.fileName = fileName;
	}

	public void serializeToLatexTable() throws FileNotFoundException {
		try {
			writer = new PrintWriter(fileName);

			writeLongTableHeader();

			writeLongTableBody();

			writeLongTableFooter();

		} finally {
			if (writer != null) {
				writer.close();
			}
		}
	}

	private void writeLongTableHeader() {
		println("\\begin{center}");
		println("\\begin{scriptsize}");
		println("\\begin{longtable}{p{0.13\\textwidth}|p{0.82\\textwidth}}");
		println("\\caption{Adaptability Scores}\\\\");
		println("\\textbf{Property} & \\textbf{Element}");
		println("\\vspace{2pt}\\\\");
		println("\\toprule");
		println("\\endfirsthead");
		println("\\multicolumn{2}{c}");
		println("{\\tablename\\ \\thetable\\ -- \\emph{Continued from previous page}}\\\\");
		println("\\endhead");
		println("\\multicolumn{2}{r}{\\emph{Continued on next page}}");
		println("\\endfoot");
		println("\\bottomrule");
		println("\\endlastfoot");
	}

	private void writeLongTableBody() {
		List<AdaptableElement> elements = new AdaptableElements().getElements();
		for (int i = 0; i < elements.size(); i++) {
			AdaptableElement element = elements.get(i);

			println("Element name & " + element.getName() + TABLE_NEWLINE);
			printColor();
			println("Documentation &" + element.getDocumentation()
					+ TABLE_NEWLINE);
			println("Expression & " + element.getLocatorExpression()
					+ TABLE_NEWLINE);
			printColor();
			println("Adaptions & " + element.getAdaptions() + TABLE_NEWLINE);
			println("Score & " + element.getNumberOfAdaptions() + TABLE_NEWLINE);

			// print a midrule expect for last assertion
			if (i != elements.size() - 1) {
				println("\\midrule");
			}
		}
	}

	private void writeLongTableFooter() {
		println("\\end{longtable}");
		println("\\end{scriptsize}");
		println("\\end{center}");
	}

	private void printColor() {
		if (useRowColor) {
			println(ROW_COLOR);
		}
	}

	private void println(String line) {
		writer.println(line);
	}
}

Enable serialization of adaptability scores to a LaTeX longtable


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

package org.eclipse.birt.core.data;

/**
 *	This class help to manipulate expressions.
 *
 */
public final class ExpressionUtil
{
	private static final String ROW_INDICATOR = "row";

	/**
	 * Return a row expression text according to given row name.
	 *
	 * @param rowName
	 * @return
	 */
	public static String createRowExpression( String rowName )
	{
		return ROW_INDICATOR + "[\"" + rowName + "\"]";
	}

	/**
	 * Return a row expression text according to given row index, which
	 * is 1-based.
	 *
	 * @param index
	 * @return
	 */
	public static String createRowExpression( int index )
	{
		return ROW_INDICATOR + "[" + index + "]";
	}
}

Add a utility class that can help to create row expressions.