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

package com.cdancy.artifactory.rest;

/**
 * Various constants that can be used in a global context.
 */
public class ArtifactoryConstants {

    public static final String ENDPOINT_SYSTEM_PROPERTY = "artifactory.rest.endpoint";
    public static final String ENDPOINT_ENVIRONMENT_VARIABLE = ENDPOINT_SYSTEM_PROPERTY.replaceAll("\\.", "_").toUpperCase();

    public static final String CREDENTIALS_SYSTEM_PROPERTY = "artifactory.rest.credentials";
    public static final String CREDENTIALS_ENVIRONMENT_VARIABLE = CREDENTIALS_SYSTEM_PROPERTY.replaceAll("\\.", "_").toUpperCase();

    public static final String TOKEN_SYSTEM_PROPERTY = "artifactory.rest.token";
    public static final String TOKEN_ENVIRONMENT_VARIABLE = TOKEN_SYSTEM_PROPERTY.replaceAll("\\.", "_").toUpperCase();

    public static final String DEFAULT_ENDPOINT = "http://127.0.0.1:7990";

    public static final String JCLOUDS_PROPERTY_ID = "jclouds.";
    public static final String ARTIFACTORY_REST_PROPERTY_ID = "artifactory.rest." + JCLOUDS_PROPERTY_ID;

    public static final String JCLOUDS_VARIABLE_ID = "JCLOUDS_";
    public static final String ARTIFACTORY_REST_VARIABLE_ID = "ARTIFACTORY_REST_" + JCLOUDS_VARIABLE_ID;

    protected ArtifactoryConstants() {
        throw new UnsupportedOperationException("Purposefully not implemented");
    }
}

Move constants into dedicated file.

Move constants into dedicated file.


Test to repo the error.

Test to repo the error.


package ru.fitgraph.rest.exceptions;
import org.apache.log4j.Logger;
import ru.fitgraph.rest.elements.ErrorResponse;

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

/**
 * Mapper for catch all internal exceptions. All uncatched exception will be processed by this
 * class.
 *
 * @author Morgen Matvey
 */
@Provider
public class InternalExceptionMapper implements ExceptionMapper<Throwable> {

    private final static Logger logger = Logger.getLogger(InternalExceptionMapper.class);

    @Override
    public Response toResponse(Throwable exception) {
        logger.error("There are unresolved exception!", exception);
        ErrorResponse response =
                new ErrorResponse("InternalServerErrorException", "Internal problem on server, try later.");
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(response).build();
    }
}

Add mapper for internal server exceptions.


package net.spy.memcached;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

import org.jmock.Mock;
import org.jmock.MockObjectTestCase;

/**
 * Test readonliness of the MemcachedNodeROImpl
 */
public class MemcachedNodeROImplTest extends MockObjectTestCase {

	public void testReadOnliness() throws Exception {
		SocketAddress sa=new InetSocketAddress(11211);
		Mock m = mock(MemcachedNode.class, "node");
		MemcachedNodeROImpl node=
			new MemcachedNodeROImpl((MemcachedNode)m.proxy());
		m.expects(once()).method("getSocketAddress").will(returnValue(sa));

		assertSame(sa, node.getSocketAddress());
		assertEquals(m.proxy().toString(), node.toString());

		for(Method meth : MemcachedNode.class.getMethods()) {
			if(meth.getName().equals("toString")) {
				// ok
			} else if(meth.getName().equals("getSocketAddress")) {
				// ok
			} else {
				Object[] args=new Object[meth.getParameterTypes().length];
				fillArgs(meth.getParameterTypes(), args);
				try {
					meth.invoke(node, args);
					fail("Failed to break on " + meth.getName());
				} catch(InvocationTargetException e) {
					assertSame(UnsupportedOperationException.class,
						e.getCause().getClass());
				}
			}
		}
	}

	private void fillArgs(Class<?>[] parameterTypes, Object[] args) {
		int i=0;
		for(Class<?> c : parameterTypes) {
			if(c == Boolean.TYPE) {
				args[i++] = false;
			} else {
				args[i++] = null;
			}
		}
	}

}

Test the readonliness of MemcachedNodeROImpl.


package etomica;

import etomica.integrator.Integrator;
import etomica.normalmode.NormalModeAnalysisDisplay2D;
import etomica.normalmode.NormalModeAnalysisDisplay3D;
import etomica.simulation.Simulation;
import etomica.space.Space;
import etomica.space3d.Space3D;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static etomica.TestSimConstructors.SCAN;

public class TestSimShortRuns {
    private static final ExecutorService exec = Executors.newSingleThreadExecutor();

    static List<Arguments> getIntegrators() throws IllegalAccessException, InstantiationException, InvocationTargetException {
        // This beautiful method will search through constructible simulations looking for ones
        // with one and only one field of type Integrator (getIntegrator isn't reliable, and with
        // more than one we don't know which one to use), instantiate the simulations, and return the integrators.
        List<Class<?>> classes =  SCAN.classNamesToClassRefs(SCAN.getNamesOfSubclassesOf(Simulation.class));
        List<Arguments> args = new ArrayList<>();

        for (Class<?> cl : classes) {
            if (cl == NormalModeAnalysisDisplay3D.class) continue;
            Field[] fields = cl.getDeclaredFields();
            List<Field> integratorFields = Arrays.stream(fields)
                    .filter(f -> Integrator.class.isAssignableFrom(f.getType()))
                    .collect(Collectors.toList());

            if (integratorFields.size() == 1) {
                Simulation sim = null;
                try {
                    sim = (Simulation) cl.getConstructor().newInstance();
                } catch (NoSuchMethodException e) {
                    try {
                        sim = (Simulation) cl.getConstructor(Space.class).newInstance(Space3D.getInstance());
                    } catch (NoSuchMethodException e1) {
                        continue;
                    }
                }

                integratorFields.get(0).setAccessible(true);
                args.add(Arguments.of(cl, (Integrator)integratorFields.get(0).get(sim)));
            }
        }

        System.out.println(args);
        return args;
    }

    @ParameterizedTest
    @MethodSource("getIntegrators")
    void testShortRuns(Class<?> simClass, Integrator simIntegrator) {
        Assertions.assertDoesNotThrow(() -> {
            simIntegrator.reset();
            Future future = exec.submit(() -> {
                while (true) {
                    simIntegrator.doStep();
                }
            });
            Thread.sleep(1000);
            future.cancel(true);
        });
    }
}

Add test which runs all sims to check they don't crash

Gathers and constructs simulation classes on the classpath, finds
the field of type Integrator, and runs the integrator for 1 second.
Currently a few like OsmosisSim crash with overlap exception because
they don't actually initialize the coordinates in the constructor.


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// This file is a part of the 'esoco-business' project.
// Copyright 2017 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany
//
// 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.esoco.entity;

import de.esoco.lib.comm.Connection;
import de.esoco.lib.comm.HttpEndpoint;
import de.esoco.lib.comm.http.HttpRequestMethod;

import static de.esoco.lib.comm.CommunicationRelationTypes.HTTP_STATUS_CODE;
import static de.esoco.lib.expression.Functions.identity;

/********************************************************************
 * The HTTP endpoint for interaction with the {@link EntitySyncService} REST
 * service.
 *
 * @author eso
 */
public class EntitySyncEndpoint extends HttpEndpoint
{
	//~ Inner Classes ----------------------------------------------------------

	/********************************************************************
	 * The base class for request methods to the {@link EntitySyncEndpoint}.
	 *
	 * @author eso
	 */
	public static class EntitySyncRequest extends HttpRequest<String, String>
	{
		//~ Constructors -------------------------------------------------------

		/***************************************
		 * Creates a new instance.
		 *
		 * @param sMethodName The name of the request method
		 */
		public EntitySyncRequest(String sMethodName)
		{
			super(sMethodName,
				  null,
				  HttpRequestMethod.POST,
				  "/api/sync/",
				  identity(),
				  identity());
		}

		//~ Methods ------------------------------------------------------------

		/***************************************
		 * @see HttpRequest#processResponse(Connection, String)
		 */
		@Override
		protected String processResponse(
			Connection rConnection,
			String	   sRawResponse)
		{
			return rConnection.get(HTTP_STATUS_CODE).toString();
		}
	}
}

sdack-19: Implement an entity modification synchronization service


package edu.cmu.cs.cloudlet.android.discovery;

import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;
import org.teleal.cling.model.meta.Device;
import org.teleal.cling.model.meta.RemoteDevice;

import edu.cmu.cs.cloudlet.android.util.KLog;

public class CloudletDevice {

	private String ipAddress;
	private boolean isUPnP;

	public CloudletDevice(Device device) {
		URL address = ((RemoteDevice) device).getIdentity().getDescriptorURL();
		this.ipAddress = address.getHost();
		this.isUPnP = true;
	}

