package com.connectsdk.device;

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

import junit.framework.Assert;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import com.connectsdk.service.DeviceService;
import com.connectsdk.service.capability.Launcher;
import com.connectsdk.service.capability.MediaPlayer;

public class ConnectableDeviceTest {

	private ConnectableDevice device;

	@Before
	public void setUp() {
		device = new ConnectableDevice();
	}

	@Test
	public void testHasCapabilityWithEmptyServices() {
		Assert.assertFalse(device.hasCapability(MediaPlayer.Display_Video));
	}

	@Test
	public void testHasCapabilityWithServices() {
		DeviceService service = Mockito.mock(DeviceService.class);
		Mockito.when(service.hasCapability(MediaPlayer.Display_Video)).thenReturn(Boolean.TRUE);
		device.services.put("service", service);
		Assert.assertTrue(device.hasCapability(MediaPlayer.Display_Video));
	}

	@Test
	public void testHasAnyCapabilities() {
		DeviceService service = Mockito.mock(DeviceService.class);
		String[] capabilities = {Launcher.Browser, Launcher.YouTube};
		Mockito.when(service.hasAnyCapability(capabilities)).thenReturn(Boolean.TRUE);
		device.services.put("service", service);
		Assert.assertTrue(device.hasAnyCapability(capabilities));
	}

	@Test
	public void testHasAnyCapabilitiesWithoutServices() {
		DeviceService service = Mockito.mock(DeviceService.class);
		String[] capabilities = {Launcher.Browser, Launcher.YouTube};
		Mockito.when(service.hasAnyCapability(capabilities)).thenReturn(Boolean.FALSE);
		device.services.put("service", service);
		Assert.assertFalse(device.hasAnyCapability(capabilities));
	}

	@Test
	public void testHasCapabilities() {
		DeviceService service = Mockito.mock(DeviceService.class);
		Mockito.when(service.hasCapability(Launcher.Browser)).thenReturn(Boolean.TRUE);
		Mockito.when(service.hasCapability(Launcher.YouTube)).thenReturn(Boolean.TRUE);
		device.services.put("service", service);

		List<String> capabilities = new ArrayList<String>();
		capabilities.add(Launcher.Browser);
		capabilities.add(Launcher.YouTube);

		Assert.assertTrue(device.hasCapabilities(capabilities));
	}

}

Add test for hasCapability* methods of ConnectableDevice


package org.fxmisc.richtext.model;

import org.fxmisc.richtext.InlineCssTextArea;
import org.junit.Test;

public class AreaTest {

    private InlineCssTextArea area = new InlineCssTextArea();

    @Test
    public void deletingTextThatWasJustInsertedShouldNotMergeTheTwoChanges() {
        area.replaceText(0, 0, "text");
        area.replaceText(0, area.getLength(), "");
        area.undo();
    }
}

Add test to insure mergeWith does not throw Exception


/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2014, Red Hat, Inc., and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.jboss.threads;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.LockSupport;

import junit.framework.TestCase;

/**
 * @author David M. Lloyd
 */
public class DeferredInterruptTestCase extends TestCase {

    public void testDeferral() throws Exception {
        final AtomicBoolean delivered0 = new AtomicBoolean();
        final AtomicBoolean deferred = new AtomicBoolean();
        final AtomicBoolean delivered = new AtomicBoolean();
        final CountDownLatch latch1 = new CountDownLatch(1);
        final CountDownLatch latch2 = new CountDownLatch(1);
        final JBossThread thread = new JBossThread(new Runnable() {
            public void run() {
                latch1.countDown();
                LockSupport.parkNanos(3000000000L);
                delivered0.set(Thread.interrupted());
                JBossThread.executeWithInterruptDeferred(new Runnable() {
                    public void run() {
                        latch2.countDown();
                        LockSupport.parkNanos(500000000L);
                        deferred.set(! Thread.interrupted());
                    }
                });
                delivered.set(Thread.interrupted());
            }
        });
        thread.start();
        latch1.await();
        thread.interrupt();
        latch2.await();
        thread.interrupt();
        thread.join();
        assertTrue(delivered0.get());
        assertTrue(deferred.get());
        assertTrue(delivered.get());
    }
}

Test case for interrupt deferral


// default package

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

import java.util.List;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

class UtilTests {

  @Nested
  class Args {

    @Test
    void empty() {
      var args = new Bach.Util.Args();
      assertLinesMatch(List.of(), args.list());
      assertEquals("Args{}", args.toString());
      assertArrayEquals(new String[0], args.toStrings());
    }

    @Test
    void touch() {
      var args =
          new Bach.Util.Args()
              .add(1)
              .add("key", "value")
              .add(true, "first")
              .add(true, "second", "more")
              .add(false, "suppressed")
              .forEach(List.of('a', 'b', 'c'), Bach.Util.Args::add);
      assertLinesMatch(
          List.of("1", "key", "value", "first", "second", "more", "a", "b", "c"), args.list());
    }
  }
}

Add unit test for common utilities


package org.sagebionetworks.bridge.redis;

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

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

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class JedisOpsTest {

    private Jedis jedis;
    private JedisOps ops;

    @Before
    public void before() {
        jedis = mock(Jedis.class);
        JedisPool pool = mock(JedisPool.class);
        when(pool.getResource()).thenReturn(jedis);
        ops = new JedisOps(pool);
    }

    @Test
    public void testZadd() {
        ops.zadd("key", 1.1, "member");
        verify(jedis, times(1)).zadd("key", 1.1, "member");
    }

    @Test
    public void testZscore() {
        ops.zscore("key", "member");
        verify(jedis, times(1)).zscore("key", "member");
    }

    @Test
    public void testZrank() {
        ops.zrank("key", "member");
        verify(jedis, times(1)).zrank("key", "member");
    }

    @Test
    public void testZrangeByScore() {
        ops.zrangeByScore("key", 1.1, 1.2);
        verify(jedis, times(1)).zrangeByScore("key", 1.1, 1.2);
    }
}

Add tests to the sorted set commands


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

public class <+FILEBASE+> {
	public static void main(String[] args) throws Exception {
		try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
			br.lines()
				.map(line -> Arrays.stream(line.split(" "))
						.mapToInt(Integer::parseInt)
						.toArray())
				.forEach(intArray -> {
					<+CURSOR+>
				});
		}
	}
}

Fix a programming contest template for Java8


/* **********************************************************************
    Copyright 2006 Rensselaer Polytechnic Institute. All worldwide rights reserved.

    Redistribution and use of this distribution in source and binary forms,
    with or without modification, are permitted provided that:
       The above copyright notice and this permission notice appear in all
        copies and supporting documentation;

        The name, identifiers, and trademarks of Rensselaer Polytechnic
        Institute are not used in advertising or publicity without the
        express prior written permission of Rensselaer Polytechnic Institute;

    DISCLAIMER: The software is distributed" AS IS" without any express or
    implied warranty, including but not limited to, any implied warranties
    of merchantability or fitness for a particular purpose or any warrant)'
    of non-infringement of any current or pending patent rights. The authors
    of the software make no representations about the suitability of this
    software for any particular purpose. The entire risk as to the quality
    and performance of the software is with the user. Should the software
    prove defective, the user assumes the cost of all necessary servicing,
    repair or correction. In particular, neither Rensselaer Polytechnic
    Institute, nor the authors of the software are liable for any indirect,
    special, consequential, or incidental damages related to the software,
    to the maximum extent the law permits.
*/

package edu.rpi.sss.util;

import org.apache.log4j.Logger;

import java.io.Serializable;
import java.lang.ref.SoftReference;
import java.util.WeakHashMap;

/** Implement a pool of objects whose values appear frequently enough that pooling
 * will result in a substantial reduction in space and or cpu.
 *
 * <p>Objects pooled must be either immutable or sharable because they will be
 * shared.
 *
 * @author Mike Douglass
 *
 * @param <T>
 */
public class ObjectPool<T> implements Serializable {
  private WeakHashMap<T, SoftReference<T>> pool =
    new WeakHashMap<T, SoftReference<T>>();

  private static long refs;
  private static long hits;

  private transient Logger log;
  private boolean debug = false;

  /**
   * @param val
   * @return value in pool
   */
  public T get(T val) {
    if (debug &&
        ((refs % 500) == 0)) {
      getLogger().debug("pool refs " + refs + ": hits " + hits);
    }
    refs++;
    SoftReference<T> poolVal = pool.get(val);

    if (poolVal != null) {
      T tval = poolVal.get();
      if (tval != null) {
        hits++;
        return tval;
      }
    }

    synchronized (pool) {
      pool.put(val, new SoftReference<T>(val));
      return val;
    }
  }

  private Logger getLogger() {
    if (log == null) {
      log = Logger.getLogger(this.getClass());
    }

    return log;
  }
}

Add an object pool to cache immutable or shared objects.


package leetcode.find_minimum_in_rotated_sorted_array;

public class Solution {
    public int findMin(int[] num) {
    	int size = num.length;
    	if(num[0] <= num[size - 1]){ // Not rotated
    		return num[0];
    	}
    	int L = -1, U = size;
    	while(L + 1 < U){
    		int mid = L + (U - L) / 2;
    		if(num[mid] > num[size - 1]){
    			L = mid;
    		}else{
    			U = mid;
    		}
    	}
    	return num[U];
    }
}

Add java solution for 153. Find Minimum in Rotated Sorted Array


package com.iluwatar.composite;

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

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

/**
 * Date: 12/11/15 - 8:12 PM
 *
 * @author Jeroen Meulemeester
 */
public class MessengerTest {

  /**
   * The buffer used to capture every write to {@link System#out}
   */
  private ByteArrayOutputStream stdOutBuffer = new ByteArrayOutputStream();

