/*
 * eXist-db Open Source Native XML Database
 * Copyright (C) 2001 The eXist-db Authors
 *
 * info@exist-db.org
 * http://www.exist-db.org
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
package org.exist.xquery.functions.fn;

import com.googlecode.junittoolbox.ParallelRunner;
import org.exist.test.ExistXmldbEmbeddedServer;
import org.exist.xquery.XPathException;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.xmldb.api.base.ResourceSet;
import org.xmldb.api.base.XMLDBException;

import static org.junit.Assert.assertEquals;

/**
 * @author Dannes Wessels
 */
@RunWith(ParallelRunner.class)
public class FunDocumentUriTest {

    @ClassRule
    public static final ExistXmldbEmbeddedServer existEmbeddedServer = new ExistXmldbEmbeddedServer(true, true, true);

    @Test
    public void testFnFunDocumentUri() {

        try {
            final ResourceSet resourceSet = existEmbeddedServer.executeQuery(
                    "declare context item := 'a'; document-uri()");

        } catch (XMLDBException ex) {
            XPathException cause = (XPathException) ex.getCause();
            assertEquals("XPTY0004", cause.getErrorCode().getErrorQName().getLocalPart());
        }
    }
}

Add test that can not be tested in XQsuite.


package org.sjj.csvstream;

import static org.junit.Assert.*;
import org.junit.Test;

public class QuotingTest {
  @Test
  public void testEncodeDecodeNestedQuotes() {
    String[] inner_data = { "3.14", "test test", "abc", "123,456.00" };
    CsvFormatter formatter = new CsvFormatter();
    String cell = formatter.format(inner_data);
    String[] outer_data = { cell, "another test", "Pipe | Test"};
    formatter = new CsvFormatter(CsvConfig.DEFAULTS.withDelimiter('|'));

    String encoded_string = formatter.format(outer_data);
//    System.out.println("Encoded_string: " + encoded_string);

    // Now break the encoded-string back apart and make sure we get the data back out.
    String[] new_outer_data = CsvParser.split(encoded_string, '|');
    for (int i = 0; i < outer_data.length; i++) {
      assertEquals(outer_data[i], new_outer_data[i]);
    }
    String[] new_inner_data = CsvParser.split(outer_data[0]);
    for (int i = 0; i < inner_data.length; i++) {
      assertEquals(inner_data[i], new_inner_data[i]);
    }
  }

}

Add test for nested CSVs


/*
 * 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.scxml.issues;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;

/**
 * Issue-specific test suite for Commons SCXML.
 *
 */
public class IssuesTestSuite extends TestCase {

    /**
     * Construct a new instance.
     */
    public IssuesTestSuite(String name) {
        super(name);
    }

    /**
     * Command-line interface.
     */
    public static void main(String[] args) {
        TestRunner.run(suite());
    }

    /**
     * Get the suite of tests
     */
    public static Test suite() {
        TestSuite suite = new TestSuite();
        suite.setName("Commons SCXML Issues Tests");
        return suite;
    }
}

Add the oacs.issues test package for adding tests specific to an issue (and its fix, if any).


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

package org.onosproject.vtnrsc.virtualport;

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

import org.junit.Test;
import org.onlab.packet.IpAddress;
import org.onosproject.vtnrsc.FixedIp;
import org.onosproject.vtnrsc.SubnetId;

import com.google.common.testing.EqualsTester;

/**
 * Unit tests for FixedIp class.
 */
public class FixedIpTest {

    final SubnetId subnetId1 = SubnetId.subnetId("lef11-95w-4er-9c9c");
    final SubnetId subnetId2 = SubnetId.subnetId("lefaa-95w-4er-9c9c");
    final IpAddress ip1 = IpAddress.valueOf("192.168.0.1");
    final IpAddress ip2 = IpAddress.valueOf("192.168.1.1");

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

    /**
     * Checks the operation of equals().
     */
    @Test
    public void testEquals() {
        FixedIp fixedIp1 = FixedIp.fixedIp(subnetId1, ip1);
        FixedIp fixedIp2 = FixedIp.fixedIp(subnetId1, ip1);
        FixedIp fixedIp3 = FixedIp.fixedIp(subnetId2, ip2);
        new EqualsTester().addEqualityGroup(fixedIp1, fixedIp2)
                .addEqualityGroup(fixedIp3).testEquals();
    }

    /**
     * Checks the construction of a FixedIp object.
     */
    @Test
    public void testConstruction() {
        FixedIp fixedIp = FixedIp.fixedIp(subnetId1, ip1);
        assertThat(ip1, is(notNullValue()));
        assertThat(ip1, is(fixedIp.ip()));
        assertThat(subnetId1, is(notNullValue()));
        assertThat(subnetId1, is(fixedIp.subnetId()));
    }
}

Add the junit test code of FixedIp


package arez.downstream;

import java.io.IOException;
import java.nio.file.Path;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import org.intellij.lang.annotations.RegExp;
import static org.testng.Assert.*;

/**
 * Index into which symbolMap can be loadded and assertions invoked on contents of index.
 */
@SuppressWarnings( "WeakerAccess" )
final class SymbolEntryIndex
{
  private final HashMap<String, ArrayList<SymbolEntry>> _classNameToEntry = new HashMap<>();

  /**
   * Read and build an index from symbolMap file.
   *
   * @param symbolMapPath the path to load symbolMap from.
   * @return the new index.
   * @throws IOException    if there is an error reading file.
   * @throws ParseException if there is an error parsing file.
   */
  @Nonnull
  static SymbolEntryIndex readSymbolMapIntoIndex( @Nonnull final Path symbolMapPath )
    throws IOException, ParseException
  {
    final SymbolEntryIndex index = new SymbolEntryIndex();
    SymbolEntry.readSymbolMap( symbolMapPath, index::addEntry );
    return index;
  }

  private void addEntry( @Nonnull final SymbolEntry entry )
  {
    _classNameToEntry
      .computeIfAbsent( entry.getClassName(), e -> new ArrayList<>() )
      .add( entry );
  }

  /**
   * Verify no entry for ClassName exists in index.
   * If a match is found then fail assertion error.
   *
   * @param pattern the pattern
   */
  void assertNoClassNameMatches( @RegExp( prefix = "^", suffix = "$" ) @Nonnull final String pattern )
  {
    assertNoClassNameMatches( Pattern.compile( "^" + pattern + "$" ) );
  }

  /**
   * Verify no entry for ClassName exists in index.
   * If a match is found then fail assertion error.
   *
   * @param pattern the pattern
   */
  void assertNoClassNameMatches( @Nonnull final Pattern pattern )
  {
    final List<String> matches =
      _classNameToEntry.keySet().stream().filter( n -> pattern.matcher( n ).matches() ).collect( Collectors.toList() );
    if ( !matches.isEmpty() )
    {
      fail( "Expected that the SymbolMap would have no classNames that match pattern " + pattern +
            " but the following classNames match: " + matches );
    }
  }
}

Add index that can be used to load and verify assert conditions about index


package main.java.meterstanden.model;
import java.io.Serializable;

import javax.persistence.*;

@Entity @IdClass(Jaarverbruik.class)
@Table(name = "JAARVERBRUIK", schema = "APP")
public class Jaarverbruik implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	//-----------// PRIVATE VARIABLES //-----------//
	@Id
	private Long id;

	@Id
	private String ms;

	private int jaar;

	private float som;

	//-----------// CONSTRUCTORS //-----------//
	public Jaarverbruik() {
		super();
	}

	//-----------// GETTERS & SETTERS //-----------//

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getMs() {
		return ms;
	}

	public void setMs(String metersoort) {
		this.ms = metersoort;
	}

	public int getJaar() {
		return jaar;
	}

	public void setJaar(int jaar) {
		this.jaar = jaar;
	}

	public float getSom() {
		return som;
	}

	public void setSom(float som) {
		this.som = som;
	}

	//-----------// METHODS //-----------//
	@Override
	public String toString() {
		return "Jaarverbruik [id=" + id + ", metersoort=" + ms + ", jaar=" + jaar + ", som=" + som + "]";
	}
}

Add java DTO for jaarverbruik


package starpunk;

import com.artemis.Entity;
import com.artemis.World;
import com.badlogic.gdx.math.MathUtils;
import starpunk.components.Position;
import starpunk.components.Sprite;

public final class EntityFactory
{
  private EntityFactory()
  {
  }

  /**
   * Create a star entity within a particular bound.
   */
  public static Entity createStar( final World world, final int width, final int height )
  {
    final Entity e = world.createEntity();

    final Position position = new Position();
    position.setX( MathUtils.random( -width / 2, width / 2 ) );
    position.setY( MathUtils.random( -height / 2, height / 2 ) );
    e.addComponent( position );

    final Sprite sprite = new Sprite();
    sprite.setName( "star" );
    final float scale = MathUtils.random( 0.5f, 1f );
    sprite.setScaleY( scale );
    sprite.setScaleX( scale );
    sprite.setR( MathUtils.random( 0.3f, 0.9f ) );
    sprite.setG( MathUtils.random( 0.3f, 0.9f ) );
    sprite.setB( MathUtils.random( 0.3f, 0.9f ) );
    sprite.setA( MathUtils.random( 0.1f, 0.5f ) );
    sprite.setLayer( Sprite.Layer.BACKGROUND );

    e.addComponent( sprite );

    return e;
  }
}

Add a factory method for stars!


package MaximumSubarray;

/**
 * User: Danyang
 * Date: 1/22/2015
 * Time: 20:49
 *
 * Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

 For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
 the contiguous subarray [4,−1,2,1] has the largest sum = 6.

 More practice:
 If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

 */