	public CloudletDevice(JSONObject device){
		this.isUPnP = false;

		try {
			this.ipAddress = device.getString("ip_address");
			double latitude = device.getDouble("latitude");
			double longitude = device.getDouble("longitude");
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

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

		CloudletDevice that = (CloudletDevice) o;
		if (this.ipAddress == that.ipAddress)
			return true;
		else
			return false;
	}

	@Override
	public String toString() {

		return "Cloudlet at " + this.ipAddress;

		// For UPnP
		// return device.isFullyHydrated() ? device.getDisplayString() : device.getDisplayString() + " *";
	}

	public String getIPAddress() {
		return this.ipAddress;
	}

}

Add class for representing founded devices from discovery service


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

Former-commit-id: c74ca5dab9d8df1370a4b25f91c09a2fb398b4c9


package gamecontrollers.checks;

import models.board.Direction;
import models.board.Space;
import models.board.TileComponent;

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

/**
 * Created by kevinnieman on 4/21/14.
 */
public class WouldTileComponentBeOnBoard {
    private List<TileComponent> visitedTiles;

    public WouldTileComponentBeOnBoard(){
        visitedTiles = new ArrayList<TileComponent>();
    }

    public boolean check(Space space, TileComponent tile){
        //clear any old calculations
        visitedTiles.clear();

        //innocent until proven guilty
        boolean onBoard = true;

        //this tile has been visited so add it to the list of visited tiles
        visitedTiles.add(tile);

        //you just moved off the board son, thats a big mistake buddy
        if(space == null)
            return false;

        //need to check if the attached tileComponent has neighbors where the space doesnt
        //get a direciton iterator from the given tile
        Iterator<Direction> iterator = tile.getDirection().iterator();

        //with this direction iterator iterate over the directions of the given tile
        while(iterator.hasNext()){
            //get the current direction
            Direction direction = iterator.next();
            //check if the tile has a conjoined tile in this direction
            if(tile.siblingExists(direction)){
                //tile has a conjoined tile in this direction
                //check if the space has a neighbor in this direction
                if(!space.hasAdjacentSpace(direction)){
                    //if the space doesnt have an adjacent space in this direction you are hanging over the board
                    return false;
                }
                else{
                    //here we know two things
                    //the space has a conjoined space in this direction
                    //the tile has a conjoined tile in this direction
                    //therefore continue to make the checks given that this tile has not been visited
                    if(!visitedTiles.contains(tile))
                        onBoard = onBoard && check(space.getAdjacentSpace(direction), tile.getConjoinedTile(direction));
                }
            }
        }

        return onBoard;
    }
}

Add check for going off board

Add check for going off board


package com.mv.hr.client;

import org.apache.log4j.Logger;

import com.mv.base.exception.ThirdPartyBadResponseException;
import com.mv.base.exception.ThirdPartyConnectivityFailureException;

/**
 * Retries synchronously an http action when it fails
 */
public class RetryHttpActionExecutor {
	private static final Logger LOG = Logger.getLogger(RetryHttpActionExecutor.class);

	private int tries;
	private int maxTries;
	private long millisecondsBetweenTries;

	public RetryHttpActionExecutor(int maxTries, long millisecondsBetweenTries) {
		this.maxTries = maxTries;
		this.millisecondsBetweenTries = millisecondsBetweenTries;
	}

	public <T> T execute(HttpActionPerformer actionPerformer, Class<T> resultClass)
			throws ThirdPartyBadResponseException, ThirdPartyConnectivityFailureException {

		tries++;

		try {
			return actionPerformer.getResponse(resultClass);
		} catch (ThirdPartyBadResponseException | ThirdPartyConnectivityFailureException e) {
			if (tries == maxTries) {
				throw e;
			}

			LOG.warn(actionPerformer.getUrlPath() + " failed. About to try again for " + (tries + 1) + " out of " + maxTries + " times...");

			try {
				Thread.sleep(millisecondsBetweenTries);
			} catch (InterruptedException ie) {
				LOG.error("Thread has been asked to interrupt while waiting between retries. Returning null as a response.", ie);
				Thread.currentThread().interrupt(); // Restore the interrupted status of the thread
				return null;
			}

			LOG.debug("After waiting " + millisecondsBetweenTries + " ms " + actionPerformer.getUrlPath() + " is about to be performed...");

			return execute(actionPerformer, resultClass);
		}
	}
}

Add executor to retry calls synchronously upon failure


/*
 * This file is part of ELKI:
 * Environment for Developing KDD-Applications Supported by Index-Structures
 *
 * Copyright (C) 2019
 * ELKI Development Team
 *
 * 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 this program. If not, see <http://www.gnu.org/licenses/>.
 */
package elki.clustering.hierarchical;

import org.junit.Test;

import elki.Algorithm;
import elki.clustering.AbstractClusterAlgorithmTest;
import elki.clustering.hierarchical.extraction.CutDendrogramByNumberOfClusters;
import elki.data.Clustering;
import elki.database.Database;
import elki.utilities.ELKIBuilder;

/**
 * Perform hierarchical clustering around medoids.
 *
 * @author Erich Schubert
 */
public class HACAMTest extends AbstractClusterAlgorithmTest {
  @Test
  public void testHACAM() {
    Database db = makeSimpleDatabase(UNITTEST + "single-link-effect.ascii", 638);
    Clustering<?> clustering = new ELKIBuilder<>(CutDendrogramByNumberOfClusters.class) //
        .with(CutDendrogramByNumberOfClusters.Par.MINCLUSTERS_ID, 3) //
        .with(Algorithm.Utils.ALGORITHM_ID, HACAM.class) //
        .build().autorun(db);
    assertFMeasure(db, clustering, 0.93998);
    assertClusterSizes(clustering, new int[] { 200, 204, 234 });
  }

  @Test
  public void testHACAM2() {
    Database db = makeSimpleDatabase(UNITTEST + "3clusters-and-noise-2d.csv", 330);
    Clustering<?> clustering = new ELKIBuilder<>(CutDendrogramByNumberOfClusters.class) //
        .with(CutDendrogramByNumberOfClusters.Par.MINCLUSTERS_ID, 3) //
        .with(Algorithm.Utils.ALGORITHM_ID, HACAM.class) //
        .build().autorun(db);
    assertFMeasure(db, clustering, 0.915037);
    assertClusterSizes(clustering, new int[] { 55, 119, 156 });
  }
}

Add unit tests for HACAM.

Add unit tests for HACAM.


package leetcode.maximum_depth_of_binary_tree;

import common.TreeNode;

public class Solution {
	public int maxDepth(TreeNode root) {
		if(root == null) return 0;
		int left = maxDepth(root.left);
		int right = maxDepth(root.right);
		if(left > right) return left + 1;
		else return right + 1;
	}
}

Add java solution for 104. Maximum Depth of Binary Tree

104. Maximum Depth of Binary Tree: https://leetcode.com/problems/maximum-depth-of-binary-tree/


package leetcode.minimum_depth_of_binary_tree;

import common.TreeNode;

public class Solution {
	public int minDepth(TreeNode root) {
		if(root == null) return 0;
		if(root.left == null){
			return minDepth(root.right) + 1;
		}else if(root.right == null){
			return minDepth(root.left) + 1;
		}else{
			return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
		}
	}

}

Add java solution for 111. Minimum Depth of Binary Tree

111. Minimum Depth of Binary Tree: https://leetcode.com/problems/minimum-depth-of-binary-tree/


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

package com.solsticesquared.schelling.utility;

import com.solsticesquared.schelling.Agent;
import com.solsticesquared.schelling.SchellingExplorer;

/**
 * Represents a mechanism for computing the "happiness" of an arbitrary agent
 * with her current neighborhood.
 */
public interface UtilityEvaluator {

    /**
     * Computes the "happiness" of the specified agent with her current
     * neighborhood according to some arbitrary logic.
     *
     * @param agent
     *        The agent whose neighborhood needs to be evaluated.
     * @param model
     *        The model to use.
     * @return The percentage of same-group neighbors (relative to an agent)
     * in a given neighborhood.
     * @throws NullPointerException
     *         If either {@code agent} or {@code model} is {@code null}.
     */
    double evaluate(final Agent agent, final SchellingExplorer model);
}

Add mechanism for an agent to compute her happiness with her current neighborhood.


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

import static org.junit.Assert.assertEquals;

import java.util.Locale;
import java.util.TimeZone;

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

public class SystemDefaultsSwitchTest {

    private static Locale TEST_DEFAULT_LOCALE;
    private static Locale DEFAULT_LOCALE_BEFORE_TEST;

    private static TimeZone DEFAULT_TIMEZONE_BEFORE_TEST;
    private static TimeZone TEST_DEFAULT_TIMEZONE;

    @BeforeClass
    public static void classSetUp() {
        DEFAULT_LOCALE_BEFORE_TEST = Locale.getDefault();
        if (!DEFAULT_LOCALE_BEFORE_TEST.equals(Locale.CANADA)) {
            Locale.setDefault(Locale.CANADA);
        } else {
            // you seem to be from Canada...
            Locale.setDefault(Locale.CHINESE);
        }
        TEST_DEFAULT_LOCALE = Locale.getDefault();

        DEFAULT_TIMEZONE_BEFORE_TEST = TimeZone.getDefault();
        TimeZone utc = TimeZone.getTimeZone("UTC");
        if (!DEFAULT_TIMEZONE_BEFORE_TEST.equals(utc)) {
            TimeZone.setDefault(utc);
        } else {
            TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
        }
        TEST_DEFAULT_TIMEZONE = TimeZone.getDefault();
    }

    @Rule
    public SystemDefaultsSwitch defaultsSwitch = new SystemDefaultsSwitch();

    @Test
    public void testDefaultLocaleNoAnnotation() throws Exception {
        assertEquals(TEST_DEFAULT_LOCALE, Locale.getDefault());
    }