  /**
   * Keep the original std-out so it can be restored after the test
   */
  private final PrintStream realStdOut = System.out;

  /**
   * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test
   */
  @Before
  public void setUp() {
    this.stdOutBuffer = new ByteArrayOutputStream();
    System.setOut(new PrintStream(stdOutBuffer));
  }

  /**
   * Removed the mocked std-out {@link PrintStream} again from the {@link System} class
   */
  @After
  public void tearDown() {
    System.setOut(realStdOut);
  }

  /**
   * Test the message from the orcs
   */
  @Test
  public void testMessageFromOrcs() {
    final Messenger messenger = new Messenger();
    testMessage(
        messenger.messageFromOrcs(),
        "Where there is a whip there is a way."
    );
  }

  /**
   * Test the message from the elves
   */
  @Test
  public void testMessageFromElves() {
    final Messenger messenger = new Messenger();
    testMessage(
        messenger.messageFromElves(),
        "Much wind pours from your mouth."
    );
  }

  /**
   * Test if the given composed message matches the expected message
   *
   * @param composedMessage The composed message, received from the messenger
   * @param message         The expected message
   */
  private void testMessage(final LetterComposite composedMessage, final String message) {
    // Test is the composed message has the correct number of words
    final String[] words = message.split(" ");
    assertNotNull(composedMessage);
    assertEquals(words.length, composedMessage.count());

    // Print the message to the mocked stdOut ...
    composedMessage.print();

    // ... and verify if the message matches with the expected one
    assertEquals(message, new String(this.stdOutBuffer.toByteArray()).trim());
  }

}

Add proper unit tests for composite pattern


/*
 * Copyright 2015-2016 LMAX Ltd.
 *
 *    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.lmax.tool.disruptor;

public final class ValidationConfigBuilder implements ValidationConfig
{
    private boolean validateExceptionHandler = true;
    private boolean validateProxyInterfaces = false;

    @Override
    public boolean validateProxyInterfaces()
    {
        return validateProxyInterfaces;
    }

    public void validateProxyInterfaces(boolean validateProxyInterfaces)
    {
        this.validateProxyInterfaces = validateProxyInterfaces;
    }

    @Override
    public boolean validateExceptionHandler()
    {
        return validateExceptionHandler;
    }

    public void validateExceptionHandler(boolean validateExceptionHandler)
    {
        this.validateExceptionHandler = validateExceptionHandler;
    }
}

Revert "delete unused class". Only unused within the project itself.


package org.scijava.notebook.converter;

public class HTMLTableBuilder {

    /** Returns the style tag used to style HTML tables */
    public static String getTableStyle(final boolean displayRowLabel) {
        String style = "";

        return style;
    }

    public static String startTable() {
        return "

";
    }

    public static String appendRowLabelHeading() {
        return " 	";
    }

    public static String appendHeadings(final String data,
        final boolean end)
    {
        final String html = "" + data + "	";
        if (end) return html + "

";
        return html;
    }

    public static String appendData(final String data,
        final boolean start, final boolean end)
    {
        String html = "";
        if (start) html += "
";
        html += "" + data + "	";
        if (end) html += "
";
        return html;
    }

    public static String appendRowLabelData(final String data) {
        String html = "
";

        if (data == null) html += " ";
        else html += data;

        html += "	";
        return html;
    }

    public static String endTable() {
        return "

";
    }
}

Add utiltiy class for making HTML tables


import java.util.Scanner;

/**
 * Created by Nathan_Zeplowitz on 4/11/15.
 */
public class VerticalLine {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.println("Enter a number");
        int n = in.nextInt();
        for (int i = 0; i < n; i++)
            System.out.println("*");
    }

}

Add Third Exercise Veritcal Line


package jsr305;

import javax.annotation.meta.When;

public class TestFooNoControlFlow {

	public @Foo(when=When.NEVER) Object notFoo;
	public @Foo(when=When.ALWAYS) Object foo;

	public @Foo(when=When.NEVER) Object returnsNotFoo() { return null; };
	public @Foo(when=When.ALWAYS) Object returnsFoo() { return null; };

	public void requiresNotFoo( @Foo(when=When.NEVER)  Object x) {  };
	public void requiresFoo( @Foo(when=When.ALWAYS)  Object x) {  };

	public void test12() {
		foo = notFoo;
	}
	public void test32() {
		foo = returnsNotFoo();
	}

	public void test21() {
		notFoo = foo;
	}
	public void test41() {
		notFoo = returnsFoo();
	}

	public void test16() {
		requiresFoo(notFoo);
	}
	public void test36() {
		requiresFoo(returnsNotFoo());
	}
	public void test25() {
		requiresNotFoo(foo);
	}
	public void test45() {
		requiresNotFoo(returnsFoo());
	}

	public void ok22() {
		foo = foo;
	}
	public void ok42() {
		foo = returnsFoo();
	}

	public void ok11() {
		notFoo = notFoo;
	}
	public void ok31() {
		notFoo = returnsNotFoo();
	}

	public void ok26() {
		requiresFoo(foo);
	}
	public void ok46() {
		requiresFoo(returnsFoo());
	}
	public void ok15() {
		requiresNotFoo(notFoo);
	}
	public void ok35() {
		requiresNotFoo(returnsNotFoo());
	}

}

Add test case for custom type qualifiers


import com.fizzed.rocker.RockerModel;
import com.fizzed.rocker.runtime.StringBuilderOutput;

public class Main {

    public static void main(String[] args) {
        RockerModel model = Hello.template("Switzerland");
        StringBuilderOutput output = model.render(StringBuilderOutput.FACTORY);
        System.out.println(output.getBuffer().toString());
    }

}

Add source files that consumes generated sources files


package net.wisedog.android.whooing.advsms.test;

import java.util.ArrayList;

import net.wisedog.android.whooing.advsms.CardInfo;
import junit.framework.TestCase;

public class CardInfoTest extends TestCase {

	public void testConvertIntArrayToString(){
		ArrayList<Integer> array = new ArrayList<Integer>();
		array.add(1);
		array.add(100);
		assertEquals("1,100", CardInfo.convertIntArrayToString(array));

		array.add(50);
		array.add(25);
		assertEquals("1,100,50,25", CardInfo.convertIntArrayToString(array));
	}

	public void testConvertStringToIntArray(){
		ArrayList<Integer> array = CardInfo.convertStringToIntArray("1,50,70");
		assertEquals(1, array.get(0).intValue());
		assertEquals(50, array.get(1).intValue());
		assertEquals(70, array.get(2).intValue());
	}
}

Add Test case for CardInfo class


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

/**
 * Given an String containing a number expressed using cientific notation, can you write a method to
 * return the value of that number?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class CientificNotation {
}

Add statement to problem 30


package com.sonian.elasticsearch;

import org.testng.annotations.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

/**
 * @author dakrone
 */
public class DiskShardsAllocatorTests {

    @Test
    public void testEnoughDiskForShard() {
        assertThat(2 + 2, equalTo(4));
    }
}

Add blank test for disk equilibrium allocator


/**
 * You and your friends are going trick-or-treating. Like everyone else, you want to
 * get as much candy as possible. Like a true engineer, you want to optimize the route so that you
 * don't have to walk too much.
 *
 * However, your mom said you can only hit one house per row so that you don't get kidnapped or worse, lost.
 * To save yourself from walking too much, you are limited to choosing the house directly below it or the house
 * at the exact diagonal to it.
 *
 * So if your neighborhood looked something like this:
 * [
 *   [ a, b, c, d ],
 *   [ e, f, g, h ],
 *   [ i, j, k, l ],
 * ]
 * From house a, the next possible houses are either e or f.
 * From house b, the next possibles houses are e, f or g.
 * From house c, the next possibles houses are f, g or h.
 * From house d, the next possibles houses are g or h.
 * From house g, the next possibles houses are i, k or l.
 *
 * Once you have reached the last row of houses, then you're done and head home.
 *
 * Given a matrix of houses and how much candy you can get at each house, find the maximum amount of candy you can
 * get while following the rules above.
 *
 * Example:
 * Input: [
 *   [ 3, 2, 4, 1 ],
 *   [ 5, 1, 6, 3 ],
 *   [ 1, 8, 2, 4 ],
 *   [ 2, 3, 1, 6 ]
 * ]
 *
 * The maximum amount of candy you can get is 21 from the route 4 -> 6 -> 8 -> 3.
 */
public int optimalRoute(int[][] houses) {}

Add trick or treat problem


/*
    An example of a menu system in a while loop
*/

import java.util.Scanner;

public class WhileMenu
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        char choice = 'Z';

        while(choice != 'X')
        {
            System.out.println("Welcome to the Menu System.");
            System.out.println("Enter \'A\' option A ");
            System.out.println("Enter \'B\' option B ");
            System.out.println("Enter \'X\' to Exit ");
            System.out.println("Please enter your choice: ");
            choice = input.next().charAt(0);
            choice = Character.toUpperCase(choice);

            switch(choice)
            {
                case 'A': System.out.println("Your choice was \'A\'");
                    break;
                case 'B': System.out.println("Your choice was \'B\'");
                    break;
                case 'X':
                    break;
                default: System.out.println("You entered an invalid choice.");
                    System.out.println("Please enter your choice: ");
                    choice = input.next().charAt(0);
                    choice = Character.toUpperCase(choice);
                    break;
            }
        }
        System.out.println("Goodbye.");

    }
}

Add an example of a menu system in a while loop


/*
 * Copyright 2016 The Netty Project
 *
 * The Netty Project 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 io.netty.handler.ssl;

import io.netty.buffer.ByteBufAllocator;
import io.netty.util.internal.ObjectUtil;

import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSessionContext;
import java.util.List;

/**
 * Adapter class which allows to wrap another {@link SslContext} and init {@link SSLEngine} instances.
 */