public class Solution {
    /**
     * O(n) iterative is trivial
     * Divide and Conquer Approach
     * O(n lgn)
     * 1. divide in half
     * 2. left max sub
     * 3. right max sub
     * 4. max sub crossing the middle point
     * @param A
     * @return
     */
    public int maxSubArray(int[] A) {
        return maxSubArray(A, 0, A.length);
    }

    int maxSubArray(int[] A, int s, int e) {
        if(s>=e)
            return Integer.MIN_VALUE;
        if(s==e-1)
            return A[s];

        int m = (s+e)/2;
        int l = maxSubArray(A, s, m);
        int r = maxSubArray(A, m, e);
        int c = maxCross(A, s, e, m);
        return Math.max(Math.max(l, r), c);
    }

    int maxCross(int[] A, int s, int e, int m) {
        int max_l = A[m];
        int max_r = A[m];

        int acc = A[m];
        for(int i=m-1; i>=s; i--) {
            acc += A[i];
            max_l = Math.max(max_l, acc);
        }
        acc = A[m];
        for(int i=m+1; i<e; i++) {
            acc += A[i];
            max_r = Math.max(max_r, acc);
        }
        return max_l+max_r-A[m];
    }
}

Divide and Conquer Approach for Max Subarray Problem


package dr.inference.operators;

import dr.inference.model.Parameter;
import dr.math.MathUtils;
import dr.xml.*;

/**
 * @author Chieh-Hsi Wu
 * Operator that performs independent random walks on k elements in a parameter
 */
public class MultipleRandomWalkIntegerOperator extends RandomWalkIntegerOperator{
    public static final String SAMPLE_SIZE = "sampleSize";
    private int sampleSize = 1;
    public MultipleRandomWalkIntegerOperator(Parameter parameter, int windowSize, int sampleSize, double weight) {
        super(parameter,windowSize, weight);
        this.sampleSize = sampleSize;
    }

    public double doOperation() {

        int[] shuffledInd = MathUtils.shuffled(parameter.getDimension());
        int index;
        for(int i = 0; i < sampleSize; i++){

            index = shuffledInd[i];

            // a random non zero integer around old value within windowSize * 2
            int oldValue = (int) parameter.getParameterValue(index);
            int newValue;
            int roll = MathUtils.nextInt(2 * windowSize);
            if (roll >= windowSize) {
                newValue = oldValue + 1 + roll - windowSize;

                if (newValue > parameter.getBounds().getUpperLimit(index))
                    newValue = 2 * (int)(double)parameter.getBounds().getUpperLimit(index) - newValue;
            } else {
                newValue = oldValue - 1 - roll;

                if (newValue < parameter.getBounds().getLowerLimit(index))
                    newValue = 2 * (int)(double)parameter.getBounds().getLowerLimit(index) - newValue;
            }

            parameter.setParameterValue(index, newValue);

        }

        return 0.0;
    }

    public static dr.xml.XMLObjectParser PARSER = new AbstractXMLObjectParser() {

        public String getParserName() {
            return "multipleRandomWalkIntegerOperator";
        }

        public Object parseXMLObject(XMLObject xo) throws XMLParseException {

            double weight = xo.getDoubleAttribute(WEIGHT);

            double w = xo.getDoubleAttribute(WINDOW_SIZE);
            if (w != Math.floor(w)) {
                throw new XMLParseException("The window size of a randomWalkIntegerOperator should be an integer");
            }

            double s = xo.getDoubleAttribute(SAMPLE_SIZE);
            if (s != Math.floor(s)) {
                throw new XMLParseException("The window size of a randomWalkIntegerOperator should be an integer");
            }

            int windowSize = (int)w;
            int sampleSize = (int)s;
            Parameter parameter = (Parameter) xo.getChild(Parameter.class);

            return new MultipleRandomWalkIntegerOperator(parameter, windowSize, sampleSize, weight);
        }

        //************************************************************************
        // AbstractXMLObjectParser implementation
        //************************************************************************

        public String getParserDescription() {
            return "This element returns a random walk operator on a given parameter.";
        }

        public Class getReturnType() {
            return MCMCOperator.class;
        }

        public XMLSyntaxRule[] getSyntaxRules() {
            return rules;
        }

        private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{
                AttributeRule.newDoubleRule(WINDOW_SIZE),
                AttributeRule.newDoubleRule(SAMPLE_SIZE),
                AttributeRule.newDoubleRule(WEIGHT),
                new ElementRule(Parameter.class)
        };

    };

}

Allow multiple independent random walks for different indices of the same parameter.


package com.googlecode.gentyref;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import com.googlecode.gentyref.GenericTypeReflector;

public class GenericTypeReflectorTest extends AbstractGenericsReflectorTest {
	@Override
	protected void testExactSuperclass(Type expectedSuperclass, Type type) {
		// test if it's really seen as a supertype
		assertTrue(GenericTypeReflector.isSuperType(expectedSuperclass, type));

		// test if the supertype of the given class is as expected
		assertEquals(expectedSuperclass, getExactSuperType(type, getClass(expectedSuperclass)));
	}

	@Override
	protected void testInexactSupertype(Type superType, Type subType) {
		// first if it's seen as a supertype
		assertTrue(GenericTypeReflector.isSuperType(superType, subType));

		if (superType instanceof ParameterizedType || superType instanceof Class) {
			// test if it's not exact
			assertFalse(superType.equals(getExactSuperType(subType, getClass(superType))));
		}
	}

	private Type getExactSuperType(Type type, Class<?> searchClass) {
		return GenericTypeReflector.getExactSuperType(type, searchClass);
	}

	@Override
	protected Type getExactReturnType(Method m, Type type) {
		return GenericTypeReflector.getExactReturnType(m, type);
	}

	@Override
	protected Type getExactFieldType(Field f, Type type) {
		return GenericTypeReflector.getExactFieldType(f, type);
	}

}

Rename main class to match project name


package no.stelar7.api.l4j8.basic.constants.types;

import javafx.util.Pair;

import java.util.*;

public final class InhibitorLocationType
{
    private InhibitorLocationType()
    {
        // empty constructor
    }

    private static final Map<MapType, Map<LaneType, Map<TeamType, Pair<Integer, Integer>>>> inhibs = new EnumMap<>(MapType.class);

    static
    {
        Map<LaneType, Map<TeamType, Pair<Integer, Integer>>> one;
        Map<TeamType, Pair<Integer, Integer>>                two;
        one = inhibs.getOrDefault(MapType.SUMMONERS_RIFT, new HashMap<>());

        two = one.getOrDefault(LaneType.BOT, new HashMap<>());
        two.put(TeamType.BLUE, new Pair<>(3452, 1236));
        two.put(TeamType.RED, new Pair<>(13604, 11316));
        one.put(LaneType.BOT, two);

        two = one.getOrDefault(LaneType.MID, new HashMap<>());
        two.put(TeamType.BLUE, new Pair<>(3203, 3208));
        two.put(TeamType.RED, new Pair<>(11598, 11667));
        one.put(LaneType.MID, two);

        two = one.getOrDefault(LaneType.TOP, new HashMap<>());
        two.put(TeamType.BLUE, new Pair<>(1171, 3571));
        two.put(TeamType.RED, new Pair<>(11261, 13676));
        one.put(LaneType.TOP, two);

        inhibs.put(MapType.SUMMONERS_RIFT, one);
    }

    public static Map<LaneType, Map<TeamType, Pair<Integer, Integer>>> getInhibMap(MapType map)
    {
        return inhibs.get(map);
    }

    public static List<Pair<Integer, Integer>> getInhibs(MapType map)
    {
        List<Pair<Integer, Integer>> retTowers = new ArrayList<>();

        inhibs.getOrDefault(map, new HashMap<>()).forEach((k, v) -> v.forEach((k2, v2) -> retTowers.add(v2)));

        return retTowers;
    }
}

Add summoners rift inhibitors to the api


package leetcode;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Stack;

/**
 * https://leetcode.com/problems/binary-tree-postorder-traversal/
 */
public class Problem145 {
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Set<TreeNode> set = new HashSet<>();
        Stack<TreeNode> stack = new Stack<>();
        stack.add(root);
        boolean right = false;
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            while (node.left == null) {
                TreeNode n = node.left;
                stack.add(n);
            }

            System.out.println("popping: " + node.val);
            while ((node.left == null || set.contains(node.left))
                && (node.right == null || set.contains(node.right))) {
                System.out.println(node.val);
                result.add(node.val);
                set.add(node);
            }
            if (node.left != null) {
                System.out.println("adding: " + node.left.val);
                stack.add(node.left);
                right = false;
            } else {
                right = true;
                if (right) {
                    if (node.right != null) {
                        System.out.println("adding: " + node.right.val);
                        stack.add(node.right);
                    }
                }
            }
        }
        return result;
    }

    private List<Integer> recursivePostOrderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        recursivePostOrderTraversal(root, result);
        return result;
    }

    private void recursivePostOrderTraversal(TreeNode root, List<Integer> result) {
        if (root == null) {
            return;
        }
        recursivePostOrderTraversal(root.left, result);
        recursivePostOrderTraversal(root.right, result);
        result.add(root.val);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.left.right.right = new TreeNode(6);

        Problem145 prob = new Problem145();
//        System.out.println(prob.recursivePostOrderTraversal(root));
        System.out.println(prob.postorderTraversal(root));
    }
}

Create a skeleton for problem 145


package de.unistuttgart.iste.rss.bugminer.cli;