    @Test
    @SystemDefaults(locale = "en_EN")
    public void testUseDifferentLocale() throws Exception {
        assertEquals(new Locale("en", "EN"), Locale.getDefault());
    }

    @Test
    public void testDefaultTimeZoneNoAnnotation() throws Exception {
        assertEquals(TEST_DEFAULT_TIMEZONE, TimeZone.getDefault());
    }

    @Test
    @SystemDefaults(timezone = "CET")
    public void testUseDifferentTimeZone() throws Exception {
        assertEquals(TimeZone.getTimeZone("CET"), TimeZone.getDefault());
    }

    @AfterClass
    public static void classTearDown() {
        Locale.setDefault(DEFAULT_LOCALE_BEFORE_TEST);
        TimeZone.setDefault(DEFAULT_TIMEZONE_BEFORE_TEST);
    }
}

Write basic unit test for SystemDefaultsSwitch


package org.synyx.urlaubsverwaltung.account.domain;

import org.junit.Test;
import org.synyx.urlaubsverwaltung.person.Person;

import java.time.LocalDate;
import java.util.List;

import static java.math.BigDecimal.TEN;
import static org.assertj.core.api.Assertions.assertThat;
import static org.synyx.urlaubsverwaltung.person.MailNotification.NOTIFICATION_USER;
import static org.synyx.urlaubsverwaltung.person.Role.USER;

public class AccountTest {

    @Test
    public void toStringTest() {
        final Person person = new Person("Theo", "Theo", "Theo", "Theo");
        person.setId(10);
        person.setPassword("Theo");
        person.setPermissions(List.of(USER));
        person.setNotifications(List.of(NOTIFICATION_USER));
        final Account account = new Account(person, LocalDate.MIN, LocalDate.MAX, TEN, TEN, TEN, "Comment");

        final String accountToString = account.toString();
        assertThat(accountToString).isEqualTo("Account[" +
            "person=10," +
            "validFrom=01.01.+1000000000," +
            "validTo=31.12.+999999999," +
            "annualVacationDays=10," +
            "vacationDays=<null>," +
            "remainingVacationDays=10," +
            "remainingVacationDaysNotExpiring=10," +
            "comment=Comment]");
        assertThat(accountToString).doesNotContain("Theo", "USER", "NOTIFICATION_USER");
    }
}

Add unit test for account to string method


package org.wikipedia.eventlogging;

import android.net.*;
import android.util.*;
import com.github.kevinsawicki.http.*;
import org.json.*;
import org.wikipedia.concurrency.*;

/**
 * Base class for all various types of events that are logged to EventLogging.
 *
 * Each Schema has its own class, and has its own constructor that makes it easy
 * to call from everywhere without having to duplicate param info at all places.
 * Updating schemas / revisions is also easier this way.
 */
public abstract class EventLoggingEvent {
    private static final String EVENTLOG_URL = "https://bits.wikimedia.org/event.gif";

    private final JSONObject data;

