/*
 * ====================================================================
 * 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */

package org.apache.http.client.methods;

import java.net.URI;

import org.apache.http.annotation.NotThreadSafe;

/**
 * HTTP PATCH method.
 *

 * The HTTP PATCH method is defined in RF5789:
 The PATCH
 * method requests that a set of changes described in the request entity be
 * applied to the resource identified by the Request- URI. Differs from the PUT
 * method in the way the server processes the enclosed entity to modify the
 * resource identified by the Request-URI. In a PUT request, the enclosed entity
 * origin server, and the client is requesting that the stored version be
 * replaced. With PATCH, however, the enclosed entity contains a set of
 * instructions describing how a resource currently residing on the origin
 * server should be modified to produce a new version.

 *

 *
 * @since 4.2
 */
@NotThreadSafe
public class HttpPatch extends HttpEntityEnclosingRequestBase {

    public final static String METHOD_NAME = "PATCH";

    public HttpPatch() {
        super();
    }

    public HttpPatch(final URI uri) {
        super();
        setURI(uri);
    }

    public HttpPatch(final String uri) {
        super();
        setURI(URI.create(uri));
    }

    @Override
    public String getMethod() {
        return METHOD_NAME;
    }

}

PATCH HTTP method Contributed by Alin Vasile <alinachegalati at yahoo dot com>


package com.jetbrains.python.debugger;

import com.intellij.xdebugger.XSourcePosition;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public interface PyPositionConverter {

  @NotNull
  PySourcePosition create(@NotNull final String file, final int line);

  @NotNull
  PySourcePosition convertToPython(@NotNull final XSourcePosition position);

  @Nullable
  XSourcePosition convertFromPython(@NotNull final PySourcePosition position);

  @Nullable
  default XSourcePosition convertFromPython(@NotNull final PySourcePosition position, String frameName) {
    return convertFromPython(position);
  }

  PySignature convertSignature(PySignature signature);
}

package com.jetbrains.python.debugger;

import com.intellij.xdebugger.XSourcePosition;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public interface PyPositionConverter {

  @NotNull
  PySourcePosition create(@NotNull final String file, final int line);

  @NotNull
  PySourcePosition convertToPython(@NotNull final XSourcePosition position);

  @Nullable
  default XSourcePosition convertFromPython(@NotNull final PySourcePosition position) {
    return null;
  }

  @Nullable
  default XSourcePosition convertFromPython(@NotNull final PySourcePosition position, String frameName) {
    return convertFromPython(position);
  }

  PySignature convertSignature(PySignature signature);
}

Add default method for compatibility


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

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

Add some tests to problem 22


/*
 * 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 SF 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.sling.metrics.impl;

import javax.annotation.Nonnull;

import org.apache.sling.metrics.api.MetricsUtil;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.commons.AdviceAdapter;

/**
 * Adapts method calls wrapping the byte code of the method with calls to a meter.
 */
public class APITimerCounterAdapter extends AdviceAdapter {

    private static final String METRICS_UTIL_CL = MetricsUtil.class.getName().replace('.', '/');
    private static final String METRICS_UTIL_DESC = "(Ljava/lang/String;)V;";
    private String timerName;

    public APITimerCounterAdapter(@Nonnull MethodVisitor mv, int access, @Nonnull String name, @Nonnull String descriptor, @Nonnull String timerName) {
        super(Opcodes.ASM4, mv, access, name, descriptor);
        this.timerName = timerName;
    }

    @Override
    protected void onMethodEnter() {
        mv.visitLdcInsn(timerName);
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, METRICS_UTIL_CL, "startAPICount", METRICS_UTIL_DESC, false);
    }

    @Override
    protected void onMethodExit(int opcode) {
        mv.visitLdcInsn(timerName);
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, METRICS_UTIL_CL, "endAPICount", METRICS_UTIL_DESC, false);
    }

}

Add APITimerCounter which only counts the first call within a thread to an API


import org.junit.*;

public class HashMapTest {

  HashMap hm;

  @Before
  public void init() {
    hm = new HashMap(7);
  }

  @Test
  public void testInsertSingleKey() {

  }

  @Test
  public void testInsertDuplicateKey() {

  }

  @Test
  public void testFindExistingKey() {

  }

  @Test
  public void testInsertInvalidKey() {

  }

}

Add skeleton test cases for hash map.


package com.anderson.hummingbird.server;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class ServerConfig {

	public class FaviconConfiguration extends WebMvcConfigurerAdapter{

		@Override
		public void addResourceHandlers(ResourceHandlerRegistry registry){
			registry.setOrder(Integer.MIN_VALUE);
			registry.addResourceHandler("/favicon.ico").addResourceLocations("/");
			registry.addResourceHandler("/static/**").addResourceLocations("/");
		}
	}
}

Configure static resource handler in springboot


/*******************************************************************************
 * Copyright (c) 2013, Salesforce.com, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *     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.
 *     Neither the name of Salesforce.com nor the names of its contributors may
 *     be used to endorse or promote products derived from this software without
 *     specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/
package com.salesforce.phoenix.exception;

import java.sql.SQLSyntaxErrorException;

import org.antlr.runtime.RecognitionException;

import com.salesforce.phoenix.parse.PhoenixSQLParser;

public class PhoenixParserException extends SQLSyntaxErrorException {
    private static final long serialVersionUID = 1L;
    private static SQLExceptionCode code = SQLExceptionCode.PARSER_ERROR;

    public PhoenixParserException(RecognitionException e, PhoenixSQLParser parser) {
        super(new SQLExceptionInfo.Builder(SQLExceptionCode.PARSER_ERROR).setRootCause(e)
                .setMessage(getParserMessage(e, parser)).build().toString(),
                code.getSQLState(), code.getErrorCode(), e);
    }

    public static String getParserMessage(RecognitionException e, PhoenixSQLParser parser) {
        // Change this method to generate our own message.
        return parser.getErrorMessage(e,parser.getTokenNames());
    }
}

Refactor the code so we can set our own message for parser error.


package at.ac.tuwien.inso.validator_tests;

import org.junit.Test;

import at.ac.tuwien.inso.exception.ValidationException;
import at.ac.tuwien.inso.service.validator.UisUserValidator;

public class UisUserValidatorTests {

    private final UisUserValidator validator = new UisUserValidator();

    @Test
    public void testEmailValidator() {
        validator.validateEmail("uis@tuwien.ac.at");
    }

    @Test (expected = ValidationException.class)
    public void testEmailInvalid() {
        validator.validateEmail("uis");
    }

    /**
     * Local email (for intranets) should not be allowed
     */
    @Test (expected = ValidationException.class)
    public void testEmailLocal() {
        validator.validateEmail("uis@tuwien");
    }

    @Test (expected = ValidationException.class)
    public void testEmailNoLocalPart() {
        validator.validateEmail("@tuwien.at");
    }

    @Test (expected = ValidationException.class)
    public void testEmailValidatorNull() {
        validator.validateEmail(null);
    }

    @Test (expected = ValidationException.class)
    public void testEmailValidatorEmpty() {
        validator.validateEmail("");
    }

    /**
     * German umlauts are valid in emails
     */
    @Test
    public void testEmailValidatorUmlauts() {
        validator.validateEmail("björn@tüdlü.at");
    }
}

Add tests for email validation


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

class MedianHeap {

    public PriorityQueue<Integer> minHeap;
    public PriorityQueue<Integer> maxHeap;

    public MedianHeap(int capacity) {
        this.minHeap = new PriorityQueue(capacity);
        this.maxHeap = new PriorityQueue(capacity, Collections.reverseOrder());
    }

    public void add(int num) {
        if (isEmpty()) {
            this.minHeap.add(num);
        } else if (num >= median()) {
            this.minHeap.add(num);
        } else {
            this.maxHeap.add(num);
        }
        rebalanceHeaps();
    }

    public double median() {
        if (minHeap.size() > maxHeap.size()) {
            return minHeap.peek();
        } else if (minHeap.size() < maxHeap.size()) {
            return maxHeap.peek();
        } else {
            return ((minHeap.peek() + maxHeap.peek()) / 2.0);
        }
    }

    private boolean isEmpty() {
        return (minHeap.size() == 0 && maxHeap.size() == 0);
    }

    private void rebalanceHeaps() {
        if (minHeap.size() - maxHeap.size() > 1) {
            maxHeap.add(minHeap.poll());
        }
        if (maxHeap.size() - minHeap.size() > 1) {
            minHeap.add(maxHeap.poll());
        }
    }

}

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int capacity = in.nextInt();
        int[] list = new int[capacity];
        MedianHeap medianHeap = new MedianHeap(capacity);

        for(int i = 0; i < capacity; i++){
            list[i] = in.nextInt();
            medianHeap.add(list[i]);
            //System.out.println("minHeap: " + medianHeap.minHeap.toString());
            //System.out.println("maxHeap: " + medianHeap.maxHeap.toString());
            System.out.printf("%.1f\n", medianHeap.median());
        }
    }
}

Solve Median w/ two heaps


package npe;

public class InSwitchStatement {