import de.unistuttgart.iste.rss.bugminer.computing.SshConnector;
import de.unistuttgart.iste.rss.bugminer.model.entities.Project;
import de.unistuttgart.iste.rss.bugminer.model.repositories.ProjectRepository;
import org.apache.commons.lang.NotImplementedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.shell.core.CommandMarker;
import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
public class BugsCommand implements CommandMarker {
	@Autowired
	private SshConnector sshConnector;

	@Autowired
	private ProjectsService projectsService;

	@Autowired
	private ProjectRepository projectRepository;

	protected BugsCommand() {
		// managed bean
	}

	@CliCommand(value = "bugs sync", help = "Synchronize the bugs in a repository with upstream issue tracker")
	public String simple(
			@CliOption(key = "project", mandatory = true, help = "the project name") final String projectName) {
		Project project = projectRepository.findByName(projectName)
				.orElseThrow(() -> new IllegalArgumentException("There is no such project"));

		throw new NotImplementedException();
	}
}

Add structure for bugs sync command


/**
 * Copyright (C) 2011 Akiban Technologies Inc.
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * 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 com.akiban.server.store.statistics;

import com.akiban.sql.pg.PostgresServerFilesITBase;
import static com.akiban.sql.TestBase.*;

import org.junit.Before;
import org.junit.Test;
import static junit.framework.Assert.*;

import java.util.*;
import java.io.File;

public class PersistitStoreIndexStatisticsIT extends PostgresServerFilesITBase
{
    public static final File RESOURCE_DIR =
        new File("src/test/resources/"
                 + IndexStatisticsYamlTest.class.getPackage().getName().replace('.', '/'));
    public static final File YAML_FILE = new File(RESOURCE_DIR, "stats.yaml");

    private IndexStatisticsService service;

    @Before
    public void loadDatabase() throws Exception {
        loadDatabase(RESOURCE_DIR);
    }

    @Before
    public void getService() throws Exception {
        service = serviceManager().getServiceByClass(IndexStatisticsService.class);
    }

    @Override
    public void openTheConnection() throws Exception {
        // TODO: Test class modularity isn't right.
    }

    @Test
    public void testLoadDump() throws Exception {
        service.loadIndexStatistics(session(), "user", YAML_FILE);
        File tempFile = File.createTempFile("stats", "yaml");
        service.dumpIndexStatistics(session(), "user", tempFile);
        assertEquals("dump matches load",
                     fileContents(YAML_FILE).replace("\r", ""),
                     fileContents(tempFile).replace("\r", ""));
    }

}

Add an IT for Persistit storage.


package org.redalert1741.steamworks;

import org.redalert1741.robotBase.logging.DataLogger;
import org.redalert1741.robotBase.logging.Loggable;

import edu.wpi.first.wpilibj.Spark;

public class Climber implements Loggable
{
	private Spark climber1;
	private Spark climber2;

	public Climber(int c1, int c2)
	{
		climber1 = new Spark(c1);
		climber2 = new Spark(c2);
	}

	@Override
	public void setupLogging(DataLogger logger)
	{
		logger.addAttribute("climber1_Setpoint");
		logger.addAttribute("climber2_Setpoint");
	}

	@Override
	public void log(DataLogger logger)
	{
		logger.log("climber1_Setpoint", climber1.get());
		logger.log("climber2_Setpoint", climber2.get());
	}

}

Add basic climber with logging


package gate.plugin.learningframework.pipelines;

import gate.creole.PackagedController;
import gate.creole.metadata.AutoInstance;
import gate.creole.metadata.AutoInstanceParam;
import gate.creole.metadata.CreoleResource;

/**
 *
 * @author Johann Petrak <johann.petrak@gmail.com>
 */
@CreoleResource(
        name = "LF_TrainTopicModel-Mallet-EN",
        comment = "Example steps to prepare and train a topic model using Mallet LDA",
        // icon = "measurements",
        autoinstances = @AutoInstance(parameters = {
          @AutoInstanceParam(name="pipelineURL", value="resources/pipelines/LF_TrainTopicModel-Mallet-EN.xgapp"),
          @AutoInstanceParam(name="menu", value="LearningFramework")}))
public class LF_TrainTopicModel_Mallet_EN extends PackagedController {

}

Add the file for creating the ready made topic model training app.


package com.alexrnl.jbetaseries.request.shows;

import com.alexrnl.jbetaseries.request.APIAddresses;
import com.alexrnl.jbetaseries.request.Request;
import com.alexrnl.jbetaseries.request.Verb;
import com.alexrnl.jbetaseries.request.parameters.ShowId;

/**
 * Unset the note on a given show for the identified user.

 * @author Alex
 */
public class ShowUnnote extends Request {

	/**
	 * Constructor #1.

	 * @param showId
	 *        the id of the show.
	 */
	public ShowUnnote (final Integer showId) {
		super(Verb.DELETE, APIAddresses.SHOWS_NOTE);
		addParameter(new ShowId(showId));
	}
}

Add the shows/note DELETE request


package leetcode;

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

/**
 * @author fredy
 */
public class Problem341 {
    public interface NestedInteger {
        // @return true if this NestedInteger holds a single integer, rather than a nested list.
        public boolean isInteger();

        // @return the single integer that this NestedInteger holds, if it holds a single integer
        // Return null if this NestedInteger holds a nested list
        public Integer getInteger();

        // @return the nested list that this NestedInteger holds, if it holds a nested list
        // Return null if this NestedInteger holds a single integer
        public List<NestedInteger> getList();
    }

    public static class NestedIterator implements Iterator<Integer> {
        public NestedIterator(List<NestedInteger> nestedList) {
            // TODO
        }

        @Override
        public Integer next() {
            // TODO:
            return null;
        }

        @Override
        public boolean hasNext() {
            // TODO:
            return false;
        }
    }

    public static void main(String[] args) {
        NestedIterator i = new NestedIterator(null);
        while (i.hasNext()) {
            System.out.println(i.next());
        }
    }
}

Create a skeleton for problem 341


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

import jaist.echonet.EOJ;
import jaist.echonet.EchonetCharacterProperty;
import jaist.echonet.EchonetNode;
import jaist.echonet.EchonetProperty;
import jaist.echonet.LocalEchonetObject;
import jaist.echonet.gui.NetworkScanner;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author haha
 */
public class TemperatureSensorApp {

    EchonetNode context;
    LocalEchonetObject temperaturesensor;
    byte numberofsensors = 1;
    static byte TEMPSENSORCLASSGROUP = 0x00;
    static byte TEMPSENSORCLASS = 0x11;

    public static void main(String args[]) {
        InetAddress address = null;
        try {
            if (args.length > 0) {
                address = InetAddress.getByName(args[0]);
            }
        } catch (UnknownHostException ex) {
            Logger.getLogger(NetworkScanner.class.getName()).log(Level.SEVERE, null, ex);
        }
        new TemperatureSensorApp(address);
    }