    /**
     * Create an EventLoggingEvent that logs to a given revision of a given schema with
     * the gven data payload.
     *
     * @param schema Schema name (as specified on meta.wikimedia.org)
     * @param revID Revision of the schema to log to
     * @param payload Data for the actual event payload. Considered to be
     *                an array of alternating key and value items (for easier
     *                construction in subclass constructors).
     *
     *                For example, what would be expressed in a more sane
     *                language as:
     *
     *                new SomeSubClass("Schema", 4200, {
     *                  "page": "List of mass murderers",
     *                  "section": "2014"
     *                });
     *
     *                would be expressed here as
     *
     *                new SomeSubClass("Schema", 4200,
     *                  "page", "List of mass murderers",
     *                  "section", "2014"
     *                );
     *
     *                This format should be only used in subclass constructors.
     *                The subclass constructors should take more explicit parameters
     *                depending on what they are logging.
     */
    protected EventLoggingEvent(String schema, int revID, String... payload) {
        data = new JSONObject();
        try {
            data.put("schema", schema);
            data.put("revision", revID);

            JSONObject event = new JSONObject();

            for (int i = 0; i < payload.length; i += 2) {
                event.put(payload[i], payload[i+1]);
            }

            data.put("event", event);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Log the current event.
     *
     * Returns immediately after queueing the network request in the background.
     */
    public void log() {
        new LogEventTask(data).execute();
    }

    private static class LogEventTask extends SaneAsyncTask<Boolean> {
        private final JSONObject data;
        public LogEventTask(JSONObject data) {
            super(1);
            this.data = data;
        }

        @Override
        public Boolean performTask() throws Throwable {
            String dataURL = Uri.parse(EVENTLOG_URL)
                    .buildUpon().query(data.toString())
                    .build().toString();
            return HttpRequest.get(dataURL).ok();
        }

        @Override
        public void onCatch(Throwable caught) {
            // Do nothing bad. EL data is ok to lose.
            Log.d("Wikipedia", "Lost EL data: " + data.toString());
        }
    }
}

Add base class for EventLogging

Add base class for EventLogging

Change-Id: I3548d6b22696a3097e976daff1e1c9711790e8e6


package org.datadog.jenkins.plugins.datadog;

import hudson.EnvVars;
import hudson.Extension;
import hudson.model.PeriodicWork;
import hudson.model.Queue;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * This class registers a {@link PeriodicWork} with Jenkins to run periodically in order to enable
 * us to compute metrics related to the size of the queue.
 */
@Extension
public class DatadogQueueListener extends PeriodicWork {
  private static final String METRIC = "v1/series";
  private static final long RECURRENCE_PERIOD = TimeUnit.MINUTES.toMillis(1);

  private static final Logger logger = Logger.getLogger(DatadogQueueListener.class.getName());
  private static final Queue queue = Queue.getInstance();
  private static final EnvVars envVars = new EnvVars();

  @Override
  public long getRecurrencePeriod() {
    return RECURRENCE_PERIOD;
  }

  @Override
  protected void doRun() throws Exception {
    logger.fine("doRun called: Computing queue metrics");
    gauge("jenkins.queue.size", queue.getApproximateItemsQuickly().size());
  }

  private void gauge(String name, int value) {
    // Setup data point, of type [<unix_timestamp>, <value>]
    JSONArray points = new JSONArray();
    JSONArray point = new JSONArray();

    long currentTime = System.currentTimeMillis() / DatadogBuildListener.THOUSAND_LONG;
    point.add(currentTime); // current time, s
    point.add(value);
    points.add(point); // api expects a list of points

    JSONObject metric = new JSONObject();
    metric.put("metric", name);
    metric.put("points", points);
    metric.put("type", "gauge");
    metric.put("host", DatadogUtilities.getHostname(envVars)); // string

    // Place metric as item of series list
    JSONArray series = new JSONArray();
    series.add(metric);

    // Add series to payload
    JSONObject payload = new JSONObject();
    payload.put("series", series);

    logger.fine(String.format("Resulting payload: %s", payload.toString()));

    try {
      DatadogHttpRequests.post(payload, METRIC);
    } catch (Exception e) {
      logger.severe(e.toString());
    }
  }
}

Add a gauge to measure the size of the build queue.

This gauge is periodically sampled every minute and emit a metric showing
the number of items present in the build queue.


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

import java.util.Map;

import javax.security.auth.callback.CallbackHandler;

/**
 * Factory to create authentication mechanisms.
 *
 * @author Darran Lofthouse
 */
public interface HttpServerAuthenticationMechanismFactory {

    /**
     * Get the names of the HTTP authentication mechanisms that can be supplied by this factory filtered by the supplied
     * properties.
     *
     * @param properties the selection criteria for the mechanisms.
     * @return the names of the supported HTTP authentication mechanisms.
     */
    String[] getMechanismNames(Map<String, ?> properties);

    /**
     * Obtain an instance of the authentication mechanism requested provided this is allowed by any policy specified within the supplied properties.
     *
     * @param mechanismName
     * @param properties
     * @param callbackHandler
     * @return
     */
    HttpServerAuthenticationMechanism createAuthenticationMechanism(String mechanismName, Map<String, ?> properties, CallbackHandler callbackHandler);

}

[ELY-176] Add the factory API/SPI for HTTP authentication mechanisms.


package org.firstinspires.ftc.team7316.util;

/**
 * A class for PID
 */
public class PIDGenerator {

    private final double p, i, d;

    private double previous, sum;

    public PIDGenerator(double p, double i, double d) {
        this.p = p;
        this.i = i;
        this.d = d;
    }

    public double pushError(double error) {
        sum += error;
        double delta = previous - error;
        double output = p*error + i*sum + d*delta;
        previous = error;
        return output;
    }

}

Create a helper class for PID

Create a helper class for PID


package com.hubspot.singularity;

public enum  HealthcheckMethod {

  GET("GET"), POST("POST");

  private String method;

  private HealthcheckMethod(String method) {
    this.method = method;
  }

  public String getMethod() {
    return method;
  }
}

Add enum for supported healthcheck methods.


package uk.ac.ebi.quickgo.annotation.metadata;

import uk.ac.ebi.quickgo.rest.metadata.MetaData;
import uk.ac.ebi.quickgo.rest.metadata.MetaDataProvider;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;

import static java.util.stream.Collectors.toList;

/**
 * Configure the provision of metadata for the Annotation service.
 *
 * @author Tony Wardell
 * Date: 07/03/2017
 * Time: 10:55
 * Created with IntelliJ IDEA.
 */
@Configuration
public class MetaDataConfig {
    private static final String SERVICE = "Annotation";
    private static final Path DEFAULT_METADATA_PATH = Paths.get("goa_uniprot.gpa-version");
    private static final Function<Stream<String>, List<MetaData>> META_DATA_MAPPER = (Stream<String> str) -> str
        .map(s -> new MetaData(null, s.substring(s.indexOf("2"))))
        .collect(toList());
    private static final int NUMBER_OF_METADATA_LINES = 1;

    @Value("${annotation.metadata.source}")
    private Resource source;

    @Bean
    MetaDataProvider metaDataProvider() throws IOException {
        Path metaDataPath = source != null ? Paths.get(source.getURI()) : DEFAULT_METADATA_PATH;
        return new MetaDataProvider(SERVICE, META_DATA_MAPPER, Files.lines(metaDataPath), NUMBER_OF_METADATA_LINES);
    }
}


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

/**
 * Transport
 *
 * @opt operations
 * @opt types
 *
 */

public interface Transport extends Endpoint
{

    /**
     * @param bytes input bytes for consumption
     * @param offset the offset within bytes where input begins
     * @param size the number of bytes available for input
     *
     * @return the number of bytes consumed
     */
    public int input(byte[] bytes, int offset, int size);

    /**
     * @param bytes array for output bytes
     * @param offset the offset within bytes where output begins
     * @param size the number of bytes available for output
     *
     * @return the number of bytes written
     */
    public int output(byte[] bytes, int offset, int size);

}

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

/**
 * Transport
 *
 * @opt operations
 * @opt types
 *
 */

public interface Transport extends Endpoint
{

    public int END_OF_STREAM = -1;
    /**
     * @param bytes input bytes for consumption
     * @param offset the offset within bytes where input begins
     * @param size the number of bytes available for input
     *
     * @return the number of bytes consumed
     */
    public int input(byte[] bytes, int offset, int size);

    /**
     * @param bytes array for output bytes
     * @param offset the offset within bytes where output begins
     * @param size the number of bytes available for output
     *
     * @return the number of bytes written
     */
    public int output(byte[] bytes, int offset, int size);

}

Add constant definition for Proton end of stream

git-svn-id: 33ed6c3feaacb64944efc691d1ae8e09b17f2bf9@1343343 13f79535-47bb-0310-9956-ffa450edef68


/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * 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.intellij.debugger.memory.component;

import com.intellij.debugger.memory.utils.StackFrameItem;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.ReferenceType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;

/**
 * @author Vitaliy.Bibaev
 */
public interface TrackedStacksContainer {
  @Nullable
  List<StackFrameItem> getStack(@NotNull ObjectReference reference);

  void addStack(@NotNull ObjectReference ref, @NotNull List<StackFrameItem> frames);

  void pinStacks(@NotNull ReferenceType referenceType);

  void unpinStacks(@NotNull ReferenceType referenceType);

  void release();
}

Add interface for container with stack-frames which was tracked


package au.gov.ga.geodesy.gws.systemtest;

import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

import org.springframework.http.HttpStatus;
import org.testng.annotations.Test;

import io.restassured.response.Response;

public class SetupTest extends BaseSystemTest {

    @Test
    public void findSetupsByIdAndDate() throws Exception {
        Response response = given()
            .get(getConfig().getWebServicesUrl() + "/setups/search/findByFourCharacterId?id=ALIC&effectiveFrom=2011-12-12&effectiveTo=2014-12-12&timeFormat=uuuu-MM-dd")
            .then()
            .statusCode(HttpStatus.OK.value())
            .extract().response();

       assertThat(response.jsonPath().get("page.totalElements"), is(3));
       assertThat(response.jsonPath().get("_embedded.setups[0].name"), is("GNSS CORS Setup"));
       assertThat(response.jsonPath().get("_embedded.setups[0].name"), is("GNSS CORS Setup"));
       assertThat(response.jsonPath().get("_embedded.setups[0].effectivePeriod.from"), is("2011-07-20T00:00:00Z"));
       assertThat(response.jsonPath().get("_embedded.setups[0].effectivePeriod.to"), is("2013-03-08T00:00:00Z"));
    }
}

Add system test for cors setups

Add system test for cors setups


/*
 * Copyright 2018, 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 io.spine.server.delivery;

import com.google.common.testing.EqualsTester;
import org.junit.Test;

import static io.spine.server.delivery.UniformAcrossTargets.forNumber;
import static io.spine.server.delivery.UniformAcrossTargets.singleShard;

/**
 * @author Alex Tymchenko
 */
public class UniformAcrossTargetsShould {

    @Test
    public void support_equality() {
        new EqualsTester().addEqualityGroup(singleShard(), singleShard(), forNumber(1))
                          .addEqualityGroup(forNumber(3), forNumber(3))
                          .addEqualityGroup(forNumber(42), forNumber(42))
                          .testEquals();
    }

    @Test(expected = IllegalArgumentException.class)
    public void not_allow_negative_number_of_shards() {
        forNumber(-1);
    }

    @Test(expected = IllegalArgumentException.class)
    public void not_allow_zero_number_of_shards() {
        forNumber(0);
    }
}

Add more tests for `UniformAcrossTargets`.


/*
 * Zorbage: an algebraic data hierarchy for use in numeric processing.
 *
 * Copyright (C) 2016-2019 Barry DeZonia
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package nom.bdezonia.zorbage.algorithm;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import nom.bdezonia.zorbage.algebras.G;
import nom.bdezonia.zorbage.procedure.Procedure1;
import nom.bdezonia.zorbage.type.data.int32.SignedInt32Member;
import nom.bdezonia.zorbage.type.storage.array.ArrayStorage;
import nom.bdezonia.zorbage.type.storage.datasource.IndexedDataSource;

/**
 *
 * @author Barry DeZonia
 *
 */
public class TestTransform1 {

	@Test
	public void test1() {
		SignedInt32Member value = G.INT32.construct();
		IndexedDataSource<SignedInt32Member> ints = ArrayStorage.allocateInts(new int[] {1,2,3});
		Procedure1<SignedInt32Member> proc = new Procedure1<SignedInt32Member>() {
			@Override
			public void call(SignedInt32Member a) {
				a.setV(17);
			}
		};

		Transform1.compute(G.INT32, proc, ints);

		assertEquals(3, ints.size());
		value.setV(0);
		ints.get(0,  value);
		assertEquals(17, value.v());
		value.setV(0);
		ints.get(1,  value);
		assertEquals(17, value.v());
		value.setV(0);
		ints.get(2,  value);
		assertEquals(17, value.v());
	}
}

Define a test for the Transform1 algorithm


/******************************************************************************
 *                                                                            *
 *                    Copyright 2018 Subterranean Security                    *
 *                                                                            *
 *  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.sandpolis.viewer.jfx.common;

import java.util.concurrent.TimeUnit;

import io.netty.util.concurrent.AbstractEventExecutor;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Future;
import javafx.application.Platform;

/**
 * This {@link EventExecutor} implementation runs tasks on the JavaFX
 * application thread. The primary motivation is to allow {@link Future}
 * listeners to be executed on the GUI update thread.

 *

 * Only one instance of this class may be created and should be accessed via
 * {@link #INSTANCE}.
 *
 * @author cilki
 * @since 5.0.0
 */
public final class FxEventExecutor extends AbstractEventExecutor {
	private FxEventExecutor() {
	}

	public static final FxEventExecutor INSTANCE = new FxEventExecutor();

	@Override
	public boolean isShuttingDown() {
		throw new UnsupportedOperationException();
	}

	@Override
	public Future<?> shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) {
		throw new UnsupportedOperationException();
	}

	@Override
	public Future<?> terminationFuture() {
		throw new UnsupportedOperationException();
	}

	@Override
	public boolean isShutdown() {
		throw new UnsupportedOperationException();
	}

	@Override
	public boolean isTerminated() {
		throw new UnsupportedOperationException();
	}

	@Override
	public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
		throw new UnsupportedOperationException();
	}

	@Override
	public boolean inEventLoop(Thread thread) {
		if (!Thread.currentThread().equals(thread))
			throw new UnsupportedOperationException(
					"FxEventExecutor supports querying the eventloop status of the current thread only");

		return Platform.isFxApplicationThread();
	}

	@Override
	public void execute(Runnable command) {
		Platform.runLater(command);
	}

	@Override
	public void shutdown() {
		Platform.exit();
	}

}

Add a JavaFX EventExecutor for Future implementations


package org.spongepowered.common.mixin.api.mcp.particles;

import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.Registry;
import org.spongepowered.api.ResourceKey;
import org.spongepowered.api.effect.particle.ParticleOption;
import org.spongepowered.api.effect.particle.ParticleType;
import org.spongepowered.asm.mixin.Mixin;

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

@Mixin(net.minecraft.particles.ParticleType.class)
public abstract class ParticleTypeMixin_API implements ParticleType {

    private ResourceKey impl$key;

    @Override
    public <V> Optional<V> getDefaultOption(ParticleOption<V> option) {
        // TODO
        return Optional.empty();
    }

    @Override
    public Map<ParticleOption<?>, Object> getDefaultOptions() {
        // TODO
        return Collections.emptyMap();
    }

