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

import java.util.logging.Level;

import javax.mail.MessagingException;
import javax.mail.Store;

import lombok.extern.java.Log;

import com.sun.mail.imap.IMAPFolder;

/**
 * Utilities for dealing with Mail
 * @author Eric F. Savage, code@efsavage.com.
 */
@Log
public class MailUtils {

	/**
	 * Closes an {@link IMAPFolder}, logging but ignoring any errors that occur
	 * while doing so.
	 *
	 * @param folder
	 *            The folder to close.
	 */
	public static void safeClose(IMAPFolder folder) {
		if (folder != null && folder.isOpen()) {
			try {
				folder.close(false);
			} catch (MessagingException e) {
				log.log(Level.WARNING, e.getMessage(), e);
			}
		}
	}

	/**
	 * Closes an {@link IMAPFolder}, logging but ignoring any errors that occur
	 * while doing so.
	 *
	 * @param store
	 *            The store to close.
	 */
	public static void safeClose(Store store) {
		if (store != null && store.isConnected()) {
			try {
				store.close();
			} catch (MessagingException e) {
				log.log(Level.WARNING, e.getMessage(), e);
			}
		}
	}

}

Add safeClose for IMAP connection objects


package leetcode.unique_paths;

public class Solution {
	public static int C(int n, int m){
		if(n - m < m) m = n - m;
		long ans = 1;
		for(int i = 1; i <= m; i++){
			ans *= n + 1 - i;
			ans /= i;
		}
		return (int)ans;
	}

    public int uniquePaths(int m, int n) {
    	if(m == 0 || n == 0) return 1;
    	return C(m + n - 2, n - 1);
    }

    public static void main(String[] args){
    	System.err.println(new Solution().uniquePaths(51, 9) + "");
    }
}

Add java solution for 62. Unique Paths


package org.dynmap;

import java.util.logging.Level;
import java.util.logging.Logger;

public class Log {
    protected static final Logger log = Logger.getLogger("Minecraft");
    protected static final String LOG_PREFIX = "[dynmap] ";
    public static boolean verbose = false;
    public static void info(String msg) {
        log.log(Level.INFO, LOG_PREFIX + msg);
    }
    public static void verboseinfo(String msg) {
        if(verbose)
            log.log(Level.INFO, LOG_PREFIX + msg);
    }
    public static void severe(Throwable e) {
        log.log(Level.SEVERE, LOG_PREFIX + "Exception occured: ", e);
    }
    public static void severe(String msg) {
        log.log(Level.SEVERE, LOG_PREFIX + msg);
    }
    public static void severe(String msg, Throwable e) {
        log.log(Level.SEVERE, LOG_PREFIX + msg, e);
    }
    public static void warning(String msg) {
        log.log(Level.WARNING, LOG_PREFIX + msg);
    }
    public static void warning(String msg, Throwable e) {
        log.log(Level.WARNING, LOG_PREFIX + msg, e);
    }
}

package org.dynmap;

import java.util.logging.Level;
import java.util.logging.Logger;

public class Log {
    protected static Logger log = Logger.getLogger("Minecraft");
    protected static String prefix = "[dynmap] ";
    public static boolean verbose = false;
    public static void setLogger(Logger logger, String pre) {
        log = logger;
        if((pre != null) && (pre.length() > 0))
            prefix = pre + " ";
        else
            prefix = "";
    }
    public static void info(String msg) {
        log.log(Level.INFO, prefix + msg);
    }
    public static void verboseinfo(String msg) {
        if(verbose)
            log.log(Level.INFO, prefix + msg);
    }
    public static void severe(Throwable e) {
        log.log(Level.SEVERE, prefix + "Exception occured: ", e);
    }
    public static void severe(String msg) {
        log.log(Level.SEVERE, prefix + msg);
    }
    public static void severe(String msg, Throwable e) {
        log.log(Level.SEVERE, prefix + msg, e);
    }
    public static void warning(String msg) {
        log.log(Level.WARNING, prefix + msg);
    }
    public static void warning(String msg, Throwable e) {
        log.log(Level.WARNING, prefix + msg, e);
    }
}

Add support for injecting logger to core


/*
 * Licensed to the University of California, Berkeley 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 tachyon.worker.keyvalue;

import java.io.IOException;

/**
 * Interface of key-value Index.
 */
public interface Index {

  /**
   * Puts a key into the index, associated with an offset into the key-value payload.
   *
   * @param key bytes of key
   * @param offset offset of this key in payload
   * @return true on success, false otherwise
   */
  boolean put(byte[] key, int offset) throws IOException;

  /**
   * Gets the bytes of value given the key
   *
   * @param key bytes of key
   * @param payload the byte array of all key value payload
   * @return bytes of value, or null if not found
   */
  byte[] get(byte[] key, PayloadReader reader) throws IOException ;

  /**
   * @return size of this index in bytes.
   */
  int byteCount();

  /**
   * @return size of this index in bytes.
   */
  int keyCount();

  /**
   * @return byte array of this index.
   */
  byte[] toByteArray();
}

Add interface of KeyValue index


package com.java.loops;

import java.util.Random;

public class E01_Loops_Mod {

	private static final int ARRAY_SIZE = 10;
	private static final int RANDOM_NUMBER_LIMIT = 100;

	public static void main(String[] args) {
		int[] array = new int[ARRAY_SIZE];
		setRandomNumbers(array);
		printArray(array);
	}

	private static void setRandomNumbers(int[] array) {
		Random random = new Random();
		for (int index = 0; index < array.length; index++) {
			array[index] = random.nextInt(RANDOM_NUMBER_LIMIT);
		}
	}

	private static void printArray(int[] array) {
		System.out.print(" | ");
		for (int number : array) {
			System.out.print(number + " | ");
		}
		System.out.println();
	}
}

Add an example for loops.


package org.robockets.buttonmanger.buttons;

import org.robockets.buttonmanger.Button;

import edu.wpi.first.wpilibj.command.Command;

public class ToggleButton extends Button {
	private boolean toggle = false;

	public ToggleButton(int joystickNumber, int buttonNumber, Command command) {
		super(joystickNumber, buttonNumber, command);
	}

	// Only runs if button is not pushed
	public void notPressed() {
		if (running) {
			stop();
		}
	}

	public void pressed() {
		if (!toggle && !running) {
			super.start();
		}
	}

	public void stop() {
		super.stop();
	}
}

Add rough toggle button support


/**
 * Copyright (C) 2016 Red Hat, 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 io.syndesis.core;

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

import static org.junit.Assert.assertEquals;

public class KeyGeneratorTest {

    @Test
    public void testCreateKey() {
        // Check to make sure we don't generate dup keys
        String last = KeyGenerator.createKey();
        for (int i = 0; i < 1000000; i++) {
            String key = KeyGenerator.createKey();
            Assert.assertNotEquals(key, last);
            last = key;
        }
    }

    @Test
    public void testGetRandomPart() {
        long last = KeyGenerator.getRandomPart(0);
        for (int i = 0; i < 1000000; i++) {
            long key = KeyGenerator.getRandomPart(0);
            Assert.assertNotEquals(key, last);
        }
    }

}

Add unit tests for the KeyGenerator


package org.gdg.frisbee.android.app;

import android.app.Application;
import org.robolectric.TestLifecycleApplication;

import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA.
 * User: maui
 * Date: 22.08.13
 * Time: 13:56
 * To change this template use File | Settings | File Templates.
 */
public class TestApp extends Application implements TestLifecycleApplication {
    @Override
    public void beforeTest(Method method) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void prepareTest(Object o) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void afterTest(Method method) {
        //To change body of implemented methods use File | Settings | File Templates.
    }
}

Fix issues with Application Lifecycle


package leetcode._3sum_closest;

import java.util.Arrays;

public class Solution {

    public int threeSumClosest(int[] num, int target) {
    	Arrays.sort(num);
    	int length = num.length;
    	int ans = num[0] + num[1] + num[2];
    	int mindiff = target - ans;
    	for(int i = 0; i < length; i++){
    		int head = i + 1, tail = length - 1;
    		while(head < tail){
    			int sum = num[i] + num[head] + num[tail];
    			int diff = target - sum;
    			if(Math.abs(diff) < mindiff){
    				mindiff = Math.abs(diff);
    				ans = sum;
    			}
    			if(diff > 0){
    				head++;
    			}else if(diff < 0){
    				tail--;
    			}else{
    				return target;
    			}
    		}
    	}
    	return ans;
    }

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

Add java solution for 16. 3Sum Closest


package util;

import com.google.gson.JsonObject;
import okhttp3.*;
import okio.Buffer;
import org.junit.Assert;

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

/**
 * Generic interceptor that matches a URL regex, checks request body params, and sends a JSON response.
 */
public class GenericInterceptor implements Interceptor {
    private static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/response");

    private String urlRegex;
    private Map<String, String> params;
    private JsonObject response;

    private GenericInterceptor() {
        this.params = new HashMap<>();
        this.response = new JsonObject();
    }