	int f(int x) {
		String s = null;
		switch (x) {
		case 0:
			s = "zero";
			break;
		case 1:
			s = "one";
			break;
		case 2:
			// impossible
			break;
		default:
			s = "unknown";
		}
		return s.hashCode();
	}

}

Make sure we flag this at the right location


public class Solution {
    public static int firstOccurrence(int[] nums, int k) {
        int first = 0;
        int last = nums.length - 1;
        while (first < last - 1) {
            int med = first + (last - first) / 2;
            if (nums[med] < k) {
                first = med;
            } else {
                last = med;
            }
        }
        if (nums[first] == k) return first;
        else if (nums[last] == k) return last;
        else return -1;
    }

    public static void main(String[] args) {
        int[] nums = { 1, 1, 1, 2, 2, 2, 2, 3, 4, 5, 6, 7, 8, 8, 10, 10, 11, 12, 16 };
        System.out.print("Array: [");
        for (int i = 0; i < nums.length; i++) {
            System.out.print(nums[i]);
            if (i != nums.length - 1) System.out.print(", ");
        }
        System.out.println("]");
        for (int k = 0; k < 20; k++) {
            int first = firstOccurrence(nums, k);
            System.out.println(k + " first found at index " + first);
        }
    }
}

Write solution to question 1 in java


/*
 * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
module org.opendaylight.yangtools.yang.parser.spi {
    exports org.opendaylight.yangtools.yang.parser.spi;
    exports org.opendaylight.yangtools.yang.parser.spi.meta;
    exports org.opendaylight.yangtools.yang.parser.spi.source;
    exports org.opendaylight.yangtools.yang.parser.spi.validation;

    requires transitive org.opendaylight.yangtools.yang.model.api;
    requires com.google.common;
    requires org.opendaylight.yangtools.yang.common;
    requires org.slf4j;

    // Annotations
    requires static com.github.spotbugs.annotations;
    requires static org.eclipse.jdt.annotation;
}

/*
 * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
module org.opendaylight.yangtools.yang.parser.spi {
    exports org.opendaylight.yangtools.yang.parser.spi;
    exports org.opendaylight.yangtools.yang.parser.spi.meta;
    exports org.opendaylight.yangtools.yang.parser.spi.source;
    exports org.opendaylight.yangtools.yang.parser.spi.validation;

    requires transitive org.opendaylight.yangtools.yang.model.api;
    requires com.google.common;
    requires org.opendaylight.yangtools.concepts;
    requires org.opendaylight.yangtools.yang.common;
    requires org.slf4j;

    // Annotations
    requires static com.github.spotbugs.annotations;
    requires static org.eclipse.jdt.annotation;
}

Add concepts to parser-spi's requires


package com.auth0;

import static java.util.Collections.emptyEnumeration;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.junit.Test;

public class Auth0ServletCallbackTest {

    @Test(expected = IllegalArgumentException.class)
    public void failOnMissingInitParameters() throws ServletException {
        final Auth0ServletCallback cb = new Auth0ServletCallback();
        cb.init(mock(ServletConfig.class));
    }

    @Test(expected = IllegalArgumentException.class)
    public void failOnMissingServletContextParameters() throws ServletException {
        final Auth0ServletCallback cb = new Auth0ServletCallback();
        final ServletConfig config = mock(ServletConfig.class);
        when(config.getInitParameter(eq("auth0.redirect_on_success"))).thenReturn("");
        when(config.getInitParameter(eq("auth0.redirect_on_error"))).thenReturn("");
        final ServletContext ctx = mock(ServletContext.class);
        when(ctx.getInitParameterNames()).thenReturn(emptyEnumeration());
        when(config.getServletContext()).thenReturn(ctx);
        cb.init(config);
    }
}

Add rudimentary tests for Auth0ServletCallback.init(ServletConfig): - failOnMissingInitParameters: passes - failOnMissingServletContextParameters: fails


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

import static play.data.Form.form;

import java.util.List;

import play.data.Form;
import play.data.validation.Constraints.Email;
import play.data.validation.Constraints.Required;
import play.data.validation.ValidationError;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

public class FormTest {

  @Test
  public void testFormValidation() {
    Form<Registration> form = form(Registration.class).bind(
        ImmutableMap.of("email", "test@benmccann.com", "password1", "changeme", "password2", "alskjfd"));
    Assert.assertTrue(form.hasErrors());
    Assert.assertTrue(form.errors().containsKey("password"));
  }

  public static class Registration {
    @Required @Email public String email;
    @Required public String password1;
    @Required public String password2;

    public String getEmail() {
      return email;
    }

    public void setEmail(String email) {
      this.email = email;
    }

    public String getPassword1() {
      return password1;
    }

    public void setPassword1(String password1) {
      this.password1 = password1;
    }

    public String getPassword2() {
      return password2;
    }

    public void setPassword2(String password2) {
      this.password2 = password2;
    }

    public List<ValidationError> validate() {
      if (!password1.equals(password2)) {
        return ImmutableList.of(new ValidationError("password", "Passwords do not match.", ImmutableList.of()));
      }
      return null;
    }
  }

}

Add a test for form validation


package pl.komunikator.komunikator;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

import pl.komunikator.komunikator.entity.User;

/**
 * Created by adrian on 19.04.2017.
 */

public class SearchedUsersAdapter extends RecyclerView.Adapter<SearchedUsersAdapter.MyViewHolder> {

    private List<User> userList;

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView name, email;
        public ImageView photo;

        public MyViewHolder(View view) {
            super(view);

        }
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return null;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

    }

    @Override
    public int getItemCount() {
        return 0;
    }
}

Create Adapter class and add boilerplate code


package tests.eu.qualimaster.common;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import eu.qualimaster.common.hardware.MultiHardwareThreadsExecutor;

/**
 * Test for multiple hardware threads.
 * @author Cui Qin
 *
 */
public class MultiHardwareThreadsExecutorTest {
    private static final Logger LOGGER = Logger.getLogger(MultiHardwareThreadsExecutorTest.class);
    /**
     * Define a server.
     * @author Cui Qin
     *
     */
    public static class Server implements Runnable {
        private int port;
        /**
         * Creates a server with the given port.
         * @param port the port number
         */
        public Server(int port) {
            this.port = port;
            try {
                @SuppressWarnings({ "unused", "resource" })
                ServerSocket serverSocket = new ServerSocket(port);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void run() {
            //do nothing
        }

        /**
         * Starts the server.
         */
        public void start() {
            new Thread(this).start();
            LOGGER.info("Server thread started with the port: " + port);
        }

    }
    /**
     * A client thread handler.
     * @author Cui Qin
     *
     */
    public static class ClientThreadHandler implements Runnable {
        /**
         * Creates a client thread handler.
         * @param ip the ip
         * @param port the port
         */
        public ClientThreadHandler(String ip, int port) {
            try {
                @SuppressWarnings({ "unused", "resource" })
                Socket socket = new Socket(ip, port);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void run() {
            //do nothing
        }

    }
    /**
     * Performs the test.
     * @param args ignored
     */
    public static void main(String[] args) {
        //Start the servers
        Server server1 = new Server(8000);
        server1.start();

        Server server2 = new Server(8001);
        server2.start();

        List<Integer> ports = new ArrayList<Integer>();
        ports.add(8000);
        ports.add(8001);
        Map<String, List<Integer>> servers = new HashMap<String, List<Integer>>();
        servers.put("localhost", ports);

        MultiHardwareThreadsExecutor executor = new MultiHardwareThreadsExecutor(servers
                , ClientThreadHandler.class, ports.size());
        executor.createMultiThreads();
    }

}

Test for multiple thread executor


package leetcode;

/**
 * https://leetcode.com/problems/game-of-life/
 */
public class Problem289 {
    public void gameOfLife(int[][] board) {
        // TODO
    }

    public static void main(String[] args) {
        Problem289 prob = new Problem289();
    }
}

Add skeleton for problem 289


package heufybot.modules;

import heufybot.utils.URLUtils;

import java.util.List;

public class Shorten extends Module
{
	public Shorten()
	{
		this.authType = Module.AuthType.Anyone;
		this.trigger = "^" + commandPrefix + "(shorten)($| .*)";
	}

	@Override
	public void processEvent(String source, String message, String triggerUser, List<String> params)
	{
		if (params.size() == 1)
		{
			bot.getIRC().cmdPRIVMSG(source, "Shorten what?");
		}
		else
		{
			String shortenedURL = URLUtils.shortenURL(params.get(1));
			if(shortenedURL == null)
			{
				bot.getIRC().cmdPRIVMSG(source, "[Shorten] Error: URL could not be shortned");
			}
			else
			{
				bot.getIRC().cmdPRIVMSG(source, "[Shorten] " + shortenedURL);
			}
		}
	}

	public String getHelp()
	{
		return "Commands: " + commandPrefix + "shorten <url> | Shortens the given URL using Googl.";
	}

	@Override
	public void onLoad()
	{
	}

	@Override
	public void onUnload()
	{
	}
}

Add a URL shortening module


package org.kedos.print;

import java.util.Arrays;

/**
 * Created by shaked on 09/11/2015.
 */
public class PrintUtils {

    /**
     * Prints the given 2D array.
     *
     * @param array 2D array to pretty print.
     */
    public static void print2DArray(int[][] array) {
        for (int i = 0; i < array.length; i++) {
            System.out.println(Arrays.toString(array[i]));
        }
    }

    /**
     * Prints the given 2D array.
     *
     * @param array 2D array to pretty print.
     */
    public static void print2DArray(long[][] array) {
        for (int i = 0; i < array.length; i++) {
            System.out.println(Arrays.toString(array[i]));
        }
    }

    /**
     * Prints the given 2D array.
     *
     * @param array 2D array to pretty print.
     */
    public static void print2DArray(float[][] array) {
        for (int i = 0; i < array.length; i++) {
            System.out.println(Arrays.toString(array[i]));
        }
    }

    /**
     * Prints the given 2D array.
     *
     * @param array 2D array to pretty print.
     */
    public static void print2DArray(double[][] array) {
        for (int i = 0; i < array.length; i++) {
            System.out.println(Arrays.toString(array[i]));
        }
    }

    /**
     * Prints the given 2D array.
     *
     * @param array 2D array to pretty print.
     */
    public static void print2DArray(boolean[][] array) {
        print2DArray(array, false);
    }

    /**
     * Prints the given 2D array.
     *
     * @param array 2D array to pretty print.
     * @param useOnesAndZeroes if true, will use 1\0 instead of @true\@false.
     */
    public static void print2DArray(boolean[][] array, boolean useOnesAndZeroes) {
        if (useOnesAndZeroes) {
            for (int i = 0; i < array.length; i++) {
                System.out.print("[");
                for (int j = 0; j < array[i].length; j++) {
                    System.out.print(array[i][j] ? "1" : "0");
                    if (j != array[i].length - 1) {
                        System.out.print(", ");
                    }
                }
                System.out.println("]");
            }
        } else {
            for (int i = 0; i < array.length; i++) {
                System.out.println(Arrays.toString(array[i]));
            }
        }
    }

}

Add new class that helpes pretty print 2D arrays.


/*
 * Copyright 2017 haeun kim
 *
 * 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 algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-09-18
 * Site       : https://www.acmicpc.net/problem/11718
 */
public class Boj11718 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        while (true){
            String input = br.readLine();
            if(input != null){
                System.out.println(input);
            }else{
                break;
            }
        }

    }

}

Solve No.11718 from Baekjoon Online Judge


// Copyright 2013 Daniel de Kok
//
// 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 eu.danieldk.dictomaton.levenshtein;

import com.carrotsearch.junitbenchmarks.AbstractBenchmark;
import eu.danieldk.dictomaton.DictionaryBuilderException;
import eu.danieldk.dictomaton.Util;
import eu.danieldk.dictomaton.categories.Benchmarks;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import java.io.IOException;
import java.util.Iterator;
import java.util.SortedSet;

@Category(Benchmarks.class)
public class LevenshteinAutomatonBenchmark extends AbstractBenchmark {
    private static SortedSet<String> d_words;