    @SuppressWarnings("ConstantConditions")
    @Override
    public ResourceKey getKey() {
        if (this.impl$key == null) {
            final ResourceLocation location = Registry.PARTICLE_TYPE.getKey((net.minecraft.particles.ParticleType<?>) (Object) this);
            this.impl$key = (ResourceKey) (Object) location;
        }
        return this.impl$key;
    }
}

Implement sponge ParticleType onto minecraft ParticleType for standard named particles.


package com.m4gik;

/**
 * The basic visible methods of any hash algorithm.
 *

 * A hash (or message digest) algorithm produces its output by iterating a basic
 * compression function on blocks of data.
 */
public interface IMessageDigest extends Cloneable {
    /**
     * Returns the algorithm's (inner) block size in bytes.
     *
     * @return the algorithm's inner block size in bytes.
     */
    int blockSize();

    /**
     * Returns a clone copy of this instance.
     *
     * @return a clone copy of this instance.
     */
    Object clone();

    /**
     * Completes the message digest by performing final operations such as
     * padding and resetting the instance.
     *
     * @return the array of bytes representing the hash value.
     */
    byte[] digest();

    /**
     * Returns the output length in bytes of this message digest algorithm.
     *
     * @return the output length in bytes of this message digest algorithm.
     */
    int hashSize();

    /**
     * Returns the canonical name of this algorithm.
     *
     * @return the canonical name of this instance.
     */
    String name();

    /**
     * Resets the current context of this instance clearing any eventually
     * cached intermediary values.
     */
    void reset();

    /**
     * A basic test. Ensures that the digest of a pre-determined message is
     * equal to a known pre-computed value.
     *
     * @return true if the implementation passes a basic self-test.
     *         Returns false otherwise.
     */
    boolean selfTest();

    /**
     * Continues a message digest operation using the input byte.
     *
     * @param b
     *            the input byte to digest.
     */
    void update(byte b);

    /**
     * Continues a message digest operation, by filling the buffer, processing
     * data in the algorithm's HASH_SIZE-bit block(s), updating the context and
     * count, and buffering the remaining bytes in buffer for the next
     * operation.
     *
     * @param in
     *            the input block.
     */
    void update(byte[] in);

    /**
     * Continues a message digest operation, by filling the buffer, processing
     * data in the algorithm's HASH_SIZE-bit block(s), updating the context and
     * count, and buffering the remaining bytes in buffer for the next
     * operation.
     *
     * @param in
     *            the input block.
     * @param offset
     *            start of meaningful bytes in input block.
     * @param length
     *            number of bytes, in input block, to consider.
     */
    void update(byte[] in, int offset, int length);
}

Create interface for digest the given message


package co.kr.godo.test.stub;

public class TestObjectDriver {
	public static void main(String[] args) {
		TestObject testObject = new TestObject();
		testObject.setStubInterface(new Stub());

		int[] params = {10,10};
		int result = testObject.Calculate(params);
		System.out.println(result);
		if (result == -400) {
			System.out.println("정상");
		} else {
			System.out.println("오류");
		}
	}
}

Test Sample : Test Stub (2) 테스트 드라이브를 생성 Test 대상 클래스 메소드 호출 - Test 대상 Class의 메소드를 호출하는 부분이 있어야 함으로


package org.eclipse.dawnsci.plotting.api.trace;

import java.util.List;

import org.eclipse.dawnsci.analysis.api.dataset.IDataset;

/**
 * A trace for adding together multiple other traces and plotting
 * them as if they were images.
 *
 * The initial version is for multiple IImageTrace but future versions
 * might include an IImageTrace covered by a vector trace.
 *
 * @author Matthew Gerring
 *
 */
public interface ICompositeTrace extends ITrace {

	/**
	 * Add a subimage to the stacked image trace. The name of the
	 * image must be unique inside the IStackedImageTrace
	 *
	 * @param index or -1 to simply add the image on to the end.
	 * @param image
	 */
	public void add(ITrace image, int index) throws IllegalArgumentException;

	/**
	 * Add a subimage to the stacked image trace.
	 * @param image
	 * @param axes
	 */
	public void removeImage(String name);

	/**
	 * @return the axes which enclose all data
	 */
	public List<IDataset> getAxes();

}

package org.eclipse.dawnsci.plotting.api.trace;

import java.util.List;

import org.eclipse.dawnsci.analysis.api.dataset.IDataset;

/**
 * A trace for adding together multiple other traces and plotting
 * them as if they were images.
 *
 * The initial version is for multiple IImageTrace but future versions
 * might include an IImageTrace covered by a vector trace.
 *
 * @author Matthew Gerring
 *
 */
public interface ICompositeTrace extends ITrace {

	/**
	 * Add a subimage to the stacked image trace. The name of the
	 * image must be unique inside the IStackedImageTrace
	 *
	 * @param index or -1 to simply add the image on to the end.
	 * @param image
	 */
	public void add(ITrace image, int index) throws IllegalArgumentException;

	/**
	 * Add a subimage to the stacked image trace.
	 * @param image
	 * @param axes
	 */
	public void removeImage(String name);

	/**
	 * @return the axes which enclose all data
	 */
	public List<IDataset> getAxes();

	/**
	 * Set the colormap for the non-rgb datasets in the composite
	 *
	 * @param name
	 */
	public void setPalette(String name);

}

Change palette in composite trace

Change palette in composite trace


package io.silverspoon.bulldog.devices.sensors;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

/**
 * Dallas DS18B20 temperature sensor implementation.
 *
 * @author sbunciak
 *
 */
public class DS18B20TemperatureSensor {

	private File deviceFile = null;

	public DS18B20TemperatureSensor(File deviceFile) {
		this.deviceFile = deviceFile;
	}

	// TODO: implement using UART?
	public float readTemperature() throws IOException {

		byte[] encoded = Files.readAllBytes(new File(deviceFile, "w1_slave").toPath());

		String tmp = new String(encoded);
		int tmpIndex = tmp.indexOf("t=");

		if (tmpIndex < 0) {
			throw new IOException("Could not read temperature!");
		}

		return Integer.parseInt(tmp.substring(tmpIndex + 2).trim()) / 1000f;
	}
}

Add support for DS18B20 Temperature Sensor


package org.owasp.appsensor.configuration;

import static org.junit.Assert.assertTrue;

import org.junit.Test;
import org.owasp.appsensor.configuration.server.ServerConfiguration;
import org.owasp.appsensor.configuration.server.ServerConfigurationReader;
import org.owasp.appsensor.configuration.server.XmlServerConfigurationReader;

public class XmlServerConfigurationReaderTest {

	@Test
	public void testConfigLoad() throws Exception {
		ServerConfigurationReader reader = new XmlServerConfigurationReader();
		ServerConfiguration configuration = reader.read("/appsensor-server-config.xml", "/appsensor_server_config_2.0.xsd");

		assertTrue("org.owasp.appsensor.analysis.impl.ReferenceStatisticalEventAnalysisEngine".equals(configuration.getEventAnalysisEngineImplementation()));
	}
}

Add test for server config file.

Add test for server config file.


/**
 * 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-2015 the original author or authors.
 */
package org.assertj.swing.core.matcher.bylabel;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.swing.test.builder.JTextFields.textField;

import org.assertj.swing.test.core.EDTSafeTestCase;
import org.junit.Test;

/**
 * Tests for {@link JLabeledTextComponentMatcher#matches(java.awt.Component)}.
 * We are looking for a text field with a label. The component to be matched
 * should have a parent.
 *
 * @author Iñaki Ibarrola
 */
public class JLabeledTextComponentMatcher_no_parent_Test extends EDTSafeTestCase {

    @Test
    public void should_Always_Return_False_When_JTextComponent_Has_No_Parent() {
        JLabeledTextComponentMatcher matcher = JLabeledTextComponentMatcher.withLabelText("hello");
        assertThat(matcher.matches(textField().createNew())).isFalse();
    }
}

Add a test to check that a component with no parent does not match.


package com.github.tomitakussaari.mysqlcluscon;

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import static org.junit.Assert.assertTrue;

public class MyslclusconDriverMysqlTest {

    @Test
    public void canConnectToRealMysql() throws SQLException {
        Connection connection = DriverManager.getConnection("jdbc:myscluscon:mysql:read_cluster://127.0.0.1:3306/myscluscon_test", "travis", "");
        assertTrue(connection.isValid(100));
    }
}

Add test verifying connect to real mysql works on travis


/*
 * 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.job.event.status;

import org.junit.jupiter.api.Test;

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

/**
 * Unit tests for {@link AbstractProgressEvent}.
 *
 * @version $Id$
 */
public class AbstractProgressEventTest
{
    private class TestableProgressEvent extends AbstractProgressEvent
    {
    }

    @Test
    public void matches()
    {
        TestableProgressEvent event = new TestableProgressEvent();
        assertTrue(event.matches(new TestableProgressEvent()));
        assertFalse(event.matches(new String("whatever")));
    }
}

[Misc] Improve mutation score (descartes). Added test for matches() (existing tests were not matching when the body of matches() was replaced by "return true").


/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param node: the node in the list should be deleted
     * @return: nothing
     */
    public void deleteNode(ListNode node) {
        /*
         * Replace the val of current node with the val of next node
         * Connect the current node with the next next node of the current node
         */
        node.val = node.next.val;
        node.next = node.next.next;
    }
}