public abstract class DelegatingSslContext extends SslContext {

    private final SslContext ctx;

    protected DelegatingSslContext(SslContext ctx) {
        this.ctx = ObjectUtil.checkNotNull(ctx, "ctx");
    }

    @Override
    public final boolean isClient() {
        return ctx.isClient();
    }

    @Override
    public final List<String> cipherSuites() {
        return ctx.cipherSuites();
    }

    @Override
    public final long sessionCacheSize() {
        return ctx.sessionCacheSize();
    }

    @Override
    public final long sessionTimeout() {
        return ctx.sessionTimeout();
    }

    @Override
    public final ApplicationProtocolNegotiator applicationProtocolNegotiator() {
        return ctx.applicationProtocolNegotiator();
    }

    @Override
    public final SSLEngine newEngine(ByteBufAllocator alloc) {
        SSLEngine engine = ctx.newEngine(alloc);
        initEngine(engine);
        return engine;
    }

    @Override
    public final SSLEngine newEngine(ByteBufAllocator alloc, String peerHost, int peerPort) {
        SSLEngine engine = ctx.newEngine(alloc, peerHost, peerPort);
        initEngine(engine);
        return engine;
    }

    @Override
    public final SSLSessionContext sessionContext() {
        return ctx.sessionContext();
    }

    /**
     * Init the {@link SSLEngine}.
     */
    protected abstract void initEngine(SSLEngine engine);
}

Allow to wrap another SslContext implementation and do extra init steps on the SSLEngine.


package de.retest.recheck.meta;

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

import org.junit.jupiter.api.Test;

class GlobalMetadataProviderTest {

	@Test
	void retrieve_should_not_throw_an_exception() throws Exception {
		final MetadataProvider cut = new GlobalMetadataProvider();

		assertThatCode( cut::retrieve ).doesNotThrowAnyException();
	}
}

Add test to ensure there are no duplicates


package sfBugsNew;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import edu.umd.cs.findbugs.annotations.NoWarning;

public class Bug1179 {