    private void validateBody(Request request) throws IOException {
        RequestBody body = request.body();
        Assert.assertNotNull(body);
        Buffer buffer = new Buffer();
        body.writeTo(buffer);
        String bodyString = buffer.readUtf8();

        for (String key : params.keySet()) {
            String value = params.get(key);
            Assert.assertTrue("Missing key: " + key, bodyString.contains("name=\"" + key + "\""));
            if (value != null)
                Assert.assertTrue("Missing key: " + value, bodyString.contains(value));
        }
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String url = request.url().toString();

        if (!url.matches(urlRegex))
            return chain.proceed(request);

        validateBody(request);

        ResponseBody body = ResponseBody.create(JSON_MEDIA_TYPE, response.toString());

        return new Response.Builder()
                .protocol(Protocol.HTTP_1_1)
                .request(request)
                .code(200)
                .message("Okay")
                .body(body)
                .build();
    }

    public static class Builder {
        private GenericInterceptor interceptor = new GenericInterceptor();

        public Builder urlRegex(String urlRegex) {
            interceptor.urlRegex = urlRegex;
            return this;
        }

        public Builder addEmptyParam(String... keys) {
            for (String key : keys)
                interceptor.params.put(key, null);
            return this;
        }

        public Builder addParam(String key, String value) {
            interceptor.params.put(key, value);
            return this;
        }

        public Builder addEmptyResponse(String... keys) {
            for (String key : keys)
                interceptor.response.addProperty(key, "test");
            return this;
        }

        public Builder addEmptyResponseObject(String key, String... objectKeys) {
            JsonObject object = new JsonObject();
            for (String objectKey : objectKeys)
                object.addProperty(objectKey, "test");
            interceptor.response.add(key, object);
            return this;
        }

        public Builder addResponse(String key, Object value) {
            interceptor.response.addProperty(key, value.toString());
            return this;
        }

        public Builder addResponse(String key, JsonObject object) {
            interceptor.response.add(key, object);
            return this;
        }

        public GenericInterceptor build() {
            return interceptor;
        }
    }
}

Add generic OkHttp Interceptor for tests


package com.filestack;

import com.filestack.transforms.Transform;
import com.filestack.util.FsService;
import io.reactivex.Scheduler;
import io.reactivex.schedulers.Schedulers;

/**
 * Holds config common to {@link FsClient}, {@link FsFile}, and {@link Transform} classes.
 */
public class FsConfig {
  protected final FsService service;
  protected final Scheduler subScheduler;
  protected final Scheduler obsScheduler;
  protected final String apiKey;
  protected final String policy;
  protected final String signature;

  /** Configures and builds new immutable instance. */
  @SuppressWarnings("unchecked")
  public static class Builder<T extends Builder<T>> {
    protected FsService fsService;
    protected Scheduler subScheduler;
    protected Scheduler obsScheduler;
    protected String apiKey;
    protected String policy;
    protected String signature;

    public T fsService(FsService fsService) {
      this.fsService = fsService;
      return (T) this;
    }

    public T subScheduler(Scheduler subScheduler) {
      this.subScheduler = subScheduler;
      return (T) this;
    }

    public T obsScheduler(Scheduler obsScheduler) {
      this.obsScheduler = obsScheduler;
      return (T) this;
    }

    public T security(String policy, String signature) {
      this.policy = policy;
      this.signature = signature;
      return (T) this;
    }

    public T apiKey(String apiKey) {
      this.apiKey = apiKey;
      return (T) this;
    }

    /** Builds new instance, setting defaults for any null requirements. */
    public FsConfig build() {
      if (fsService == null) {
        fsService = new FsService();
      }
      if (subScheduler == null) {
        subScheduler = Schedulers.io();
      }
      if (obsScheduler == null) {
        obsScheduler = Schedulers.computation();
      }
      return new FsConfig(this);
    }
  }

  protected FsConfig(Builder<?> builder) {
    service = builder.fsService;
    subScheduler = builder.subScheduler;
    obsScheduler = builder.obsScheduler;
    apiKey = builder.apiKey;
    policy = builder.policy;
    signature = builder.signature;
  }

  public FsService getService() {
    return service;
  }

  public Scheduler getSubScheduler() {
    return subScheduler;
  }

  public Scheduler getObsScheduler() {
    return obsScheduler;
  }

  public String getApiKey() {
    return apiKey;
  }

  public boolean hasSecurity() {
    return policy != null && signature != null;
  }

  public String getPolicy() {
    return policy;
  }

  public String getSignature() {
    return signature;
  }
}

Add new class to store common config


package es.sandbox.spikes.java8.lambda;

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

import java.util.Arrays;
import java.util.List;

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

/**
 * Created by jeslopalo on 29/12/15.
 */

public class LambdaSpecs {

    private static final String[] ARRAY_OF_STRINGS = new String[]{"a", "b", "c"};

    private StringBuilder result;

    @Before
    public void setup() {
        this.result = new StringBuilder();
    }

    private void assertThatTheResultIs(String expected) {
        assertThat(this.result.toString()).isEqualTo(expected);
    }

    @Test
    public void the_arrow_is_the_body_separator() {
        Arrays.asList(ARRAY_OF_STRINGS)
                .forEach((String e) -> this.result.append(e));

        assertThatTheResultIs("abc");
    }

    @Test
    public void the_argument_type_can_be_inferred() {
        Arrays.asList(ARRAY_OF_STRINGS)
                .forEach(e -> this.result.append(e));

        assertThatTheResultIs("abc");
    }

    @Test
    public void complex_bodies_can_be_wrapped_into_curly_brackets() {
        Arrays.asList(ARRAY_OF_STRINGS)
                .forEach(e -> {
                    final String upper = e.toUpperCase();
                    this.result.append(upper);
                });

        assertThatTheResultIs("ABC");
    }

    @Test
    public void it_may_reference_to_local_variables() {
        final String separator = ",";

        Arrays.asList(ARRAY_OF_STRINGS)
                .forEach(e -> this.result.append(e).append(separator));

        assertThatTheResultIs("a,b,c,");
    }

    @Test
    public void it_may_return_a_value() {
        final List<String> elements = Arrays.asList("c", "a", "b");

        elements.sort((e1, e2) -> {
            int result = e1.compareTo(e2);
            return result;
        });

        assertThat(elements).containsExactly("a", "b", "c");
    }

    @Test
    public void return_statements_is_not_required_if_body_is_oneliner() {
        final List<String> elements = Arrays.asList("c", "a", "b");

        elements.sort((e1, e2) -> e1.compareTo(e2));

        assertThat(elements).containsExactly("a", "b", "c");
    }
}

Add Lambda tests for general specs


package beaform;

import static org.junit.Assert.assertEquals;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import beaform.dao.DbTaskHandler;

/**
 * Test some debugging utilities
 *
 * @author Steven Post
 *
 */
public class DbTaskHandlerTest {

	static final Logger LOG = LoggerFactory.getLogger(DbTaskHandlerTest.class);
	volatile String testString;

	@Test
	public void testCallableAddTask() throws InterruptedException, ExecutionException {
		final Callable<String> task = new Callable<String>() {

			@Override
			public String call() {
				return "testje";
			}
		};
		final Future<String> future = DbTaskHandler.addTask(task);
		final String resultString = future.get();
		assertEquals("This isn't the expected string", "testje", resultString);
	}

	@Test
	public void testRunnableAddTask() throws InterruptedException, ExecutionException {
		final Runnable task = new Runnable() {

			@Override
			public void run() {
				DbTaskHandlerTest.this.testString = "teststring";
			}
		};
		final Future<Void> future = DbTaskHandler.addTask(task);
		future.get();
		assertEquals("This isn't the expected string", "teststring", this.testString);
	}

}

Add tests for the DbTaskHandler


package hex;

import hex.nn.NN;
import hex.nn.NNModel;
import junit.framework.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import water.JUnitRunnerDebug;
import water.Key;
import water.TestUtil;
import water.UKV;
import water.fvec.Frame;
import water.fvec.NFSFileVec;
import water.fvec.ParseDataset2;
import water.util.Log;

public class NeuralNetSpiralsTest2 extends TestUtil {
  @BeforeClass public static void stall() {
    stall_till_cloudsize(JUnitRunnerDebug.NODES);
  }