    @BeforeClass
    public static void initializeExpensive() throws DictionaryBuilderException, IOException {
        d_words = Util.loadWordList("eu/danieldk/dictomaton/web2-1");
    }

    @Test
    public void distance1Benchmark() {
        int i = 0;
        Iterator<String> iter = d_words.iterator();
        while (i++ < 10000 && iter.hasNext()) {
            String word = iter.next();
            Assert.assertNotNull(new LevenshteinAutomaton(word, 1));
        }
    }

    @Test
    public void distance2Benchmark() {
        int i = 0;
        Iterator<String> iter = d_words.iterator();
        while (i++ < 10000 && iter.hasNext()) {
            String word = iter.next();
            Assert.assertNotNull(new LevenshteinAutomaton(word, 2));
        }
    }
}

Add a benchmark for Levenshtein automaton construction.


package com.jose.feelagaininecuador.alert_dialogs;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.os.Bundle;

/**
 * Created by Jose on 11/25/2015.
 */
public class AlertDialogFragment extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Context context = getActivity();
        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setTitle("Lo siento!")
                .setMessage("Hubo un error, por favor intentar de nuevo.")
                .setPositiveButton("OK", null);

        AlertDialog dialog = builder.create();
        return dialog;
    }
}

Add alert dialog to handle errors


package com.nincraft.ninbot.components.channel;

import com.nincraft.ninbot.NinbotTest;
import com.nincraft.ninbot.components.common.Emojis;
import com.nincraft.ninbot.components.config.component.ComponentService;
import lombok.val;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.SelfUser;
import net.dv8tion.jda.api.entities.VoiceChannel;
import net.dv8tion.jda.api.events.guild.voice.GuildVoiceJoinEvent;
import net.dv8tion.jda.api.requests.RestAction;
import net.dv8tion.jda.api.requests.restaction.ChannelAction;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;

import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;

public class TempVoiceChannelManagerTest extends NinbotTest {

    @Mock
    TempVoiceChannelRepository tempVoiceChannelRepository;

    @Mock
    ComponentService componentService;

    @InjectMocks
    TempVoiceChannelManager tempVoiceChannelManager;

    @Test
    public void onGuildVoiceJoin() {
        val guild = Mockito.mock(Guild.class);
        val joinEvent = Mockito.mock(GuildVoiceJoinEvent.class);
        val jda = Mockito.mock(JDA.class);
        val selfUser = Mockito.mock(SelfUser.class);
        val member = Mockito.mock(Member.class);
        val voiceChannelJoined = Mockito.mock(VoiceChannel.class);
        val restAction = Mockito.mock(ChannelAction.class);

        when(joinEvent.getGuild()).thenReturn(guild);
        when(guild.getId()).thenReturn("1");
        when(guild.getJDA()).thenReturn(jda);
        when(jda.getSelfUser()).thenReturn(selfUser);
        when(guild.getMember(selfUser)).thenReturn(member);
        when(joinEvent.getChannelJoined()).thenReturn(voiceChannelJoined);
        when(joinEvent.getMember()).thenReturn(member);
        when(voiceChannelJoined.getName()).thenReturn(Emojis.PLUS + " wot");
        when(member.hasPermission(any(Permission.class))).thenReturn(true);
        when(member.getEffectiveName()).thenReturn("Nincodedo");
        when(guild.createVoiceChannel(anyString())).thenReturn(restAction);

        tempVoiceChannelManager.onGuildVoiceJoin(joinEvent);

        verify(guild, times(1)).createVoiceChannel("Nincodedo's wot");
    }
}

Add temp voice channel test


package leetcode.gas_station;

public class Solution {
	public int canCompleteCircuit(int[] gas, int[] cost) {
		if (gas.length == 0)
			return -1;
		int N = gas.length;
		int min = 0, mini = 0;
		int cur = 0;
		for(int i = 0; i < N; i++){
			if(cur < min){
				min = cur;
				mini = i;
			}
			int remain = cur + gas[i] - cost[i];
			cur = remain;
		}
		if(cur < 0) return -1;
		return mini;
	}

	public static void main(String[] args) {
		int[] gas = new int[10000]; // 3897~10000, 1~3896
		int[] cost = new int[10000]; //3311~10000, 1~3310
		for(int i = 0; i < 10000; i++){
			gas[i] = (3896 + i) % 10000 + 1;
			cost[i] = (3310 + i) % 10000 + 1;
		}
		System.err.println(new Solution().canCompleteCircuit(gas, cost));
		System.err.println(new Solution().canCompleteCircuit(new int[]{1, 2}, new int[]{2, 1}));
	}
}

Add java solution for 134. Gas Station


/*
 * This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later.
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla Foundation, either version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Mozilla Public License for more details.
 *
 * You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/
 */

package org.openlmis.report.mapper;

import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.ResultSetType;
import org.openlmis.report.builder.FacilityReportQueryBuilder;
import org.openlmis.report.builder.RepairManagementReportQueryBuilder;
import org.openlmis.report.model.params.FacilityReportParam;
import org.openlmis.report.model.params.RepairManagementEquipmentListParam;
import org.openlmis.report.model.params.RepairManagementReportParam;
import org.openlmis.report.model.report.FacilityReport;
import org.openlmis.report.model.report.RepairManagementEquipmentList;
import org.openlmis.report.model.report.RepairManagementReport;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface RepairManagementReportMapper {

    @SelectProvider(type=RepairManagementReportQueryBuilder.class, method="SelectEquipmentCountByStatusEnergySql")
    @Options(resultSetType = ResultSetType.SCROLL_SENSITIVE, fetchSize=10,timeout=0,useCache=true,flushCache=true)
    List<RepairManagementReport> SelectEquipmentCountByStatusEnergy(
            @Param("filterCriteria") RepairManagementReportParam filterCriteria,
            @Param("userId") Long userId
    );

    @SelectProvider(type=RepairManagementReportQueryBuilder.class, method="RepairManagementEquipmentListSql")
    @Options(resultSetType = ResultSetType.SCROLL_SENSITIVE, fetchSize=10,timeout=0,useCache=true,flushCache=true)
    List<RepairManagementEquipmentList> RepairManagementEquipmentList(
            @Param("filterCriteria") RepairManagementEquipmentListParam filterCriteria,
            @Param("userId") Long userId
    );

}