    @NoWarning("OBL_UNSATISFIED_OBLIGATION")
    public void bug(Connection connection) throws SQLException {
        PreparedStatement ps = null;
        try {
            ps = connection.prepareStatement("SELECT * FROM Employees");

        } catch (Exception e) {

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

Add test case; could not reproduce false positive report


/*
 * Copyright [2007] [University Corporation for Advanced Internet Development, 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 org.opensaml.xml.signature.impl;

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

import org.apache.log4j.Logger;
import org.opensaml.xml.security.CriteriaSet;
import org.opensaml.xml.security.SecurityException;
import org.opensaml.xml.security.credential.Credential;
import org.opensaml.xml.security.keyinfo.KeyInfoCredentialResolver;
import org.opensaml.xml.signature.Signature;
import org.opensaml.xml.signature.SignatureTrustEngine;

/**
 * Evaluate a signature in sequence using a chain of subordinate trust engines.  If the signature may be established as
 * trusted by any of the subordinate engines, the token is considered trusted. Otherwise it is considered
 * untrusted.
 *
 */
public class ChainingSignatureTrustEngine implements SignatureTrustEngine {

    /** Class logger. */
    private static Logger log = Logger.getLogger(ChainingSignatureTrustEngine.class);

    /** The chain of subordinate trust engines.  */
    private List<SignatureTrustEngine> engines;

    /** Constructor. */
    public ChainingSignatureTrustEngine() {
        engines = new ArrayList<SignatureTrustEngine>();
    }

    /**
     * Get the list of configured trust engines which constitute the trust evaluation chain.
     *
     * @return the modifiable list of trust engines in the chain
     */
    public  List<SignatureTrustEngine> getChain() {
        return engines;
    }

    /** {@inheritDoc} */
    public KeyInfoCredentialResolver getKeyInfoResolver() {
        // Chaining signature trust engine does not support an attached KeyInfoResolver
        return null;
    }

    /** {@inheritDoc} */
    public boolean validate(Signature token, CriteriaSet trustBasisCriteria) throws SecurityException {
        for (SignatureTrustEngine engine : engines) {
            if (engine.validate(token, trustBasisCriteria)) {
                if (log.isDebugEnabled()) {
                    log.debug("Signature was trusted by chain member: " + engine.getClass().getName());
                }
                return true;
            }
        }
        return false;
    }

    /** {@inheritDoc} */
    public boolean validate(byte[] signature, byte[] content, String algorithmURI, CriteriaSet trustBasisCriteria,
            Credential candidateCredential) throws SecurityException {
        for (SignatureTrustEngine engine : engines) {
            if (engine.validate(signature, content, algorithmURI, trustBasisCriteria, candidateCredential)) {
                if (log.isDebugEnabled()) {
                    log.debug("Signature was trusted by chain member: " + engine.getClass().getName());
                }
                return true;
            }
        }
        return false;
    }

}

Add impl of chaining signature trust engine.


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

package space.npstr.wolfia.config;

import io.undertow.connector.ByteBufferPool;
import io.undertow.server.DefaultByteBufferPool;
import io.undertow.websockets.jsr.WebSocketDeploymentInfo;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

/**
 * This just exists to get rid off a nasty Undertow warning
 * <p>
 * io.undertow.websockets.jsr: "UT026010: Buffer pool was not set on WebSocketDeploymentInfo, the default pool will be used"
 */
@Configuration
public class WebsocketConfig {

    @Bean
    public WebServerFactoryCustomizer undertowWebSocketServletWebServerCustomizer() {
        return new UndertowWebSocketServletWebServerCustomizer();
    }

    private static class UndertowWebSocketServletWebServerCustomizer
            implements WebServerFactoryCustomizer<UndertowServletWebServerFactory>, Ordered, DisposableBean {

        // Optimal size for direct buffers is 16kB according to Undertow docs
        // http://undertow.io/undertow-docs/undertow-docs-2.0.0/index.html#the-undertow-buffer-pool
        private final ByteBufferPool buffers = new DefaultByteBufferPool(true, 16 * 1024, 100, 12);

        @Override
        public void customize(UndertowServletWebServerFactory factory) {
            factory.addDeploymentInfoCustomizers(deploymentInfo -> {
                WebSocketDeploymentInfo info = (WebSocketDeploymentInfo) deploymentInfo.getServletContextAttributes().get(WebSocketDeploymentInfo.ATTRIBUTE_NAME);
                if (info == null) {
                    info = new WebSocketDeploymentInfo();
                    deploymentInfo.addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, info);
                }

                info.setBuffers(this.buffers);
            });
        }

        @Override
        public int getOrder() {
            return Ordered.LOWEST_PRECEDENCE;
        }

        @Override
        public void destroy() {
            this.buffers.close();
        }
    }
}

Fix undertow warning about missing config


package com.oasisfeng.pattern.update;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.util.Log;

/**
 * Device experience friendly package update observer, eliminated the legacy broadcast receiver if running on Android 3.1+
 *
 *
First, define two classes extending this abstract class, as following:
 *

   class PackageUpdateObserver extends AbstractPackageUpdateObserver {

       {@literal @}Override protected void onPackageUpdated(final Context context) {
           // Anything to be done after package update
       }
   }

   class PackageUpdateObserverLegacy extends PackageUpdateObserver {
   }

 * Then, declare two broadcast receivers in your AndroidManifest.xml
 *

   <receiver android:name=".PackageUpdateObserverLegacy">
       <intent-filter>
           <action android:name="android.intent.action.PACKAGE_REPLACED" />
           <data android:scheme="package" />
       </intent-filter>
   </receiver>

   <receiver android:name=".PackageUpdateObserver">
       <intent-filter>
           <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
       </intent-filter>
   </receiver>

 * @author Oasis
 */
public abstract class AbstractPackageUpdateObserver extends BroadcastReceiver {

    abstract protected void onPackageUpdated(final Context context);

    @Override public void onReceive(final Context context, final Intent intent) {
        if (Intent.ACTION_PACKAGE_REPLACED.equals(intent.getAction())) {
            // Disable legacy receiver on Android 3.1+ for better device experience.
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
                for (final ResolveInfo receiver : context.getPackageManager().queryBroadcastReceivers(intent, 0)) {
                    Class<?> clazz; try { clazz = Class.forName(receiver.activityInfo.name);
                    } catch (final ClassNotFoundException e) {
                        Log.e(TAG, "Cannot find receiver: " + receiver.activityInfo.name);
                        continue;
                    }
                    if (! AbstractPackageUpdateObserver.class.isAssignableFrom(clazz)) continue;  // Skip other receivers.
                    final ComponentName component = new ComponentName(context, clazz);
                    context.getPackageManager().setComponentEnabledSetting(component,
                            PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
                }
                return;     // No need to proceed since Intent.ACTION_MY_PACKAGE_REPLACED will also be triggered.
            }
            // Ignore packages other than myself
            if (! context.getPackageName().equals(intent.getData().getSchemeSpecificPart())) return;
        } else if (! Intent.ACTION_MY_PACKAGE_REPLACED.equals(intent.getAction())) return;

        Log.i(TAG, "Package updated");
        onPackageUpdated(context);
    }

    private static final String TAG = "Installer";
}

Add device experience friendly package update observer pattern.


package de.lmu.ifi.dbs.elki.algorithm.clustering;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;

import de.lmu.ifi.dbs.elki.algorithm.AbstractAlgorithm;
import de.lmu.ifi.dbs.elki.algorithm.result.clustering.ClusteringResult;
import de.lmu.ifi.dbs.elki.algorithm.result.clustering.Clusters;
import de.lmu.ifi.dbs.elki.data.ClassLabel;
import de.lmu.ifi.dbs.elki.data.DatabaseObject;
import de.lmu.ifi.dbs.elki.database.AssociationID;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.utilities.Description;

/**
 * Pseudo clustering using labels.
 *
 * This "algorithm" puts elements into the same cluster when they agree in their labels.
 * I.e. it just uses a predefined clustering, and is mostly useful for testing and evaluation
 * (e.g. comparing the result of a real algorithm to a reference result / golden standard).
 *
 * @author Erich Schubert
 *
 * @param <O>
 */
public class ByLabelClustering<O extends DatabaseObject> extends AbstractAlgorithm<O> implements Clustering<O> {
  /**
   * Holds the result of the algorithm.
   */
  private ClusteringResult<O> result;

  /**
   * Return clustering result
   */
  public ClusteringResult<O> getResult() {
    return result;
  }

  /**
   * Obtain a description of the algorithm
   */
  public Description getDescription() {
    return new Description("ByLabelClustering", "Clustering by label",
        "Cluster points by a (pre-assigned!) label. For comparing results with a reference clustering.", "");
  }

  /**
   * Run the actual clustering algorithm.
   *
   * @param database The database to process
   */
  @Override
  protected void runInTime(Database<O> database) throws IllegalStateException {
    HashMap<String, Collection<Integer>> labelmap = new HashMap<String, Collection<Integer>>();

    for (Iterator<Integer> iter = database.iterator(); iter.hasNext();) {
      Integer id = iter.next();
      String label = null;

      // try class label first
      ClassLabel classlabel = database.getAssociation(AssociationID.CLASS, id);
      if (classlabel != null) label = classlabel.toString();

      // fall back to other labels
      if (label == null)
        label = database.getAssociation(AssociationID.LABEL, id);

      if (labelmap.containsKey(label))
        labelmap.get(label).add(id);
      else {
        Collection<Integer> n = new java.util.Vector<Integer>();
        n.add(id);
        labelmap.put(label,n);
      }
    }

    Integer[][] rarray = new Integer[labelmap.size()][];
    int i = 0;
    for (Collection<Integer> ids : labelmap.values()) {
      rarray[i] = (Integer[]) ids.toArray(new Integer[0]);
      i++;
    }
    result = new Clusters<O>(rarray, database);
  }
}

Add a new trivial clustering algorithm using existing labels. Useful for comparing results to a golden standard.


package org.apache.poi;

/**
 * This is an internal class, it should not be considered as a public API:
 * this class will be deleted without any warning.
 */
@Deprecated
public class PptPoiBridge {

	public static void removeRelation(POIXMLDocumentPart parent, POIXMLDocumentPart child) {
		parent.removeRelation(child);
	}

}

Enable to replace an image while keeping its properties and order


//
// ParallelRead.java
//

import java.io.File;
import loci.formats.ImageReader;

/**
 * Reads all files in given directory in parallel,
 * using a separate thread for each.
 *
 *

Source code:

 *
Trac,
 * SVN

 */
public class ParallelRead implements Runnable {
  private String id;

  public ParallelRead(String id) {
    this.id = id;
  }

  public void run() {
    try {
      ImageReader r = new ImageReader();
      r.setId(id);
      System.out.println(Thread.currentThread().getName() +
        ": id=" + id +
        ", sizeX=" + r.getSizeX() +
        ", sizeY=" + r.getSizeY() +
        ", sizeZ=" + r.getSizeZ() +
        ", sizeT=" + r.getSizeT() +
        ", sizeC=" + r.getSizeC());
      r.close();
    }
    catch (Exception exc) {
      exc.printStackTrace();
    }
  }

  public static void main(String[] args) {
    String dir = args[0];
    File[] list = new File(dir).listFiles();
    for (int i=0; i<list.length; i++) {
      ParallelRead pr = new ParallelRead(list[i].getAbsolutePath());
      new Thread(pr).start();
    }
  }
}

Test class for reading from many files in parallel.


package org.bitcoinj.net.discovery;

import org.bitcoinj.evolution.SimplifiedMasternodeList;
import org.bitcoinj.evolution.SimplifiedMasternodeListEntry;

import javax.annotation.Nullable;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 * Created by hashengineering on 12/5/18.
 */
public class MasternodePeerDiscovery implements PeerDiscovery {

    ArrayList<InetSocketAddress> masternodeSeeds;
    private int pnseedIndex;

    /**
     * Supports finding peers by IP addresses
     *
     * @param mnList IP addresses for seed addresses.
     */
    public MasternodePeerDiscovery(SimplifiedMasternodeList mnList) {
        masternodeSeeds = new ArrayList<InetSocketAddress>(mnList.size());
        mnList.forEachMN(true, new SimplifiedMasternodeList.ForeachMNCallback() {
            @Override
            public void processMN(SimplifiedMasternodeListEntry mn) {
                masternodeSeeds.add(mn.getService().toSocketAddress());
            }
        });
    }

    /**
     * Acts as an iterator, returning the address of each node in the list sequentially.
     * Once all the list has been iterated, null will be returned for each subsequent query.
     *
     * @return InetSocketAddress - The address/port of the next node.
     * @throws PeerDiscoveryException
     */
    @Nullable
    public InetSocketAddress getPeer() throws PeerDiscoveryException {
        try {
            return nextPeer();
        } catch (UnknownHostException e) {
            throw new PeerDiscoveryException(e);
        }
    }

    @Nullable
    private InetSocketAddress nextPeer() throws UnknownHostException, PeerDiscoveryException {
        if (masternodeSeeds == null || masternodeSeeds.isEmpty())
            throw new PeerDiscoveryException("No masternodes seeds configured; unable to find any peers");

        if (pnseedIndex >= masternodeSeeds.size()) return null;
        return masternodeSeeds.get(pnseedIndex++);
    }

    /**
     * Returns an array containing all the Dash nodes within the list.
     */
    @Override
    public InetSocketAddress[] getPeers(long services, long timeoutValue, TimeUnit timeoutUnit) throws PeerDiscoveryException {
        if (services != 0)
            throw new PeerDiscoveryException("Pre-determined peers cannot be filtered by services: " + services);
        try {
            return allPeers();
        } catch (UnknownHostException e) {
            throw new PeerDiscoveryException(e);
        }
    }

    private InetSocketAddress[] allPeers() throws UnknownHostException {
        return masternodeSeeds.toArray(new InetSocketAddress[0]);
    }

    @Override
    public void shutdown() {
    }
}

Add PeerDiscovery for getting peers from a simplified masternode list


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

import com.vaadin.server.Page;
import com.vaadin.shared.Position;
import com.vaadin.ui.Notification;

/**
 * Utility class for formatted notifications.
 *
 * @author Ryan Gilera
 */
public class NotificationUtil {
    /**
     * Creates an error notification with a single parameter for caption.
     *
     * @param caption The main message of the notification
     */
    public static void showError(String caption) {
        showError(caption, "");
    }

    /**
     * Creates an error notification with two parameters for caption and
     * description.
     *
     * @param caption The main message of the notification
     * @param description Secondary description message
     */
    public static void showError(String caption, String description) {
        Notification errorNotification;

        caption = "<i class=\"fa fa-exclamation-circle fa-2x\"></i>  "
                    + caption;
        if (description.isEmpty()) {
            errorNotification = new Notification(caption,
                    Notification.Type.ERROR_MESSAGE);
        } else {
            errorNotification = new Notification(caption, description,
                    Notification.Type.ERROR_MESSAGE);
        }

        errorNotification.setHtmlContentAllowed(true);
        errorNotification.setPosition(Position.TOP_CENTER);

        errorNotification.show(Page.getCurrent());
    }
}

Add custom notification utility helper


package lintcode.bst;

import fundamentals.tree.TreeNode;

/**
 */
public class MyBst {

    // 85-Insert Node in a Binary Search Tree
    public TreeNode insertNode(TreeNode root, TreeNode node) {
        if (root == null) return node;
        if (node.val < root.val) {
            root.left = insertNode(root.left, node);
        } else {
            root.right = insertNode(root.right, node);
        }
        return root;
    }

}

Implement my binary search tree


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

public class RandomArrayGenerator {

	private final int size;

	private final int min;
	private final int max;

	public RandomArrayGenerator(int recordSize, int max) {
		this(recordSize, max, 0);
	}

	public RandomArrayGenerator(int recordSize, int max, int min) {
		this.size = recordSize;
		this.max = max;
		this.min = min;
	}

	public List<Integer> generateRandomNumbers() {
		Random generator = new Random();
		List<Integer> list = new ArrayList<>(size);
		for (int i = 0; i < size; i++) {
			list.add(generator.nextInt(max - min) + min);
		}
		return list;
	}
}

Add an utility to generate random arrays for algorith testing


/*
  Insert Node at the end of a linked list
  head pointer input could be NULL as well for empty list
  Node is defined as
  class Node {
     int data;
     Node next;
  }
*/
    // This is a "method-only" submission.
    // You only need to complete this method.
Node Reverse(Node head) {

  Node prev = null;
  Node curr = head;
  Node next = null;

  while(curr != null) {
    next = curr.next;
    curr.next = prev;
    prev = curr;

    curr = next;
  }

  return prev;
}

Solve reverse a linked list


import java.io.FileInputStream;

import org.docx4j.convert.in.Doc;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;

public class DocToPDFConverter extends DocxToPDFConverter {

	public DocToPDFConverter(String inputFilePath, String outputFilePath) {
		super(inputFilePath, outputFilePath);
	}

	@Override
	protected WordprocessingMLPackage getMLPackage(FileInputStream iStream) throws Exception{
	    WordprocessingMLPackage mlPackage = Doc.convert(iStream);
		return mlPackage;
	}

}

import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.PrintStream;

import org.docx4j.convert.in.Doc;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;

public class DocToPDFConverter extends DocxToPDFConverter {

	public DocToPDFConverter(String inputFilePath, String outputFilePath) {
		super(inputFilePath, outputFilePath);
	}

	@Override
	protected WordprocessingMLPackage getMLPackage(FileInputStream iStream) throws Exception{
		PrintStream originalStdout = System.out;

		//Disable stdout temporarily as Doc convert produces alot of output
		System.setOut(new PrintStream(new OutputStream() {
			public void write(int b) {
				//DO NOTHING
			}
		}));
		WordprocessingMLPackage mlPackage = Doc.convert(iStream);

		System.setOut(originalStdout);
		return mlPackage;
	}

}

Disable stdout when convert doc to docx


package com.tlswe.awsmock.ec2.servlet;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import com.tlswe.awsmock.ec2.control.MockEC2QueryHandler;

@RunWith(PowerMockRunner.class)
@PrepareForTest({MockEC2QueryHandler.class, HttpServletRequest.class, HttpServletResponse.class})
public class MockEc2EndpointServletTest {

    @Mock
    HttpServletRequest request;

    @Mock
    HttpServletResponse response;

    @Mock
    MockEC2QueryHandler handler;

    Map<String, String[]> queryParams = new HashMap<String, String[]>();

    @Before
    public void doSetup(){
      PowerMockito.mockStatic(MockEC2QueryHandler.class);
      Mockito.when(MockEC2QueryHandler.getInstance()).thenReturn(handler);
      Mockito.when(request.getParameterMap()).thenReturn(queryParams);
    }

    @Test
    public void Test_doPost() throws IOException{
        MockEc2EndpointServlet mockEc2EndpointServlet = new MockEc2EndpointServlet();
        mockEc2EndpointServlet.doPost(request, response);
    }

    @Test
    public void Test_doGet() throws IOException{
        MockEc2EndpointServlet mockEc2EndpointServlet = new MockEc2EndpointServlet();
        mockEc2EndpointServlet.doPost(request, response);
    }

}

Add JUnit tests for MockEc2EndpointServlet


/*
Copyright (c) 2014, Colorado State University
All rights reserved.

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 holder 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 galileo.test.graph;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({
    FeaturePathQuery.class,
})
public class TestSuite { }

Add test suite for graph classes


/*
 * Copyright 2016 Exorath
 *
 * 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.exorath.service.treasurehunt.test;

import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.exorath.service.commons.dynamoDBProvider.DynamoDBProvider;
import com.exorath.service.treasurehunt.Service;
import com.exorath.service.treasurehunt.Treasure;
import com.exorath.service.treasurehunt.dynamodb.DynamoDBService;
import org.junit.Assert;
import org.junit.Test;

import java.util.UUID;

public class DynamoDBServiceTest {

	@Test
	public void testGetTreasuresEqualsSetTreasures() {
		UUID playerId = UUID.randomUUID();
		Service srv = new DynamoDBService(getDynamoDBProvider());
		srv.setTreasure(playerId, "testTreasure1");
		srv.setTreasure(playerId, "testTreasure2");
		srv.setTreasure(playerId, "testTreasure3");
		srv.setTreasure(playerId, "testTreasure4");

		Treasure[] treasures = srv.getTreasures(playerId);
		Assert.assertEquals(treasures.length, 4);

		boolean testTreasuse1AccountFor = false;
		boolean testTreasuse2AccountFor = false;
		boolean testTreasuse3AccountFor = false;
		boolean testTreasuse4AccountFor = false;
		for (Treasure t : treasures) {
			if (t.getId().equals("testTreasure1")) {
				testTreasuse1AccountFor = true;
			} else if (t.getId().equals("testTreasure2")) {
				testTreasuse2AccountFor = true;
			} else if (t.getId().equals("testTreasure3")) {
				testTreasuse3AccountFor = true;
			} else if (t.getId().equals("testTreasure4")) {
				testTreasuse4AccountFor = true;
			}
		}
		Assert.assertTrue(testTreasuse1AccountFor && testTreasuse2AccountFor && testTreasuse3AccountFor && testTreasuse4AccountFor);
	}

	private DynamoDBProvider getDynamoDBProvider() {
		AmazonDynamoDBClient client = new AmazonDynamoDBClient().withEndpoint("http://localhost:8000");
		DynamoDB db = new DynamoDB(client);
		return () -> db;
	}
}

Create test for DynamoDBService functionality


package org.pdxfinder.controllers;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ShutDownHook implements ApplicationContextAware {

    private ApplicationContext context;

    @PostMapping("/shutdown")
    public void shutdownContext() {
        ((ConfigurableApplicationContext) context).close();
    }

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        this.context = ctx;

    }
}

Add shut down hook for properly shutting down the admin app


/*
 * See LICENSE file in distribution for copyright and licensing information.
 */
package seph.lang.ast;

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

import seph.lang.SephObject;
import seph.lang.Text;

/**
 * @author Ola Bini
 */
public class LiteralMessageTest {
    @Test
    public void ensure_class_exists() {
        assertEquals("seph.lang.ast.LiteralMessage", seph.lang.ast.LiteralMessage.class.getName());
    }

    @Test
    public void is_a_seph_object() {
        assertTrue("A LiteralMessage should be a SephObject", new LiteralMessage(null, null) instanceof SephObject);
    }

    @Test
    public void is_a_message() {
        assertTrue("A LiteralMessage should be a Message", new LiteralMessage(null, null) instanceof Message);
    }

    @Test
    public void has_a_next_pointer() {
        Message one = new LiteralMessage(null, null);
        LiteralMessage two = new LiteralMessage(null, one);
        assertSame(one, two.next());
    }

    @Test
    public void has_a_name_based_one_the_literal_class() {
        LiteralMessage msg = new LiteralMessage(new Text("foo"), null);
        assertEquals("<literal:seph.lang.Text>", msg.name());
    }

    @Test
    public void has_an_empty_list_of_arguments() {
        LiteralMessage msg = new LiteralMessage(null, null);
        assertArrayEquals(new Message[0], msg.arguments());
    }

    @Test
    public void with_next_returns_a_new_object_with_the_same_literal() {
        SephObject lit = new Text("bar");
        LiteralMessage msg = new LiteralMessage(lit, null);
        assertSame(lit, msg.withNext(null).literal());
    }

    @Test
    public void with_next_returns_a_new_object_with_a_new_next() {
        Message expected = new LiteralMessage(null, null);
        LiteralMessage msg = new LiteralMessage(null, null);
        assertSame(expected, msg.withNext(expected).next());
    }

    @Test
    public void literal_returns_the_literal_given() {
        SephObject lit = new Text("bar");
        LiteralMessage msg = new LiteralMessage(lit, null);
        assertSame(lit, msg.literal());
    }

    @Test
    public void is_literal_returns_true() {
        LiteralMessage msg = new LiteralMessage(null, null);
        assertTrue(msg.isLiteral());
    }
}// LiteralMessageTest

Add tests for literal messages


//
// Mass_Importer.java
//

import ij.IJ;
import ij.gui.YesNoCancelDialog;
import ij.io.DirectoryChooser;
import ij.plugin.PlugIn;
import java.io.File;
import java.util.HashSet;
import java.util.Vector;
import loci.formats.FilePattern;
import loci.formats.ImageReader;
import loci.plugins.LociImporter;

/**
 * Processes all image files in the chosen directory,
 * grouping files with similar names.
 *
 * @author Curtis Rueden ctrueden at wisc.edu
 */
public class Mass_Importer implements PlugIn {

  public void run(String arg) {
    // prompt user for directory to process
    DirectoryChooser dc = new DirectoryChooser("Bio-Formats Mass Importer");
    String dirPath = dc.getDirectory();

    // create a list of files we have already processed
    HashSet done = new HashSet();

    // image reader object, for testing whether a file is in a supported format
    ImageReader tester = new ImageReader();

    // list of files to actually open with Bio-Formats Importer
    Vector filesToOpen = new Vector();

    // process all files in the chosen directory
    File dir = new File(dirPath);
    File[] files = dir.listFiles();
    IJ.showStatus("Scanning directory");
    for (int i=0; i<files.length; i++) {
      String id = files[i].getAbsolutePath();
      IJ.showProgress((double) i / files.length);

      // skip files that have already been processed
      if (done.contains(id)) continue;

      // skip unsupported files
      if (!tester.isThisType(id, false)) continue;

      // use FilePattern to group files with similar names
      String name = files[i].getName();
      FilePattern fp = new FilePattern(name, dirPath);

      // get a list of all files part of this group, and mark them as done
      String[] used = fp.getFiles();
      for (int j=0; j<used.length; j++) done.add(used[j]);

      filesToOpen.add(id);
    }
    IJ.showProgress(1.0);
    IJ.showStatus("");

    // confirm that user wants to proceed in opening the file groups
    int numToOpen = filesToOpen.size();
    if (numToOpen == 0) {
      IJ.showMessage("No file groups found.");
      return;
    }
    String groups = numToOpen == 1 ?
      "1 file group" : (numToOpen + " file groups");
    YesNoCancelDialog confirm = new YesNoCancelDialog(IJ.getInstance(),
      "Bio-Formats Mass Importer", "Found " + groups + " in directory '" +
      dirPath + "'; proceed?");
    if (!confirm.yesPressed()) return;

    // launch the Bio-Formats Importer plugin to open each group of files
    for (int i=0; i<numToOpen; i++) {
      String id = (String) filesToOpen.get(i);
      String params =
        "location=[Local machine] " +
        "windowless=true " +
        "group_files=true " +
        "open=[" + id + "] ";
      new LociImporter().run(params);
    }
    IJ.showStatus("");
  }

}

Add "Bio-Formats Mass Importer" example plugin.


package sonata.kernel.placement.monitor;

import com.fasterxml.jackson.annotation.JsonProperty;

public class MonitorStats {

    /* current
    {"NET_out": "648 B", "MEM_used": "1.07 MiB", "PIDS": "3", "NET_in": "1.596 kB",
    "MEM_limit": "15.67 GiB", "CPU": "0.00%", "MEM_%": "0.01%"}
    */
    /* experimental
    {'NET_out': [], 'CPU_%': 0.0, 'MEM_used': 1101824, 'PIDS': 4,
    'NET_in': ['Total', '0'], 'SYS_time': 1479224676000000000L, 'MEM_limit': 16827117568, 'MEM_%': 6.54790694572272e-05}
    */
    /* new
    {'MEM_used': 790528, 'PIDS': 2, 'BLOCK_out': [], 'NET_out': 648,
     'SYS_time': 1479522691737230080L, 'MEM_limit': 16827117568,
     'NET_in': 648, 'BLOCK_in': ['Total', '0'], 'MEM_%': 4.6979406710947397e-05, 'CPU_%': 0.0}
    */

    @JsonProperty("NET_out")
    String netOut;
    @JsonProperty("NET_in")
    String netIn;
    @JsonProperty("MEM_used")
    String memoryUsed;
    @JsonProperty("PIDS")
    String processIds;
    @JsonProperty("MEM_limit")
    String memoryLimit;
    @JsonProperty("CPU")
    String cpu;
    @JsonProperty("MEM_%")
    String memoryPercentage;

    public String getNetOut() {
        return netOut;
    }

    public void setNetOut(String netOut) {
        this.netOut = netOut;
    }

    public String getNetIn() {
        return netIn;
    }

    public void setNetIn(String netIn) {
        this.netIn = netIn;
    }

    public String getMemoryUsed() {
        return memoryUsed;
    }

    public void setMemoryUsed(String memoryUsed) {
        this.memoryUsed = memoryUsed;
    }

    public String getProcessIds() {
        return processIds;
    }

    public void setProcessIds(String processIds) {
        this.processIds = processIds;
    }

    public String getMemoryLimit() {
        return memoryLimit;
    }

    public void setMemoryLimit(String memoryLimit) {
        this.memoryLimit = memoryLimit;
    }

    public String getCpu() {
        return cpu;
    }

    public void setCpu(String cpu) {
        this.cpu = cpu;
    }

    public String getMemoryPercentage() {
        return memoryPercentage;
    }

    public void setMemoryPercentage(String memoryPercentage) {
        this.memoryPercentage = memoryPercentage;
    }
}

Add monitor statistics class for json mapping


package com.github.dkanellis.fikey.storage;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.yubico.u2f.data.DeviceRegistration;

import java.util.*;

/**
 * @author Dimitris
 */
public class DataStorage<T, K, V> {

    private LoadingCache<T, Map<K, V>> users;
    private Map<K, V> requests;

    public DataStorage() {
        this.requests = new HashMap<>();
        this.users = CacheBuilder.newBuilder().build(new CacheLoader<T, Map<K, V>>() {
            @Override
            public Map<K, V> load(T key) throws Exception {
                return new HashMap<>();
            }
        });
    }

    public void addRequest(K key, V value) {
        requests.put(key, value);
    }

    public V removeRequest(K key) {
        return requests.remove(key);
    }

    public void addDeviceToUser(T username, K key, V value) {
        users.getUnchecked(username).put(key, value);
    }

    public Iterable<DeviceRegistration> getDevicesFromUser(T username) {
        List<DeviceRegistration> registrations = new ArrayList<>();
        for (V serialized : getSerializedDevices(username)) {
            registrations.add(DeviceRegistration.fromJson((String) serialized));
        }
        return registrations;
    }

    private Collection<V> getSerializedDevices(T username) {
        return users.getUnchecked(username).values();
    }

}

Add user and device storage


package leetcode.candy;

import java.util.ArrayList;

public class Solution {
    public int candy(int[] ratings) {
        if(ratings == null || ratings.length == 0) return 0;
        int n = ratings.length;
        ArrayList<Integer> minimals = new ArrayList<Integer>();
        for(int i = 0; i < n; i++){
        	if((i == 0 || ratings[i - 1] >= ratings[i]) && (i == n - 1 || ratings[i + 1] >= ratings[i])){
        		minimals.add(i);
        	}
        }
        int[] candies = new int[n];
        for(int minimal : minimals){
        	candies[minimal] = 1;
        	for(int i = minimal + 1; i < n && ratings[i] > ratings[i - 1]; i++){
        		if(candies[i] < candies[i - 1] + 1){
        			candies[i] = candies[i - 1] + 1;
        		}
        	}
        	for(int i = minimal - 1; i >= 0 && ratings[i] > ratings[i + 1]; i--){
        		if(candies[i] < candies[i + 1] + 1){
        			candies[i] = candies[i + 1] + 1;
        		}
        	}
        }
        int sum = 0;
        for(int x : candies){
        	sum += x;
        }
        return sum;
    }

    public static void main(String[] args){
    	System.err.println(new Solution().candy(new int[]{-1, 0, 1, 2, 3, 4, 4, 2, 1, 0}));
    }
}

Add java solution for 135. Candy


package org.jboard.jboard.sandbox;

public class Uncaught
{

	public static void main(String[] args)
	{
		Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
		{

			@Override
			public void uncaughtException(Thread t, Throwable e)
			{
				System.out.println("Hello world!");

			}
		});

		throw new RuntimeException("Hello kitty.");

		//System.out.println("Bye Bye");

	}

}

Add a class to the sandbox


package de.retest.recheck.ui.diff;

import static de.retest.recheck.ui.diff.ElementDifferenceFinder.getNonEmptyDifferences;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;

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

import org.junit.Test;

import de.retest.recheck.ui.descriptors.Element;

public class ElementDifferenceFinderTest {