    public TemperatureSensorApp(InetAddress address) {
        context = new EchonetNode(address);
        context.registerEchonetObject(getTemperatureSensorInstance());
        Thread t = context.start();
        //prevent exit of program; t is a daemon thread.
        while (true) {
            try {
                t.join();
            } catch (InterruptedException ex) {
                Logger.getLogger(TemperatureSensorApp.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private LocalEchonetObject getTemperatureSensorInstance() {
        EOJ sensoreoj = new EOJ(TEMPSENSORCLASSGROUP, TEMPSENSORCLASS, numberofsensors++);
        List<EchonetProperty> properties = new ArrayList<>();
        properties.add(new EchonetCharacterProperty((byte) 0x80, true, false, true, 1, 0, new byte[]{0x30}));
        properties.add(new EchonetProperty((byte) 0xE0, true, false, true, 2, 1) {

            short temperature = 0;

            @Override
            public byte[] read() {
                byte[] result = new byte[2];
                //convert the temperature
                result[0] = (byte) (temperature >> 8);
                result[1] = (byte) (temperature & 0x00ff);
                System.out.println("Current temperature: " + temperature * 10 + "\n");

                //increase temperature for next time
                temperature++;
                return result;
            }

            @Override
            public boolean write(byte[] data) {
                throw new UnsupportedOperationException("This will never be called");
            }

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

        LocalEchonetObject sensor = new LocalEchonetObject(sensoreoj, properties);
        return sensor;
    }
}

Add sample temperature sensor application.


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

package com.michaelrocks.lightsaber;

import javax.inject.Provider;

public class SingletonProvider<T> implements Provider<T> {
    private final Provider<T> provider;
    private volatile T instance;
    private final Object instanceLock = new Object();

    public SingletonProvider(final Provider<T> provider) {
        this.provider = provider;
    }

    @Override
    public T get() {
        if (instance == null) {
            synchronized (instanceLock) {
                if (instance == null) {
                    instance = provider.get();
                }
            }
        }
        return instance;
    }
}

Implement provider for singleton scope


package gov.nih.nci.objectCart.jUnit.applicationService.impl;
import gov.nih.nci.objectCart.util.xml.ValidationErrorHandler;
import gov.nih.nci.objectCart.util.xml.Validator;

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

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import junit.framework.TestCase;

public class GMETest extends TestCase{

		public void test1()
		{
			SAXParserFactory factory = SAXParserFactory.newInstance();
			factory.setValidating(false);
			factory.setNamespaceAware(true);

			SchemaFactory schemaFactory = SchemaFactory
					.newInstance("http://www.w3.org/2001/XMLSchema");

			String schema = Validator.getSchema("gme://caCORE.caBIG/3.0/gov.nih.nci.cadsr.domain");

			System.out.println(schema);
//			try {
//			factory.setSchema(
//					schemaFactory.newSchema(
//							new Source[] {new StreamSource(schema)} ));
//
//			SAXParser parser = factory.newSAXParser();
//
//			XMLReader reader = parser.getXMLReader();
//
//			reader.setErrorHandler(new ValidationErrorHandler());
//			StringReader strReader = new StringReader("TEST DATA HERE");
//			InputSource inputSource = new InputSource(strReader);
//
//			reader.parse(inputSource);
//
//			} catch (SAXException se){
//				se.printStackTrace();
//			} catch (IOException ioe){
//				ioe.printStackTrace();
//			} catch (ParserConfigurationException pce){
//				pce.printStackTrace();
//			}
		}

}

Test for GME connection. Still not working


/*
 *  Copyright 2012 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.editor;

import java.beans.PropertyEditorSupport;

import com.ajah.util.Identifiable;

/**
 * Generic class that will map an enum based on its {@link Identifiable#getId()}
 * method.
 *
 * @author Eric F. Savage, code@efsavage.com.
 *
 * @param <E>
 */
public class IdentifiableEnumPropertyEditor<E extends Identifiable<?>> extends PropertyEditorSupport {

	private E[] values;

	/**
	 * Pass the result of Enum.getValues() because I can't seem to find a way to
	 * derive this from the type parameter.
	 *
	 * @param values
	 *            The values of the enum.
	 */
	public IdentifiableEnumPropertyEditor(E[] values) {
		this.values = values;
	}

	/**
	 * Sets the property value by parsing a given String. May raise
	 * java.lang.IllegalArgumentException if either the String is badly
	 * formatted or if this kind of property can't be expressed as text.
	 *
	 * @param text
	 *            The string to be parsed.
	 */
	@Override
	public void setAsText(String text) throws java.lang.IllegalArgumentException {
		for (E candidate : this.values) {
			if (candidate.getId().toString().equals(text)) {
				setValue(candidate);
				return;
			}
		}
		throw new java.lang.IllegalArgumentException(text);
	}

	/**
	 * Gets the property value as a string suitable for presentation to a human
	 * to edit.
	 *
	 * @return The property value as a string suitable for presentation to a
	 *         human to edit.
	 *

	 *         Returns null if the value can't be expressed as a string.
	 *

	 *         If a non-null value is returned, then the PropertyEditor should
	 *         be prepared to parse that string back in setAsText().
	 */
	@SuppressWarnings("unchecked")
	@Override
	public String getAsText() {
		return (this.getValue() != null) ? ((E) this.getValue()).getId().toString() : null;
	}

}

Add property editor for identifiable enums


public class Solution {

    public int rob(int[] nums) {

        int current = 0;
        int last = 0;

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

            int tmp = current;
            current = Math.max(last + nums[i], current);
            last = tmp;

        }

        return current;

    }

}

Create : 198 House Robber


package org.jdbi.v3.pg;

import com.opentable.db.postgres.embedded.EmbeddedPostgreSQLRule;

import org.jdbi.v3.DBI;
import org.jdbi.v3.Handle;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

/**
 * Helper for a single, superuser privileged Postgres database.
 */
public class PostgresDbRule implements TestRule {

    public EmbeddedPostgreSQLRule pg = new EmbeddedPostgreSQLRule();
    private DBI dbi;
    private Handle h;

    @Override
    public Statement apply(Statement base, Description description) {
        return pg.apply(new Statement() {
            @Override
            public void evaluate() throws Throwable {
                dbi = DBI.create(pg.getEmbeddedPostgreSQL().getDatabase("postgres", "postgres"))
                        .installPlugin(new PostgresJdbiPlugin());
                h = dbi.open();

                try {
                    base.evaluate();
                } finally {
                    dbi = null;
                    h.close();
                    h = null;
                }
            }
        }, description);
    }

    public DBI getDbi() {
        if (dbi == null) throw new AssertionError("Test not running");
        return dbi;
    }

    public Handle getSharedHandle() {
        if (h == null) throw new AssertionError("Test not running");
        return h;
    }
}

Add a Rule to make writing tests easy


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

package com.google.bitcoin.examples;

import com.google.bitcoin.core.*;

import java.io.File;
import java.math.BigInteger;
import java.net.InetAddress;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * RefreshWallet loads a wallet, then processes the block chain to update the transaction pools within it.
 */
public class RefreshWallet {
    public static void main(String[] args) throws Exception {
        File file = new File(args[0]);
        Wallet wallet = Wallet.loadFromFile(file);
        System.out.println(wallet.toString());

        // Set up the components and link them together.
        final NetworkParameters params = NetworkParameters.testNet();
        BlockStore blockStore = new MemoryBlockStore(params);
        NetworkConnection conn = new NetworkConnection(InetAddress.getLocalHost(), params,
                                                       blockStore.getChainHead().getHeight(), 60000);
        BlockChain chain = new BlockChain(params, wallet, blockStore);
        Peer peer = new Peer(params, conn, chain);
        peer.start();

        wallet.addEventListener(new WalletEventListener() {
            public void onCoinsReceived(Wallet w, Transaction tx, BigInteger prevBalance, BigInteger newBalance) {
                System.out.println("\nReceived tx " + tx.getHashAsString());
                System.out.println(tx.toString());
            }
        });

        // Now download and process the block chain.
        CountDownLatch progress = peer.startBlockChainDownload();
        long max = progress.getCount();  // Racy but no big deal.
        if (max > 0) {
            System.out.println("Downloading block chain. " + (max > 1000 ? "This may take a while." : ""));
            long current = max;
            while (current > 0) {
                double pct = 100.0 - (100.0 * (current / (double) max));
                System.out.println(String.format("Chain download %d%% done", (int) pct));
                progress.await(1, TimeUnit.SECONDS);
                current = progress.getCount();
            }
        }
        peer.disconnect();
        wallet.saveToFile(file);
        System.out.println("\nDone!\n");
        System.out.println(wallet.toString());
    }
}

Add a program that just loads a wallet, runs through the block chain, and then saves/prints out the resulting wallet at the end.


/*
 * Copyright 2013-2016 Netherlands Forensic Institute
 *
 * 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 nl.minvenj.nfi.metal;

import static nl.minvenj.nfi.metal.Shorthand.con;
import static nl.minvenj.nfi.metal.Shorthand.def;
import static nl.minvenj.nfi.metal.Shorthand.ref;
import static nl.minvenj.nfi.metal.Shorthand.seq;

import java.io.IOException;

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

import nl.minvenj.nfi.metal.data.ByteStream;
import nl.minvenj.nfi.metal.data.Environment;
import nl.minvenj.nfi.metal.data.ParseResult;
import nl.minvenj.nfi.metal.encoding.Encoding;
import nl.minvenj.nfi.metal.token.Token;
import nl.minvenj.nfi.metal.util.InMemoryByteStream;

public class DefSizeTest {
    public static final Token FORMAT =
        seq(
            def("length", con(4)),
            def("data", ref("length"))
        );

    @Test
    public void testValidLength() throws IOException {
        final ByteStream stream = new InMemoryByteStream(new byte[]{
            0x00, 0x00, 0x00, 0x02, // length = 2
            0x04, 0x08
        });
        final ParseResult result = FORMAT.parse(new Environment(stream), new Encoding());

        Assert.assertTrue(result.succeeded());
        Assert.assertArrayEquals(
            new byte[]{0x04, 0x08},
            result.getEnvironment().order.flatten().get("data").getValue()
        );
    }

    @Test
    public void testInvalidLength() throws IOException {
        final ByteStream stream = new InMemoryByteStream(new byte[]{
            -1, -1, -1, -1, // length = -1
            0x04, 0x08
        });
        final ParseResult result = FORMAT.parse(new Environment(stream), new Encoding());

        Assert.assertFalse(result.succeeded());
        Assert.assertEquals(-1, result.getEnvironment().order.flatten().get("length").asNumeric().intValue());
    }
}

Test valid vs. invalid length reference handling


/*
 * Copyright 2011 Greplin, Inc. All Rights Reserved.
 */

package com.greplin.lucene.query;

import com.sun.istack.internal.Nullable;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanFilter;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.FilterClause;

/**
 * Static utility methods for Filters.
 */
public final class Filters {

  /** Not instantiable. */
  private Filters() { }

  /**
   * Returns a filter that allows documents that match every constituent
   * filter.  For convenience, null values are accepted and ignored.  If
   * all values are null, null will be returned.
   * @param filters the filters to combine
   * @return the combined filter
   */
  @Nullable public static Filter and(@Nullable final Filter... filters) {
    final BooleanFilter booleanFilter = new BooleanFilter();

    Filter lastFilter = null;
    int count = 0;
    for (Filter filter : filters) {
      if (filter != null) {
        booleanFilter.add(new FilterClause(filter, BooleanClause.Occur.MUST));
        count += 1;
        lastFilter = filter;
      }
    }

    if (count == 0) {
      return null;
    } else if (count == 1) {
      return lastFilter;
    } else {
      return booleanFilter;
    }
  }

  /**
   * Returns a filter matching the inverse of the given filter.
   * @param filter the filter to return the opposite ofnegate
   * @return the negated filter
   */
  public static Filter not(final Filter filter) {
    final BooleanFilter booleanFilter = new BooleanFilter();
    booleanFilter.add(new FilterClause(filter, BooleanClause.Occur.MUST_NOT));
    return booleanFilter;
  }

}

Add static utility methods for filters


package at.ac.tuwien.inso.controller.student;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.security.Principal;
import java.util.List;

import at.ac.tuwien.inso.entity.Course;
import at.ac.tuwien.inso.entity.Student;
import at.ac.tuwien.inso.service.CourseService;
import at.ac.tuwien.inso.service.StudentService;
import at.ac.tuwien.inso.service.SubjectService;
import at.ac.tuwien.inso.service.course_recommendation.RecommendationService;

@Controller
@RequestMapping("/student/courses/semester/subject")
public class StudentCoursesForSemesterAndSubjectController {

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

    @Autowired
    private CourseService courseService;

    @Autowired
    private SubjectService subjectService;

    @GetMapping
    public String courses(@RequestParam Long subjectId, Model model) {

        log.info("getting courses for subject " + subjectId);

        List<Course> courses = courseService.findCoursesForSubjectAndCurrentSemester(subjectService.findOne(subjectId));

        if (courses.size() == 1) {
            log.info("Subject only has one course this semester. Redirecting to course");
            return "redirect:/student/courses/" + courses.get(0).getId();
        }

        model.addAttribute("coursesForSemesterAndSubject", courses);
        return "/student/courses-for-subject";
    }

}

Add controller for courses of a subject in the current semester


package org.usfirst.frc2832.Robot_2016.vision;

import java.util.NavigableMap;
import java.util.TreeMap;

public class InterpolatedLookupTable {
	private NavigableMap<Double, Double> map;

	public InterpolatedLookupTable() {
		map = new TreeMap<>();
	}

	public void put(double key, double value) {
		map.put(key, value);
	}

	/**
	 * Gets a value, interpolating linearly
	 * @param key The key, or x-coordinate
	 * @return The value at key, or the analytic expansion of it
	 */
	public double get(double key) {
		if (map.containsKey(key))
			return (map.get(key));

		Double keyHigh = map.higherKey(key);
		Double keyLow  = map.lowerKey(key);

		if (keyHigh == null)
			keyHigh = map.lastKey();
		if (keyLow == null)
			keyLow = map.firstKey();

		double valLow = map.get(keyLow);
		double valHigh = map.get(keyHigh);

		if (keyHigh == keyLow)
			return (valLow);

		double t = (key - keyLow) / (keyHigh - keyLow);
		return ((1 - t) * valLow + (t) * valHigh);
	}
}

Add amazing lookup table class


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

package org.apache.flink.api.connector.sink;

import org.apache.flink.api.common.serialization.SerializationSchema;
import org.apache.flink.metrics.MetricGroup;
import org.apache.flink.util.UserCodeClassLoader;

import java.util.function.Supplier;

/**
 * Adapter between {@link Sink.InitContext} and {@link SerializationSchema.InitializationContext}.
 */
public class InitContextInitializationContextAdapter
        implements SerializationSchema.InitializationContext {

    private final UserCodeClassLoader userCodeClassLoader;
    private final Supplier<MetricGroup> metricGroupSupplier;
    private MetricGroup cachedMetricGroup;

    public InitContextInitializationContextAdapter(
            UserCodeClassLoader userCodeClassLoader, Supplier<MetricGroup> metricGroupSupplier) {
        this.userCodeClassLoader = userCodeClassLoader;
        this.metricGroupSupplier = metricGroupSupplier;
    }

    @Override
    public MetricGroup getMetricGroup() {
        if (cachedMetricGroup == null) {
            cachedMetricGroup = metricGroupSupplier.get();
        }
        return cachedMetricGroup;
    }

    @Override
    public UserCodeClassLoader getUserCodeClassLoader() {
        return userCodeClassLoader;
    }
}

Add adapter between Sink.InitContext and SerializationSchema.InitializationContext


package com.thinkbiganalytics.metadata.upgrade.v084;

/*-
 * #%L
 * kylo-upgrade-service
 * %%
 * Copyright (C) 2017 ThinkBig Analytics
 * %%
 * 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.
 * #L%
 */

import com.thinkbiganalytics.KyloVersion;
import com.thinkbiganalytics.metadata.modeshape.JcrMetadataAccess;
import com.thinkbiganalytics.server.upgrade.KyloUpgrader;
import com.thinkbiganalytics.server.upgrade.UpgradeException;
import com.thinkbiganalytics.server.upgrade.UpgradeState;

import org.modeshape.jcr.api.Workspace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.jcr.RepositoryException;

/**
 * Initializes all of the ModeShape indexes introduced in 0.8.4.
 */
@Component("reindexUpgradeAction084")
@Order(0)
@Profile(KyloUpgrader.KYLO_UPGRADE)
public class ReindexUpgradeAction implements UpgradeState {

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

    @Override
    public boolean isTargetVersion(KyloVersion version) {
        return version.matches("0.8", "4", "");
    }

    @Override
    public void upgradeTo(final KyloVersion startingVersion) {
        log.info("Re-indexing metadata for version:: {}", startingVersion);

        try {
            Workspace workspace = (Workspace) JcrMetadataAccess.getActiveSession().getWorkspace();
            workspace.reindex();
        } catch (RepositoryException e) {
            log.error("Failed to re-index metadata", e);
            throw new UpgradeException("Failed to re-index metadata", e);
        }
    }
}

Initialize ModeShape indexes during 0.8.4 upgrade.


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

package io.spine.io;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junitpioneer.jupiter.TempDirectory;
import org.junitpioneer.jupiter.TempDirectory.TempDir;

import java.io.File;
import java.net.URL;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.UUID;

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

@DisplayName("Resource files should")
@ExtendWith(TempDirectory.class)
class ResourceFilesTest {

    @Test
    @DisplayName("return an empty iterator if queried for a non-existing file ")
    void throwOnInvalidFileName(@TempDir Path path) {
        Path nonExistentFilePath = path.resolve(UUID.randomUUID()
                                                    .toString());
        File nonExistingFile = nonExistentFilePath.toFile();
        String name = nonExistingFile.getName();
        Iterator<URL> result = ResourceFiles.loadAll(name);
        assertFalse(result.hasNext());
    }
}

Add a resource files test.


/*
 * 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.jsmpp.bean;

import static org.junit.Assert.assertEquals;

import org.testng.annotations.Test;

public class DeliverSmTest {

  @Test
  public void testDeliverSm() {
    DeliverSm deliverSm = new DeliverSm();
    deliverSm.sourceAddr = "31612345678";
    deliverSm.sourceAddrTon = TypeOfNumber.INTERNATIONAL.value();
    deliverSm.sourceAddrNpi = NumberingPlanIndicator.ISDN.value();
    deliverSm.destAddress = "33600000000";
    deliverSm.destAddrTon = TypeOfNumber.INTERNATIONAL.value();
    deliverSm.destAddrNpi = NumberingPlanIndicator.ISDN.value();
    deliverSm.setOptionalParameters(
        new OptionalParameter.Message_state((byte) 0x02),
        new OptionalParameter.Receipted_message_id("123456"));

    assertEquals(OptionalParameter.Message_state.Message_state_enum.DELIVERED,
        ((OptionalParameter.Message_state)deliverSm.getOptionalParameter(OptionalParameter.Tag.MESSAGE_STATE)).getMessageState());
    assertEquals("123456",
        ((OptionalParameter.Receipted_message_id) deliverSm.getOptionalParameter(OptionalParameter.Tag.RECEIPTED_MESSAGE_ID)).getValueAsString());
  }

}

Add unit test for deliver_sm with optional parameters.


package whelk.export.servlet;

import org.junit.Assert;
import org.junit.Test;
import whelk.Document;
import whelk.Whelk;
import whelk.triples.JsonldSerializer;

import java.util.List;
import java.util.Set;

public class Other {
    /**
     * These tests have nothing to do with OAIPMH. Rather they are here because this test suite is the only one that
     * combines requiring example data, and being able to do white box code testing (test code internals).
     */

    /**
     * This test case dissolves a record into triples, and then reassembles the tripples. The reassembled version
     * must equal the original version.
     */
    /* This testcase unfortunately breaks due to repeatableTerms/forcedSetTerms inconsistencies. Reactivate once fixed!
    @Test
    public void testTripleDissolutionReassembly() throws Exception
    {
        Whelk whelk = Whelk.createLoadedCoreWhelk();
        Set<String> repeatableTerms = whelk.getJsonld().getRepeatableTerms();

        Document originalDocument = whelk.getStorage().load("s93qhl340tcvtcp"); // Alice in Wonderland and Through the looking-glass

        List<String[]> triples = new JsonldSerializer().deserialize(originalDocument.data);

        Document reassembledDocument = new Document(JsonldSerializer.serialize(triples, repeatableTerms));
        JsonldSerializer.normalize(reassembledDocument.data, reassembledDocument.getCompleteId(), false);
        JsonldSerializer.normalize(reassembledDocument.data, reassembledDocument.getCompleteId(), false);

        //System.out.println("original:\n" + originalDocument.getDataAsString());
        //System.out.println("reassembly:\n" + reassembledDocument.getDataAsString());

        Assert.assertEquals(reassembledDocument.getChecksum(), originalDocument.getChecksum());
    }
    */
}

Add triple-reassembly testcase. Unfortunately it won't pass at the moment, because the 'repeatableterms' logic isn't completely consistent.


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

package com.splunk;

import java.util.Map;

import org.junit.Test;

public class EntityTest extends SDKTestCase {
    private static final String QUERY = "search index=_internal | head 10";

    private static final String KEY = "isSavedSearch";
    private static final String VALUE = "0";

    @Test
    public void testMapOverrides() {
        Entity entity = service.getJobs().create(QUERY);

        assertFalse(entity.isEmpty());
        assertEquals(VALUE, entity.get(KEY));
        assertTrue(entity.containsKey(KEY));
        assertTrue(entity.containsValue(VALUE));
        assertTrue(entity.keySet().contains(KEY));
        assertTrue(entity.values().contains(VALUE));
        for (Map.Entry<String, Object> e : entity.entrySet()) {
            assertTrue(entity.containsKey(e.getKey()));
            assertTrue(entity.containsValue(e.getValue()));
        }

        try {
            entity.putAll(null);
            fail("Expected UnsupportedOperationException.");
        } catch (UnsupportedOperationException e) {
            // Good
        }

        try {
            entity.clear();
            fail("Expected UnsupportedOperationException.");
        } catch (UnsupportedOperationException e) {
            // Good
        }

        try {
            entity.remove(null);
            fail("Expected UnsupportedOperationException.");
        } catch (UnsupportedOperationException e) {
            // Good
        }
    }
}

Test map overrides on Entity.


package info.u_team.u_team_test2.init;

import org.apache.logging.log4j.LogManager;

import info.u_team.u_team_core.api.construct.*;
import info.u_team.u_team_test2.TestMod2;
import net.minecraft.block.Block;
import net.minecraftforge.event.RegistryEvent.Register;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;

@Construct(modid = TestMod2.MODID)
public class Test2CommonBusRegister implements IModConstruct {

	@Override
	public void construct() {
		Bus.MOD.bus().get().addGenericListener(Block.class, this::registerCall);
	}

	private void registerCall(Register<Block> event) {
		LogManager.getLogger().info("Hello from the register event for test mod 2");
	}

}

Add test common bus register for test mod 2


/*
 * 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.karaf.tooling.exam.regression;

import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import static org.apache.karaf.tooling.exam.options.KarafDistributionOption.editConfigurationFilePut;
import static org.apache.karaf.tooling.exam.options.KarafDistributionOption.karafDistributionConfiguration;
import static org.ops4j.pax.exam.CoreOptions.maven;
import static org.ops4j.pax.exam.CoreOptions.scanFeatures;

import javax.inject.Inject;

import org.apache.karaf.features.FeaturesService;
import org.apache.karaf.tooling.exam.options.configs.FeaturesCfg;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.Configuration;
import org.ops4j.pax.exam.junit.ExamReactorStrategy;
import org.ops4j.pax.exam.junit.JUnit4TestRunner;
import org.ops4j.pax.exam.spi.reactors.AllConfinedStagedReactorFactory;

/**
 * This test should validate if the versionAsInProject tags work as expected.
 */
@RunWith(JUnit4TestRunner.class)
@ExamReactorStrategy(AllConfinedStagedReactorFactory.class)
public class MixFeatureAndDeployFolderFalseTest {

    @Inject
    private FeaturesService featuresService;

    @Configuration
    public Option[] config() {
        return new Option[]{
            karafDistributionConfiguration()
                .frameworkUrl(
                    maven().groupId("org.apache.karaf").artifactId("apache-karaf").type("zip")
                        .versionAsInProject())
                .useDeployFolder(false), editConfigurationFilePut(FeaturesCfg.BOOT,
                "config,standard,region,package,ssh"),
            scanFeatures(maven().groupId("org.apache.karaf.features").artifactId("standard").type("xml")
                .classifier("features").versionAsInProject(), "kar").start() };
    }

    @Test
    public void test() throws Exception {
        assertFalse(featuresService.isInstalled(featuresService.getFeature("management")));
        assertTrue(featuresService.isInstalled(featuresService.getFeature("kar")));
    }

}

Add itest to prove fixes


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

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

import org.testng.annotations.Test;

import org.jenetics.example.tsp.GPX.*;

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

	@Test
	public void writeGPX() throws IOException {
		final GPX gpx = new GPX();
		gpx.addWayPoint(GPX.Location.of(23, 34));
		gpx.addWayPoint(GPX.Location.of(24, 35));

		GPX.write(gpx, System.out);
	}

	@Test
	public void readGPX() throws IOException {
		final String resource = "/org/jenetics/example/tsp/gpx_way_points.gpx";
		try (InputStream in = getClass().getResourceAsStream(resource)) {
			final GPX gpx = GPX.read(GPX.class, in);
			GPX.write(gpx, System.out);
		}
	}

}

Add test for GPX data-structures.


package org.labkey.dbutils.jooq;

import org.jetbrains.annotations.Nullable;
import org.jooq.DataType;
import org.jooq.Field;
import org.jooq.Record;
import org.jooq.Table;
import org.labkey.api.data.AbstractTableInfo;
import org.labkey.api.data.DbSchema;
import org.labkey.api.data.JdbcType;
import org.labkey.api.data.SQLFragment;
import org.labkey.api.query.ExprColumn;
import org.labkey.api.query.UserSchema;

/**
 * Created by jon on 3/28/17.
 */
public abstract class jOOQTableInfo<RecordType extends Record> extends AbstractTableInfo {
    protected UserSchema userSchema;

    public jOOQTableInfo(String tableName, String dbSchema, UserSchema userSchema) {
        super(DbSchema.get(dbSchema), tableName);
        this.userSchema = userSchema;

        registerColumns();
    }

    protected void registerColumns() {
        for (Field field : getjOOQTable().fields()) {
            this.registerColumn(field);
        }
    }

    protected void registerColumn(Field field) {
        DataType fieldType = field.getDataType();
        JdbcType jdbcType = JdbcType.valueOf(fieldType.getSQLType());
        String name = field.getName();

        this.addColumn(new ExprColumn(this, name, new SQLFragment(ExprColumn.STR_TABLE_ALIAS + "." + name), jdbcType));
    }

    @Override
    protected SQLFragment getFromSQL() {
        SQLFragment sql = new SQLFragment();

        try (jOOQConnection jOOQConnection = new jOOQConnection(userSchema.getSchemaName())) {
            sql.append(jOOQConnection.create().selectFrom(getjOOQTable()).getSQL());
        }

        return sql;
    }

    @Nullable
    @Override
    public UserSchema getUserSchema() {
        return this.userSchema;
    }

    public abstract Table<RecordType> getjOOQTable();
}

Add TableInfo wrapper for jOOQ Tables.


/*
 * 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.protonj2.client.exceptions;

import org.apache.qpid.protonj2.client.Message;

/**
 * Exception thrown from {@link Message} instances when the body section specified
 * violates the configure message format of the message that is being created.
 */
public class ClientMessageFormatViolationException extends ClientException {

    private static final long serialVersionUID = -7731216779946825581L;

    public ClientMessageFormatViolationException(String message) {
        super(message);
    }

    public ClientMessageFormatViolationException(String message, Throwable cause) {
        super(message, cause);
    }
}

Add new exception type to throw when validating message body sections


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

/**
* @author Vera Y. Petrashkova
* @version $Revision$
*/

package org.apache.harmony.security.tests.support;

import java.security.KeyStore;

/**
 * Additional class extends KeyStore.LoadStoreParameter
 */
public class MyLoadStoreParams implements
        KeyStore.LoadStoreParameter {

    KeyStore.ProtectionParameter protPar;

    public MyLoadStoreParams(KeyStore.ProtectionParameter p) {
        this.protPar = p;
    }

    public KeyStore.ProtectionParameter getProtectionParameter() {
        return protPar;
    }
}

Remove unnecessary check - testing scenario may need to pass null parameter


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

package imagej.script.io;

import imagej.io.AbstractIOPlugin;
import imagej.io.IOPlugin;
import imagej.script.ScriptService;

import java.io.IOException;

import org.scijava.plugin.Plugin;

/**
 * {@link IOPlugin} for scripts.
 *
 * @author Curtis Rueden
 * @see ScriptService
 */
@Plugin(type = IOPlugin.class)
public class ScriptIOPlugin extends AbstractIOPlugin<String> {

	// -- IOPlugin methods --

	@Override
	public Class<String> getDataType() {
		return String.class;
	}

	@Override
	public boolean supportsOpen(final String source) {
		final ScriptService scriptService =
			getContext().getService(ScriptService.class);
		return scriptService.canHandleFile(source);
	}

	@Override
	public String open(final String source) throws IOException {
		final ScriptService scriptService =
			getContext().getService(ScriptService.class);
		// TODO: Use the script service to open the file in the script editor.
		return null;
	}

}

Add I/O plugin stub for scripts


/*
 * Copyright (c) 2016 Spotify AB
 *
 * 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.
 */

/**
 * Extends the {@link java.util.concurrent.CompletableFuture Java completable future} API.  The main
 * entry point of this package is the {@link com.spotify.futures.CompletableFutures} class, that
 * contains useful static utility methods.
 *
 * <p> This package uses the convention that all method parameters are non-null by default, i.e.
 * unless indicated by a {@link javax.annotation.Nullable @Nullable} annotation.
 *
 * @since 0.1.0
 */
@ParametersAreNonnullByDefault
package com.spotify.futures;

import javax.annotation.ParametersAreNonnullByDefault;

Document the main package of the library


package com.github.onsdigital.babbage.api.endpoint;

import com.github.davidcarboni.restolino.framework.Api;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.core.Context;
import java.io.IOException;

/**
 * Created by mrout on 29/08/2017.
 */

@Api
public class Healthcheck {

    @GET
    public void get(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException {
        response.setStatus(HttpServletResponse.SC_OK);
    }
}

Add healthcheck endpoint to service


import java.util.*;

class Player {

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);

        // game loop
        while (true) {
            String enemy1 = in.next(); // name of enemy 1
            int dist1 = in.nextInt(); // distance to enemy 1
            String enemy2 = in.next(); // name of enemy 2
            int dist2 = in.nextInt(); // distance to enemy 2

            // Write an action using System.out.println()

            // Enter the code here

            if (dist1 < dist2) {
                System.out.println(enemy1);
            } else {
                System.out.println(enemy2);
            }
        }
    }
}

Add source code to Onboarding game


package org.apache.pig.impl.logicalLayer.validators;

import org.apache.pig.impl.logicalLayer.LogicalOperator;
import org.apache.pig.impl.logicalLayer.LogicalPlan;
import org.apache.pig.impl.plan.CompilationMessageCollector;
import org.apache.pig.impl.plan.PlanValidationException;
import org.apache.pig.impl.plan.PlanValidator;

public class SchemaAliasValidator extends PlanValidator<LogicalOperator, LogicalPlan> {
    public SchemaAliasValidator() {
    }

    public void validate(LogicalPlan plan,
                         CompilationMessageCollector msgCollector)
                                        throws PlanValidationException {
        // The first msgCollector is used in visitor
        // The second msgCollector is used by the validator
        super.validateSkipCollectException(new SchemaAliasVisitor(plan),
                                           msgCollector) ;

    }
}

Duplicate column names in foreach do not throw parser error


package leetcode.intersection_of_two_linked_lists;

import common.ListNode;

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA == null || headB == null){
        	return null;
        }
        if(headA == headB)
        	return headA;
        ListNode endA = headA, endB = headB;
        while(endA.next != null)
        	endA = endA.next;
        while(endB.next != null)
        	endB = endB.next;
        if(endA != endB)
        	return null;
        ListNode end = endA;
        end.next = headA;
        ListNode tortoise = headB.next, hare = headB.next.next;
        while(tortoise != hare){
        	tortoise = tortoise.next;
        	hare = hare.next.next;
        }
        hare = headB;
        while(hare != tortoise){
        	hare = hare.next;
        	tortoise = tortoise.next;
        }
        end.next = null;
        return tortoise;
    }
}