Add Repair Management Repair Mapper


package info.u_team.u_team_core.intern.command.uteamcore;

import java.util.*;

import com.mojang.brigadier.builder.ArgumentBuilder;

import net.minecraft.command.*;
import net.minecraft.command.arguments.ResourceLocationArgument;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.biome.provider.BiomeProvider;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.registries.ForgeRegistries;

public class LocateBiomeSubCommand {

	public static ArgumentBuilder<CommandSource, ?> register() {
		return Commands.literal("locatebiome") //
				.requires(source -> source.hasPermissionLevel(2)) //
				.then(Commands.argument("biome", ResourceLocationArgument.resourceLocation()) //
						.suggests((context, builder) -> ISuggestionProvider.suggest(ForgeRegistries.BIOMES.getKeys().stream().map(ResourceLocation::toString), builder)) //
						.executes(context -> locateBiome(context.getSource(), context.getArgument("biome", ResourceLocation.class))));
	}

	private static int locateBiome(CommandSource source, ResourceLocation biome) {
		final ServerWorld world = source.getWorld();
		final BiomeProvider biomeProvider = world.getChunkProvider().getChunkGenerator().getBiomeProvider();
		final Random random = new Random(world.getSeed());

		final BlockPos pos = biomeProvider.func_225531_a_(0, world.getSeaLevel(), 0, 256, Arrays.asList(ForgeRegistries.BIOMES.getValue(biome)), random);

		return 0;
	}

}

Add basic location biome command


package devopsdistilled.operp.client.abstracts;

import devopsdistilled.operp.server.data.entity.Entiti;

public abstract class AbstractEditEntityPaneModel<E extends Entiti, PMO extends EditEntityPaneModelObserver<E>>
		extends AbstractPaneModel<PMO> implements EditEntityPaneModel<E, PMO> {

	protected E entity;

	@Override
	public abstract String getTitle();

	@Override
	public void setEntity(E entity) {
		this.entity = entity;
		for (PMO observer : observers) {
			observer.updateEntity(entity);
		}
	}

	@Override
	public E getEntity() {
		return entity;
	}

	@Override
	public void update() {
		super.update();
		setEntity(getEntity());
	}
}

Add abstract Impl for EditEntityPaneModel


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

import java.util.Collection;

import com.google.common.collect.Lists;
import org.mockito.Mockito;
import org.testng.annotations.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.times;

import com.datastax.driver.core.policies.ConstantSpeculativeExecutionPolicy;
import com.datastax.driver.core.utils.CassandraVersion;

/**
 * Test that needs a real CCM cluster (as opposed to SCassandra for other specex tests), because
 * it uses a protocol v3 feature.
 */
public class SpeculativeExecutionIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {

    TimestampGenerator timestampGenerator;

    @Override
    protected Collection<String> getTableDefinitions() {
        return Lists.newArrayList("create table foo(k int primary key, v int)");
    }

    @Override
    protected Cluster.Builder configure(Cluster.Builder builder) {
        timestampGenerator = Mockito.spy(ServerSideTimestampGenerator.INSTANCE);
        return builder
            .withTimestampGenerator(timestampGenerator)
            .withQueryOptions(new QueryOptions().setDefaultIdempotence(true))
                // Set an artificially low timeout to force speculative execution
            .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(1, 2));
    }

    /**
     * Validates that if a query gets speculatively re-executed, the second execution uses the same default timestamp.
     *
     * @test_category tracing
     * @jira_ticket JAVA-724
     * @expected_result timestamp generator invoked only once for a query that caused two executions.
     */
    @Test(groups = "short")
    @CassandraVersion(major = 2.1)
    public void should_use_same_default_timestamp_for_all_executions() {
        Metrics.Errors errors = cluster.getMetrics().getErrorMetrics();

        Mockito.reset(timestampGenerator);
        long execStartCount = errors.getSpeculativeExecutions().getCount();

        BatchStatement batch = new BatchStatement();
        for (int k = 0; k < 1000; k++) {
            batch.add(new SimpleStatement("insert into foo(k,v) values (?,1)", k));
        }
        session.execute(batch);

        assertThat(errors.getSpeculativeExecutions().getCount()).isEqualTo(execStartCount + 1);
        Mockito.verify(timestampGenerator, times(1)).next();
    }
}

Test that speculative executions use the same timestamp (JAVA-724).


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

package org.onosproject.vtnrsc.virtualport;

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

import org.junit.Test;
import org.onlab.packet.IpAddress;
import org.onlab.packet.MacAddress;
import org.onosproject.vtnrsc.AllowedAddressPair;

import com.google.common.testing.EqualsTester;

/**
 * Unit tests for AllowedAddressPair class.
 */
public class AllowedAddressPairTest {

    final IpAddress ip1 = IpAddress.valueOf("192.168.0.1");
    final IpAddress ip2 = IpAddress.valueOf("192.168.0.2");
    final MacAddress mac1 = MacAddress.valueOf("fa:16:3e:76:83:88");
    final MacAddress mac2 = MacAddress.valueOf("aa:16:3e:76:83:88");

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

    /**
     * Checks the operation of equals().
     */
    @Test
    public void testEquals() {
        AllowedAddressPair p1 = AllowedAddressPair
                .allowedAddressPair(ip1, mac1);
        AllowedAddressPair p2 = AllowedAddressPair
                .allowedAddressPair(ip1, mac1);
        AllowedAddressPair p3 = AllowedAddressPair
                .allowedAddressPair(ip2, mac2);
        new EqualsTester().addEqualityGroup(p1, p2).addEqualityGroup(p3)
                .testEquals();
    }

    /**
     * Checks the construction of a AllowedAddressPair object.
     */
    @Test
    public void testConstruction() {
        AllowedAddressPair allowedAddressPair = AllowedAddressPair
                .allowedAddressPair(ip1, mac1);
        assertThat(ip1, is(notNullValue()));
        assertThat(ip1, is(allowedAddressPair.ip()));
        assertThat(mac1, is(notNullValue()));
        assertThat(mac1, is(allowedAddressPair.mac()));
    }
}

Add the junit test code of AllowedAddressPair


package leetcode.rotate_image;

public class Solution {
    public void rotate(int[][] matrix) {
        if(matrix == null) return;
        if(matrix.length == 0) return;
        int size = matrix.length;
        for(int i = 0; i < (size + 1) / 2; i++){
        	for(int j = 0; j < size / 2; j++){
        		int tmp;
        		tmp = matrix[i][j];
        		matrix[i][j] = matrix[size - 1 - j][i];
        		matrix[size - 1 - j][i] = matrix[size - 1 - i][size - 1 - j];
        		matrix[size - 1 - i][size - 1 - j] = matrix[j][size - 1 - i];
        		matrix[j][size - 1 - i] = tmp;
        	}
        }
    }

    public static void main(String[] args){
    	final int N = 5;
    	int[][] matrix = new int[N][];
    	for(int i = 0; i < N; i++){
    		matrix[i] = new int[N];
    		for(int j = 0; j < N; j++){
    			matrix[i][j] = i * N + j;
    		}
    	}
    	new Solution().rotate(matrix);
    	for(int i = 0; i < N; i++){
    		for(int j = 0; j < N; j++){
    			System.err.print(matrix[i][j] + ", ");
    		}
    		System.err.println("");
    	}
    }
}

Add java solution for 48. Rotate Image


package org.robolectric;

import static com.google.common.truth.Truth.assertThat;

import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.ParameterizedRobolectricTestRunner.Parameter;
import org.robolectric.ParameterizedRobolectricTestRunner.Parameters;
import org.robolectric.annotation.Config;