	@Test
	public void getNonEmptyDifferences_should_be_robust() {
		getNonEmptyDifferences( null );
		getNonEmptyDifferences( new ArrayList<>() );
	}

	@Test
	public void getNonEmptyDifferences_should_handle_empty_element_diffs() {
		final List<Difference> empty = new ArrayList<>();
		empty.add( new ElementDifference() );
		assertThat( getNonEmptyDifferences( empty ) ).hasSize( 0 );
	}

	@Test
	public void getNonEmptyDifferences_should_ignore_attribute_diffs() {
		final List<AttributeDifference> attributeDiff = new ArrayList<>();
		attributeDiff.add( new AttributeDifference( "text", "Mark", "Karl" ) );
		final AttributesDifference attributeDifference = new AttributesDifference( attributeDiff );
		assertThat( getNonEmptyDifferences( singletonList( attributeDifference ) ) ).hasSize( 0 );
	}

	@Test
	public void getNonEmptyDifferences_should_return_nonempty_differences() throws Exception {
		final List<AttributeDifference> attributeDiff = new ArrayList<>();
		attributeDiff.add( new AttributeDifference( "text", "Mark", "Karl" ) );
		final AttributesDifference attributeDifference = new AttributesDifference( attributeDiff );
		final List<Difference> nonempty = new ArrayList<>();
		nonempty.add( new ElementDifference( mock( Element.class ), attributeDifference, null, null, null,
				new ArrayList<>() ) );
		assertThat( getNonEmptyDifferences( nonempty ) ).hasSize( 1 );
	}

}

Add test and move easy to move methods...


package org.uma.jmetal.qualityIndicator;

import org.uma.jmetal.util.VectorUtils;
import org.uma.jmetal.util.checking.Check;

/**
 * @author Antonio J. Nebro <antonio@lcc.uma.es>
 *
 */
public abstract class QualityIndicator {
  protected double[][] referenceFront = null;