  @Test public void run() {
    Key file = NFSFileVec.make(find_test_file("smalldata/neural/two_spiral.data"));
    Key parse = Key.make();
    Frame frame = ParseDataset2.parse(parse, new Key[]{file});

    NN p = new NN();
    p.seed = 7401699394609084302l;
    p.rate = 0.007;
    p.rate_annealing = 0;
    p.epochs = 20000;
    p.hidden = new int[]{100};
    p.activation = NN.Activation.Tanh;
    p.max_w2 = Double.MAX_VALUE;
    p.l1 = 0;
    p.l2 = 0;
    p.momentum_start = 0;
    p.momentum_ramp = 0;
    p.momentum_stable = 0;
    p.initial_weight_distribution = NN.InitialWeightDistribution.Normal;
    p.initial_weight_scale = 2.5;
    p.loss = NN.Loss.CrossEntropy;
    p.source = frame;
    p.response = frame.lastVec();
    p.validation = null;
    p.score_interval = 10;
    p.exec();

    NNModel mymodel = UKV.get(p.dest());
    Frame pred = mymodel.score(frame);

    water.api.ConfusionMatrix CM = new water.api.ConfusionMatrix();
    CM.actual = frame;
    CM.vactual = frame.lastVec();
    CM.predict = pred;
    CM.vpredict = pred.vecs()[0];
    CM.serve();
    StringBuilder sb = new StringBuilder();
    double error = CM.toASCII(sb);
    Log.info(sb);
    if (error != 0) {
      Assert.fail("Classification error is not 0, but " + error);
    }
    frame.delete();
    mymodel.delete();
  }
}

Add spirals test case for NN.


import java.util.*;

public class FisherYatesShuffle
{
    public void shuffle(int[] nums)
    {
        if (nums == null || nums.length == 0) return;

        Random r = new Random();

        for (int i = nums.length-1; i >= 0; i--)
        {
            int j = r.nextInt(i+1);

            int t = nums[j];
            nums[j] = nums[i];
            nums[i] = t;
        }
    }
}

Add implementation for Fisher-Yates Shuffle


package com.lintcode;

/**
 * @author : Joshua
 * Date:     1/25/16
 * @see 二进制求和
 */
public class AddBinary {
    public String addBinary(String a, String b) {
        // Write your code here
        int result = Integer.parseInt(a, 2) + Integer.parseInt(b, 2);
        return Integer.toBinaryString(result);
    }
}

Add binary add problem solutions


/*
 * Copyright (C) 2015 Pedro Vicente Gomez Sanchez.
 *
 * 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.lynx;

import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class LynxConfigTest {

  private static final String ANY_FILTER = "AnyFilter";

  @Test public void shouldUse2500AsMaxNumberOfTracesByDefault() {
    LynxConfig lynxConfig = new LynxConfig();

    assertEquals(2500, lynxConfig.getMaxNumberOfTracesToShow());
  }

  @Test public void shouldUseNullFilterByDefault() {
    LynxConfig lynxConfig = new LynxConfig();

    assertNull(lynxConfig.getFilter());
  }

  @Test public void shouldHasNoFilterByDefault() {
    LynxConfig lynxConfig = new LynxConfig();

    assertFalse(lynxConfig.hasFilter());
  }

  @Test public void shouldReturnTrueIfHasAnyFilterConfiguredDifferentOfNull() {
    LynxConfig lynxConfig = new LynxConfig().withFilter(ANY_FILTER);

    assertTrue(lynxConfig.hasFilter());
  }
}

Add some tests to LynxConfig


package problems;

public class BinaryTreeMaximumPathsum {

    // Definition for binary tree
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

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

    public int maxPathSum(TreeNode root) {
        if (root == null)
            return 0;
        return pathSum(root)[1];
    }

    int[] pathSum(TreeNode r) {
        int[] out = new int[2]; // out[0] long leg, out[1] pathSum

        int leftMax = 0, rightMax = 0, leftSum = Integer.MIN_VALUE, rightSum = leftSum;
        if (r.left != null) {
            int[] left = pathSum(r.left);
            leftMax = Math.max(0, left[0]);
            leftSum = left[1];
        }
        if (r.right != null) {
            int[] right = pathSum(r.right);
            rightMax = Math.max(0, right[0]);
            rightSum = right[1];
        }

        out[0] = r.val + Math.max(leftMax, rightMax);
        out[1] = Math.max(r.val + leftMax + rightMax, Math.max(leftSum, rightSum));
        return out;
    }
}

Add Binary Tree Maximum Pathsum


/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2014 - 2015 Board of Regents of the University of
 * Wisconsin-Madison, University of Konstanz and Brian Northan.
 * %%
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * #L%
 */

package net.imagej.ops.arithmetic.real;

import static org.junit.Assert.assertEquals;
import net.imagej.ops.AbstractOpTest;
import net.imglib2.type.numeric.real.DoubleType;

import org.junit.Test;

/**
 * Tests {@link RealArccsc}.
 *
 * @author Alison Walter
 * @author Curtis Rueden
 */
public class RealArccscTest extends AbstractOpTest {

	@Test
	public void testArccsc() {
		assertArccsc(-1, -Math.PI/2);
		assertArccsc(1, Math.PI/2);
		assertArccsc(2, Math.PI/6);
		assertArccsc(-2, -Math.PI/6);
		assertArccsc((2*Math.sqrt(3))/3, Math.PI/3);
		assertArccsc(-(2*Math.sqrt(3))/3, -Math.PI/3);
	}

	private void assertArccsc(double i, double o) {
		final DoubleType in = new DoubleType(i);
		final DoubleType out = ops.math().arccsc(in.createVariable(), in);
		assertEquals(o, out.get(), 1e-15);
	}

}

Add test for RealArccsc functionality


package org.realityforge.arez.api2;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

class TestObservable
  extends Observable
{
  public TestObservable( @Nonnull final ArezContext context,
                         @Nullable final String name )
  {
    super( context, name );
  }

  public TestObservable( @Nonnull final ArezContext context,
                         @Nullable final String name,
                         @Nullable final Observer observer )
  {
    super( context, name, observer );
  }
}

Introduce a basic observable for testing


/*
 * This file is released under terms of BSD license
 * See LICENSE file for more information
 */

package cx2x.translator.language;

import static org.junit.Assert.*;

import cx2x.xcodeml.exception.IllegalDirectiveException;
import org.junit.Test;

/**
 * JUnit test class for the CLAW language parser and information holding class.
 *
 * @author clementval
 */
public class ClawLanguageTest {

  /**
   * Test various input for the CLAW loop fusion directive.
   */
  @Test
  public void FusionTest(){
    // Valid directives
    analyzeValidClawLoopFusion("claw loop-fusion", null);
    analyzeValidClawLoopFusion("claw loop-fusion group(g1)", "g1");
    analyzeValidClawLoopFusion("claw loop-fusion group( g1 )", "g1");
    analyzeValidClawLoopFusion("claw loop-fusion group ( g1   ) ", "g1");
    analyzeValidClawLoopFusion("claw loop-fusiongroup(g1)", "g1");

    // Unvalid directives
    analyzeUnvalidClawLanguage("claw loop-fusion group");
    analyzeUnvalidClawLanguage("claw loop-fusion (i,j,k)");
    analyzeUnvalidClawLanguage("claw loop-fusion group()");
    analyzeUnvalidClawLanguage("claw loop-fusion group(   )");
  }

  /**
   * Assert the result for valid loop fusion CLAW directive
   * @param raw       Raw string valud of the CLAW directive to be analyzed.
   * @param groupName Group name to be found if any.
   */
  private void analyzeValidClawLoopFusion(String raw, String groupName){
    try {
      ClawLanguage l = ClawLanguage.analyze(raw);
      assertEquals(ClawDirective.LOOP_FUSION, l.getDirective());
      if(groupName != null){
        assertTrue(l.hasGroupOption());
        assertEquals(groupName, l.getGroupName());
      } else {
        assertFalse(l.hasGroupOption());
        assertNull(l.getGroupName());
      }
    } catch(IllegalDirectiveException idex){
      fail();
    }
  }

  /**
   * Assert any unvalid claw raw input
   * @param raw Raw string valud of the CLAW directive to be analyzed.
   */
  private void analyzeUnvalidClawLanguage(String raw){
    ClawLanguage l = null;
    try {
      l = ClawLanguage.analyze(raw);
      fail();
    } catch (IllegalDirectiveException pex){
      assertNull(l);
    }
  }
}

Add new junit class for the CLAW language parser + loop-fusion test


package dr.inference.operators;

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

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

    public double doOperation() {

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

            index = shuffledInd[i];

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

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

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

            parameter.setParameterValue(index, newValue);

        }

        return 0.0;
    }

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

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

        public Object parseXMLObject(XMLObject xo) throws XMLParseException {

            double weight = xo.getDoubleAttribute(WEIGHT);

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

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

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

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

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

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

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

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

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

    };

}

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


package org.robockets.stronghold.robot.autonomous;

import org.robockets.stronghold.robot.drivetrain.AssistedDrive;
import org.robockets.stronghold.robot.drivetrain.AssistedRotateType;
import org.robockets.stronghold.robot.drivetrain.AssistedTranslateType;
import org.robockets.stronghold.robot.highgoalshooter.FreeFire;

import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 * ALL VALUES ARE TEMPORARY
 */
public class AutoShootCleat extends CommandGroup {

    public  AutoShootCleat(int defense) {
        addSequential(new MoveToMiddleGoal(defense));
        addSequential(new AssistedDrive(AssistedTranslateType.ENCODER, AssistedRotateType.ENCODER, 24, 0));
        addSequential(new FreeFire());
    }
}

Add skeleton for auto shoot cleat


package seedu.taskitty.commons.util;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.Collection;

import org.junit.Test;

//@@author A0130853L
public class CollectionUtilTest {

    @Test
    public void isAnyNull_returnsTrue() {
        boolean result = CollectionUtil.isAnyNull("hi", "bye", null);
        assertEquals(result, true);
    }

    @Test
    public void elementsAreUnique_returnsTrue() {
        Collection<Object> listOfStrings = new ArrayList<Object>();
        listOfStrings.add("hi");
        listOfStrings.add("bye");
        boolean result = CollectionUtil.elementsAreUnique(listOfStrings);
        assertEquals(result, true);
    }
    @Test
    public void elementsAreUnique_returnsFalse() {
        Collection<Object> listOfStrings = new ArrayList<Object>();
        listOfStrings.add("hi");
        listOfStrings.add("hi");
        boolean result = CollectionUtil.elementsAreUnique(listOfStrings);
        assertEquals(result, false);
    }

}