Delete Node in Singly Linked List for Lintcode


package net.ssehub.kernel_haven.test_utils;

import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

import net.ssehub.kernel_haven.SetUpException;
import net.ssehub.kernel_haven.analysis.AnalysisComponent;
import net.ssehub.kernel_haven.config.Configuration;

/**
 * Contains a helper method to execute analysis components.
 *
 * @author Adam
 */
public class AnalysisComponentExecuter {

    /**
     * Don't allow any instances.
     */
    private AnalysisComponentExecuter() {
    }

    /**
     * Creates and executes the given {@link AnalysisComponent} class.
     *
     * @param componentClass The component class to create and execute.
     * @param config The {@link Configuration} for the component. null if no special settings are needed.
     * @param inputs The input values for the component. The first dimension represent the different
     *      {@link AnalysisComponent} inputs; the second dimension represent that values that each input component
     *      should create.
     *
     * @param <T> The output type of the analysis component.
     *
     * @return The list of results that the component created.
     */
    public static <T> List<T> executeComponent(Class<?> componentClass, Configuration config, Object[]... inputs) {

        // create an empty configuration is none is passed to us
        if (config == null) {
            try {
                config = new TestConfiguration(new Properties());
            } catch (SetUpException e) {
                throw new RuntimeException("Can't create test configuration", e);
            }
        }

        // create input components based on the inputs parameter
        AnalysisComponent<?>[] inputComponents = new AnalysisComponent[inputs.length];
        for (int i = 0; i < inputs.length; i++) {
            try {
                inputComponents[i] = new TestAnalysisComponentProvider<>(inputs[i]);
            } catch (SetUpException e) {
                throw new RuntimeException("Can't create test input component", e);
            }
        }

        // create an array with the parameter types, to get the right constructor
        Class<?>[] parameterTypes = new Class[1 + inputComponents.length];
        parameterTypes[0] = Configuration.class;
        for (int i = 0; i < inputComponents.length; i++) {
            parameterTypes[i + 1] = AnalysisComponent.class;
        }

        // create an array with the parameter values, to pass to the consturctor
        Object[] parameterValues = new Object[1 + inputComponents.length];
        parameterValues[0] = config;
        for (int i = 0; i < inputComponents.length; i++) {
            parameterValues[i + 1] = inputComponents[i];
        }

        List<T> result = new LinkedList<>();

        try {
            // instantiate the component
            @SuppressWarnings("unchecked")
            AnalysisComponent<T> component = (AnalysisComponent<T>)
                    componentClass.getConstructor(parameterTypes).newInstance(parameterValues);

            // execute the component
            T r;
            while ((r = component.getNextResult()) != null) {
                result.add(r);
            }

        } catch (ReflectiveOperationException | ClassCastException | SecurityException e) {
            throw new RuntimeException("Can't instantiate analysis component", e);
        }

        return result;
    }

}

Create helper method for testing analysis components


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

import java.util.EnumSet;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;

import org.springframework.context.ApplicationContext;

/**
 * @author Eric F. Savage, code@efsavage.com.
 *
 */
public class FilterUtils {

	/**
	 * Convenience method for adding a filter to all requests.
	 *
	 * @see ServletContext#addFilter(String, Class)
	 * @param filterClass
	 *            The class of Filter to instantiate.
	 * @param servletContext
	 */
	public static void add(Class<? extends Filter> filterClass, ServletContext servletContext) {
		FilterRegistration.Dynamic mdcInsertingServletFilterReg = servletContext.addFilter(filterClass.getName(), filterClass);
		mdcInsertingServletFilterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
	}

	/**
	 * Convenience method for adding a filter that is available as a Spring
	 * bean/service to all requests.
	 *
	 * @see ServletContext#addFilter(String, Class)
	 * @param filterClass
	 *            The class of Filter to instantiate.
	 * @param appContext
	 *            The application context to find the bean in.
	 * @param servletContext
	 */
	public static void add(Class<? extends Filter> filterClass, ApplicationContext appContext, ServletContext servletContext) {
		Filter filter = appContext.getBean(filterClass);
		FilterRegistration.Dynamic mdcInsertingServletFilterReg = servletContext.addFilter(filterClass.getName(), filter);
		mdcInsertingServletFilterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
	}

}

Add helper methods for servlet filters

Add helper methods for servlet filters


package org.fastnate.data;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.hibernate.SessionFactory;
import org.hibernate.SessionFactoryObserver;
import org.hibernate.boot.SchemaAutoTooling;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.tool.hbm2ddl.ImportScriptException;

/**
 * Imports data on startup of Hibernate, if {@link SessionFactoryOptions#getSchemaAutoTooling() schema auto tooling} is
 * set either to {@link SchemaAutoTooling#CREATE} or {@link SchemaAutoTooling#CREATE_DROP}.
 *
 * @author Tobias Liefke
 */
public class DatabaseStartupImport implements SessionFactoryObserver {

	private static final long serialVersionUID = 1L;

	@Override
	public void sessionFactoryClosed(final SessionFactory factory) {
		// Nothing to do
	}

	@Override
	public void sessionFactoryCreated(final SessionFactory factory) {
		// Only import, if Hibernate has just created an empty database
		final SchemaAutoTooling autoTooling = factory.getSessionFactoryOptions().getSchemaAutoTooling();
		if (autoTooling == SchemaAutoTooling.CREATE || autoTooling == SchemaAutoTooling.CREATE_DROP) {
			// Find a connection
			final SessionFactoryImplementor sessionFactoryImplementor = (SessionFactoryImplementor) factory;
			try (Connection connection = sessionFactoryImplementor.getServiceRegistry()
					.getService(ConnectionProvider.class).getConnection()) {
				// Import data
				new EntityImporter(new Properties()).importData(connection);
			} catch (final SQLException | IOException e) {
				throw new ImportScriptException("Could not import SQL data: " + e, e);
			}
		}
	}
}

Add an example for a connected startup importer


package io.syndesis.qe.pages.dashboard;

import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Condition.visible;

import org.openqa.selenium.By;

import com.codeborne.selenide.SelenideElement;

import io.syndesis.qe.pages.SyndesisPageObject;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by sveres on 11/15/17.
 */
@Slf4j
public class DashboardPage extends SyndesisPageObject {

	private static final class Element {
		public static final By ROOT = By.cssSelector("syndesis-dashboard");
	}

	@Override
	public SelenideElement getRootElement() {
		return $(Element.ROOT);
	}

	@Override
	public boolean validate() {
		return $(Element.ROOT).is(visible);
	}

	SelenideElement getConnection(String connectionTitle) {
		log.info("searching for connection {}", connectionTitle);
		return this.getRootElement().$(String.format("h2.card-pf-title.text-center[title=\"%s\"]", connectionTitle));
	}

	void goToConnection(String connectionTitle) {
		log.info("searching for connection {}", connectionTitle);
		this.getConnection(connectionTitle).shouldBe(visible).click();
	}

	boolean isIntegrationPresent(String integrationName) {
		log.info("Checking if integration {} is present in the list", integrationName);
		SelenideElement integration = this.getRootElement().find(By.cssSelector(String.format("div[innertext='%s']", integrationName)));
		return integration.is(visible);
	}

}

[update] Work on e2e refactoring to Java - dashboard


/*
 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.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;

/**
 * Check that certain seq_region_attribs are present.
 */
public class SeqRegionAttribsPresent extends SingleDatabaseTestCase {

	private String[] attribCodes = { "GeneNo_knwCod", "GeneNo_novCod" };

	/**
	 * Create a new SeqRegionAttribsPresent healthcheck.
	 */
	public SeqRegionAttribsPresent() {

		addToGroup("release");
		setDescription("Check that certain seq_region_attribs are present.");

	}

	/**
	 * This only really applies to core databases
	 */
	public void types() {

		removeAppliesToType(DatabaseType.OTHERFEATURES);
		removeAppliesToType(DatabaseType.ESTGENE);
		removeAppliesToType(DatabaseType.VEGA);
		removeAppliesToType(DatabaseType.CDNA);

	}

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

		boolean result = true;

		Connection con = dbre.getConnection();

		for (int i = 0; i < attribCodes.length; i++) {

			String code = attribCodes[i];
			int count = getRowCount(con, "SELECT COUNT(*) FROM attrib_type at, seq_region_attrib sa WHERE sa.attrib_type_id=at.attrib_type_id AND at.code='" + code + "'");

			if (count == 0) {

				ReportManager.problem(this, con, "No seq_region_attribs of code " + code + " - there should be some. This may indicate that the seq_region_attribs.pl script needs to be run.");
				result = false;

			} else {

				ReportManager.correct(this, con, count + " seq_region_attrib entries for " + code);

			}
		}

		return result;

	} // run

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

} // SeqRegionAttribsPresent


package seedu.taskitty.model;

import javafx.collections.FXCollections;
import seedu.taskitty.commons.core.UnmodifiableObservableList;
import seedu.taskitty.commons.exceptions.DataConversionException;
import seedu.taskitty.commons.exceptions.IllegalValueException;
import seedu.taskitty.model.task.Task;
import seedu.taskitty.model.task.TaskDate;
import seedu.taskitty.model.task.TaskTime;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.util.*;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static seedu.taskitty.testutil.TestUtil.assertThrows;