Add java solution for 160. Intersection of Two Linked Lists


package ru.stqa.selenium;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;

import java.util.List;
import java.util.concurrent.TimeUnit;

public class SearchMovieTest extends TestNgTestBase{

  @Test
    public void testSearchMovie() throws Exception {
    //login
    LoginTest.testLogin(driver);

    //search movie
    driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
    WebDriverWait wait = new WebDriverWait(driver, 30);
    List<WebElement> movieBoxesBefore = driver.findElements(By.xpath("//*[@class='movie_box']"));
    driver.findElement(By.xpath("//*[@class='movie_box']")).click();
    driver.findElement(By.xpath("//*[@title='Remove']")).click();
    wait.until(ExpectedConditions.alertIsPresent());
    Alert alert = driver.switchTo().alert();
    alert.accept();

    //check movies counter
    driver.findElement(By.linkText("Home")).click();
    wait.until(ExpectedConditions. //wait for home page to load
            presenceOfElementLocated(By.
                    xpath("//*[@class='searchbox']")));
    List<WebElement> movieBoxesAfter = driver.findElements(By.xpath("//*[@class='movie_box']"));
    if (movieBoxesAfter.size() != movieBoxesBefore.size() - 1)
      throw new Error("Фильм не удален");
  }
}

Revert "1. moviesAfter в AddMovieTest не получает нужного значения. Wait дожидается загрузки searchbox, но фильмы могут загрузиться позже. Нужно ждать загрузки именно нужного элемента."