Add collectionUtil test to improve coverage


package year2017;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 *
Largest Number

 *
Determine the largest number that can be formed from a group of individual numbers.
 * For example, given the numbers 50, 2, 1, 9 the largest number that can be formed is 95021.

 *
 * @author John Cameron
 * @see Problem Descrption and Requirements
 */
public class LargestNumber {

    public static void main(String[] args) {

        /*
            This will read data from a file. To keep things simple, a test value is hard-coded.
            Exceptions do not need to be handled for this problem.
            //String input = new String(Files.readAllBytes(Paths.get("largestnumber1.txt")), StandardCharsets.US_ASCII);
        */

        String input = "201 3 77 5632 41 18";

        List<Integer> numbers = Arrays.stream(input.trim().split(Pattern.quote(" ")))
                .mapToInt(Integer::parseInt).boxed().collect(Collectors.toList());

        numbers.sort((o1, o2) -> {
            int first1 = determineFirstDigit(o1);
            int first2 = determineFirstDigit(o2);

            if (first1 == first2) {
                return o2.compareTo(o1);
            } else {
                return (first1 > first2) ? -1 : 1;
            }
        });

        System.out.println("Input: " + input);

        System.out.println(
                "Largest Number: " + numbers.stream().map(Object::toString).collect(Collectors.joining())
        );

    }

    private static int determineFirstDigit(int number) {
        if (number < 0)
            throw new IllegalArgumentException("Must be positive");

        if (number < 10)
            return number;

        return Character.getNumericValue(String.valueOf(number).charAt(0));
    }

}

Add Largest Number (2017) solution


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

package net.imagej.legacy;

import net.imagej.legacy.ui.LegacyUI;

import org.scijava.Context;
import org.scijava.ui.UIService;

/**
 * Launches ImageJ with the legacy UI.
 *
 * @author Curtis Rueden
 */
public class Main {

	public static void main(String[] args) {
		final Context context = new Context();
		context.service(UIService.class).showUI(LegacyUI.NAME);
	}
}

Add a main class for launching the legacy UI


package bcgTree.gui;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class BcgTree extends JFrame {
	private static final long serialVersionUID = 1L;

	public static void main(String[] args) {
		BcgTree mainWindow = new BcgTree();
		mainWindow.pack();
		mainWindow.setVisible(true);
	}

	public BcgTree(){
		this.setTitle("bcgTree");
		this.setLayout(new GridLayout(4, 1));
		JLabel titleLabel = new JLabel("bcgTree v1.0.0");
		titleLabel.setHorizontalAlignment(JLabel.CENTER);
		this.add(titleLabel);
		this.add(new JButton("Check Requirements"));
		this.add(new JButton("Set Parameters"));
		JButton actionButton = new JButton("Action!");
		this.add(actionButton);
		actionButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				System.out.println(System.getProperty("user.dir"));
				try {
					Process proc = Runtime.getRuntime().exec("perl "+System.getProperty("user.dir")+"/../bin/bcgTree.pl --help");
					InputStream stderr = proc.getInputStream();
		            InputStreamReader isr = new InputStreamReader(stderr);
		            BufferedReader br = new BufferedReader(isr);
		            String line = null;
		            while ( (line = br.readLine()) != null)
		                System.out.println(line);
		            int exitVal = proc.waitFor();
		            System.out.println("Process exitValue: " + exitVal);
				} catch (IOException | InterruptedException e1) {
					e1.printStackTrace();
				}
			}
		});
	}

}

Add simple JFrame that can execute bcgTree from a relative path


package com.tacitknowledge.performance.degrade;

import java.util.concurrent.TimeUnit;

import com.tacitknowledge.performance.Component;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;

/** @author Ivan Frolov (ifrolov@tacitknowledge.com) */
public class Discard implements Component
{
    private final long timeout;

    public Discard(final long timeout)
    {
        this.timeout = timeout;
    }

    @Override
    public void initChannel(final SocketChannel ch)
    {
        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
            @Override
            public void channelActive(final ChannelHandlerContext ctx) throws Exception
            {
                ctx.executor().schedule(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        ctx.channel().close();
                    }
                }, timeout, TimeUnit.MILLISECONDS);
            }

            @Override
            public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception
            {
                //discard
            }

            @Override
            public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception
            {
                ctx.channel().close();
            }
        });
    }
}

Implement 'discard incoming packets and keep connection open' degradation handler.


/*
 Copyright 2006 Paul Zepernick

 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 net.sf.pzfilereader.parserutils;

import net.sf.pzfilereader.util.ParserUtils;
import junit.framework.TestCase;

/**
 * Tests the functionality of the left trim in the ParserUtils
 *
 * @author paul zepernick
 */
public class LTrimTest extends TestCase{

    /**
     * Make sure all spaces are properly removed from the front of the String
     *
     */
    public void testTrimLeadingSpaces(){
        final String testS = "     RemoveAllSpacesFromMe";
        assertEquals(true , ParserUtils.lTrim(testS).indexOf(" ") == -1);
    }

    /**
     * Make sure all spaces are properly removed from the front of the String
     * leaving the trailing spaces at the end
     *
     */
    public void testTrimLeadingSpacesWithTrailingSpaces(){
        final String testS = "     RemoveAllSpacesFromMe     ";
        final String tResult = ParserUtils.lTrim(testS);
        assertEquals(true , !tResult.startsWith(" ") && tResult.endsWith(" "));
    }

    /**
     * Make sure all TAB chars are properly removed from the front of the String
     * leaving the trailing spaces at the end
     *
     */
    public void testTrimLeadingTabs(){
        final String testS = "\t\t\tRemoveAllSpacesFromMe     ";
        final String tResult = ParserUtils.lTrim(testS);
        assertEquals(true , !tResult.startsWith("\t") && tResult.endsWith(" "));
    }

    /**
     * Make sure all TAB chars are properly removed from the front of the String
     * leaving the trailing spaces at the end
     *
     */
    public void testKeepLeadingTabs(){
        final String testS = "     \t\t\tRemoveAllSpacesFromMe     ";
        final String tResult = ParserUtils.lTrimKeepTabs(testS);
        assertEquals(true , !tResult.startsWith("\t") && tResult.endsWith(" "));
    }

    public static void main(final String[] args) {
        junit.textui.TestRunner.run(LTrimTest.class);
    }
}

Test cases for lTrim and lTrimKeepTabs


/*******************************************************************************
 * Mission Control Technologies, Copyright (c) 2009-2012, United States Government
 * as represented by the Administrator of the National Aeronautics and Space
 * Administration. All rights reserved.
 *
 * The MCT platform is 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.
 *
 * MCT includes source code licensed under additional open source licenses. See
 * the MCT Open Source Licenses file included with this distribution or the About
 * MCT Licenses dialog available at runtime from the MCT Help menu for additional
 * information.
 *******************************************************************************/
package gov.nasa.arc.mct.scenario.actions;

import gov.nasa.arc.mct.components.AbstractComponent;

import java.awt.Component;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.Collection;

import javax.swing.ProgressMonitor;

public class CSVExporter {
	private Component component;
	private Collection<AbstractComponent> components;
	private File file;

	public CSVExporter(Component component,
			Collection<AbstractComponent> components, File file) {
		super();
		this.component = component;
		this.components = components;
		this.file = file;
	}

	public void export() {
		final CSVExportWorker worker = new CSVExportWorker(components, file);
		final ProgressMonitor monitor = new ProgressMonitor(component, "Exporting", "CSV export", 0, 100);
		monitor.setMillisToDecideToPopup(200);
		monitor.setMillisToPopup(750);

		worker.addPropertyChangeListener(new PropertyChangeListener() {
			@Override
			public void propertyChange(PropertyChangeEvent evt) {
				monitor.setProgress(worker.getProgress());
			}
		});

		worker.execute();
	}

}

Add class to manage CSV export


package org.liveontologies.proof.util;

import java.util.AbstractList;
import java.util.List;

/**
 * A skeleton implementation for conversion of inferences
 *
 * @author Yevgeny Kazakov
 *
 * @param <I>
 *            the type of conclusion and premises of the input inference
 * @param <O>
 *            the type of conclusion and premises of the output inference
 */
public abstract class AbstractConvertedInference<I, O> implements Inference<O> {

	private final Inference<I> input_;

	public AbstractConvertedInference(Inference<I> input) {
		this.input_ = input;
	}

	public Inference<I> getInput() {
		return input_;
	}

	@Override
	public String getName() {
		return input_.getName();
	}

	@Override
	public O getConclusion() {
		return convert(input_.getConclusion());
	}

	@Override
	public List<? extends O> getPremises() {
		final List<? extends I> inputPremises = input_.getPremises();
		return new AbstractList<O>() {

			@Override
			public O get(int index) {
				return convert(inputPremises.get(index));
			}

			@Override
			public int size() {
				return inputPremises.size();
			}
		};
	}

	protected abstract O convert(I conclusion);

}

Add abstract generic inference converter class


//5. Longest Palindromic Substring
/**
 * Given a string s, find the longest palindromic substring in s.
 * You may assume that the maximum length of s is 1000.
 *
 * Example:
 * Input: "babad"
 * Output: "bab"
 * Note: "aba" is also a valid answer.
 *
 * Example:
 * Input: "cbbd"
 * Output: "bb"
 *
 * Tags: String
 * Similar Problems: (H) Shortest Palindrome (E) Palindrome Permutation (H) Palindrome Pairs
 *
 * @author Xinyue Zhang
 *
 */