public class TaskTest {

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

    @Test
    public void invalidDateFormat_exceptionThrown() throws Exception {
        thrown.expect(IllegalValueException.class);
        TaskDate date = new TaskDate("25-12-2016");
    }

    @Test
    public void invalidDate_exceptionThrown() throws Exception {
        thrown.expect(IllegalValueException.class);
        TaskDate date = new TaskDate("29/2/2015");
    }

    @Test
    public void invalidTimeFormat_exceptionThrown() throws Exception {
        thrown.expect(IllegalValueException.class);
        TaskTime date = new TaskTime("3pm");
    }

    @Test
    public void invalidTime_exceptionThrown() throws Exception {
        thrown.expect(IllegalValueException.class);
        TaskDate date = new TaskDate("25:00");
    }
}

Add new test for Task

Add new test for Task


package com.google.sps.servlets;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;
import com.github.mustachejava.DefaultMustacheFactory;
import com.google.gson.Gson;
import com.google.sps.data.UrlRequest;

/** Servlet that shows projects.*/
@WebServlet("/project")
public class ProjectServlet extends HttpServlet {

  private static final String API_KEY = "API_KEY";  // Insert the API_KEY here for testing.
  private static final String API_PATH = "https://api.globalgiving.org/api/public/projectservice/projects/%s";

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Map<String, String> queryParameters = new HashMap<>();
    queryParameters.put("api_key", API_KEY);
    String idString = request.getParameter("id");
    String path = String.format(API_PATH, idString);
    String jsonString = UrlRequest.urlQuery(path, queryParameters);

    Gson gson = new Gson();
    Map jsonMap = gson.fromJson(jsonString, Map.class);

    MustacheFactory mf = new DefaultMustacheFactory();
    Mustache mustache = mf.compile("project.html");
    response.setContentType("text/html;");
    mustache.execute(response.getWriter(), jsonMap).flush();
  }
}

Add servlet to serve html file with specific project information


package com.autonomy.abc.selenium.page;

import com.hp.autonomy.frontend.selenium.util.AppPage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class ErrorPage implements AppPage {
    private WebDriver driver;

    public ErrorPage(WebDriver driver) {
        this.driver = driver;
        waitForLoad();
    }

    public String getErrorCode() {
        return driver.findElement(By.tagName("h1")).getText();
    }

    public String getErrorTitle() {
        return driver.findElement(By.tagName("h3")).getText();
    }

    public String getErrorDescription() {
        return driver.findElement(By.cssSelector(".error-desc p")).getText();
    }

    public WebElement redirectButton() {
        return driver.findElement(By.tagName("a"));
    }

    @Override
    public void waitForLoad() {
        new WebDriverWait(driver, 20)
                .withMessage("loading error page")
                .until(ExpectedConditions.presenceOfElementLocated(By.tagName("a")));
    }
}

Add error page to represent 401, 500 pages etc


package eu.europa.esig.dss.client.http.proxy;

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

public class ProxyDaoImpl implements ProxyDao {

	protected Map<ProxyKey, ProxyPreference> proxyPreferences = new HashMap<ProxyKey, ProxyPreference>();

	public void setHttpsHost(String httpsHost) {
		update(ProxyKey.HTTPS_HOST, httpsHost);
	}

	public void setHttpsPort(String httpsPort) {
		update(ProxyKey.HTTPS_PORT, httpsPort);
	}

	public void setHttpsUser(String httpsUser) {
		update(ProxyKey.HTTPS_USER, httpsUser);
	}

	public void setHttpsPassword(String httpsPassword) {
		update(ProxyKey.HTTPS_PASSWORD, httpsPassword);
	}

	public void setHttpsExclude(String httpsExclude) {
		update(ProxyKey.HTTPS_EXCLUDE, httpsExclude);
	}

	public void setHttpsEnable(String httpsEnable) {
		update(ProxyKey.HTTPS_ENABLED, httpsEnable);
	}

	public void setHttpHost(String httpHost) {
		update(ProxyKey.HTTP_HOST, httpHost);
	}

	public void setHttpPort(String httpPort) {
		update(ProxyKey.HTTP_PORT, httpPort);
	}

	public void setHttpUser(String httpUser) {
		update(ProxyKey.HTTP_USER, httpUser);
	}

	public void setHttpPassword(String httpPassword) {
		update(ProxyKey.HTTP_PASSWORD, httpPassword);
	}

	public void setHttpExclude(String httpExclude) {
		update(ProxyKey.HTTP_EXCLUDE, httpExclude);
	}

	public void setHttpEnable(String httpEnable) {
		update(ProxyKey.HTTP_ENABLED, httpEnable);
	}

	private void update(ProxyKey key, String value) {
		ProxyPreference proxyPreference = proxyPreferences.get(key);
		if (proxyPreference == null) {
			proxyPreference = new ProxyPreference(key, value);
			proxyPreferences.put(key, proxyPreference);
		} else {
			proxyPreference.setValue(value);
		}
	}

	@Override
	public ProxyPreference get(ProxyKey id) {
		return proxyPreferences.get(id);
	}

	@Override
	public Collection<ProxyPreference> getAll() {
		return proxyPreferences.values();
	}

	@Override
	public void update(ProxyPreference entity) {
		proxyPreferences.put(entity.getProxyKey(), entity);
	}

}

Add an implementation of ProxyDao to inject properties with Spring


package de.morphbit.thymeleaf.helper;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class ResourcePathFinder {

	private final String directory;
	private final ClassLoader loader;

	public ResourcePathFinder(String directory) {
		this.directory = directory;
		this.loader = Thread.currentThread().getContextClassLoader();
	}

	public List<String> findResourceFiles(boolean recursively) {
		return getResourceFiles(directory, new ArrayList<>(), recursively);
	}

	private List<String> getResourceFiles(String dir, List<String> files,
	        boolean recursively) {
		URL url = loader.getResource(dir);
		String path = url.getPath();
		for (File file : new File(path).listFiles()) {
			if (recursively && file.isDirectory()) {
				return getResourceFiles(concatPath(dir, file.getName()), files,
				    recursively);
			} else {
				files.add(concatPath(dir, file.getName()));
			}
		}
		return files;
	}

	private String concatPath(String path1, String path2) {
		if (path1 == null) {
			return path2;
		}
		return path1.replaceAll("[/|\\\\]*$", "") + "/"
		        + path2.replaceAll("^[/|\\\\]*", "");
	}
}

Add helper class to find resource files

Add helper class to find resource files


package com.tacitknowledge.performance.degrade;

import java.util.concurrent.TimeUnit;

import com.tacitknowledge.performance.Component;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.socket.SocketChannel;

/**
 * TODO: refactor this. For higher traffic rates use buffers larger then 1 byte size and calculate appropriate delays
 * TODO: separate configs for up and down traffics
 *
 * @author Ivan Frolov (ifrolov@tacitknowledge.com) */
public class SlowDown implements Component
{
    private final long millisecondsPerByte;

    public SlowDown(final long millisecondsPerByte)
    {
        this.millisecondsPerByte = millisecondsPerByte;
    }

    @Override
    public void initChannel(final SocketChannel ch)
    {
        ch.config().setReceiveBufferSize(1);
        ch.pipeline().addLast(new SlowDownHandler(millisecondsPerByte));
    }

    public static class SlowDownHandler extends ChannelDuplexHandler
    {
        private final long millisecondsPerByte;

        public SlowDownHandler(final long millisecondsPerByte)
        {
            this.millisecondsPerByte = millisecondsPerByte;
        }

        @Override
        public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception
        {
            ctx.executor().schedule(new Runnable()
            {
                @Override
                public void run()
                {
                    ctx.fireChannelRead(msg);
                }
            }, millisecondsPerByte, TimeUnit.MILLISECONDS);
        }

        @Override
        public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) throws Exception
        {
            final ByteBuf buf = (ByteBuf) msg;
            Runnable task = new Runnable()
            {
                private int ix = buf.readerIndex();
                @Override
                public void run()
                {
                    if(ix < buf.writerIndex()) {
                        ctx.writeAndFlush(Unpooled.wrappedBuffer(buf.copy(ix, 1)));
                        ix++;
                        ctx.executor().schedule(this, millisecondsPerByte, TimeUnit.MILLISECONDS);
                    } else {
                        promise.setSuccess();
                    }
                }
            };

            ctx.executor().submit(task);
        }
    }
}

Implement traffic slowdown degradation handler.


package router.client.api2;

import java.util.ArrayList;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class RouteManager
{
  @Nonnull
  private OnChangeCallbackChain collectOnChangeCallbacks( @Nonnull String location )
  {
    return new OnChangeCallbackChain( new ArrayList<>() );
  }

  @Nonnull
  private OnEnterCallbackChain collectOnEnterCallbacks( @Nonnull String location )
  {
    return new OnEnterCallbackChain( new ArrayList<>() );
  }

  @Nonnull
  private OnLeaveCallbackChain collectOnLeaveCallbacks( @Nullable String location )
  {
    return new OnLeaveCallbackChain( new ArrayList<>() );
  }

  public void route( @Nullable final String previousLocation,
                     @Nonnull final String newLocation,
                     @Nullable final Runnable routingCompleteAction )
  {
    collectOnChangeCallbacks( newLocation ).
      onChange( previousLocation,
                () -> runIfNonNull( routingCompleteAction ),
                () -> collectOnLeaveCallbacks( previousLocation ).
                  onLeave( () ->
                             collectOnEnterCallbacks( newLocation ).onEnter( () -> runIfNonNull( routingCompleteAction ) ) ) );
  }

  private void runIfNonNull( @Nullable final Runnable routingCompleteAction )
  {
    if ( null != routingCompleteAction )
    {
      routingCompleteAction.run();
    }
  }
}