package org.cyclops.colossalchests.block;

import net.minecraft.client.model.ModelChest;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.cyclops.colossalchests.ColossalChests;
import org.cyclops.colossalchests.client.render.tileentity.RenderTileEntityUncolossalChest;
import org.cyclops.colossalchests.tileentity.TileUncolossalChest;
import org.cyclops.cyclopscore.config.extendedconfig.BlockContainerConfig;

/**
 * Config for the {@link ColossalChest}.
 * @author rubensworks
 *
 */
public class UncolossalChestConfig extends BlockContainerConfig {

    /**
     * The unique instance.
     */
    public static UncolossalChestConfig _instance;

    /**
     * Make a new instance.
     */
    public UncolossalChestConfig() {
        super(
                ColossalChests._instance,
        	true,
            "uncolossalChest",
            null,
            UncolossalChest.class
        );
    }

    @Override
    @SideOnly(Side.CLIENT)
    public void onRegistered() {
        super.onRegistered();
        ModelChest model = new ModelChest();
        ColossalChests._instance.getProxy().registerRenderer(TileUncolossalChest.class, new RenderTileEntityUncolossalChest(model));
    }

}

Add missing Uncolossal Chest config


package util.game;

import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import util.gdl.grammar.Gdl;
import util.kif.KifReader;