public class Solution {
    public String longestPalindrome(String s) {
        int n = s.length();
        if (n < 2) return s;

        int start = 0, i = 0, maxLen = 0;
        //the max length is 2 * (n - i)
        while (i < n - 1 && maxLen < 2 * (n - i)) {
            int left = i, right = i;
            //skip duplicates, which are palindromic string
            while (right < n - 1 && s.charAt(right) == s.charAt(right + 1))
                right++;

            i = right + 1;

            while (left > 0 && right < n - 1 && s.charAt(left - 1) == s.charAt(right + 1)) {
                left--;
                right++;
            }
            //update max length
            int curLen = right - left + 1;
            if (curLen > maxLen) {
                maxLen = curLen;
                start = left;
            }
        }

        return s.substring(start, start + maxLen);
    }

    public static void main(String args[]) {
        String s = "babbad";
        Solution sol = new Solution();
        System.out.println(sol.longestPalindrome(s));
    }
}

Add solution for 5. Longest Palindromic Substring


package com.google.maps.android.clustering.algo;

import android.annotation.TargetApi;
import android.os.Build;
import android.util.Log;
import android.util.LruCache;

import com.google.maps.android.clustering.Cluster;
import com.google.maps.android.clustering.ClusterItem;

import java.util.Set;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
public class PreCachingDecorator<T extends ClusterItem> implements Algorithm<T> {
    private final static String TAG = PreCachingDecorator.class.getName();
    private final Algorithm<T> mAlgorithm;
    private final LruCache<Integer, Set<? extends Cluster<T>>> mCache = new LruCache<Integer, Set<? extends Cluster<T>>>(5);
    private final ReadWriteLock mCacheLock = new ReentrantReadWriteLock();

    public PreCachingDecorator(Algorithm<T> algorithm) {
        mAlgorithm = algorithm;
    }

    public void addItem(T item) {
        mAlgorithm.addItem(item);
        clearCache();
    }

    public void removeItem(T item) {
        mAlgorithm.removeItem(item);
        clearCache();
    }

    private void clearCache() {
        mCache.evictAll();
    }

    @Override
    public Set<? extends Cluster<T>> getClusters(double zoom) {
        int discreteZoom = (int) zoom;
        Set<? extends Cluster<T>> results = getClustersInternal(discreteZoom);
        new Thread(new PrecacheRunnable(discreteZoom + 1)).start();
        new Thread(new PrecacheRunnable(discreteZoom - 1)).start();
        return results;
    }

    public Set<? extends Cluster<T>> getClustersInternal(int discreteZoom) {
        Log.d(TAG, "getClusters: zoom " + discreteZoom);
        Set<? extends Cluster<T>> results;
        mCacheLock.readLock().lock();
        results = mCache.get(discreteZoom);
        mCacheLock.readLock().unlock();

        if (results == null) {
            mCacheLock.writeLock().lock();
            results = mCache.get(discreteZoom);
            if (results == null) {
                Log.d(TAG, "cache miss for zoom " + discreteZoom);
                results = mAlgorithm.getClusters(discreteZoom);
                mCache.put(discreteZoom, results);
            } else {
                Log.d(TAG, "cache hit for zoom " + discreteZoom);
            }
            mCacheLock.writeLock().unlock();
        } else {
            Log.d(TAG, "cache hit for zoom " + discreteZoom);
        }
        return results;
    }

    private class PrecacheRunnable implements Runnable {
        private final int mZoom;

        public PrecacheRunnable(int zoom) {
            mZoom = zoom;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // ignore. keep going.
            }
            long start = System.currentTimeMillis();
            getClustersInternal(mZoom);
            Log.d(TAG, "pre-filling cache for zoom " + mZoom + " took " + (System.currentTimeMillis() - start));
        }
    }
}

Add a decorator Algorithm that quantizes zoom level, fetches and caches (with LruCache) the clusters for the two adjacent zoom levels.


package it.reply.orchestrator.service.security;

import it.reply.orchestrator.dto.security.IndigoOAuth2Authentication;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
@PropertySource(value = { "classpath:security.properties" })
public class OAuth2TokenService {

  @Value("${security.enabled}")
  private boolean securityEnabled;

  public boolean isSecurityEnabled() {
    return securityEnabled;
  }

  public String getOAuth2Token() {
    if (!securityEnabled) {
      throw new IllegalStateException("Security is not enabled");
    }
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth == null || !(auth instanceof IndigoOAuth2Authentication)) {
      throw new IllegalStateException("User is not authenticated");
    }
    IndigoOAuth2Authentication indigoAuth = (IndigoOAuth2Authentication) auth;
    return indigoAuth.getPrincipal().toString();
  }
}

Add Service to obtain authN info


/*
 * (C) Copyright 2021 Boni Garcia (http://bonigarcia.github.io/)
 *
 * 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.github.bonigarcia.wdm.test.docker;

import static java.lang.invoke.MethodHandles.lookup;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.condition.OS.LINUX;
import static org.slf4j.LoggerFactory.getLogger;

import java.net.HttpURLConnection;
import java.net.URL;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;

import io.github.bonigarcia.wdm.WebDriverManager;

/**
 * Test with Chrome beta in Docker.
 *
 * @author Boni Garcia
 * @since 5.0.0
 */
@EnabledOnOs(LINUX)
class DockerFirefoxBetaTest {

    final Logger log = getLogger(lookup().lookupClass());

    static final int WAIT_TIME_SEC = 10;

    WebDriver driver;

    WebDriverManager wdm = WebDriverManager.firefoxdriver().browserInDocker()
            .browserVersion("beta").enableVnc();

    @BeforeEach
    void setupTest() {
        driver = wdm.create();
    }

    @AfterEach
    void teardown() {
        wdm.quit();
    }

    @Test
    void test() throws Exception {
        String sutUrl = "https://github.com/bonigarcia/webdrivermanager";
        driver.get(sutUrl);
        String title = driver.getTitle();
        log.debug("The title of {} is {}", sutUrl, title);
        assertThat(title)
                .contains("Automated driver management for Selenium WebDriver");

        URL dockerSessionUrl = wdm.getDockerNoVncUrl();
        HttpURLConnection huc = (HttpURLConnection) dockerSessionUrl
                .openConnection();
        assertThat(huc.getResponseCode()).isEqualTo(HTTP_OK);

        // Active wait to manually inspect
        Thread.sleep(SECONDS.toMillis(WAIT_TIME_SEC));
    }

}

Include Firefox beta in Docker test


package org.jdesktop.beans.editors;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
 * A demo program to showcase {@link PaintPicker}.
 *
 * @author Karl Schaefer
 */
@SuppressWarnings("all")
public class PaintPickerDemo extends JFrame {
    /**
     * {@inheritDoc}
     */
    @Override
    protected void frameInit() {
        super.frameInit();

        setTitle("PaintPicker Demo");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        add(new PaintPicker());

        pack();
    }

    /**
     * Demo entry point.
     *
     * @param args
     *            unused
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new PaintPickerDemo().setVisible(true);
            }
        });
    }
}

Add demo for paint picker.


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

import org.testng.annotations.Test;

import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;

public class TestMySqlJdbcConfig
{
    @Test
    public void testIsUrlWithoutDatabase()
    {
        assertTrue(isUrlWithoutDatabase("jdbc:mysql://example.net:3306"));
        assertTrue(isUrlWithoutDatabase("jdbc:mysql://example.net:3306/"));
        assertFalse(isUrlWithoutDatabase("jdbc:mysql://example.net:3306/somedatabase"));
    }

    private static boolean isUrlWithoutDatabase(String url)
    {
        MySqlJdbcConfig config = new MySqlJdbcConfig();
        config.setConnectionUrl(url);
        return config.isUrlWithoutDatabase();
    }
}

Test MySQL JDBC URL verification


/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the “License”). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.client.block;

import alluxio.client.ClientContext;
import alluxio.exception.ExceptionMessage;
import alluxio.underfs.UnderFileSystem;

import java.io.IOException;

/**
 * Implementation of {@link UnderStoreBlockInStream} which directly accesses the under storage
 * from the client.
 */
public class DirectUnderStoreBlockInStream extends UnderStoreBlockInStream {
  /**
   * Constructor for a direct under store block in stream.
   *
   * @param initPos position in the file
   * @param length length of the block
   * @param fileBlockSize file block size
   * @param ufsPath path in the ufs
   * @throws IOException if an error occurs initializing the stream to the ufs file
   */
  public DirectUnderStoreBlockInStream(long initPos, long length, long fileBlockSize,
      String ufsPath) throws IOException {
    super(initPos, length, fileBlockSize, ufsPath);
  }