/** Tests for the {@link Parameter} annotation */
@RunWith(ParameterizedRobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public final class ParameterizedRobolectricTestRunnerParameterTest {

  @Parameter(value = 0)
  public boolean booleanValue;

  @Parameter(value = 1)
  public int intValue;

  @Parameter(value = 2)
  public String stringValue;

  @Parameter(value = 3)
  public String expected;

  @Test
  public void parameters_shouldHaveValues() {
    assertThat("" + booleanValue + intValue + stringValue).isEqualTo(expected);
  }

  @Parameters(name = "{index}: booleanValue = {0}, intValue = {1}, stringValue = {2}")
  public static Collection<Object[]> parameters() {
    return Arrays.asList(
        new Object[][] {
          {true, 1, "hello", "true1hello"},
          {false, 2, "robo", "false2robo"},
        });
  }
}

Add a test for ParameterizedRobolectricTestRunner's @Parameter


package com.github.changeworld.redis.client.lettuce;

import com.github.changeworld.redis.client.SpringDataRedisClient;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.data.redis.connection.lettuce.DefaultLettucePool;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import redis.embedded.RedisServer;

import java.io.IOException;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

/**
 * @author changeworld
 */
public class SpringDataRedisClientTest {
    private static RedisServer redisServer;

    private static final String FOO = "foo";
    private static final String BAR = "bar";
    private static final String HOST = "localhost";
    private static final int PORT = 6379;

    @BeforeClass
    public static void beforeClass() throws IOException {
        redisServer = new RedisServer(PORT);
        redisServer.start();
    }

    @AfterClass
    public static void afterClass() throws IOException {
        redisServer.stop();
    }

    @Test
    public void shouldSpringDataRedisCanSet() {
        Boolean flag = true;
        try {
            DefaultLettucePool defaultLettucePool = new DefaultLettucePool(HOST, PORT);
            defaultLettucePool.afterPropertiesSet();
            LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(defaultLettucePool);
            lettuceConnectionFactory.afterPropertiesSet();
            lettuceConnectionFactory.setShareNativeConnection(true);
            SpringDataRedisClient client = new SpringDataRedisClient(lettuceConnectionFactory);
            client.set(FOO, BAR);
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
            fail();
        }
        assertTrue(flag);
    }

    @Test
    public void shouldSpringDataRedisCanGetAfterSet() {
        try {
            DefaultLettucePool defaultLettucePool = new DefaultLettucePool(HOST, PORT);
            defaultLettucePool.afterPropertiesSet();
            LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(defaultLettucePool);
            lettuceConnectionFactory.afterPropertiesSet();
            lettuceConnectionFactory.setShareNativeConnection(true);
            SpringDataRedisClient client = new SpringDataRedisClient(lettuceConnectionFactory);
            client.set(FOO, BAR);
            assertTrue(client.get(FOO).equals(BAR));
        } catch (Exception e) {
            e.printStackTrace();
            fail();
        }
    }
}

Add Spring Data Redis via lettuce client


package magic.lang;

import static org.junit.Assert.*;

import org.junit.Test;

public class TestTools {

	@Test public void testHashCode() {
		assertEquals(0, Tools.hash(null));
	}
}

Add basic tests for hash values


/*
 * Copyright 2017 haeun kim
 *
 * 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 algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-10-03
 * Site       : https://www.acmicpc.net/problem/2941
 */

public class Boj2941 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        char[] input = br.readLine().toCharArray();
        int result = 0;
        for(int i=0; i<input.length; i++){
            if(input[i]=='=' || input[i]=='-'){
                result--;
                if(i>1 && input[i-1] == 'z' && input[i-2]=='d'){
                    result--;
                }
            }else if(i>0 && input[i]=='j'){
                if(input[i-1]=='l' || input[i-1]=='n'){
                    result--;
                }
            }

            result++;

        }
        System.out.println(result);
    }

}

Solve No.2941 from Baekjoon Online Judge


/**
 * Copyright (c) 2014 by Wen Yu.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Any modifications to this file must keep this entire header intact.
 */

package cafe.image.core;

import java.awt.image.BufferedImage;
import cafe.image.core.ImageMeta;

/**
 * Wrapper for an image frame
 *
 * @author Wen Yu, yuwen_66@yahoo.com
 * @version 1.0 11/21/2014
 */
public class ImageFrame {
	// Frame parameters
	private BufferedImage frame;
	private ImageMeta frameMeta;

	public ImageFrame(BufferedImage frame) {
		this(frame, ImageMeta.DEFAULT_IMAGE_META);
	}

	public ImageFrame(BufferedImage frame, ImageMeta frameMeta) {
		this.frame = frame;
		this.frameMeta = frameMeta;
	}
	public BufferedImage getFrame() {
		return frame;
	}

	public ImageMeta getFrameMeta() {
		return frameMeta;
	}

	public void setFrameMeta(ImageMeta frameMeta) {
		this.frameMeta = frameMeta;
	}
}

Rename from TIFFFrame and moved to cafe.image.core


import java.util.Scanner;

/**
 * This program computes the maximum in an integer array inputted by the user
 **/
public class MaxArray {
    public static void main(String[] args) {
        System.out.println("Find Maximum - Enter numbers >= 0");
        Scanner m = new Scanner(System.in);
        // Java arrays need to have their size known when they are created,
        // either by declaring the array manually or giving it a size.
        System.out.println("Input the size of the array");
        int size = m.nextInt();
        int a[] = new int[size];
        int max = -100;
        for (int i = 0; i < a.length; i++) {
            // The "i + 1" in parens will ensure that the correct number is
            // printed to the console. Java works like the standard order of
            // operations, so things in parens will be evaluated first.
            System.out.println("Input number #" + (i+1));
            a[i] = m.nextInt();
            if (a[i] > max) {
                max = a[i];
            }
        }
        System.out.println("The maximum is: " + max);
    }
}

Add problem 1 to unit 2


package name.falgout.jeffrey.testing.junit.guice;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.jupiter.api.Assertions.fail;

import com.google.inject.AbstractModule;
import javax.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ConditionEvaluationResult;
import org.junit.jupiter.api.extension.ExecutionCondition;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.RegisterExtension;

@IncludeModule(InjectableExtensionModule.class)
class InjectExtensionsTest {
  @RegisterExtension @Inject InjectableExtension customExtension;

  @Test
  void instanceExtensionInjection() {
    assertThat(customExtension).isNotNull();
  }

  @Test
  void thisTestShouldBeSkipped() {
    fail("This test should have been skipped.");
  }
}

final class InjectableExtensionModule extends AbstractModule {
  @Override
  protected void configure() {
    bind(String.class).toInstance("thisTestShouldBeSkipped");
  }
}

final class InjectableExtension implements ExecutionCondition {
  private final String testMethodToSkip;

  @Inject
  InjectableExtension(String testMethodToSkip) {
    this.testMethodToSkip = testMethodToSkip;
  }

  @Override
  public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
    if (context.getRequiredTestMethod().getName().equals(testMethodToSkip)) {
      return ConditionEvaluationResult.disabled("Disabled by InjectableExtension.");
    }

    return ConditionEvaluationResult.enabled("");
  }
}

Add a test for injecting extensions.


package alma.alarmsystem.clients.test;

import cern.laser.client.data.Alarm;
import cern.laser.client.services.selection.AlarmSelectionListener;
import cern.laser.client.services.selection.LaserSelectionException;
import alma.acs.component.client.ComponentClientTestCase;
import alma.alarmsystem.clients.CategoryClient;

public class CategoryClientChildren extends ComponentClientTestCase implements AlarmSelectionListener {
	/**
	 *  The categoryClient to test
	 */
	private CategoryClient categoryClient;

	/**
	 * Constructor
	 *
	 * @throws Exception
	 */
	public CategoryClientChildren() throws Exception {
		super(CategoryClientThreshold.class.getName());
	}

	/**
	 * @see extends ComponentClientTestCase
	 */
	public void setUp() throws Exception {
		super.setUp();

		categoryClient = new CategoryClient(getContainerServices());
		assertNotNull(categoryClient);
	}

	/**
	 * @see extends ComponentClientTestCase
	 */
	public void teraDown() throws Exception {
		categoryClient.close();
		super.tearDown();
	}

	/**
	 * @see cern.laser.client.services.selection.AlarmSelectionListener#onAlarm(cern.laser.client.data.Alarm)
	 */
	@Override
	public void onAlarm(Alarm alarm) {	}

	/**
	 * @see cern.laser.client.services.selection.AlarmSelectionListener#onException(cern.laser.client.services.selection.LaserSelectionException)
	 */
	@Override
	public void onException(LaserSelectionException e) {}

	/**
	 * Test getParents for NODE and MULTIPLICITY reduction
	 *
	 * @throws Exception
	 */
	public void testGetNodeChildren() throws Exception {
		categoryClient.connect(this);

		// Multiplicity
		alma.alarmsystem.Alarm[] alarms = categoryClient.getChildren("TEST:MCAUSE:1", false);
		assertEquals(5, alarms.length);

		alarms = categoryClient.getChildren("TEST:MULTI3:2", false);
		assertEquals(0, alarms.length);

		// Node
		alarms= categoryClient.getChildren("TEST:NODE1:1", true);
		assertEquals(1, alarms.length);
		assertEquals("TEST:NODE2:1", alarms[0].alarmId);

		alarms= categoryClient.getChildren("TEST:NODE2:1", true);
		assertEquals(1, alarms.length);
		assertEquals("TEST:NODE3:1", alarms[0].alarmId);

		alarms= categoryClient.getChildren("TEST:NODE3:1", true);
		assertEquals(0, alarms.length);
	}
}

Test getChildren of the CategoryClient


/*
 * This file is part of ELKI:
 * Environment for Developing KDD-Applications Supported by Index-Structures
 *
 * Copyright (C) 2017
 * ELKI Development Team
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package de.lmu.ifi.dbs.elki.math.statistics.distribution.estimator;

import java.util.Random;

import org.junit.Test;

import de.lmu.ifi.dbs.elki.math.statistics.distribution.ExponentiallyModifiedGaussianDistribution;
import de.lmu.ifi.dbs.elki.utilities.datastructures.arraylike.DoubleArrayAdapter;

/**
 * Regression test the Olivier Norberg estimation for the EMG distribution.
 *
 * Note: this estimator works only for positively skewed data?
 *
 * @author Erich Schubert
 */