  /**
   * Default constructor
   */
  public QualityIndicator() {
  }

  /**
   * Constructor
   * @param referenceFrontFile
   */
  public QualityIndicator(String referenceFrontFile) {
    setReferenceFront(referenceFrontFile);
  }

  /**
   * Constructor
   * @param referenceFront
   */
  public QualityIndicator(double[][] referenceFront) {
    this.referenceFront = referenceFront;
  }

  public abstract double compute(double[][] front) ;

  public void setReferenceFront(String referenceFrontFile) {
    Check.isNotNull(referenceFrontFile);

    referenceFront = VectorUtils.readVectors(referenceFrontFile);
  }

  public void setReferenceFront(double[][] referenceFront) {
    this.referenceFront = referenceFront;
  }

  /**
   * This method returns true if lower indicator values are preferred and false otherwise
   *
   * @return
   */
  public abstract boolean isTheLowerTheIndicatorValueTheBetter();

  public double[][] getReferenceFront() {
    return referenceFront;
  }

  public abstract String getName() ;
  public abstract String getShortName() ;
}

Add new package in jmetal-experimental


package com.easternedgerobotics.rov.io.joystick;

import com.easternedgerobotics.rov.test.TestEventPublisher;
import com.easternedgerobotics.rov.value.VideoFlipValueA;
import com.easternedgerobotics.rov.value.VideoFlipValueB;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.mockito.Matchers;
import org.mockito.Mockito;
import rx.Observable;
import rx.observers.TestSubscriber;
import rx.schedulers.TestScheduler;
import rx.subjects.TestSubject;

import java.util.Arrays;
import java.util.Collection;
import java.util.function.Function;

@RunWith(Parameterized.class)
public final class JoystickControllerButtonTest {
    @Parameters(name = "Joystick button #{0} should emit a value of {1}")
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] {
            {JoystickController.CAMERA_A_VIDEO_FLIP_JOYSTICK_BUTTON, VideoFlipValueA.class},
            {JoystickController.CAMERA_B_VIDEO_FLIP_JOYSTICK_BUTTON, VideoFlipValueB.class},
        });
    }

    private final int index;

    private final Class clazz;

    public JoystickControllerButtonTest(final int index, final Class clazz) {
        this.index = index;
        this.clazz = clazz;
    }

    @SuppressWarnings("unchecked")
    @Test
    public void buttonPressDoesEmitSingleValueOfCorrectType() {
        final TestScheduler scheduler = new TestScheduler();
        final TestSubscriber subscriber = new TestSubscriber();
        final TestSubject subj = TestSubject.create(scheduler);
        final TestEventPublisher eventPublisher = new TestEventPublisher(scheduler);
        final JoystickController joystickController = new JoystickController(eventPublisher, Function.identity());

        final Joystick joystick = Mockito.mock(Joystick.class);
        Mockito.when(joystick.axes())
            .thenReturn(Observable.never());
        Mockito.when(joystick.button(Matchers.intThat(argument -> !argument.equals(index))))
            .thenReturn(Observable.never());
        Mockito.when(joystick.button(Mockito.eq(index)))
            .thenReturn(subj);

        joystickController.onNext(joystick);

        eventPublisher.valuesOfType(clazz).subscribe(subscriber);
        subj.onNext(Joystick.BUTTON_DOWN);
        subj.onNext(Joystick.BUTTON_UP);
        scheduler.triggerActions();

        subscriber.assertValueCount(1);
        Assert.assertTrue("Emitted type is not correct", subscriber.getOnNextEvents().get(0).getClass().equals(clazz));
    }
}