  @Override
  protected void setUnderStoreStream(long pos) throws IOException {
    if (mUnderStoreStream != null) {
      mUnderStoreStream.close();
    }
    if (pos < 0 || pos > mLength) {
      throw new IOException(ExceptionMessage.FAILED_SEEK.getMessage(pos));
    }
    UnderFileSystem ufs = UnderFileSystem.get(mUfsPath, ClientContext.getConf());
    mUnderStoreStream = ufs.open(mUfsPath);
    // The stream is at the beginning of the file, so skip to the correct absolute position.
    if ((mInitPos + pos) != 0 && mInitPos + pos != mUnderStoreStream.skip(mInitPos + pos)) {
      throw new IOException(ExceptionMessage.FAILED_SKIP.getMessage(pos));
    }
    // Set the current block position to the specified block position.
    mPos = pos;
  }
}

Implement direct under store block in stream.


package de.unibonn.iai.eis.diachron.qualitymetrics.utilities;

import com.hp.hpl.jena.graph.Triple;

import de.unibonn.iai.eis.diachron.qualitymetrics.accessibility.availability.Dereferencibility;
import de.unibonn.iai.eis.diachron.qualitymetrics.accessibility.availability.RDFAccessibility;
import de.unibonn.iai.eis.diachron.qualitymetrics.accessibility.availability.SPARQLAccessibility;
import de.unibonn.iai.eis.diachron.qualitymetrics.accessibility.availability.UnstructuredData;

public class TestClass {

	//test class for the metrics implemented
	public static void main(String [] args){
		  TestLoader t = new TestLoader();
		  t.loadDataSet();

		  //Objects for Classed to be tested
		  RDFAccessibility rdfa= new RDFAccessibility();
		  SPARQLAccessibility sparqla= new SPARQLAccessibility();
		  Dereferencibility derefa= new Dereferencibility();
		  UnstructuredData unstra = new UnstructuredData();

		  //Test for RDF accessibility class

		  for(Triple tr : t.getStreamingTriples()){
		   //System.out.println(tr.getSubject());
		   rdfa.compute(tr);
		   System.out.println("The metric RDF accessibility value triple:"+tr.getObject()+" is "+rdfa.metricValue());

		  }

		  //Test for SPARQL accessibility

		  for(Triple tr : t.getStreamingTriples()){
			   //System.out.println(tr.getSubject());
			   sparqla.compute(tr);
			   System.out.println("The metric SPARQL accessibility value triple: "+tr.getObject()+" is "+sparqla.metricValue());

			  }
		  System.out.println("Dereferencebility test begins");
		  //Test for Deferencibility accessibility
		  // Passing all the triple for the calculation of the metric value
		  for(Triple tr : t.getStreamingTriples())
			 {
			  System.out.println(tr.getObject());
			  derefa.compute(tr);

			  unstra.compute(tr);
			 }
		  //Print the metric values calculated
		  System.out.println("Metric value for Derefrencibility is: " + derefa.metricValue());
		  System.out.println("Metric value for Unstructureddata is: " + unstra.metricValue());

		 }
}

Test class added to main branch


/*
 * 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.facebook.presto.sql.analyzer;

import com.facebook.presto.sql.tree.Node;
import com.facebook.presto.sql.tree.NodeRef;
import com.facebook.presto.util.maps.IdentityLinkedHashMap;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static java.util.Collections.newSetFromMap;

/**
 * Temporary class facilitating conversions from/to identity-based Maps and Sets
 */
public class NodeRefCollections
{
    public static <K extends Node, V> IdentityLinkedHashMap<K, V> toIdentityMap(Map<NodeRef<K>, V> map)
    {
        IdentityLinkedHashMap<K, V> result = new IdentityLinkedHashMap<>();
        for (Entry<NodeRef<K>, V> entry : map.entrySet()) {
            result.put(entry.getKey().getNode(), entry.getValue());
        }
        return result;
    }

    public static <K extends Node, V> Map<NodeRef<K>, V> fromIdentityMap(IdentityLinkedHashMap<K, V> map)
    {
        Map<NodeRef<K>, V> result = new LinkedHashMap<>();
        for (Entry<K, V> entry : map.entrySet()) {
            result.put(NodeRef.of(entry.getKey()), entry.getValue());
        }
        return result;
    }

    public static <T extends Node> Set<T> toIdentitySet(Set<NodeRef<T>> set)
    {
        Set<T> result = newSetFromMap(new IdentityLinkedHashMap<>());
        set.stream()
                .map(NodeRef::getNode)
                .forEach(result::add);
        return result;
    }

    public static <T extends Node> Set<NodeRef<T>> fromIdentitySet(Set<T> set)
    {
        return set.stream()
                .map(NodeRef::of)
                .collect(toImmutableSet());
    }

    private NodeRefCollections()
    {
    }
}

Implement temporary conversion methods from/to identity-collections


/*
 * Copyright 2019 Immutables Authors and Contributors
 *
 * 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.immutables.criteria.inmemory;

import org.immutables.criteria.backend.Backend;
import org.immutables.criteria.typemodel.StringTemplate;
import org.junit.jupiter.api.Nested;

class InMemoryIntegrationTest {

  private final Backend backend = new InMemoryBackend();

  @Nested
  class StringTest extends StringTemplate {
    private StringTest() {
      super(backend);
    }
  }
}

Add Integration tests to InMemory backend


/**
 * 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.jena.fuseki;

import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.jena.riot.WebContent;
import org.apache.jena.riot.web.HttpOp;
import org.apache.jena.riot.web.HttpResponseHandler;
import org.apache.jena.web.HttpSC;
import org.junit.Test;

import static org.apache.commons.lang3.StringUtils.substringAfter;
import static org.apache.commons.lang3.StringUtils.substringBefore;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.core.Is.is;

public class TestMetrics extends AbstractFusekiTest {

    @Test
    public void can_retrieve_metrics() {
        RecordingResponseHandler responseHandler = new RecordingResponseHandler();

        HttpOp.execHttpGet( ServerCtl.urlRoot() + "$/metrics" ,
                "",
                responseHandler);

        assertThat(responseHandler.statusCode, is(HttpSC.OK_200));
        assertThat(responseHandler.contentType, is(WebContent.contentTypeTextPlain));
        assertThat(responseHandler.encoding, is(WebContent.charsetUTF8));
        assertThat(responseHandler.content, containsString("fuseki_requests_good"));
    }

    static class RecordingResponseHandler implements HttpResponseHandler {

        private int statusCode;
        private String contentType;
        private String encoding;
        private String content;

        @Override
        public void handle(String baseIRI, HttpResponse response) throws IOException {
            statusCode = response.getStatusLine().getStatusCode();
            String rawContentType = response.getEntity().getContentType().toString();
            contentType = substringBefore( substringAfter(rawContentType, "Content-Type: "), ";");
            encoding = substringAfter(rawContentType, "charset=");
            content = IOUtils.toString( response.getEntity().getContent(), encoding);
        }

    }

}

Add rudimentary test for metrics


/*
 * 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.felix.webconsole;

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

import org.osgi.service.http.HttpContext;

/**
 * The WebConsoleSecurityProvider3 extends the
 * {@link WebConsoleSecurityProvider2} interface and adds the ability to perform log-out operation.
 *

 * If a registered {@link WebConsoleSecurityProvider} service implements this
 * interface the {@link #logout(HttpServletRequest, HttpServletResponse)}
 * method is called when the user clicks the logout button.
 *
 * If this service is missing and basic authentication is used, then new authentication is requested.
 *
 * In any case, the logout procedure will invalidate the current session and will remove the
 * {@link HttpContext#REMOTE_USER}, {@link HttpContext#AUTHORIZATION} attributes from the request and the session.
 *
 * @since 4.2.8; Web Console Bundle 4.2.8
 */
public interface WebConsoleSecurityProvider3 extends WebConsoleSecurityProvider2
{

    /**
     * This method will be called by the web console when the user clicks the logout button. The security provider
     * shouldn't invalidate the session, it will be invalidated after this method exits.
     *
     * However the security provider must delete any cookies or objects, that matters during the authorization process.
     *
     * @param request the request
     * @param response the response
     */
    void logout(HttpServletRequest request, HttpServletResponse response);
}

Add mising security provider 3


/*
 * Licensed to David Pilato under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch 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 fr.pilato.elasticsearch.crawler.fs.framework;

import fr.pilato.elasticsearch.crawler.fs.test.framework.AbstractFSCrawlerTestCase;
import org.junit.Test;

import java.security.NoSuchAlgorithmException;

import static fr.pilato.elasticsearch.crawler.fs.framework.SignTool.sign;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

public class SignToolTest extends AbstractFSCrawlerTestCase {

    @Test
    public void testSign() throws NoSuchAlgorithmException {
        String signature = sign("ABCD");
        assertThat(signature, is("cb8ca4a7bb5f9683c19133a84872ca7"));
    }

}

Add a test for the SignTool utility


package checkpoint.andela.buffer;

import checkpoint.andela.parser.Reactant;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created by Semiu on 25/01/2016.
 */
public class Buffers {
  private static BlockingQueue<String> logBuffer = new ArrayBlockingQueue<String>(1);
  private static BlockingQueue<Reactant> fileBuffer = new ArrayBlockingQueue<Reactant>(1);

  public static BlockingQueue<String> getLogBuffer(){
    return logBuffer;
  }

  public static BlockingQueue<Reactant> getFileBuffer(){
    return fileBuffer;
  }
}

Create Buffer package and Buffer files that serves as the temporary storage


package org.mapdb;

import org.junit.Test;

import java.util.Map;

import static org.junit.Assert.assertTrue;

public class Issue157Test {