/**
 * Test game repository that provides rulesheet-only access to games with no
 * associated metadata or other resources, to be used only for unit tests.
 *
 * @author Sam
 */
public final class TestGameRepository extends GameRepository {
    protected Set<String> getUncachedGameKeys() {
        Set<String> theKeys = new HashSet<String>();
        for(File game : new File("games/test").listFiles()) {
            if(!game.getName().endsWith(".kif")) continue;
            theKeys.add(game.getName().replace(".kif", ""));
        }
        return theKeys;
    }

    protected Game getUncachedGame(String theKey) {
    	try {
    		List<Gdl> theRules = KifReader.read(new File("games/test/" + theKey + ".kif").getAbsolutePath());
    		return new Game(theKey, null, null, null, null, theRules);
    	} catch (Exception e) {
    		throw new RuntimeException(e);
    	}
    }
}

Add a game repository specifically for unit tests, that can provide a listing of all of the available test games and load rulesheet-only versions of specific games.


public class MatrixChainMultiplication {
    public static void main(String[] args) {
        System.out.println(solve(new int[] { 6, 4, 30, 2, 10, 5 }));
    }

    public static int solve(int[] matrices) {
        int length = matrices.length;
        int[][] dp = new int[length][length];

        for (int i = 0; i < length; i ++) {
            for (int j = 0; j < length; j ++) {
                dp[i][j] = i == j ? 0 : Integer.MAX_VALUE;
            }
        }

        for (int jump = 1; jump < length - 1; jump ++) {
            for (int i = 1; i + jump < length; i ++) {
                int j = i + jump;
                int product = matrices[i - 1] * matrices[j];
                for (int k = i; k < j; k ++) {
                    dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k + 1][j] + (product * matrices[k]));
                }
            }
        }

        for (int i = 0; i < length; i ++) {
            for (int j = 0; j < length; j ++) {
                if (dp[i][j] == Integer.MAX_VALUE) {
                    System.out.print("-\t");
                } else {
                    System.out.print(dp[i][j] + "\t");
                }
            }
            System.out.println("");
        }

        return dp[1][length - 1];

    }
}

Add matrix chain multiplication algorithm


package org.apache.markt;

import java.util.EnumSet;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class ConfigListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        Filter f = new NoopFilter();

        FilterRegistration.Dynamic reg = sce.getServletContext().addFilter("noop", f);
        reg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // NO-OP
    }
}

Add a listener to configure the filter


package com.exalttech.trex.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RCPCommands {
    private static final class Commands {
        private static final String GET_ACTIVE_PGIDS = "get_active_pgids";
        private static final String GET_PGID_STATS = "get_pgid_stats";
    }

    private RCPCommands() {}

    public static String getActivePGIds() throws JsonProcessingException {
        return sendRequest(Commands.GET_ACTIVE_PGIDS, null);
    }

    public static String getPGIdStats(List<Integer> pgIds) throws JsonProcessingException {
        if (pgIds == null) {
            pgIds = new ArrayList<>();
        }
        final Map<String, Object> parameters = new HashMap<>();
        parameters.put("pgids", pgIds);
        return sendRequest(Commands.GET_PGID_STATS, parameters);
    }

    // Should be removed from here, it is needed only for old architecture
    private static String sendRequest(final String command, final Map<String, Object> parameters) throws
            JsonProcessingException
    {
        String stringParameters = "";
        if (parameters != null) {
            final String jsonParameters = new ObjectMapper().writeValueAsString(parameters);
            stringParameters = jsonParameters.substring(1, jsonParameters.length() - 1);
        }
        return ConnectionManager.getInstance().sendRequest(command, stringParameters);
    }
}

Add getActivePGIds and getPGIdStats commands.


package me.haosdent.cgroup.manage;

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

public class TestAdmin {

  @Before
  public void setUp() {}

  @After
  public void tearDown() {}

  @Test
  public void testUmount() {}

  @Test
  public void testCreateGroup() {}
}

Add admin manage test class.


package me.haosdent.cgroup.manage;

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

public class TestGroup {

  @Before
  public void setUp() {}

  @After
  public void tearDown() {}

  @Test
  public void testDelete() {}
}

Add group manage test class.


package com.netflix.suro.routing.filter;

import com.google.common.base.Predicate;

/**
 * A contract for filtering events. These filters can be applied/defined both at the publisher and subscriber level.

 * It is recommended to use a filter language as specified in {@link com.netflix.suro.routing.filter.lang} which provides
 * flexible ways of defining filters. However, for programmatic creation of simple or custom filters it may be easy
 * to directly implement this interface.

 * The structure of the event filters is entirely opaque to the event bus and all processing related to evaluation of
 * the same is left to the implementations.
 */
public interface MessageFilter extends Predicate<Object> {

    // Emphasize that every {@code MessageFilter} instance can be used as a key
    // in a collection.
    public int hashCode();

    public boolean equals(Object o);
}

Fix compilation error caused by missing class


package com.hubspot.singularity;

import com.codahale.metrics.servlets.MetricsServlet;
import io.dropwizard.Bundle;
import io.dropwizard.lifecycle.ServerLifecycleListener;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.eclipse.jetty.server.Server;