public class EMGOlivierNorbergEstimatorTest extends AbstractDistributionEstimatorTest {
  @Test
  public void testEstimator() {
    final EMGOlivierNorbergEstimator est = instantiate(EMGOlivierNorbergEstimator.class, ExponentiallyModifiedGaussianDistribution.class);
    ExponentiallyModifiedGaussianDistribution gen = new ExponentiallyModifiedGaussianDistribution(1, 2, .1, new Random(0L));
    double[] data = new double[10000];
    for(int i = 0; i < data.length; i++) {
      data[i] = gen.nextRandom();
    }
    ExponentiallyModifiedGaussianDistribution dist;
    dist = est.estimate(data, DoubleArrayAdapter.STATIC);
    assertStat("mean", dist.getMean(), 1, -0.026544709107593434);
    assertStat("stddev", dist.getStddev(), 2, 0.17902812796064094);
    assertStat("lambda", dist.getLambda(), .1, -0.0010032987771384089);
  }
}

Add a test for Olivier Norberg EMG estimator.


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

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;

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

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {RefreshScopeNullBeanIntegrationTests.TestConfiguration.class})
public class RefreshScopeNullBeanIntegrationTests {

	@Autowired
	private MyCustomComponent myCustomComponent;

	@Autowired
	private org.springframework.cloud.context.scope.refresh.RefreshScope scope;

	@Test
	@DirtiesContext
	public void testRefreshBean() {
		assertThat(this.myCustomComponent).isNotNull();
		// ...and then refresh, so the bean is re-initialized:
		// this.scope.refreshAll();
	}

	protected static class OptionalService { }

	public static class MyCustomComponent {

		private final OptionalService optionalService;

		public MyCustomComponent(OptionalService optionalService) {
			this.optionalService = optionalService;
		}
	}

	@Configuration
	protected static class OptionalConfiguration {

		@Bean
		@RefreshScope
		public OptionalService service() {
			return null;
		}
	}

	@Configuration
	@Import({ RefreshAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, OptionalConfiguration.class })
	protected static class TestConfiguration {

		@Autowired(required = false)
		private OptionalService optionalService;

		@Bean
		public MyCustomComponent myCustomComponent() {
			return new MyCustomComponent(optionalService);
		}
	}

}

Test for NPE when calling getClass() in RefreshScope


/*------------------------------------------------------------------------------
 Copyright (c) CovertJaguar, 2011-2016

 This work (the API) is licensed under the "MIT" License,
 see LICENSE.md for details.
 -----------------------------------------------------------------------------*/

package mods.railcraft.api.core.items;

import mods.railcraft.api.tracks.TrackType;
import net.minecraft.block.BlockRailBase;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;

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

/**
 * Created by CovertJaguar on 3/6/2017 for Railcraft.
 *
 * @author CovertJaguar <http://www.railcraft.info>
 */
public interface ISpikeMaulTarget {
    List<ISpikeMaulTarget> spikeMaulTargets = new ArrayList<>();

    boolean matches(World world, BlockPos pos, IBlockState state);

    boolean setToTarget(World world, BlockPos pos, IBlockState state, EntityPlayer player, BlockRailBase.EnumRailDirection shape, TrackType trackType);

}

Simplify Spike Maul target definitions and move to API.


package leetcode;

/**
 * https://leetcode.com/problems/odd-even-linked-list/
 */
public class Problem328 {
    public class ListNode {
        int val;
        ListNode next;

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

    public ListNode oddEvenList(ListNode head) {
        // TODO
        return null;
    }

    public static void main(String[] args) {
        Problem328 prob = new Problem328();
    }
}

Create a skeleton for problem 328


public class Solution {

    public boolean judgeCircle(String moves) {

        int x = 0;
        int y = 0;

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

            switch (moves.charAt(i)) {

                case 'R' :
                    x++;
                    break;
                case 'L' :
                    x--;
                    break;
                case 'U' :
                    y++;
                    break;
                case 'D' :
                    y--;
                    break;

            }

        }

        return x == 0 && y == 0;

    }

}

Create : 657 Judge Route Circle


package stopheracleum.validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import stopheracleum.model.User;
import stopheracleum.service.UserService;

/**
 * Validator for {@link stopheracleum.model.User} class,
 * implements {@link Validator} interface.
 */

@Component
public class UserValidator implements Validator {

    @Autowired
    private UserService userService;

    @Override
    public boolean supports(Class<?> aClass) {
        return User.class.equals(aClass);
    }

    @Override
    public void validate(Object o, Errors errors) {
        User user = (User) o;

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "Required");
        if (user.getUsername().length() < 8 || user.getUsername().length() > 32) {
            errors.rejectValue("username", "Size.userForm.username");
        }

        if (userService.findByUsername(user.getUsername()) != null) {
            errors.rejectValue("username", "Duplicate.userForm.username");
        }

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "Required");
        if (user.getPassword().length() < 8 || user.getPassword().length() > 32) {
            errors.rejectValue("password", "Size.userForm.password");
        }

        if (!user.getConfirmPassword().equals(user.getPassword())) {
            errors.rejectValue("confirmPassword", "Different.userForm.password");
        }
    }
}

Add data validator for user class


package leetcode;

/**
 * https://leetcode.com/problems/ugly-number/
 */
public class Problem263 {
    public boolean isUgly(int num) {
        return false;
    }

    public static void main(String[] args) {
        Problem263 prob = new Problem263();
        System.out.println(prob.isUgly(6)); // true
        System.out.println(prob.isUgly(8)); // true
        System.out.println(prob.isUgly(14)); // false
    }
}

Create a skeleton for problem 263


package net.darkmist.alib.io;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;

public class DataIOUtil
{
	/**
	 * Only stati methods.
	 */
	private DataIOUtil()
	{
	}

	private static class DataInputAsStream extends InputStream
	{
		private DataInput din;

		DataInputAsStream(DataInput din)
		{
			if((this.din = din)==null)
				throw new NullPointerException("DataInput cannot be null.");
		}

		@Override
		public int read() throws IOException
		{
			return din.readByte();
		}

		// note that DataOutput.readFully does NOT follow the same
		// samantics as read(byte[]...) so is not directly wrapped.
	}

	public static InputStream asInputStream(DataInput din)
	{
		if(din instanceof InputStream)
			return (InputStream)din;
		return new DataInputAsStream(din);
	}

	public static Reader asReader(DataInput din)
	{
		return new InputStreamReader(asInputStream(din));
	}

	private static class DataOutputAsStream extends OutputStream
	{
		private DataOutput dout;

		DataOutputAsStream(DataOutput dout)
		{
			if((this.dout = dout)==null)
				throw new NullPointerException("DataOutput cannot be null.");
		}

		@Override
		public void write(int b) throws IOException
		{
			dout.write(b);
		}

		@Override
		public void write(byte[] bytes, int off, int len) throws IOException
		{
			dout.write(bytes, off, len);
		}

		@Override
		public void write(byte[] bytes) throws IOException
		{
			dout.write(bytes);
		}
	}

	public static OutputStream asOutputStream(DataOutput dout)
	{
		if(dout instanceof OutputStream)
			return (OutputStream)dout;
		return new DataOutputAsStream(dout);
	}

	public static Writer asWriter(DataOutput dout)
	{
		return new OutputStreamWriter(asOutputStream(dout));
	}
}

Add utils for DataInput & DataOutput


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

import java.io.IOException;
import javax.xml.bind.DatatypeConverter;

/**
 *
 * @author cferraro
 */
public class CudaDr_memory {

    public CudaDr_memory() {
    }

    String cuMemAlloc(Frontend fe, Result res, long size) throws IOException{

        Buffer b = new Buffer();
        byte[] bits = this.longToByteArray(size);
           for (int i =0; i< bits.length;i++){
               b.AddByte(bits[i] & 0xFF);
        }
        String pointer = "";
        fe.Execute("cuMemAlloc",b,res);
        pointer = getHex(res,8);
        return pointer;
    }

        private String getHex (Result res,int size) throws IOException{

        byte[] array=new byte[size];
        for (int i=0; i<size;i++){
            byte bit=res.getInput_stream().readByte();
            array[i]=bit;
        }
        String hex = DatatypeConverter.printHexBinary(array);
        System.out.println(hex);
        return hex;
    }

    void cuMemcpyHtoD(Frontend fe, Result res, String dst, float[] src, int count) throws IOException {

        Buffer b = new Buffer();
         byte[] bits = this.longToByteArray(count);
           for (int i =0; i< bits.length;i++){
               b.AddByte(bits[i] & 0xFF);
        }
        b.Add(dst);
           for (int i =0; i< bits.length;i++){
               b.AddByte(bits[i] & 0xFF);
        }
        b.Add(src);
        fe.Execute("cuMemcpyHtoD", b, res);

    }

     public byte[] longToByteArray(long value) {
        return new byte[] {
            (byte) value,
            (byte) (value >> 8),
            (byte) (value >> 16),
            (byte) (value >> 24),
            (byte) (value >> 32),
            (byte) (value >> 40),
            (byte) (value >> 48),
            (byte) (value >> 56)

        };
    }

}