Add joystick controller button tests


/**
 *
 */
package com.github.podd.sensors.test;

import static org.junit.Assert.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;

/**
 * @author ans025
 *
 */
public class SensorGetTest
{

    /**
     * @throws java.lang.Exception
     */
    @Before
    public void setUp() throws Exception
    {
    }

    /**
     * @throws java.lang.Exception
     */
    @After
    public void tearDown() throws Exception
    {
    }

    @Test
    public void testGet() throws Exception
    {
        final ClientResource clientResource = new ClientResource("http://152.83.198.37/TC_LOG00.CSV");

        final Representation representation = clientResource.get();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        representation.write(outputStream);

    }

}

Add experimental sensor access test code


package com.davidmogar.njc.syntactic;

import java.lang.reflect.Field;

public abstract class Tokens {

    /* Primitive types */
    public static final int CHARACTER = 257;
    public static final int DOUBLE = 258;
    public static final int INTEGER = 259;
    public static final int VOID = 260;

    /* Control flow */
    public static final int IF = 270;
    public static final int WHILE = 271;

    /* Other reserved words */
    public static final int MAIN = 290;
    public static final int RETURN = 291;

    public static String getTokenNameByValue(int value) {
        String token = "";

        try {
            for (Field field : Tokens.class.getFields()) {
                if ((int) field.get(new Integer(0)) == value) {
                    token = field.getName();
                }
            }
        } catch (IllegalAccessException e) {
            // Just ignore it
        }

        return token;
    }
}

Add a class to hold all possible tokens


package edu.usc.glidein.util;

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

import org.globus.gsi.GlobusCredential;
import org.globus.gsi.GlobusCredentialException;

public class CredentialUtil
{
	public static void save(GlobusCredential credential, File file)
	throws IOException
	{
		// Create the file if it doesn't exist
		file.createNewFile();

		// Change file permissions
		CommandLine chmod = new CommandLine();
		chmod.setExecutable(new File("/bin/chmod"));
		chmod.addArgument("600");
		chmod.addArgument(file.getAbsolutePath());
		chmod.execute();
		int exitCode = chmod.getExitCode();
		if(exitCode != 0){
			throw new IOException(
					"Unable to change proxy permissions\n\n"+
					"Stdout:\n"+chmod.getOutput()+
					"Stderr:\n"+chmod.getError());
		}

		// Save the credential to the file
		FileOutputStream pstream =
			new FileOutputStream(file);
		credential.save(pstream);
		pstream.close();
	}

	public static GlobusCredential load(File file)
	throws IOException
	{
		try {
			FileInputStream fis = new FileInputStream(file);
			GlobusCredential cred = new GlobusCredential(fis);
			fis.close();
			return cred;
		} catch (GlobusCredentialException gce) {
			IOException ioe = new IOException("Invalid credential");
			ioe.initCause(gce);
			throw ioe;
		}
	}
}

Add credential util to store and load GlobusCredentials from files. Automatically changes permissions of file.


package com.raychenon.licensedroid.license;

/**
 * @author Raymond Chenon
 * https://opensource.org/licenses/BSD-2-Clause
 */
public class BSD2License extends LicenseInfos{
    @Override
    public String getName() {
        return "SD 2-Clause \"Simplified\" or \"FreeBSD\" license";
    }

    @Override
    public String getShortDescription() {
        return "All rights reserved.\n" +
                "\n" +
                "Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n" +
                "\n" +
                "1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n" +
                "\n" +
                "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.\n" +
                "\n" +
                "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 HOLDER 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.";
    }

    public String getCopyrightFormat() {
        return String.format("Copyright (c) %s, %s", YEAR, COPYRIGHT_HOLDER);
    }

}

Add the BSD 2-Clause "Simplified" or "FreeBSD" license


package com.jayway.maven.plugins.android.standalonemojos;

import com.jayway.maven.plugins.android.*;
import io.takari.maven.testing.TestResources;
import io.takari.maven.testing.executor.MavenExecutionResult;
import io.takari.maven.testing.executor.MavenInstallations;
import io.takari.maven.testing.executor.MavenRuntime;
import io.takari.maven.testing.executor.MavenVersions;
import io.takari.maven.testing.executor.junit.MavenJUnitTestRunner;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.io.File;

/**
 * Test the lint mojo. Tests options' default values and parsing. Tests the parameters passed to lint.
 *
 * @author Stéphane Nicolas <snicolas@octo.com>
 * @author Benoit Billington
 *
 */
@RunWith( MavenJUnitTestRunner.class )
@MavenInstallations( {"target/maven-installation/apache-maven-3.2.3"} )
@MavenVersions( {"3.0.5", "3.2.3"} )
public class LintMojoIntegrationTest
{
    @Rule
    public final TestResources resources = new TestResources();

    public final MavenRuntime verifier;

    public LintMojoIntegrationTest(MavenRuntime.MavenRuntimeBuilder builder)
    throws Exception
    {
        this.verifier = builder.withCliOptions( "-X" ).build();
    }

    /**
     * Test project with skip lint flag to true
     *
     * @throws Exception
     */
    @Test
    public void testSkipConfig() throws Exception
    {
        File basedir = resources.getBasedir( "lint-config-project0" );
        MavenExecutionResult result = verifier
                .forProject(basedir)
                .execute( PluginInfo.getQualifiedGoal( "lint" ) );

        result.assertErrorFreeLog();

        result.assertLogText( "Skipping lint analysis" );
    }

    /**
     * Tests execution of Lint
     *
     * @throws Exception
     */
    @Test
    public void testDefaultUnskippedLintConfig() throws Exception
    {
        File basedir = resources.getBasedir( "lint-config-project1" );
        MavenExecutionResult result = verifier
                .forProject(basedir)
                .execute( PluginInfo.getQualifiedGoal( "lint" ) );

        result.assertErrorFreeLog();

        result.assertLogText( "Lint analysis completed successfully" );
    }

}

Add basic Lint integration tests


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

import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

/**
 * Tests for {@link ReleaseInfo}.
 */
public class ReleaseInfoTest {

  @Test
  public void getReleaseInfo() throws Exception {
    ReleaseInfo info = ReleaseInfo.getReleaseInfo();

    // Validate name
    assertThat(info.getName(), containsString("Beam"));

    // Validate semantic version
    String version = info.getVersion();
    String pattern = "\\d+\\.\\d+\\.\\d+.*";
    assertTrue(
        String.format("%s does not match pattern %s", version, pattern),
        version.matches(pattern));
  }
}

Add a test of ReleaseInfo


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

import com.google.common.collect.ImmutableMap;
import io.trino.testing.BaseDynamicPartitionPruningTest;
import io.trino.testing.QueryRunner;
import org.intellij.lang.annotations.Language;

import java.util.List;

import static java.lang.String.format;
import static java.util.stream.Collectors.joining;

public class TestHiveDynamicPartitionPruningTest
        extends BaseDynamicPartitionPruningTest
{
    @Override
    protected QueryRunner createQueryRunner()
            throws Exception
    {
        return HiveQueryRunner.builder()
                .setExtraProperties(EXTRA_PROPERTIES)
                .setHiveProperties(ImmutableMap.of("hive.dynamic-filtering-probe-blocking-timeout", "1h"))
                .setInitialTables(REQUIRED_TABLES)
                .build();
    }

    @Override
    protected void createLineitemTable(String tableName, List<String> columns, List<String> partitionColumns)
    {
        @Language("SQL") String sql = format(
                "CREATE TABLE %s WITH (format = 'TEXTFILE', partitioned_by=array[%s]) AS SELECT %s FROM tpch.tiny.lineitem",
                tableName,
                partitionColumns.stream().map(column -> "'" + column + "'").collect(joining(",")),
                String.join(",", columns));
        getQueryRunner().execute(sql);
    }
}

Add back test for Hive dynamic filtering of partition


package cgeo.geocaching.utils;

import java.net.URLEncoder;

/**
 * Utilities used for translating
 */
public final class TranslationUtils {

    private static final String translationWebsite = "http://translate.google.com/";
    private static final String translationAutoSelect = "#auto";
    private static final String translationFieldSeparator = "|";