import javax.servlet.ServletContext;

/**
 * Expose Dropwizard's metrics registry to {@link com.hubspot.jackson.jaxrs.PropertyFilteringMessageBodyWriter}
 * via the servlet context.
 *
 * This class is picked up by autoconfig
 */
public class MetricsBundle implements Bundle {

  @Override
  public void initialize(Bootstrap<?> bootstrap) { }

  @Override
  public void run(final Environment environment) {
    // need to wait until the server is started to do this otherwise an IllegalStateException is thrown
    environment.lifecycle().addServerLifecycleListener(new ServerLifecycleListener() {
      @Override
      public void serverStarted(Server server) {
        ServletContext context = environment.getJerseyServletContainer().getServletContext();
        context.setAttribute(MetricsServlet.METRICS_REGISTRY, environment.metrics());
      }
    });
  }
}

Add a bundle to set the correct MetricsRegistry on the ServletContext


// [START apps_script_execute]
/**
 * Call the API to run an Apps Script function that returns a list
 * of folders within the user's root directory on Drive.
 *
 * @return list of String folder names and their IDs
 * @throws IOException
 */
private List<String> getDataFromApi()
        throws IOException, GoogleAuthException {
    // ID of the script to call. Acquire this from the Apps Script editor,
    // under Publish > Deploy as API executable.
    String scriptId = "ENTER_YOUR_SCRIPT_ID_HERE";

    List<String> folderList = new ArrayList<String>();

    // Create an execution request object.
    ExecutionRequest request = new ExecutionRequest()
            .setFunction("getFoldersUnderRoot");

    // Make the request.
    Operation op =
            mService.scripts().run(scriptId, request).execute();

    // Print results of request.
    if (op.getError() != null) {
        throw new IOException(getScriptError(op));
    }
    if (op.getResponse() != null &&
            op.getResponse().get("result") != null) {
        // The result provided by the API needs to be cast into
        // the correct type, based upon what types the Apps Script
        // function returns. Here, the function returns an Apps
        // Script Object with String keys and values, so must be
        // cast into a Java Map (folderSet).
        Map<String, String> folderSet =
                (Map<String, String>)(op.getResponse().get("result"));

        for (String id: folderSet.keySet()) {
            folderList.add(
                    String.format("%s (%s)", folderSet.get(id), id));
        }
    }

    return folderList;
}

/**
 * Interpret an error response returned by the API and return a String
 * summary.
 *
 * @param op the Operation returning an error response
 * @return summary of error response, or null if Operation returned no
 *     error
 */
private String getScriptError(Operation op) {
    if (op.getError() == null) {
        return null;
    }

    // Extract the first (and only) set of error details and cast as a Map.
    // The values of this map are the script's 'errorMessage' and
    // 'errorType', and an array of stack trace elements (which also need to
    // be cast as Maps).
    Map<String, Object> detail = op.getError().getDetails().get(0);
    List<Map<String, Object>> stacktrace =
            (List<Map<String, Object>>)detail.get("scriptStackTraceElements");

    java.lang.StringBuilder sb =
            new StringBuilder("\nScript error message: ");
    sb.append(detail.get("errorMessage"));

    if (stacktrace != null) {
        // There may not be a stacktrace if the script didn't start
        // executing.
        sb.append("\nScript error stacktrace:");
        for (Map<String, Object> elem : stacktrace) {
            sb.append("\n  ");
            sb.append(elem.get("function"));
            sb.append(":");
            sb.append(elem.get("lineNumber"));
        }
    }
    sb.append("\n");
    return sb.toString();
}
// [END apps_script_execute]

Migrate Apps Script Execution Snippet


package no.panopticon.client.sensor.impl;

import no.panopticon.client.model.Measurement;
import no.panopticon.client.sensor.Sensor;

import java.time.LocalDateTime;
import java.util.List;

import static java.util.Collections.singletonList;

public class ReportTimeSensor implements Sensor {
    @Override
    public List<Measurement> measure() {
        return singletonList(
                new Measurement("report.generated", "INFO", LocalDateTime.now().toString(), 0)
        );
    }
}

Add a sensor which gives the time for when the report was generated


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.laadadra.fitools.option;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

/**
 *
 * @author nabil.laadadra
 */
@RunWith(Suite.class)
@Suite.SuiteClasses(
{
  com.laadadra.fitools.option.OptionTest.class, com.laadadra.fitools.option.GaussianTest.class
})
public class OptionTestSuite
{

  @BeforeClass
  public static void setUpClass() throws Exception
  {
  }

  @AfterClass
  public static void tearDownClass() throws Exception
  {
  }

  @Before
  public void setUp() throws Exception
  {
  }

  @After
  public void tearDown() throws Exception
  {
  }

}

Add test suite for option tests


package leetcode.recover_binary_search_tree;

import java.util.Random;

import common.TreeNode;

public class Solution {
	TreeNode OffendingNode1;
	TreeNode OffendingNode2;
	TreeNode prev;

	public void inOrder(TreeNode node){
		if(node != null){
			inOrder(node.left);
			if(OffendingNode1 == null && prev != null && prev.val > node.val){
				OffendingNode1 = prev;
			}
			if(OffendingNode1 != null && OffendingNode2 == null && node.val > OffendingNode1.val){
				OffendingNode2 = prev;
			}
			prev = node;
			inOrder(node.right);
		}
	}

    public void recoverTree(TreeNode root) {
    	prev = OffendingNode1 = OffendingNode2 = null;
    	inOrder(root);
    	if(OffendingNode2 == null){
    		OffendingNode2 = prev;
    	}
    	int tmp = OffendingNode1.val;
    	OffendingNode1.val = OffendingNode2.val;
    	OffendingNode2.val = tmp;
    }

	public static int fillNumber = 0;

	public static void inOrder(TreeNode node, boolean gen){
		if(node != null){
			inOrder(node.left, gen);
			if(gen)
				node.val = fillNumber++;
			System.err.print(node.val + " ");
			inOrder(node.right, gen);
		}
	}

    public static void main(String[] args){
    	final int N = 15;
    	TreeNode[] tree = new TreeNode[N];
    	for(int i = N - 1; i >= 0; i--){
    		tree[i] = new TreeNode(0);
    		if(i * 2 + 1 < N)
    			tree[i].left = tree[i * 2 + 1];
    		if(i * 2 + 2 < N)
    			tree[i].right = tree[i * 2 + 2];
    	}
    	inOrder(tree[0], true);
    	System.err.println("");

    	Random r = new Random();
    	int x = r.nextInt(N);
    	int y = x;
    	while(y == x){
    		y = r.nextInt(N);
    	}
    	System.err.println(tree[x].val + " swaps " + tree[y].val);
    	int tmp = tree[x].val;
    	tree[x].val = tree[y].val;
    	tree[y].val = tmp;

    	inOrder(tree[0], false);
    	System.err.println("");

    	new Solution().recoverTree(tree[0]);

    	inOrder(tree[0], false);
    	System.err.println("");

    	TreeNode tn1 = new TreeNode(2);
    	TreeNode tn2 = new TreeNode(1);
    	tn1.right = tn2;
    	inOrder(tn1, false);
    	System.err.println("");
    	new Solution().recoverTree(tn1);
    	inOrder(tn1, false);
    	System.err.println("");
    }
}

Add java solution for 99. Recover Binary Search Tree


package de.fau.amos.virtualledger.dtos;

public class SavingsAccountSubGoal {

    private String name;
    private String amount;

    public String getName() {
        return name;
    }

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

    public String getAmount() {
        return amount;
    }

    public void setAmount(final String amount) {
        this.amount = amount;
    }
}

Add data object for saving SubGoals


package com.jakewharton.trakt.services;

import com.jakewharton.trakt.entities.TvShow;
import retrofit.http.GET;
import retrofit.http.Path;

/**
 * Endpoints for Show.
 */
public interface Show {

    @GET("/show/summary.json/{apikey}/{title}")
    TvShow summary(
            @Path("title") String slug
    );

    @GET("/show/summary.json/{apikey}/{title}")
    TvShow summary(
            @Path("title") int tvdbId
    );

    @GET("/show/summary.json/{apikey}/{title}/extended")
    TvShow summaryExtended(
            @Path("title") String slug
    );

    @GET("/show/summary.json/{apikey}/{title}/extended")
    TvShow summaryExtended(
            @Path("title") int tvdbId
    );

}

Add retrofit interface for show summary.


package uk.org.taverna.scufl2.api.common;

import org.junit.Test;

import uk.org.taverna.scufl2.api.ExampleWorkflow;
import uk.org.taverna.scufl2.api.common.Visitor.VisitorAdapter;
import uk.org.taverna.scufl2.api.container.WorkflowBundle;

public class TestSetParent {
	WorkflowBundle example = new ExampleWorkflow().makeWorkflowBundle();

	Scufl2Tools tools = new Scufl2Tools();

	@Test
	public void checkParents() throws Exception {
		example.accept(new VisitorAdapter() {
			@Override
			public boolean visit(WorkflowBean node) {
				if (node instanceof Child) {
					Child child = (Child) node;
					WorkflowBean parent = child.getParent();
					WorkflowBean expectedParent = getCurrentPath().peek();
					if (!(parent == expectedParent)) {
						throw new IllegalStateException("Wrong parent for "
								+ node + ": " + parent + ", expected: "
								+ expectedParent);
					}
				}
				return true;
			}

			@Override
			public boolean visitEnter(WorkflowBean node) {
				visit(node);
				return super.visitEnter(node);
			}
		});
	}

}

Test that all parents are set