Add CUDA memory manage functions


package net.imagej.ops.views;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.Shear;
import net.imglib2.RandomAccessible;
import net.imglib2.view.TransformView;

import org.scijava.ItemIO;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

@Plugin(type = ViewOps.Shear.class, name = ViewOps.Shear.NAME)
public class DefaultShear<T> extends
		AbstractView<RandomAccessible<T>, TransformView<T>> implements
		Shear<RandomAccessible<T>, TransformView<T>> {

	@Parameter(type = ItemIO.INPUT)
	private int shearDimension;

	@Parameter(type = ItemIO.INPUT)
	private int referenceDimension;

	@Override
	public TransformView<T> compute(RandomAccessible<T> input) {
		throw new UnsupportedOperationException();
	}

}

Add default implementation of Shear interface.


package leetcode.palindrome_number;

public class Solution {
    public boolean isPalindrome(int x) {
    	if(x < 0) return false;
    	if(x == 0) return true;
    	int U = 1, L = 1;
    	for(int i = 1; x / 10 >= i; i *= 10){
    		U = i * 10;
    	}
    	while(L < U && (x / U) % 10 == (x / L) % 10){
    		L *= 10;
    		U /= 10;
    	}
    	return L >= U;
    }

    public static void main(String[] args){
    	System.err.println(new Solution().isPalindrome(2147447413));
    }
}

Add java solution for 9. Palindrome Number


package lb2xp;

import static org.junit.Assert.fail;

import org.junit.Test;

public class TestMBC
{
    @Test
    public void testExpand()
    {
        fail( "Not yet implemented" );
    }
}

Add JUnite test case stub


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

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

public class FragmentActivityTestCases extends ActivityInstrumentationTestCase2<FragmentActivity> {
	//declare activity and widgets
	private FragmentActivity myFragmentActivity;
	private TextView myView;

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

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

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

	// Use Case 1, test 1/2
	public void testReadStoryFragments {
		String fragment = myView.getText();
		assertNotEquals(fragment, null);
	}

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

}

Put both test cases for use case 1 in here and changed the name so that it *might* potentially compile


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

package org.apache.commons.codec.net;

/**
 * Tests Utils. Methods currently get 100%/100% line/branch code coverage from other tests classes.
 *
 * @author Gary Gregory
 * @version $Id: $
 */
public class UtilsTest {

    /**
     * We could make the constructor private but there does not seem to be a point to jumping through extra code hoops
     * to restrict instantiation right now.
     */
    public void testConstructor() {
        new Utils();
    }

}

Bring code coverage to 100%/100% line/branch.


package leetcode.game_of_life;

public class Solution {
    public void gameOfLife(int[][] board) {
        if(board == null || board.length == 0 || board[0].length == 0) return;
        int w = board[0].length, h = board.length;
        for(int i = 0; i < h; i++){
            for(int j = 0; j < w; j++){
                int count = 0;
                for(int k = -1; k <= 1; k++){
                    for(int l = -1; l <= 1; l++){
                        if(k == 0 && l == 0){
                            continue;
                        }
                        if(i + k < 0 || i + k >= h) continue;
                        if(j + l < 0 || j + l >= w) continue;
                        if((board[i + k][j + l] & 1) != 0) count++;
                    }
                }
                if((board[i][j] & 1) == 1){
                    if(count == 2 || count == 3) board[i][j] |= 2;
                }else{
                    if(count == 3) board[i][j] |= 2;
                }
            }
        }
        for(int i = 0; i < h; i++){
            for(int j = 0; j < w; j++){
                board[i][j] >>= 1;
            }
        }
    }
}

Add solution for Game of Life


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

package org.scijava;

/**
 * A marker interface for optional SciJava components.
 * <p>
 * Some components might be discoverable, but cannot alwayts be initialized,
 * e.g. when relying on proprietary libraries. Such components can be marked
 * with this interface to indicate that failure to initialize should not
 * necessarily imply loud warnings in the log, for example.
 * </p>
 *
 * @author Johannes Schindelin
 * @see {@link org.scijava.service.Service}
 */
public interface Optional { }

Add an interface for optional components


package leetcode.search_in_rotated_sorted_array;

import java.util.Random;

public class Solution {
	public int search(int[] A, int target) {
		int size = A.length;
		if(size == 0) return -1;
		if(size == 1){
			if(target == A[0]){
				return 0;
			}else{
				return -1;
			}
		}
		if(target <= A[size - 1]){
			if(A[size - 1] == target) return size - 1;
			if(A[0] == target) return 0;
			int U = size - 1;
			int L = 0;
			while(L < U - 1){
				int mid = (U + L) / 2;

				if(A[mid] == target) return mid;
				if(A[mid] > A[size - 1] || A[mid] < target){
					L = mid;
				}else{
					U = mid;
				}
			}
			return -1;
		}else if(target >= A[0]){
			if(A[0] == target) return 0;
			if(A[size - 1] == target) return size - 1;
			int U = size - 1;
			int L = 0;
			while(L < U - 1){
				int mid = (U + L) / 2;
				if(A[mid] == target) return mid;
				if(A[mid] < A[0] || A[mid] > target){
					U = mid;
				}else{
					L = mid;
				}
			}
			return -1;
		}else{
			return -1;
		}
    }

	public static void main(String[] args){
		final int N = 3;
		int[] ary = new int[N];
		int r = 0;
		System.err.println("sol.seaerch(new int[]{1, 3}, 1) = " + (new Solution().search(new int[]{1, 3}, 1)));
		while(r == 0){
			r = new Random().nextInt(N);
		}
		System.err.println("r = " + r);
		for(int i = 0; i < N; i++){
			ary[(i + r) % N] = i * 2;
		}
		Solution sol = new Solution();
		System.err.println("sol.search(ary, 100) = " + (sol.search(ary, 100)));
		for(int i = 0; i < 2 * N; i++){
			int ret = sol.search(ary, i);
			if(i % 2 == 0){
				if(ret == -1 || ary[ret] != i) System.err.println("WA: should have found");
			}else{
				if(ret != -1) System.err.println("Should be -1 when i = " + i);
			}
		}
	}
}

Add java solution for 33. Search in Rotated Sorted Array


package com.epam.cdp.jee.todo;

import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * This class uses CDI to alias Java EE resources, such as the persistence context, to CDI beans
 *
 * <p>
 * Example injection on a managed bean field:
 * </p>
 */
public class Resources {
    // use @SuppressWarnings to tell IDE to ignore warnings about field not being referenced
    // directly
    @SuppressWarnings("unused")
    @Produces
    @PersistenceContext
    private EntityManager entityManager;

}

Add alias for JEE resources


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

package io.spine.validate;

import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * A change in a {@linkplain io.spine.validate.FieldValue value of a field}.
 */
public final class FieldValueChange {

    /**
     * A value that used to be the value of the field.
     *
     *
Nullable because when a field is set for the first time, old value has never existed
     * and can be considered {@code null}.
     */
    private final @Nullable FieldValue oldValue;

    /**
     * A value that the field is going to obtain as a result of this change.
     */
    private final FieldValue newValue;

    /** Creates an instance of the field change from the given values. */
    private FieldValueChange(@Nullable FieldValue oldValue, FieldValue newValue) {
        this.oldValue = oldValue;
        this.newValue = newValue;
    }

    /**
     * Creates a new instance of a field change based on the specified values.
     *
     *
{@code oldValue} can be {@code null}, because a first time the field is set the old
     * value does not exist, therefore can be considered {@code null}.
     *
     * @param oldValue
     *         a value that the field had before this change
     * @param newValue
     *         a value that the field is going to have as a result of this change
     * @return a new instance of a field change
     */
    public static FieldValueChange of(@Nullable FieldValue oldValue, FieldValue newValue) {
        return new FieldValueChange(oldValue, newValue);
    }

    /**
     * Creates a new instance of a field change that signifies the first change of the field.
     *
     *
If this method is used to instantiate a {@code FieldValueChange}, the old value is going
     * to be {@code null}.
     *
     * @param singleValue
     *         a value that the field is going to have as a result of this change
     * @return a new instance of a field change
     */
    static FieldValueChange firstValueEver(FieldValue singleValue) {
        return new FieldValueChange(null, singleValue);
    }

    /** Returns a value that the field is going to have as a result of this change. */
    FieldValue newValue() {
        return newValue;
    }

    /** Returns a value that the field used to have before this change took place.*/
    FieldValue oldValue() {
        return oldValue;
    }
}

Introduce an entity that represents a change of the value of a field


package org.xdi.service.util;

import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;

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

/**
 * Class which provides external resources for injection
 *
 * @author Yuriy Movchan Date: 14/03/2017
 */
public class Resources {

	@Produces
	public Logger getLogger(InjectionPoint ip) {
		Class<?> clazz = ip.getMember().getDeclaringClass();

		return LoggerFactory.getLogger(clazz);
	}

}

Move logger factory to oxCore