    @Test
    public void concurrent_BTreeMap() throws InterruptedException {
        DBMaker dbMaker = DBMaker.newMemoryDB().cacheDisable().asyncWriteDisable();
        DB db = dbMaker.make();
        final BTreeMap<Integer, String> map = db.getTreeMap("COL_2");
        map.clear();

        Thread t1 = new Thread() {
            public void run() {
                for(int i=0; i<=10000; i++) {
                    map.put(i, "foo");
                }
            }
        };

        Thread t2 = new Thread() {
            public void run() {
                for(int i=10000; i>=0; i--) {
                    map.put(i, "bar");
                }
            }
        };

        t1.start();
        t2.start();

        t1.join();
        t2.join();

//        map.printTreeStructure();

        for(Map.Entry entry : map.entrySet()) {
//            System.out.println(entry.getKey() + " => " + entry.getValue());
            assertTrue(""+entry.getKey(),"bar".equals(entry.getValue())||"foo".equals(entry.getValue()));
        }

    }
}

Add test case for previous commit


package lejos.nxt;

/**
 * Exception thrown when errors are detected in a sensor device state.
 * @author andy
 *
 */
public class SensorException extends RuntimeException
{
    /**
     *
     */
    private static final long serialVersionUID = 5846698127613306496L;

    public SensorException()
    {
    }

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

    public SensorException(Throwable cause)
    {
        super (cause);
    }

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

Add exception used for sensor errors


package gui.misc;

import javafx.animation.Interpolator;
import javafx.beans.property.Property;
import lombok.Getter;

public class TransitionData<T> {
    @Getter
    private Property<T> property;
    @Getter
    private int ms;
    @Getter
    private Interpolator interpolator;

    public TransitionData(Property<T> property, int ms, Interpolator interpolator) {
        this.property = property;
        this.ms = ms;
        this.interpolator = interpolator;
    }
}

Create wrapper class for often used paramters in TransitionHelper


package leetcode.reverse_integer;

public class Solution {
    public int reverse(int x) {
    	int ret = 0;
    	while(x != 0){
    		ret *= 10;
    		ret += x % 10;
    		x /= 10;
    	}
    	return ret;
    }
    public static void main(String[] args){
    	System.err.println("" + new Solution().reverse(1234));
    	System.err.println("" + new Solution().reverse(1000));
    	System.err.println("" + new Solution().reverse(-1234));
    }
}

Add java solution for 7. Reverse Integer


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

package org.ensembl.healthcheck.testcase.generic;

import java.sql.Connection;

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

/**
 * Check for genes, transcripts and exons where the is_current column is
 * anything other than 1. Any value other than 1 will cause problems for Ensembl
 * databases.
 */
public class IsCurrent extends SingleDatabaseTestCase {

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

		addToGroup("post_genebuild");
		addToGroup("release");

		setDescription("Check for genes, transcripts and exons where the is_current column is anything other than 1.");

	}

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

		boolean result = true;

		Connection con = dbre.getConnection();

		String[] types = { "gene", "transcript", "exon" };

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

			String table = types[i];

			int rows = getRowCount(con, "SELECT COUNT(*) FROM " + table + " WHERE is_current IS NULL OR is_current != 1");

			if (rows > 0) {

				ReportManager.problem(this, con, rows + " " + table + "s have is_current set to null or some value other than 1");
				result = false;

			} else {

				ReportManager.correct(this, con, "All " + table + "s have is_current=1");

			}

		}

		return result;

	} // run

} // IsCurrent

Check that all gene, transcript and exon is_current = 1


package tdse3.tdse3.util;

import tdse3.tdse3.Controller;
import tdse3.tdse3.Tdse3Factory;

public class Standalone {

	public static void main(String[] args) {
		Controller controller = Tdse3Factory.eINSTANCE.createController();
		while (true) {
			print(controller);
			controller.tick();
		}
	}

	private static void print(Controller controller) {
		System.out.println("cars: " + controller.getCarLight().getColors() +
				"peds: " + controller.getPedLight().getColors());
	}

}

Test program for model code


package org.intermine.webservice.server.output;

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

import org.intermine.api.InterMineAPI;
import org.intermine.api.LinkRedirectManager;
import org.intermine.api.results.ResultElement;
import org.intermine.model.InterMineObject;
import org.intermine.web.logic.PortalHelper;
import org.json.JSONObject;

public class TableCellFormatter
{

    private static final String CELL_KEY_URL = "url";
    private static final String CELL_KEY_VALUE = "value";
    private static final String CELL_KEY_CLASS = "class";
    private static final String CELL_KEY_ID = "id";

    private final LinkRedirectManager redirector;
    private final InterMineAPI im;

    public TableCellFormatter(InterMineAPI im) {
        this.im = im;
        this.redirector = im.getLinkRedirector();
    }

    /**
     * Get the JSONObject that represents each cell in the results row
     * @param cell The result element with the data
     * @return A JSONObject
     */
    public JSONObject toJSON(ResultElement cell) {
        Map<String, Object> mapping = new HashMap<String, Object>();
        if (cell == null || cell.getId() == null) {
            mapping.put(CELL_KEY_URL, null);
            mapping.put(CELL_KEY_VALUE, null);
        } else {
            String link = null;
            if (redirector != null) {
                link = redirector.generateLink(im, (InterMineObject) cell.getObject());
            }
            if (link == null) {
                link = PortalHelper.generateReportPath(cell);
            }
            mapping.put(CELL_KEY_URL, link);
            mapping.put(CELL_KEY_CLASS, cell.getType());
            mapping.put(CELL_KEY_ID, cell.getId());
            mapping.put(CELL_KEY_VALUE, cell.getField());
        }
        JSONObject ret = new JSONObject(mapping);
        return ret;
    }
}

Refactor json cell formatting into own class


/*
 * Copyright 2001-2005 The Apache Software Foundation.
 *
 * 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.apache.jmeter.protocol.http.control.gui;

import junit.framework.TestCase;

import org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase;

/**
 * @version $Revision$ on $Date$
 */
public class TestHttpTestSampleGui extends TestCase {
		private HttpTestSampleGui gui;

		public TestHttpTestSampleGui(String name) {
			super(name);
		}

		public void setUp() {
			gui = new HttpTestSampleGui();
		}

		public void testCloneSampler() throws Exception {
			HTTPSamplerBase sampler = (HTTPSamplerBase) gui.createTestElement();
			sampler.addArgument("param", "value");
			HTTPSamplerBase clonedSampler = (HTTPSamplerBase) sampler.clone();
			clonedSampler.setRunningVersion(true);
			sampler.getArguments().getArgument(0).setValue("new value");
			assertEquals("Sampler didn't clone correctly", "new value", sampler.getArguments().getArgument(0)
					.getValue());
		}
}

Move last of unit test code to test tree


package de.linkvt.bachelor.features.dataranges;

import de.linkvt.bachelor.features.Feature;
import de.linkvt.bachelor.features.FeatureCategory;

import org.semanticweb.owlapi.model.OWLDataProperty;
import org.semanticweb.owlapi.model.OWLDatatype;
import org.semanticweb.owlapi.model.OWLDatatypeRestriction;
import org.semanticweb.owlapi.model.OWLFacetRestriction;
import org.semanticweb.owlapi.model.OWLLiteral;
import org.semanticweb.owlapi.vocab.OWLFacet;
import org.springframework.stereotype.Component;

@Component
public class OwlDatatypeRestrictionFeature extends Feature {
  @Override
  public void addToOntology() {
    OWLDatatype datatype = factory.getOWLDatatype(":DatatypeRestrictionDatatype", pm);

    OWLFacetRestriction fr1 = factory.getOWLFacetRestriction(OWLFacet.MIN_LENGTH, 10);
    OWLLiteral patternLiteral = factory.getOWLLiteral("DatatypeRestrictionLiteral");
    OWLFacetRestriction fr2 = factory.getOWLFacetRestriction(OWLFacet.PATTERN, patternLiteral);

    OWLDatatypeRestriction restriction = factory.getOWLDatatypeRestriction(datatype, fr1, fr2);

    OWLDataProperty property = factory.getOWLDataProperty(":datatypeRestrictionProperty", pm);
    addToGenericDomainAndNewRange(property, restriction);
  }

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

  @Override
  public String getToken() {
    return "restrictiondata";
  }

  @Override
  public FeatureCategory getCategory() {
    return FeatureCategory.DATA_RANGES;
  }
}

Add a datatype restriction feature


/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.client.file.policy;

import alluxio.client.block.BlockWorkerInfo;
import alluxio.util.network.NetworkAddressUtils;
import alluxio.wire.WorkerNetAddress;

import com.google.common.base.Objects;
import com.google.common.collect.Lists;

import java.util.Collections;
import java.util.List;

import javax.annotation.concurrent.ThreadSafe;
/**
 * A policy that returns local host first, and if the local worker doesn't have enough availability,
 * it randomly picks a worker from the active workers list for each block write.
 * If No worker meets the demands, return local host.
 */
@ThreadSafe
public class LocalFirstWithoutEvictionPolicy implements FileWriteLocationPolicy {
  private String mLocalHostName;
  /**
   * Constructs a {@link LocalFirstWithoutEvictionPolicy}.
   */
  public LocalFirstWithoutEvictionPolicy() {
    mLocalHostName = NetworkAddressUtils.getLocalHostName();
  }