    /**
     * Build a URI for Google Translate
     *
     * @param toLang
     *            The two-letter lowercase ISO language codes as defined by ISO 639-1
     * @param text
     *            The text to be translated
     * @return URI ready to be parsed
     */
    public static String buildTranslationURI(final String toLang, final String text) {
        return translationWebsite + translationAutoSelect + translationFieldSeparator + toLang + translationFieldSeparator + URLEncoder.encode(text).replace("+", "%20");
    }

}

Add translation utility class. Adds method to build a URI for Google Translate.


package io.github.Cnly.Crafter.Crafter.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;

public class CompatUtils
{

    @SuppressWarnings("unchecked")
    public static Collection<Player> getOnlinePlayers()
    {

        Method m;
        Object obj = null;
        try
        {
            m = Bukkit.class.getMethod("getOnlinePlayers");
            obj = m.invoke(null, (Object[])null);
        }
        catch (NoSuchMethodException | SecurityException
                | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException e)
        {
            throw new RuntimeException(
                    "Cannot invoke Bukkit.getOnlinePlayers()", e);
        }

        if (obj instanceof Player[])
        {
            return Arrays.asList((Player[])obj);
        }
        else if (obj instanceof Collection)
        {
            return (Collection<Player>)obj;
        }
        else
        {
            throw new RuntimeException(
                    "Unknown getOnlinePlayers() return type!");
        }

    }

}

Add a getOnlinePlayers() that support both old and new ones


/**
 * Copyright (C) 2016 Joshua Auerbach
 *
 * 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 test;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.HttpClients;

/**
 * Just a test that we are able to communicate with the EncodingService at localhost:9879
 */
public class TestEncodingService {
	public static void main(String[] args) throws Exception {
		FileEntity entity = new FileEntity(new File(args[0]));
		HttpClient client = HttpClients.createDefault();
		HttpPost post = new HttpPost("http://localhost:9879");
		entity.setContentType("text/plain");
		post.setEntity(entity);
		HttpResponse resp = client.execute(post);
		int code = resp.getStatusLine().getStatusCode();
		if (code == HttpStatus.SC_OK) {
			HttpEntity answer = resp.getEntity();
			InputStream s = answer.getContent();
			BufferedReader rdr = new BufferedReader(new InputStreamReader(s));
			String line = rdr.readLine();
			while (line != null) {
				System.out.println(line);
				line = rdr.readLine();
			}
			rdr.close();
			s.close();
		} else
			System.out.println(resp.getStatusLine());
	}
}

Add Java test for encoding service (only for testing).


package edu.northwestern.bioinformatics.studycalendar.domain;

import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;

/**
 * @author Rhett Sutphin
 */
public class OracleCompatibilityTest extends StudyCalendarTestCase {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @SuppressWarnings({ "unchecked" })
    public void testAllConfiguredSequencesLessThan30Characters() throws Exception {
        AnnotationSessionFactoryBean sessionFactoryBean
            = (AnnotationSessionFactoryBean) getDeployedApplicationContext().getBean("&sessionFactory");
        Iterator<PersistentClass> mappedClasses = sessionFactoryBean.getConfiguration().getClassMappings();
        while (mappedClasses.hasNext()) {
            PersistentClass pc =  mappedClasses.next();
            Class<?> clazz = pc.getMappedClass();
            GenericGenerator generator = clazz.getAnnotation(GenericGenerator.class);
            if (generator == null) {
                log.debug("{} has no declared generator", clazz.getName());
                continue;
            }
            Parameter sequence = null;
            for (Parameter parameter : generator.parameters()) {
                if ("sequence".equals(parameter.name())) {
                    sequence = parameter; break;
                }
            }
            if (sequence == null) {
                fail("Generator for " + clazz.getName() + " has no sequence parameter");
            }
            assertTrue("Oracle sequence for " + clazz.getName() + " is too long: " + sequence.value() + " (" + sequence.value().length() + " chars). It must be no more than 30 characters. Bering will generate an appropriately named sequence; be sure to configure the same one in the class annotation.",
                sequence.value().length() <= 30);
        }
    }
}

Test for checking that all configured (in the annotations) sequences for oracle are less than 30 characters


package edu.ntnu.idi.goldfish;

import edu.ntnu.idi.goldfish.configurations.Config;
import edu.ntnu.idi.goldfish.configurations.Lynx;
import edu.ntnu.idi.goldfish.mahout.DBModel;
import edu.ntnu.idi.goldfish.preprocessors.Preprocessor;
import edu.ntnu.idi.goldfish.preprocessors.PreprocessorStat;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.recommender.Recommender;

public class Timing {

    public int i = 1;

    public static DataSet set;

	// disable Mahout logging output
	static {
		 System.setProperty("org.apache.commons.logging.Log",
		 "org.apache.commons.logging.impl.NoOpLog");
	}

	public static void main(String[] args) throws Exception {
        new Timing(args);
    }

    public Timing(String[] args) throws Exception {
        // start timing of rebuild
        StopWatch.start("totalRebuild");

        // load dataset from database into DataModel
        StopWatch.start("getModel");

        DBModel.startServer();
        DataModel model = DataSet.MovielensMock1M.getModel();

//
        System.out.format("%s (%d users, %d items)\n", StopWatch.str("getModel"), model.getNumUsers(), model.getNumItems());

        // set configuration parameters and preprocessor
        Config config = new Lynx()
                .set("model", model)
                .set("minTimeOnPage", 25000)
                .set("correlationLimit", 0.3)
                .set("rating", 4)
                .set("predictionMethod", PreprocessorStat.PredictionMethod.ClosestNeighbor);

        // preprocess dataModel
        StopWatch.start("preprocess");
        Preprocessor preprocessor = new PreprocessorStat();
        model = preprocessor.preprocess(config);
        System.out.format("%s (%d users, %d items)\n", StopWatch.str("preprocess"), model.getNumUsers(), model.getNumItems());

        // build Recommendation model
        StopWatch.start("buildRecommender");
        Recommender newRecommender = ((Lynx) config).getBuilder().buildRecommender(model);
        StopWatch.print("buildRecommender");

    }
}

Add timing class to evaluate the preprocessor performance on a large synthesized dataset


// Author: Param Singh <paramsingh258@gmail.com>
// http://www.spoj.com/problems/PHONELST/

import java.io.*;
class Trie {
    private class Node {
        Node children[];
        boolean flag;
        Node() {
            children = new Node[10];
            for (int i = 0; i < 10; i++)
                children[i] = null;
            flag = false;
        }
    }

    private Node root;

    Trie() {
        root = new Node();
    }

    private void insert(Node vertex, String s) {
        if (s.equals("")) {
            vertex.flag = true;
            return;
        }
        else {
            int next = s.charAt(0) - '0';
            if (vertex.children[next] == null) {
                vertex.children[next] = new Node();
            }
            insert(vertex.children[next], s.substring(1, s.length()));
        }
    }

    public void insert(String s) {
        insert(root, s);
    }

    private boolean query(Node vertex, String s) {
        if (s.equals("")) {
            return false;
        }
        if (vertex.flag) {
            return true;
        }
        else {
            int c = s.charAt(0) - '0';
            return query(vertex.children[c], s.substring(1, s.length()));
        }
    }

    public boolean query(String s) {
        return query(root, s);
    }
}

class PhoneLST {
        public static void main(String[] args) throws IOException {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(isr);
        int t = Integer.parseInt(in.readLine());
        for (int term = 0; term < t; term++) {
            int n = Integer.parseInt(in.readLine());
            String a[] = new String[n];
            Trie tr = new Trie();
            int i;
            for (i = 0; i < n; i++) {
                a[i] = in.readLine();
                tr.insert(a[i]);
            }
            boolean flag = false;
            for (i = 0; i < n; i++) {
                if (tr.query(a[i])) {
                    flag = true;
                    break;
                }
            }
            if (flag)
                System.out.println("NO");
            else
                System.out.println("YES");
        }
    }
}

Solve PHONELST for practice of tries


/*
 * Hivemall: Hive scalable Machine Learning Library
 *
 * Copyright (C) 2013-2014
 *   National Institute of Advanced Industrial Science and Technology (AIST)
 *   Registration Number: H25PRO-1520
 *
 * 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.
 *
 * 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 hivemall.mix.server;

import hivemall.io.DenseModel;
import hivemall.io.PredictionModel;
import hivemall.io.WeightValue;
import hivemall.mix.MixMessage.MixEventName;
import hivemall.mix.client.MixClient;
import hivemall.utils.lang.CommandLineUtils;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import junit.framework.Assert;

import org.apache.commons.cli.CommandLine;
import org.junit.Test;

public class MixServerTest {

    @Test
    public void testScenario1() throws InterruptedException {
        CommandLine cl = CommandLineUtils.parseOptions(new String[] { "-port", "11212",
                "-sync_threshold", "3" }, MixServer.getOptions());
        MixServer server = new MixServer(cl);
        ExecutorService serverExec = Executors.newSingleThreadExecutor();
        serverExec.submit(server);

        PredictionModel model = new DenseModel(16777216, false);
        model.configureClock();
        MixClient client = new MixClient(MixEventName.average, "scenario1", "localhost:11212", false, 2, model);
        model.setUpdateHandler(client);

        final Random rand = new Random(43);
        for(int i = 0; i < 100000; i++) {
            Integer feature = Integer.valueOf(rand.nextInt(100));
            float weight = (float) rand.nextGaussian();
            model.set(feature, new WeightValue(weight));
        }

        Thread.sleep(10 * 1000);
        int numMixed = model.getNumMixed();
        //System.out.println("number of mix events: " + numMixed);
        Assert.assertTrue("number of mix events: " + numMixed, numMixed > 0);

        serverExec.shutdown();
    }

}

Add a unit test for MixServer