/*
 * (C) Copyright 2019 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;

import static org.junit.Assert.assertTrue;

import java.net.MalformedURLException;
import java.net.URL;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

import io.appium.java_client.android.AndroidDriver;

/**
 * Test with Appium and Android.
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 1.0.0
 */
public class AppiumTest {

    private WebDriver driver;

    @Before
    public void setupTest() throws MalformedURLException {
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability("browserName", "chrome");
        capabilities.setCapability("deviceName", "Samsung Galaxy S6");
        driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"),
                capabilities);
    }

    @After
    public void teardown() {
        if (driver != null) {
            driver.quit();
        }
    }

    @Test
    public void test() {
        driver.get("https://en.wikipedia.org/wiki/Main_Page");
        assertTrue(
                driver.getTitle().equals("Wikipedia, the free encyclopedia"));
    }

}

Include test for Chrome in Android with Appium


/*
 * Copyright (C) 2011 Benoit GUEROUT <bguerout at gmail dot com> and Yves AMSELLEM <amsellem dot yves at gmail dot 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 org.jongo.use_native;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.regex.Pattern;

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

public class DocumentNativeTest extends NativeTestBase {

    private MongoCollection<Document> collection;

    @Before
    public void setUp() throws Exception {
        collection = jongo.getCollection("friends", Document.class);
    }

    @After
    public void tearDown() throws Exception {
        collection.drop();
    }

    @Test
    public void canUseDocumentBuilderFromDriver() throws Exception {

        Document doc = new Document().append("name", "Abby");

        collection.insertOne(doc);

        assertThat(collection.countDocuments(doc)).isEqualTo(1);
    }

    @Test
    public void canUseFilterBuilderFromDriver() throws Exception {

        Document doc = new Document().append("name", "Abby");

        collection.insertOne(doc);

        Document result = collection.find(Filters.regex("name", Pattern.compile("^A"))).first();
        assertThat(result.get("name")).isEqualTo("Abby");
    }

}

Add test class to ensure native api works with Filters


package com.sleekbyte.tailor.grammar;

import com.sleekbyte.tailor.Tailor;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.*;

import static org.junit.Assert.assertEquals;

public class GrammarTest {

    protected static final String TEST_INPUT_DIR = "src/test/java/com/sleekbyte/tailor/grammar/";
    protected static final String NEWLINE_REGEX = "\\r?\\n";

    protected ByteArrayOutputStream errContent;
    protected ByteArrayOutputStream outContent;
    protected File[] swiftFiles;

    @Before
    public void setUp() {
        File curDir = new File(TEST_INPUT_DIR);
        swiftFiles = curDir.listFiles((File file, String name) -> name.endsWith(".swift"));
        outContent = new ByteArrayOutputStream();
        System.setOut(new PrintStream(outContent));
    }

    @After
    public void tearDown() {
        System.setOut(null);
    }

    @Test
    public void testRule() throws IOException {
        for ( File swiftFile: swiftFiles) {
            errContent = new ByteArrayOutputStream();
            System.setErr(new PrintStream(errContent));
            String[] command = { (TEST_INPUT_DIR + swiftFile.getName()) };
            Tailor.main(command);
            assertEquals(errContent.toString(), "");
            System.setErr(null);
        }
    }

}

Add test to check if snippets parse correctly


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

import com.google.inject.BindingAnnotation;

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

/**
 * An annotation used for naming {@link ChannelBinding} injections.
 *
 *

{@code @ChannelId("SomeChannel") @Inject
 * ChannelBinding.RawDataChannel channel;}

 */
@BindingAnnotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ChannelId {

    /**
     * Gets the channel id.
     *
     * @return The channel id
     */
    String value();
}

Add an annotation to inject ChannelBindings


package leetcode.multiply_strings;

public class Solution {
	private static final int MODULUS = 1000000000;
	private static final int DIGITS_PER_ELE = 9;
    public String multiply(String num1, String num2) {
    	long[] bignum1 = new long[(num1.length() + 8) / 9];
    	int num1length = num1.length();
    	long[] bignum2 = new long[(num2.length() + 8) / 9];
    	int num2length = num2.length();
    	for(int i = 0; i < bignum1.length; i++){
    		bignum1[i] = Long.parseLong(num1.substring(Math.max(0, num1length - (i + 1) * DIGITS_PER_ELE), num1length - i * DIGITS_PER_ELE));
    	}
    	for(int i = 0; i < bignum2.length; i++){
    		bignum2[i] = Long.parseLong(num2.substring(Math.max(0, num2length - (i + 1) * DIGITS_PER_ELE), num2length - i * DIGITS_PER_ELE));
    	}

    	long[] result = new long[bignum1.length + bignum2.length];
    	for(int i = 0; i < bignum1.length; i++){
    		for(int j = 0; j < bignum2.length; j++){
    			result[i + j] += bignum1[i] * bignum2[j];
    		}
    	}
    	for(int i = 0; i < bignum1.length + bignum2.length - 1; i++){
    		result[i + 1] += result[i] / MODULUS;
    		result[i] %= MODULUS;
    	}
    	int idx;
    	for(idx = bignum1.length + bignum2.length - 1; idx > 0 && result[idx] == 0; idx--);
    	StringBuilder ans = new StringBuilder();
    	ans.append(String.format("%d", result[idx--]));
    	for(;idx >= 0; idx--){
    		ans.append(String.format("%09d", result[idx]));
    	}
    	return ans.toString();
    }

    public static void main(String[] args){
    	System.err.println(new Solution().multiply("9999999999", "9999999999"));
    }
}

Add java solution for 43. Multiply Strings


import java.util.regex.Matcher;
import java.util.regex.Pattern;

import uk.co.uwcs.choob.modules.Modules;
import uk.co.uwcs.choob.support.IRCInterface;
import uk.co.uwcs.choob.support.events.ChannelAction;
import uk.co.uwcs.choob.support.events.ChannelMessage;
import uk.co.uwcs.choob.support.events.Message;
import uk.co.uwcs.choob.support.events.PrivateAction;

public class Face
{
	Modules mods;
	private final IRCInterface irc;

	public Face(final Modules mods, final IRCInterface irc)
	{
		this.mods = mods;
		this.irc = irc;
	}

	public String[] info()
	{
		return new String[] { "Face Plugin", "The Choob Team", "choob@uwcs.co.uk",
				"$Rev: 1166 $$Date: 2009-06-11 10:27:00 +0100 (Thu, 11 June 2009) $" };
	}

	public final String filterReplaceRegex = "([^\\s]+)face";
	private final Pattern compiledFilterReplaceRegex = Pattern.compile(filterReplaceRegex);

	public void filterReplace(final Message mes)
	{
		if (!(mes instanceof ChannelMessage))
			return;

		final String message = mes.getMessage();

		try
		{
			// Run the filter regex with the trigger.
			Matcher matcher = Pattern.compile(irc.getTriggerRegex() + filterReplaceRegex).matcher(message);
			if (!matcher.find())
				return;

			final String nick = matcher.group(1);

			irc.sendContextMessage(mes, nick + ": Waa!");
		}
		catch (final Exception e)
		{
			e.printStackTrace();
		}
	}
}

Add face plugin. If someone wants to make it so that this only matches if an alias of the same name doesn't exist, that would be cool. ¬_¬


package net.onrc.onos.api.intent;

/**
 * This interface is for generator of IntentId.
 *
 * <p>
 * {@link #getNewId()} generates a globally unique {@link IntentId} instance
 * on each invocation. Application developers should not generate IntentId
 * by themselves. Instead use an implementation of this interface.
 * </p>
 */
public interface IntentIdGenerator {
    /**
     * Generates a globally unique {@link IntentId} instance.
     *
     * @return a globally unique {@link IntentId} instance.
     */
    public IntentId getNewId();
}

Add an interface to generate IntentIds


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

/**
 * Given an array of strings, can you write a method to return return just words that matches with
 * a pattern containing the "*" regular expression.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class AsteriskRegularExpression {

}

Add statement to problem 35


package util;

import exception.UploadException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;

import javax.annotation.Nullable;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.SocketException;

/**
 * Custom RequestBody to handle reading from a section of a file rather than the entire file.
 */
public class ChunkRequestBody extends RequestBody {
    private String filepath;
    private long offset;
    private int chunkSize;
    private MediaType mediaType;

    public ChunkRequestBody(String filepath, MediaType mediaType, long offset, int chunkSize) {
        this.filepath = filepath;
        this.mediaType = mediaType;
        this.offset = offset;
        this.chunkSize = chunkSize;
    }

    @Nullable
    @Override
    public MediaType contentType() {
        return this.mediaType;
    }

    @Override public long contentLength() {
        return chunkSize;
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        RandomAccessFile source = new RandomAccessFile(filepath, "r");
        byte[] bytes = new byte[Upload.CHUNK_SIZE];

        source.seek(offset);
        source.read(bytes, 0, chunkSize);
        source.close();

        try {
            sink.write(bytes, 0, chunkSize);
            sink.close();
        } catch (SocketException e){
            throw new UploadException();
        }
    }
}

Add custom RequestBody to upload file chunks