  @Override
  public WorkerNetAddress getWorkerForNextBlock(Iterable<BlockWorkerInfo> workerInfoList,
      long blockSizeBytes) {
    // try the local host first
    WorkerNetAddress localWorkerNetAddress = null;
    for (BlockWorkerInfo workerInfo : workerInfoList) {
      if (workerInfo.getNetAddress().getHost().equals(mLocalHostName)) {
        localWorkerNetAddress = workerInfo.getNetAddress();
        if (workerInfo.getAvailableBytes() >= blockSizeBytes) {
          return localWorkerNetAddress;
        }
      }
    }

    // otherwise randomly pick a worker that has enough availability
    List<BlockWorkerInfo> shuffledWorkers = Lists.newArrayList(workerInfoList);
    Collections.shuffle(shuffledWorkers);
    for (BlockWorkerInfo workerInfo : shuffledWorkers) {
      if (workerInfo.getAvailableBytes() >= blockSizeBytes) {
        return workerInfo.getNetAddress();
      }
    }
    return localWorkerNetAddress;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (!(o instanceof LocalFirstWithoutEvictionPolicy)) {
      return false;
    }
    LocalFirstWithoutEvictionPolicy that = (LocalFirstWithoutEvictionPolicy) o;
    return Objects.equal(mLocalHostName, that.mLocalHostName);
  }

  @Override
  public int hashCode() {
    return Objects.hashCode(mLocalHostName);
  }

  @Override
  public String toString() {
    return Objects.toStringHelper(this)
        .add("localHostName", mLocalHostName)
        .toString();
  }
}

Add a LocalFirstPolicy that without evict action


/*
@VaadinApache2LicenseForJavaFiles@
 */
package com.vaadin.terminal.gwt.client.ui;

import java.util.ArrayList;
import java.util.Collection;

import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.terminal.gwt.client.VPaintableMap;
import com.vaadin.terminal.gwt.client.VPaintableWidget;
import com.vaadin.terminal.gwt.client.VPaintableWidgetContainer;

public abstract class VAbstractPaintableWidgetContainer extends
        VAbstractPaintableWidget implements VPaintableWidgetContainer {

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

    public Collection<VPaintableWidget> getChildren() {
        Collection<VPaintableWidget> children = new ArrayList<VPaintableWidget>();

        addDescendantPaintables(getWidgetForPaintable(), children,
                VPaintableMap.get(getConnection()));

        return children;
    }

    private static void addDescendantPaintables(Widget widget,
            Collection<VPaintableWidget> paintables, VPaintableMap paintableMap) {
        // FIXME: Store hierarchy instead of doing lookup every time

        if (widget instanceof HasWidgets) {
            for (Widget child : (HasWidgets) widget) {
                VPaintableWidget paintable = paintableMap.getPaintable(child);
                if (paintable != null) {
                    // If child is a paintable, add it to the collection
                    paintables.add(paintable);
                } else {
                    // Else keep looking for paintables inside the child widget
                    addDescendantPaintables(child, paintables, paintableMap);
                }
            }
        }
    }

}

Fix file that was accidentally emptied in previous commit


package org.gnieh.logback;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

public class TestPercentEscaping {

    static Logger logger = LoggerFactory.getLogger(TestPercentEscaping.class);

    public static void main(String[] args) {
        MDC.put(SystemdJournal.MESSAGE_ID, "we get away with %s, since it uses the null terminator arg");
        logger.info("fine");
        MDC.put(SystemdJournal.MESSAGE_ID, "we get away with %i as well, and it converts to 0");
        logger.info("fine");

        // Everything below will crash unless % is escaped (% -> %%)

        MDC.put(SystemdJournal.MESSAGE_ID, "this %s %s crashes since there's no 2nd subsequent arg");
        logger.info("boom");

        MDC.put(SystemdJournal.MESSAGE_ID, "this %1$ causes the JVM to abort");
        logger.info("boom");
    }

}

Add test to reproduce the % crash


package test;

import static org.junit.Assert.*;

import org.junit.BeforeClass;
import org.junit.Test;

import controller.Logic;
import controller.Parser;
import controller.UserInput;

public class ParserTest {

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {

	}

	@Test
	public void taskTypeTest() { // sample test
		Parser parser = new Parser();
		String test1 = "add go to sleep";
		UserInput input = parser.parse(test1);
		assertTrue(input.isFloat());
		assertFalse(input.isDeadline());
		assertFalse(input.isRepeated());

		String test2 = "add go to sleep by tomorrow";
		input = parser.parse(test2);
		assertTrue(input.isDeadline());
		assertFalse(input.isFloat());

		String test3 = "add go to sleep by 11 Oct";
		input = parser.parse(test3);
		assertTrue(input.isDeadline());
		assertFalse(input.isFloat());
	}

}

Add a unit test for Parser


/**
 * @file TestFormat.java
 * @author Valery Samovich
 * @version 1
 * @date 2015/02/06
 */

package com.samovich.basics.fundamentals.numbers;

import java.util.Calendar;

public class TestFormat {

    public static void main(String[] args) {

        // "n" A new line character appropriate to the platform running
        // the application. You should always use %n, rather than \n.

        System.out.println("Integers:");
        long n = 461012;
        // A decimal integer with new line
        System.out.format("%d%n", n);
        // Eight characters in width, with leading zeroes as necessary.
        System.out.format("%08d%n", n);
        System.out.println("");

        System.out.println("Floats:");
        System.out.println("Numbers:");
        double pi = Math.PI;
        // A float
        System.out.format("%f%n", pi);
        // Three places after decimal point.
        System.out.format("%.3f%n", pi);
        System.out.println("");

        System.out.println("Date & Time Conversation:");
        Calendar c = Calendar.getInstance();
        // http://docs.oracle.com/javase/tutorial/java/data/numberformat.html
        System.out.format("%tB %te, %tY%n", c, c, c);
        System.out.format("%tl:%tM %tp%n", c, c, c);
        System.out.format("%tD%n", c);

    }

}

Add Formatting Numeric Print Output example


package com.continuuity.internal.app.scheduler;

import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
*
*/
public class LogPrintingJob implements Job {

  private static final Logger LOG = LoggerFactory.getLogger(LogPrintingJob.class);

  @Override
  public void execute(JobExecutionContext context) throws JobExecutionException {
    try {
      LOG.info("Received Trigger at {}", context.getScheduledFireTime().toString());

      JobDataMap map = context.getMergedJobDataMap();
      String[] keys = map.getKeys();

      Preconditions.checkArgument(keys != null);
      Preconditions.checkArgument(keys.length > 0);
      LOG.info("Number of parameters {}", keys.length);
      for (String key : keys){
        LOG.info("Parameter key: {}, value: {}", key, map.get(key));
      }
    } catch (Throwable e) {
      throw Throwables.propagate(e);
    }
    throw new JobExecutionException("excepion");
  }
}

Add back accidentally deleted file


package flyway.asdi;

import fi.nls.oskari.domain.map.view.View;
import fi.nls.oskari.map.view.ViewService;
import fi.nls.oskari.map.view.ViewServiceIbatisImpl;
import org.flywaydb.core.api.migration.jdbc.JdbcMigration;
import org.json.JSONObject;

import java.sql.Connection;

/**
 * Created by MMLDEV on 16.1.2018.
 */
public class V1_14_0__projection_appsetups implements JdbcMigration {

    // EPSG:3571-3576 (North Pole LAEAs) 3575 already exists
    private static final String[] PROJECTIONS_TO_ADD = new String[] {"EPSG:3571", "EPSG:3572", "EPSG:3573", "EPSG:3574", "EPSG:3576"};

    public void migrate(Connection connection)
            throws Exception {
        ViewService service = new ViewServiceIbatisImpl();
        View defaultView = service.getViewWithConf(service.getDefaultViewId());
        for(String srs : PROJECTIONS_TO_ADD) {
            View view = defaultView.cloneBasicInfo();
            JSONObject opts = view.getMapOptions();
            opts.put("srsName", srs);
            service.addView(view);
        }
    }

}

Add appsetups for new projections


package org.jenkins.tools.test.hook;

import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jenkins.tools.test.model.PomData;

public class AwsJavaSdkHook extends AbstractMultiParentHook {
    private static final Logger LOGGER = Logger.getLogger(AwsJavaSdkHook.class.getName());

    @Override
    protected String getParentFolder() {
        return "aws-java-sdk";
    }

    @Override
    protected String getParentProjectName() {
        return "aws-java-sdk-parent";
    }

    @Override
    public boolean check(Map<String, Object> info) {
        return isAwsJavaSdkPlugin(info);
    }

    private boolean isAwsJavaSdkPlugin(Map<String, Object> moreInfo) {
        PomData data = (PomData) moreInfo.get("pomData");
        return isAwsJavaSdkPlugin(data);
    }

    private boolean isAwsJavaSdkPlugin(PomData data) {
        if (data.parent != null) {
            return data.parent.artifactId.equalsIgnoreCase("aws-java-sdk-parent");
        } else {
            LOGGER.log(Level.WARNING, "Artifact {0} has no parent POM, likely it was incrementalified (JEP-305). " +
                    "Will guess the plugin by artifact ID. FTR JENKINS-55169", data.artifactId);
            return data.artifactId.contains("aws-java-sdk");
        }
    }
}

Add hook to support aws-java-sdk multimodule project