Add idea/spike about layout of callback chains


/*
 * Copyright (C) 2006 WTSI & EBI
 *
 * 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.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;

/**
 * Check that cigar lines in the identity_xref table are in the same format as
 * they are in the alignment tables, i.e. start with a number rather than a
 * letter.
 */

public class IdentityXrefCigarLines extends SingleDatabaseTestCase {

	/**
	 * Creates a new instance of Ditag.
	 */
	public IdentityXrefCigarLines() {

		addToGroup("post_genebuild");
		addToGroup("release");
		setDescription("Check that cigar lines in the identity_xref table are in the same format, as they are in the alignment tables, i.e. start with a number rather than a letter");

	}

	/**
	 * This test only applies to core databases.
	 */
	public void types() {

		removeAppliesToType(DatabaseType.OTHERFEATURES);
		removeAppliesToType(DatabaseType.ESTGENE);
		removeAppliesToType(DatabaseType.VEGA);
		removeAppliesToType(DatabaseType.CDNA);

	}

	/**
	 * Test various things about ditag features.
	 *
	 * @param dbre
	 *          The database to use.
	 * @return Result.
	 */
	public boolean run(DatabaseRegistryEntry dbre) {

		boolean result = true;

		Connection con = dbre.getConnection();

		int rows = getRowCount(con, "SELECT COUNT(*) FROM identity_xref WHERE cigar_line REGEXP '^[MDI]'");

		if (rows > 0) {

			ReportManager.problem(this, con, rows + " cigar lines in identity_xref appear to be in the wrong format (number first)");
			result = false;

		} else {

			ReportManager.correct(this, con, "All cigar lines in identity_xref are in the correct format");
		}

		return result;

	}

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

}

Check that cigar lines in the identity_xref table are in the same format, as they are in the alignment tables, i.e. start with a number rather than a letter.


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Iterator;
import java.util.LinkedList;

class ColumnNames
{
    public static void main(String[] args) throws Exception
    {
        File file = new File(args[0]);
        BufferedReader in = new BufferedReader(new FileReader(file));
        String line;

        while ((line = in.readLine()) != null) {
            int number = Integer.parseInt(line.trim());
            System.out.println(convertToExcelColumnName(number));
        }

        in.close();
    }

    private static final int OFFSET = (int) 'A';

    private static String convertToExcelColumnName(int number)
    {
        number--;
        LinkedList<Character> result = new LinkedList<>();

        while (number >= 0) {
            int quotient = number / 26;
            int remainder = number % 26;
            result.add((char) (OFFSET + remainder));
            number = quotient - 1;
        }

        StringBuilder sb = new StringBuilder();

        Iterator it = result.descendingIterator();
        while(it.hasNext()){
            sb.append(it.next());
        }

        return sb.toString();
    }
}

Add Java solution to the column names problem


// You should obtain the registration token from your backend
// pushToken is optional and you include it if you want us to handle push notifications
twilioAuth.setPushToken(pushToken);

Remove invalid comment in snippet

Remove invalid comment in snippet


package org.twig.syntax;

import org.junit.Assert;
import org.junit.Test;
import org.twig.exception.SyntaxErrorException;

public class TokenStreamTests {
    @Test
    public void canNext() throws SyntaxErrorException {
        TokenStream tokenStream = new TokenStream("aFile");
        Token token1 = new Token(Token.Type.TEXT, "foo", 1);
        tokenStream.add(token1);
        Token token2 = new Token(Token.Type.VAR_START, null, 1);
        tokenStream.add(token2);

        Assert.assertSame("1st nexted token should be token1", token1, tokenStream.next());
        Assert.assertSame("2nd nexted token should be token2", token2, tokenStream.next());
    }

    @Test
    public void canLook() throws SyntaxErrorException {
        TokenStream tokenStream = new TokenStream("aFile");
        Token token1 = new Token(Token.Type.TEXT, "foo", 1);
        tokenStream.add(token1);

        Assert.assertSame("Look at token at index 0 should return 1st token", token1, tokenStream.look(0));
        Assert.assertSame("1st nexted token should be 1st token even after looking", token1, tokenStream.next());
    }
}

Add unit tests for TokenStream

Add unit tests for TokenStream


package com.valerysamovich.java.trail.basic.statements.switchstatement;

public class SwitchDemo2 {

    public static void main(String[] args) {

        // variables
        int month = 2;
        int year = 2000;
        int numDays = 0;

        // switch statement
        switch (month) {
            case 1: case 3: case 5: case 7: case 8: case 10: case 12:
                numDays = 31;
                break;
            case 4: case 6: case 9: case 11:
                numDays = 30;
                break;
            case 2:
                if (((year % 4 == 0) && (year % 100 == 0)) || (year % 400 == 0)) {
                    numDays = 29;
                } else {
                    numDays = 28;
                }
                break;
            default:
                System.out.println("Invalid month.");
        }

        System.out.println("Number of days = " + numDays);
    }

}

Add Switch Example with multiple case labels


package org.csanchez.aws.glacier.actions;

import org.csanchez.aws.glacier.utils.MockTestHelper;
import org.jmock.Expectations;
import org.junit.Before;
import org.junit.Test;

import com.amazonaws.services.glacier.AmazonGlacierClient;
import com.amazonaws.services.glacier.model.ListVaultsRequest;
import com.amazonaws.services.glacier.model.ListVaultsResult;

public class VaultsTest extends MockTestHelper {

    private AmazonGlacierClient client;

    @Before
    public void setUp() {
        client = mock( AmazonGlacierClient.class );
    }

    @Test
    public void vaults_singleResultsList() {
        ListVaultsResult result = mock( ListVaultsResult.class );

        expectThat( vaultServiceCallWith( result ) );
        expectThat( hasMoreResults( result, false ) );

        new Vaults( client ).call();
    }

    @Test
    public void vaults_multipleResultsList() {
        ListVaultsResult firstResult = mock( ListVaultsResult.class, "Result with marker" );
        ListVaultsResult secondResult = mock( ListVaultsResult.class, "Result with no marker" );

        expectThat( vaultServiceCallWith( firstResult ) );
        expectThat( hasMoreResults( firstResult, true ) );
        expectThat( vaultServiceCallWith( secondResult ) );
        expectThat( hasMoreResults( secondResult, false ) );

        new Vaults( client ).call();
    }

    private Expectations vaultServiceCallWith( final ListVaultsResult result ) {
        return new Expectations() {
            {
                one( client ).listVaults( with( any( ListVaultsRequest.class ) ) );
                will( returnValue( result ) );
            }
        };
    }

    private Expectations hasMoreResults( final ListVaultsResult result, final boolean hasMoreResults ) {
        return new Expectations() {
            {
                allowing( result ).getVaultList();

                one( result ).getMarker();
                if ( hasMoreResults ) {
                    will( returnValue( "marker" ) );
                } else {
                    will( returnValue( null ) );
                }
            }
        };
    }
}

Add tests for Vaults callable to ensure that all vaults are acquired (multiple service calls are necessary if there are over 1000 vaults)


package info.u_team.u_team_core.data;

import java.io.IOException;

import org.apache.logging.log4j.*;

import com.google.common.base.Preconditions;

import net.minecraft.data.*;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.model.generators.*;

public abstract class CommonBlockStatesProvider extends BlockStateProvider {

	protected final Marker marker;

	public CommonBlockStatesProvider(DataGenerator generator, String modid, ExistingFileHelper existingFileHelper) {
		super(generator, modid, existingFileHelper);
		marker = MarkerManager.getMarker(getName());
	}

	@Override
	public void act(DirectoryCache cache) throws IOException {
		this.cache = cache;
		generatedModels.clear();
		registerModels0();
		generatedModels.values().forEach(model -> {
			try {
				final ResourceLocation location = model.getLocation();
				CommonProvider.write(cache, model.toJson(), generator.getOutputFolder().resolve("assets/" + location.getNamespace() + "/models/" + location.getPath() + ".json"));
			} catch (IOException ex) {
				CommonProvider.LOGGER.error(marker, "Could not write data.", ex);
			}
		});
		this.cache = null;
	}

	// We need to overide registerModels, but this method is marked final...
	private void registerModels0() {
		registeredBlocks.clear();
		registerStatesAndModels();

		registeredBlocks.forEach((block, generatedState) -> {
			try {
				final ResourceLocation location = Preconditions.checkNotNull(block.getRegistryName());
				CommonProvider.write(cache, generatedState.toJson(), generator.getOutputFolder().resolve("assets/" + location.getNamespace() + "/blockstates/" + location.getPath() + ".json"));
			} catch (IOException ex) {
				CommonProvider.LOGGER.error(marker, "Could not write data.", ex);
			}
		});
	}

	@Override
	public String getName() {
		return "Block-States | Block-Models";
	}
}

Add block state / block models provider

Add block state / block models provider