/*
 * OpenRemote, the Home of the Digital Home.
 * Copyright 2008-2014, OpenRemote Inc.
 *
 * See the contributors.txt file in the distribution for a
 * full listing of individual contributors.
 *
 * 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 org.openremote.exception;

/**
 * A runtime (unchecked) exception type to indicate implementation errors (code paths that
 * should not be reached under normal conditions). Differentiating the exception type to make
 * it easier to distinguish from other predefined exception types that may originate for example
 * from third party libraries. This allows clear distinction between OpenRemote error conditions
 * and other errors that may be handled separately.
 *
 * @author Juha Lindfors
 */
public class IncorrectImplementationException extends OpenRemoteRuntimeException
{

  // TODO : Should be moved to a base package once one is created   [JPL]

  /**
   * Constructs a new implementation exception with a given message.
   *
   * @param msg
   *          human-readable error message
   */
  public IncorrectImplementationException(String msg)
  {
    super(msg);
  }

  /**
   * Constructs a new implementation exception with a parameterized message.
   *
   * @param msg
   *          human-readable error message
   *
   * @param params
   *          exception message parameters -- message parameterization must be
   *          compatible with {@link java.text.MessageFormat} API
   *
   * @see java.text.MessageFormat
   */
  public IncorrectImplementationException(String msg, Object... params)
  {
    super(msg, params);
  }

  /**
   * Constructs a new implementation exception with a given message and root cause.
   *
   * @param msg
   *          human-readable error message
   *
   * @param cause
   *          root exception cause
   */
  public IncorrectImplementationException(String msg, Throwable cause)
  {
    super(msg, cause);
  }

  /**
   * Constructs a new implementation exception with a parameterized message and root cause.
   *
   * @param msg
   *          human-readable error message
   *
   * @param cause
   *          root exception cause
   *
   * @param params
   *          exception message parameters -- message parameterization must be
   *          compatible with {@link java.text.MessageFormat} API
   *
   * @see java.text.MessageFormat
   */
  public IncorrectImplementationException(String msg, Throwable cause, Object... params)
  {
    super(format(msg, params), cause);
  }

}

Add an exception type for implementation error. Including here until a common base package has been set up.


/**
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
package com.codeup.movies.catalog;

import com.codeup.movies.Movie;
import com.codeup.movies.Movies;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.Collections;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class AddMovieTest {

    @Test
    public void it_adds_a_new_movie() {
        addMovie.withDetails("Home", 4, "home.png", Collections.emptyList());

        verify(movies).add(any(Movie.class));
    }

    @Before
    public void configureCommand() {
        addMovie = new AddMovie(movies);
    }

    private AddMovie addMovie;

    @Mock
    Movies movies;
}

Add tests for AddMovie class.


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

package org.scijava.io;

import java.nio.ByteBuffer;

/**
 * {@link Location} backed by a {@link ByteBuffer}.
 *
 * @author Curtis Rueden
 */
public class BytesLocation extends AbstractLocation {

	private final ByteBuffer bytes;

	public BytesLocation(final ByteBuffer bytes) {
		this.bytes = bytes;
	}

	public BytesLocation(final byte[] bytes) {
		this(ByteBuffer.wrap(bytes));
	}

	public BytesLocation(final byte[] bytes, final int offset, final int length) {
		this(ByteBuffer.wrap(bytes, offset, length));
	}

	// -- ByteArrayLocation methods --

	/** Gets the associated {@link ByteBuffer}. */
	public ByteBuffer getByteBuffer() {
		return bytes;
	}

}

Add a location type backed by a byte array


/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package org.mozilla.focus.utils;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;

import java.util.Locale;

import static org.junit.Assert.assertEquals;

@RunWith(RobolectricTestRunner.class)
public class LocalesTest {
    @Test
    public void testLanguage() {
        assertEquals("en", Locales.getLanguage(Locale.getDefault()));
    }

    @Test
    public void testHebrewIsrael() {
        final Locale locale = new Locale("iw", "IL");

        assertEquals("he", Locales.getLanguage(locale));
        assertEquals("he-IL", Locales.getLanguageTag(locale));
    }

    @Test
    public void testIndonesianIndonesia() {
        final Locale locale = new Locale("in", "ID");

        assertEquals("id", Locales.getLanguage(locale));
        assertEquals("id-ID", Locales.getLanguageTag(locale));
    }

    @Test
    public void testYiddishUnitedStates() {
        final Locale locale = new Locale("ji", "US");

        assertEquals("yi", Locales.getLanguage(locale));
        assertEquals("yi-US", Locales.getLanguageTag(locale));
    }

    @Test
    public void testEmptyCountry() {
        final Locale locale = new Locale("en");

        assertEquals("en", Locales.getLanguage(locale));
        assertEquals("en", Locales.getLanguageTag(locale));
    }
}

Add unit tests for Locales class.


// Copyright (c) 2006- Facebook
// Distributed under the Thrift Software License
//
// See accompanying file LICENSE or visit the Thrift site at:
// http://developers.facebook.com/thrift/

package com.facebook.thrift.transport;

import com.facebook.thrift.TByteArrayOutputStream;
import java.io.UnsupportedEncodingException;

/**
 * Memory buffer-based implementation of the TTransport interface.
 *
 * @author Chad Walters <chad@powerset.com>
 */
public class TMemoryBuffer extends TTransport {

  /**
   *
   */
  public TMemoryBuffer(int size) {
    arr_ = new TByteArrayOutputStream(size);
  }

  @Override
  public boolean isOpen() {
    return true;
  }

  @Override
  public void open() {
    /* Do nothing */
  }

  @Override
  public void close() {
    /* Do nothing */
  }

  @Override
  public int read(byte[] buf, int off, int len) {
    byte[] src = arr_.get();
    int amtToRead = (len > arr_.len() - pos_ ? arr_.len() - pos_ : len);
    if (amtToRead > 0) {
      System.arraycopy(src, pos_, buf, off, amtToRead);
      pos_ += amtToRead;
    }
    return amtToRead;
  }

  @Override
  public void write(byte[] buf, int off, int len) {
    arr_.write(buf, off, len);
  }

  /**
   * Output the contents of the memory buffer as a String, using the supplied
   * encoding
   * @param enc  the encoding to use
   * @return the contents of the memory buffer as a String
   */
  public String toString(String enc) throws UnsupportedEncodingException {
    return arr_.toString(enc);
  }

  // The contents of the buffer
  private TByteArrayOutputStream arr_;

  // Position to read next byte from
  private int pos_;
}

Add Java memory buffer transport implementation.


package com.aesthetikx.hubski.adapter;

import java.util.List;

public class BaseTreeListItem implements TreeListItem {

    private boolean visible;
    private boolean expanded;
    private List<? extends BaseTreeListItem> children;
    private int depth;

    public BaseTreeListItem(List<? extends BaseTreeListItem> children, boolean visible, boolean expanded, int depth) {
        this.children = children;
        this.visible = visible;
        this.expanded = expanded;
        this.depth = depth;
    }

    @Override
    public boolean isExpanded() {
        return expanded;
    }

    @Override
    public void setExpanded(boolean expanded) {
        this.expanded = expanded;
        for (BaseTreeListItem child: children) {
            child.parentToggled(expanded, isVisible());
        }
    }

    @Override
    public void parentToggled(boolean parentExpanded, boolean parentVisible) {
        setVisible( parentVisible && parentExpanded );
        for (BaseTreeListItem child: children) child.parentToggled(isExpanded(), isVisible());
    }

    @Override
    public void toggleExpanded() {
        setExpanded(!isExpanded());
    }

    @Override
    public boolean isVisible() {
        return visible;
    }

    @Override
    public void setVisible(boolean visible) {
        this.visible = visible;
    }

    @Override
    public int getDepth() {
        return depth;
    }

}

Implement tree list item with base tree list item


package com.aviras.mrassistant.models;

import io.realm.annotations.PrimaryKey;

/**
 * Created by ashish on 8/6/16.
 */
public class Doctor {

    @PrimaryKey
    private int id;

    private String name;

    private String address;

    private String notes;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getNotes() {
        return notes;
    }

    public void setNotes(String notes) {
        this.notes = notes;
    }
}

Add model to represent doctor


/*
 * 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.spotify.reaper.service;

import org.apache.cassandra.repair.RepairParallelism;

import java.util.Set;

/**
 * Represents the parameters of a repair command given to Cassandra.
 */
public class RepairParameters {
  public final RingRange tokenRange;
  public final String keyspaceName;
  public final Set<String> columnFamilies;
  public final RepairParallelism repairParallelism;

  public RepairParameters(RingRange tokenRange, String keyspaceName, Set<String> columnFamilies,
      RepairParallelism repairParallelism) {
    this.tokenRange = tokenRange;
    this.keyspaceName = keyspaceName;
    this.columnFamilies = columnFamilies;
    this.repairParallelism = repairParallelism;
  }
}

Add type to hold parameters of issued repair commands


package pete.metrics.adaptability;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Counts occurences of XML elements in a BPMN process, sorted by the name of
 * the element. The list of relevant elements is determined by the class
 * RelevantElements. The class will become obsolete once elements
 * are determined by an XPath expression and not their name.
 *
 */
class SimpleNodeCounter {

	private HashMap<String, AtomicInteger> elements;

	private boolean isStrict;

	private List<String> relevantElements;

	public SimpleNodeCounter() {
		setUp(true);
	}

	public SimpleNodeCounter(boolean isStrict) {
		setUp(isStrict);
	}

	private void setUp(boolean isStrict) {
		elements = new HashMap<String, AtomicInteger>();
		this.isStrict = isStrict;
		relevantElements = new RelevantElements().getRelevantElements();
	}

	public void addToCounts(Node node) {
		// ignore text nodes
		if (isTextNode(node)) {
			return;
		}

		addToMap(node);

		NodeList children = node.getChildNodes();
		if (children != null) {
			for (int i = 0; i < children.getLength(); i++) {
				addToCounts(children.item(i));
			}
		}
	}

	private boolean isTextNode(Node node) {
		return node.getNodeType() == Node.TEXT_NODE;
	}

	private void addToMap(Node node) {
		String nodeName = node.getLocalName();
		if (isStrict && !relevantElements.contains(nodeName)) {
			return;
		}

		if (elements.containsKey(nodeName)) {
			AtomicInteger count = elements.get(nodeName);
			count.incrementAndGet();
		} else {
			elements.put(nodeName, new AtomicInteger(1));
		}
	}

	public void clear() {
		elements = new HashMap<String, AtomicInteger>();
	}

	public void writeToCsv(Path file) {
		try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(file,
				Charset.defaultCharset()))) {
			writer.println("element;number");
			for (String key : elements.keySet()) {
				AtomicInteger value = elements.get(key);
				writer.println(key + ";" + value);
			}
		} catch (IOException e) {
			System.err.println(e.getMessage());
		}
	}

	public Map<String, AtomicInteger> getElementNumbers() {
		return Collections.unmodifiableMap(elements);
	}
}

Rename ElementCounter and mark for deprecation


public class Solution {

    public int[] twoSum(int[] nums, int target) {

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

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

                if (nums[j] == (target - nums[i])) {
                    return new int[] {i, j};
                }

            }
        }

        return null;

    }

}

Create : 1 Two Sum


/*
 * Copyright © 2015 by Frank W. Rahn. Alle Rechte vorbehalten. All rights reserved.
 */
package de.rahn.finances.web;

import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.ConfigFileApplicationContextInitializer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;

import de.rahn.finances.SecuritiesManagementApplication;

/**
 * Einen Test für den {@link ApplicationController}.
 * @author Frank W. Rahn
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SecuritiesManagementApplication.class,
	initializers = ConfigFileApplicationContextInitializer.class)
@WebAppConfiguration
public class ApplicationControllerTest {

	@Autowired
	private WebApplicationContext webApplicationContext;

	private MockMvc mockMvc;

	/**
	 * Initialisiere diesen Test.
	 */
	@Before
	public void setUp() throws Exception {
		mockMvc = webAppContextSetup(webApplicationContext).build();
	}

	/**
	 * Test method for {@link ApplicationController#index()}.
	 */
	@Test
	public void testIndex() throws Exception {
		mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(view().name("index"))
			.andExpect(content().string(containsString("Wertpapierverwaltung")));
	}

	/**
	 * Test method for {@link ApplicationController#info()}.
	 */
	@Test
	public void testInfo() throws Exception {
		mockMvc.perform(get("/info")).andExpect(status().isOk()).andExpect(view().name("info"))
			.andExpect(content().string(containsString("Management-API")));
	}

}

Test für den ApplicationController erstellt


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

package org.apache.tapestry5.internal.util;

import org.apache.tapestry5.ioc.Invokable;
import org.apache.tapestry5.services.InvalidationEventHub;

/**
 * A utility class for managing a cacheable result that can be recomputed when needed.
 */
public class RecomputableSupport
{
    private volatile int masterVersion = 1;

    /**
     * Invalidates any existing {@link #create(org.apache.tapestry5.ioc.Invokable)} wrappers} such that they will
     * re-perform the computation when next invoked.
     */
    public void invalidate()
    {
        masterVersion++;
    }

    /**
     * Forces {@link #invalidate()} to be invoked when the hub emits an {@linkplain InvalidationEventHub#addInvalidationCallback(Runnable) invalidation callback}.
     *
     * @param hub
     */
    public void initialize(InvalidationEventHub hub)
    {
        hub.addInvalidationCallback(new Runnable()
        {
            @Override
            public void run()
            {
                invalidate();
            }
        });
    }

    /**
     * Wraps a computation with caching logic; once computed, the Invokable will return the same value, until
     * {@link #invalidate()} is invoked.
     *
     * @param invokable
     *         a computation to perform, whose results are cacheable until invalidated
     * @param <T>
     *         type of result
     * @return caching-enabled wrapper around invokable
     */
    public <T> Invokable<T> create(final Invokable<T> invokable)
    {
        return new Invokable<T>()
        {
            private volatile int localVersion = masterVersion;

            private volatile T cachedResult;

            @Override
            public T invoke()
            {
                // Has the master version changed since the computation was last executed?
                if (localVersion != masterVersion)
                {
                    cachedResult = null;
                    localVersion = masterVersion;
                }

                if (cachedResult == null)
                {
                    cachedResult = invokable.invoke();
                }

                return cachedResult;
            }
        };
    }
}

Add a utility for caching/recomputing computations


/**
 * 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.camel.itest.karaf;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.junit.PaxExam;

@RunWith(PaxExam.class)
public class CamelAwsSdbTest extends BaseKarafTest {

    public static final String COMPONENT = extractName(CamelAwsSdbTest.class);

    @Test
    public void test() throws Exception {
    	testComponent(COMPONENT);
    }

}

Create single Karaf feature tests for single components, aws-sdb test


import java.util.Stack;

public class MinStack {

    private int min;
    private Stack<Integer> stack;

    /** initialize your data structure here. */
    public MinStack() {

        min = Integer.MAX_VALUE;
        stack = new Stack<Integer>();

    }

    public void push(int x) {

        if (x <= min) {
            stack.push(min);
            min = x;
        }

        stack.push(x);

    }

    public void pop() {

        if (stack.pop() == min) {
            min = stack.pop();
        }

    }

    public int top() {
        return stack.peek();
    }

    public int getMin() {
        return min;
    }

}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */

Create : 155 Min Stack


/**
 * Copyright 2016, RadiantBlue Technologies, 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 messaging.job;

/**
 * Callback class to communicate the completion status of a Worker.
 *
 * @author Patrick.Doody
 *
 */
public interface WorkerCallback {
	/**
	 * Fired when the Worker has finished running; success or fail.
	 *
	 * @param jobId
	 *            The Job ID being processed that has completed
	 */
	void onComplete(String jobId);
}

Add Callback for Component Workers


/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
public class Foo {
  public static String foo = String.format("q");
}

Fix test: remove copyright notice from testdata file


package com.netflix.karyon.health;

public abstract class AbstractHealthIndicator implements HealthIndicator {
    private final String name;

    public AbstractHealthIndicator(String name) {
        this.name = name;
    }

    public AbstractHealthIndicator() {
        this.name = getClass().getSimpleName();
    }

    @Override
    public String getName() {
        return name;
    }
}

package com.netflix.karyon.health;

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

public abstract class AbstractHealthIndicator implements HealthIndicator {
    private final String name;

    /**
     *  Creates an AbstractHealthIndicator with the specified name
     *
     * @paran name name     Name of this Health Indicator
     *
     */
    public AbstractHealthIndicator(String name) {
        this.name = name;
    }

    /**
     * Creates an AbstractHealthIndicator with a default name
     *
     */
    public AbstractHealthIndicator() {
        this.name = getClass().getSimpleName();
    }

    @Override
    public String getName() {
        return name;
    }

    /**
     *
     * Create a healthy status
     *
     * @return a healthy status
     */

    protected final HealthIndicatorStatus healthy() {
        return HealthIndicatorStatuses.create(getName(), true, Collections.<String, Object> emptyMap(), null);
    }

    /**
     *
     * Create a healthy status
     *
     * @param attr  Map of the attributes describing status
     * @return a healthy status
     */
    protected final HealthIndicatorStatus healthy(Map<String, Object> attr) {
        return HealthIndicatorStatuses.create(getName(), true, attr, null);
    }

    /**
     *
     * Create an unhealthy status
     *
     * @return a unhealthy status
     */
    protected final HealthIndicatorStatus unhealthy() {
        return HealthIndicatorStatuses.create(getName(), false, Collections.<String, Object> emptyMap(), null);
    }

    /**
     *
     * Create an unhealthy status
     *
     * @return a unhealthy status
     */
    protected final HealthIndicatorStatus unhealthy(Map<String, Object> attr) {
        return HealthIndicatorStatuses.create(getName(), false, attr, null);
    }

    /**
     *
     * Create an unhealthy status
     *
     * @return a unhealthy status
     */
    protected final HealthIndicatorStatus unhealthy(Throwable t) {
        return HealthIndicatorStatuses.create(getName(), false, Collections.<String, Object> emptyMap(), t);
    }

    /**
     *
     * Create an unhealthy status
     *
     * @return a unhealthy status
     */
    protected final HealthIndicatorStatus unhealthy(Map<String, Object> attr, Throwable t) {
        return HealthIndicatorStatuses.create(getName(), false, attr, t);
    }

}

Add helper methods for returning indicator status


package br.com.rogrs;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {

	@Test
	public void contextLoads() {
	}

}

Test para o contexto da app


/*
 * MIT License
 *
 * Copyright (c) 2017 Dennis Neufeld
 *
 * 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 space.npstr.sqlsauce;

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

/**
 * Created by napster on 17.10.17.
 * <p>
 * Helper class to contain JPQL results
 */
public class Entry<K, V> {
    public final K key;
    public final List<V> stats;

    public Entry(final K user, final V stat) {
        this.key = user;
        this.stats = Collections.singletonList(stat);
    }

    public Entry(final K user, final V stat0, final V stat1) {
        this.key = user;
        this.stats = Arrays.asList(stat0, stat1);
    }
}

Add Helper class for multiple result queries


package edu.emory.cellbio.ijbat.dm;

import edu.emory.cellbio.ijbat.SlideSet;
import edu.emory.cellbio.ijbat.ex.ImgLinkException;
import edu.emory.cellbio.ijbat.ex.LinkNotFoundException;
import edu.emory.cellbio.ijbat.ex.SlideSetException;
import imagej.ImageJ;
import imagej.data.Dataset;
import imagej.data.DatasetService;
import imagej.io.IOService;
import imagej.io.event.FileSavedEvent;
import io.scif.io.img.ImgSaver;
import java.io.File;
import net.imglib2.img.ImgPlus;
import org.scijava.event.EventService;

/**
 *
 * @author Benjamin Nanes
 */
@LinkerInfo( underlying = "java.lang.String", processed = "imagej.data.Dataset",
        typeCode = "tiff", name = "Image File (Tiff)")
public class SaveTiffLinker extends LinkLinker<Dataset> {

    private IOService ios;
    private DatasetService dss;

    // -- Constructors --

    public SaveTiffLinker() {
        super();
    }

    public SaveTiffLinker(ImageJ context, SlideSet owner) {
        super(context, owner);
        ios = context.io();
        dss = context.dataset();
    }

    // -- Methods --

    @Override
    public Dataset process(String underlying) throws SlideSetException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Class<Dataset> getProcessedClass(Object underlying) {
        return Dataset.class;
    }

    @Override
    public void write(String path, Dataset data) throws SlideSetException {
        final ImgPlus imp = data.getImgPlus();
        String wd = owner.getWorkingDirectory();
        wd = wd == null ? "" : wd;
        if(!(new File(path)).isAbsolute())
             path = wd + File.separator + path;
        if(!(new File(path).exists()))
            throw new LinkNotFoundException(path + " does not exist!");
        final ImgSaver iSave = new ImgSaver();  // This changes to a DatasetService method by 7.5
        iSave.setContext(dss.getContext());
        try {
            iSave.saveImg(path, imp);
            dss.getContext().getService(EventService.class)
                 .publish(new FileSavedEvent(data.getSource()));
        } catch(Exception e) {
            throw new ImgLinkException(e);
        }
    }

}

Add Linker for saving Tiff images


/*
 * Copyright (c) 2012 Mateusz Parzonka, Eric Bodden
 * 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
 *
 * Contributors:
 * Mateusz Parzonka - initial API and implementation
 */
package prm4j.api;

public abstract class MatchHandler {

    /**
     * Retrieve bound objects with getBoundObject(...) TODO doc method.
     *
     * @param bindings
     */
    public abstract void handleMatch(IBinding[] bindings);

    /**
     * Retrieves the object which was stored in the monitor bindings. The object may be null if selected
     * object was already garbage collected in the monitored application.
     *
     * @param param
     *            selects the object from the bindings
     * @param bindings
     *            current bindings when the match was completed
     * @return the object which was bound to the given parameter. null, if the object was already garbage
     *         collected.
     */
    protected
 P getBoundObject(Parameter
 param, IBinding[] bindings) {
	// matches are rare, so we simply search the bindings linearly
	for (IBinding binding : bindings) {
	    if (binding != null && binding.getParameterId() == param.getParameterId()) {
		@SuppressWarnings("unchecked")
		P boundObject = (P) binding.get();
		return boundObject;
	    }
	}
	throw new IllegalArgumentException("Bound object for parameter ["
		+ "] coult not be retrieved from the bindings!");
    }

}

Add base class for handling matches


package com.xpn.xwiki.it.xmlrpc;

import java.net.URL;
import java.util.Map;

import junit.framework.TestCase;

import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.apache.xmlrpc.client.util.ClientFactory;
import com.xpn.xwiki.xmlrpc.ConfluenceRpcInterface;
import com.xpn.xwiki.xmlrpc.PageSummary;
import com.xpn.xwiki.xmlrpc.SpaceSummary;

public class AnonymousAccessTest extends TestCase
{
	private ConfluenceRpcInterface xwikiRpc;

	public void setUp() throws Exception
    {
        super.setUp();

        XmlRpcClient rpcClient = new XmlRpcClient();
        XmlRpcClientConfigImpl clientConfig = new XmlRpcClientConfigImpl();
        clientConfig.setServerURL(new URL("http://127.0.0.1:8080/xwiki/xmlrpc"));
        rpcClient.setConfig(clientConfig);

        ClientFactory factory = new ClientFactory(rpcClient);
        xwikiRpc = (ConfluenceRpcInterface) factory.newInstance(ConfluenceRpcInterface.class);

        // no login to get a token, use "" as a token
    }

    public void testReadAllPages() throws Exception
    {
        Object[] spaceObjs = getXWikiRpc().getSpaces("");
        for (int i = 0; i < spaceObjs.length; i++) {
        	SpaceSummary spaceSummary = new SpaceSummary((Map)spaceObjs[i]);
            String key = spaceSummary.getKey();
            Object[] pages = getXWikiRpc().getPages("", key);
            for (int j = 0; j < pages.length; j++) {
                PageSummary pageSummary = new PageSummary((Map)pages[j]);
                String id = pageSummary.getId();
                getXWikiRpc().getPage("", id);
            }
        }
    }

	private ConfluenceRpcInterface getXWikiRpc()
	{
		return xwikiRpc;
	}
}

Test for XWIKI-1558 (anonymous access via XMLRPC).


package org.ovirt.engine.core.common;

import org.junit.Test;

import java.util.BitSet;
import java.util.Set;
import java.util.TreeSet;

import static org.junit.Assert.assertTrue;

public class AuditLogTypeTest {

    private static final int bitsetSize = 12000;

    @Test
    public void testAuditLogTypeValueUniqueness() {
        BitSet bitset = new BitSet(bitsetSize);
        Set<Integer> nonUniqueValues = new TreeSet<Integer>();

        for (AuditLogType alt : AuditLogType.values()) {
            if (bitset.get(alt.getValue())) {
                nonUniqueValues.add(alt.getValue());
            }
            else {
                bitset.set(alt.getValue());
            }
        }
        assertTrue("AuditLogType contains the following non unique values: " + nonUniqueValues, nonUniqueValues.isEmpty());
    }
}

Add uniqueness test to AuditLogValue


package pl.komunikator.komunikator.adapter;

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

import java.util.List;

import pl.komunikator.komunikator.R;
import pl.komunikator.komunikator.entity.User;
import pl.komunikator.komunikator.viewHolder.EmptyViewHolder;

/**
 * Created by adrian on 22.05.2017.
 */

public class ConversationCreatorAdapter extends RecyclerView.Adapter {

    private static final int NO_CONTACTS = 404;
    private List<User> mContacts;

    public ConversationCreatorAdapter(List<User> contacts) {
        mContacts = contacts;
    }

    @Override
    public int getItemCount() {
        int size = mContacts.size();
        if (size > 0) {
            return size;
        } else {
            size += 1;
            return size;
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (mContacts.size() == 0) {
            return NO_CONTACTS;
        } else {
            return super.getItemViewType(position);
        }
    }

    public class CheckBoxedContactViewHolder extends RecyclerView.ViewHolder {

        public TextView nameTextView, emailTextView;
        public ImageView avatarImageView;
        public CheckBox checkBox;

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

            nameTextView = (TextView) view.findViewById(R.id.contactName);
            emailTextView = (TextView) view.findViewById(R.id.contactEmail);
            avatarImageView = (ImageView) view.findViewById(R.id.contactImageView);
            checkBox = (CheckBox) view.findViewById(R.id.contactCheckBox);
        }

    }

    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View view;

        if (viewType == NO_CONTACTS) {
            view = inflater.inflate(R.layout.item_no_results, parent, false);
            return new EmptyViewHolder(view);
        } else {
            view = inflater.inflate(R.layout.item_contact_checkbox, parent, false);
            return new CheckBoxedContactViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        if (getItemViewType(position) == NO_CONTACTS) {
            return;
        }

        User contact = mContacts.get(position);

        CheckBoxedContactViewHolder viewHolder = (CheckBoxedContactViewHolder) holder;
        viewHolder.nameTextView.setText(contact.getUsername());
        viewHolder.emailTextView.setText(contact.getEmail());
    }

}

Implement an adapter for checkBoxed contacts


package bisq.desktop;

import bisq.desktop.components.InputTextField;
import bisq.desktop.components.TitledGroupBg;
import bisq.desktop.util.FormBuilder;

import bisq.common.util.Tuple2;

import com.jfoenix.controls.JFXTextField;

import javafx.application.Application;

import javafx.stage.Stage;

import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

public class ComponentsDemo extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        GridPane gridPane = new GridPane();
        gridPane.getStyleClass().add("content-pane");
        gridPane.setVgap(20);

        int rowIndex = 0;

        final TitledGroupBg helloGroup = FormBuilder.addTitledGroupBg(gridPane, rowIndex++, 4, "Hello Group", 20);

        final Button button = FormBuilder.addButton(gridPane, rowIndex++, "Hello World");
        button.setDisable(true);
        button.getStyleClass().add("action-button");

        final Button buttonEnabled = FormBuilder.addButton(gridPane, rowIndex++, "Hello World");
        buttonEnabled.getStyleClass().add("action-button");

        final Tuple2<Label, InputTextField> inputTuple = FormBuilder.addLabelInputTextField(gridPane, rowIndex++, "Enter something title");
        InputTextField inputTextField = inputTuple.second;
        inputTextField.setLabelFloat(true);
        inputTextField.setPromptText("Enter something");

        final JFXTextField jfxTextField = new JFXTextField("US Dollar (USD)");
        jfxTextField.setLabelFloat(true);
        jfxTextField.setPromptText("Currency");

        final ComboBox<String> comboBox = FormBuilder.<String>addLabelComboBox(gridPane, rowIndex++, "Numbers", "Select number", 0).second;
        ObservableList list = FXCollections.observableArrayList();
        list.addAll("eins", "zwei", "drei");
        comboBox.setItems(list);

        Scene scene = new Scene(gridPane, 1000, 650);
        scene.getStylesheets().setAll(
                "/bisq/desktop/bisq.css",
                "/bisq/desktop/images.css");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

Add demo class to test customization of components


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

package net.uncontended.precipice.metrics;

import org.HdrHistogram.AtomicHistogram;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

public class DefaultLatencyMetricsTest {

    @Mock
    private AtomicHistogram histogram;

    private DefaultLatencyMetrics metrics;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);

        metrics = new DefaultLatencyMetrics(histogram);
    }

    @Test
    public void latencyIsStoredInHistogram() {
        when(histogram.getMaxValue()).thenReturn(10L);
        when(histogram.getValueAtPercentile(50.0)).thenReturn(2L);
        when(histogram.getValueAtPercentile(90.0)).thenReturn(7L);
        when(histogram.getValueAtPercentile(99.0)).thenReturn(8L);
        when(histogram.getValueAtPercentile(99.9)).thenReturn(9L);
        when(histogram.getValueAtPercentile(99.99)).thenReturn(9L);
        when(histogram.getValueAtPercentile(99.999)).thenReturn(10L);

        LatencyBucket snapshot = metrics.getLatencySnapshot();

        assertEquals(10L, snapshot.latencyMax);
        assertEquals(2L, snapshot.latency50);
        assertEquals(7L, snapshot.latency90);
        assertEquals(8L, snapshot.latency99);
        assertEquals(9L, snapshot.latency999);
        assertEquals(9L, snapshot.latency9999);
        assertEquals(10L, snapshot.latency99999);

    }
}

Add tests for latency util


package org.mashad.jbsbe.iso;

import java.time.LocalDateTime;
import java.time.YearMonth;

import org.mashad.jbsbe.annotation.AutoStan;
import org.mashad.jbsbe.annotation.Iso8583;
import org.mashad.jbsbe.annotation.IsoField;

import lombok.Builder;

@Iso8583(type=0x200)
@Builder
@AutoStan
public class PurchaseRequest3 {
	@IsoField(index=10)
	public LocalDateTime date;
	@IsoField(index=4)
	public Long amount;
	@IsoField(index=5)
	public YearMonth expirationDate;
	@IsoField(index=35)
	public String cardNumber;

}

Add needed request for test


package me.haosdent.cgroup.util;

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

public class TestThreads {

  @Before
  public void setUp() {}

  @After
  public void tearDown() {}

  @Test
  public void testGetThreadId() {}
}

Add threads util test class.


/**
 * Test if with else nested inside if without else, and also
 * precedence of logical OR and AND.
 *
 * @author Elvis Stansvik <elvstone@gmail.com>
 */
class IfElseInsideIfWithoutElse {
    public static void main(String[] arg) {
        int a;
        int b;
        int c;
        boolean A;
        boolean B;
        boolean C;
        A = true;
        B = true;
        C = false;

        a = 33;
        b = 5;
        c = 6;
        if (A)
            if (C || A && B)
                a = 1;
            else if (B && A)
                b = 2;
            else if (C)
                b = 3;
            else
                c = 3;

        // Expected is a = 1, b = 5, c = 6.
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
    }
}

Add test case for if with else inside if without else.


package liquibase.sqlgenerator.core;

import liquibase.database.Database;
import liquibase.database.core.FirebirdDatabase;
import liquibase.exception.ValidationErrors;
import liquibase.sql.Sql;
import liquibase.sql.UnparsedSql;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.statement.core.FindForeignKeyConstraintsStatement;

public class FindForeignKeyConstraintsGeneratorFirebird extends AbstractSqlGenerator<FindForeignKeyConstraintsStatement> {
    @Override
    public int getPriority() {
        return PRIORITY_DATABASE;
    }

    @Override
    public boolean supports(FindForeignKeyConstraintsStatement statement, Database database) {
        return database instanceof FirebirdDatabase;
    }

    @Override
    public ValidationErrors validate(FindForeignKeyConstraintsStatement findForeignKeyConstraintsStatement, Database database, SqlGeneratorChain sqlGeneratorChain) {
        ValidationErrors validationErrors = new ValidationErrors();
        validationErrors.checkRequiredField("baseTableName", findForeignKeyConstraintsStatement.getBaseTableName());
        return validationErrors;
    }

    @Override
    public Sql[] generateSql(FindForeignKeyConstraintsStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
        StringBuilder sb = new StringBuilder();

        sb.append("SELECT ");
        sb.append("a.RDB$RELATION_NAME as ").append(FindForeignKeyConstraintsStatement.RESULT_COLUMN_BASE_TABLE_NAME).append(", ");
        sb.append("b.RDB$FIELD_NAME as ").append(FindForeignKeyConstraintsStatement.RESULT_COLUMN_BASE_TABLE_COLUMN_NAME).append(", ");
        sb.append("d.RDB$RELATION_NAME as ").append(FindForeignKeyConstraintsStatement.RESULT_COLUMN_FOREIGN_TABLE_NAME).append(", ");
        sb.append("e.RDB$FIELD_NAME as ").append(FindForeignKeyConstraintsStatement.RESULT_COLUMN_FOREIGN_COLUMN_NAME).append(",");
        sb.append("a.RDB$CONSTRAINT_NAME as ").append(FindForeignKeyConstraintsStatement.RESULT_COLUMN_CONSTRAINT_NAME).append(" ");
        sb.append("FROM (((RDB$RELATION_CONSTRAINTS a LEFT OUTER JOIN RDB$INDEX_SEGMENTS b ON b.RDB$INDEX_NAME = a.RDB$INDEX_NAME) ");
        sb.append("LEFT OUTER JOIN RDB$INDICES c ON c.RDB$INDEX_NAME = a.RDB$INDEX_NAME) ");
        sb.append("LEFT OUTER JOIN RDB$RELATION_CONSTRAINTS d ON d.RDB$INDEX_NAME = c.RDB$FOREIGN_KEY AND d.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY') ");
        sb.append("LEFT OUTER JOIN RDB$INDEX_SEGMENTS e ON e.RDB$INDEX_NAME = d.RDB$INDEX_NAME AND e.RDB$FIELD_POSITION = b.RDB$FIELD_POSITION ");
        sb.append("WHERE a.RDB$RELATION_NAME='").append(statement.getBaseTableName()).append("' AND a.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY'");

        return new Sql[] { new UnparsedSql(sb.toString()) };
    }
}

Implement FindForeignKeyConstraintsGenerator for Firebird (CORE-2070)


package net.md_5.bungee.protocol;

import io.netty.buffer.ByteBuf;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
public class MinecraftInput
{

    private final ByteBuf buf;

    public byte readByte()
    {
        return buf.readByte();
    }

    public short readUnisgnedByte()
    {
        return buf.readUnsignedByte();
    }

    public int readInt()
    {
        return buf.readInt();
    }

    public String readString()
    {
        short len = buf.readShort();
        char[] c = new char[ len ];
        for ( int i = 0; i < c.length; i++ )
        {
            c[i] = buf.readChar();
        }

        return new String( c );
    }
}

package net.md_5.bungee.protocol;

import io.netty.buffer.ByteBuf;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
public class MinecraftInput
{

    private final ByteBuf buf;

    public byte readByte()
    {
        return buf.readByte();
    }

    public short readUnsignedByte()
    {
        return buf.readUnsignedByte();
    }

    public int readInt()
    {
        return buf.readInt();
    }

    public String readString()
    {
        short len = buf.readShort();
        char[] c = new char[ len ];
        for ( int i = 0; i < c.length; i++ )
        {
            c[i] = buf.readChar();
        }

        return new String( c );
    }
}

Fix typo in unused readUnsignedByte method of MinecraftProtocol


/*
 * Copyright 2017 Hex <hex@hex.lc>
 * and other copyright owners as documented in the project's IP log.
 *
 * 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.basinmc.sink.command;

import org.basinmc.faucet.command.Color;
import org.basinmc.faucet.command.Communicable;
import org.basinmc.faucet.command.annotation.Alias;
import org.basinmc.faucet.command.annotation.Command;
import org.basinmc.faucet.command.annotation.DateFormat;
import org.basinmc.faucet.command.annotation.Description;
import org.basinmc.faucet.command.annotation.Option;
import org.basinmc.faucet.command.annotation.Subcommand;
import org.basinmc.faucet.command.annotation.Supercommand;

import java.util.Optional;

// TODO - this class does nothing currently but serve as an example command implementation.
@Command("basinctl") // all hail our systemd overlords
@Alias("b")
@Description("Provides userspace access and control to server-specific functions.")
public class BasinCommand {
    @Supercommand
    public void printServerState(Communicable sender) {
        sender.sendMessage(Color.GOLD + "Basin Server Software");
    }

    @Subcommand("plugins")
    @Alias("pl")
    @Alias("bundles")
    @Description("List plugins.")
    public void plugins(Communicable sender,
                        @Option(desc = "Nicely format output in a table", shortOpt = 't', longOpt = "table") boolean table,
                        @Option(desc = "Hide initialization states", shortOpt = 'H', longOpt = "hide-init") boolean hideinit,
                        @Option(desc = "Show internal bundles", shortOpt = 'a', longOpt = "show-all") boolean all) {

    }

    @Subcommand("restart")
    @Alias("reload")
    @Description("Restart a bundle.")
    public void restart(Communicable sender,
                        @Option(desc = "Bundle to restart, defaults to the server") Optional<String> bundleName,
                        @Option(desc = "Delay before the restart occurs", shortOpt = 'd', longOpt = "delay") @DateFormat long delay,
                        @Option(desc = "Notify online players", shortOpt = 'n', longOpt = "notify") boolean notify) {

    }
}

Add an example command implementation.


/*
 * This file is part of Lorenz, licensed under the MIT License (MIT).
 *
 * Copyright (c) Jamie Mansfield <https://www.jamierocks.uk/>
 * 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 me.jamiemansfield.lorenz.test.model.jar;

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

import me.jamiemansfield.lorenz.model.jar.ArrayType;
import me.jamiemansfield.lorenz.model.jar.MethodDescriptor;
import me.jamiemansfield.lorenz.model.jar.ObjectType;
import me.jamiemansfield.lorenz.model.jar.PrimitiveType;
import me.jamiemansfield.lorenz.model.jar.Type;
import org.junit.Test;

/**
 * A variety of unit tests pertaining to the de-obfuscation
 * pertaining to {@link MethodDescriptor}.
 */
public final class TypeTest {

    @Test
    public void arrayType() {
        final String raw = "[[I";
        final Type type = Type.of(raw);
        assertTrue("Type should be an ArrayType!", type instanceof ArrayType);
        assertEquals(raw, type.getObfuscated());
        final ArrayType array = (ArrayType) type;
        assertEquals(2, array.getDimCount());
        assertEquals(PrimitiveType.INT, array.getComponent());
    }

    @Test
    public void objectTest() {
        final String raw = "Lme/jamiemansfield/Test;";
        final Type type = Type.of(raw);
        assertTrue("Type should be an ObjectType!", type instanceof ObjectType);
        assertEquals(raw, type.getObfuscated());
    }

    @Test
    public void primtiveTest() {
        final String raw = "Z";
        final Type type = Type.of(raw);
        assertTrue("Type should be an PrimitiveType!", type instanceof PrimitiveType);
        assertEquals(PrimitiveType.BOOLEAN, type);
        assertEquals(raw, type.getObfuscated());
    }

}

Add unit tests for type models


/**
 * Copyright (c) 2008-2012, http://www.snakeyaml.org
 *
 * 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.yaml.snakeyaml.issues.issue139;

import java.util.List;
import java.util.Map;

import junit.framework.TestCase;

import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeTuple;

public class UniqueKeyTest extends TestCase {

    public void testNotUnique() {
        String data = "{key: 1, key: 2}";
        Yaml yaml = new Yaml(new UniqueKeyConstructor());
        try {
            yaml.load(data);
            fail("The same key must be rejected");
        } catch (Exception e) {
            assertEquals("The key is not unique key", e.getMessage());
        }
    }

    private class UniqueKeyConstructor extends Constructor {

        @Override
        protected void constructMapping2ndStep(MappingNode node, Map<Object, Object> mapping) {
            List<NodeTuple> nodeValue = (List<NodeTuple>) node.getValue();
            for (NodeTuple tuple : nodeValue) {
                Node keyNode = tuple.getKeyNode();
                Node valueNode = tuple.getValueNode();
                Object key = constructObject(keyNode);
                if (key != null) {
                    key.hashCode();// check circular dependencies
                }
                Object value = constructObject(valueNode);
                Object old = mapping.put(key, value);
                if (old != null) {
                    throw new YAMLException("The key is not unique " + key);
                }
            }
        }
    }

}

Add example of unique keys


package com.novoda.merlin;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;

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

@RunWith(MerlinRobolectricTestRunner.class)
public class MerlinBuilderShould {

    @Test
    public void buildInstanceWithLoggingEnabled() throws Exception {
        Merlin merlin = new MerlinBuilder()
                .withLogging(true)
                .build(Robolectric.application);

        assertTrue(MerlinLog.LOGGING);
    }

    @Test
    public void buildInstanceWithLoggingDisabled() throws Exception {
        Merlin merlin = new MerlinBuilder()
                .withLogging(false)
                .build(Robolectric.application);

        assertFalse(MerlinLog.LOGGING);
    }

}

Test that the merlin builder configures logging appropriately


import java.util.*;

class Fibonacci {

    static int nth_fibonacci(int n) {
        if(n<=1) {
            return n;
        }

        // Create dp array
        int dp[] = new int[n + 1];

        // Initialise first two elements
        dp[0] = 0;
        dp[1] = 1;

        // Build dp array
        for(int i = 2; i <= n; i++) {
            dp[i] = dp[i - 1] + dp[i - 2];
        }

        // Return nth element
        return dp[n];
    }

    public static void main(String[] args) {
        int n = 4;
        System.out.println(nth_fibonacci(n)); // 3
    }
}

Add Java implementation for Nth Fibonacci number


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

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import nom.bdezonia.zorbage.algebras.G;
import nom.bdezonia.zorbage.type.data.float64.real.Float64MatrixMember;
import nom.bdezonia.zorbage.type.data.float64.real.Float64Member;

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

	@Test
	public void test1() {

		Float64Member result = G.DBL.construct();
		Float64MatrixMember matrix = new Float64MatrixMember(
				3, 3, new double[] {0,1,2,
						            3,4,5,
						            6,7,8});
		MatrixTrace.compute(G.DBL, matrix, result);
		assertEquals(12, result.v(), 0);
	}
}

Define a test for the MatrixTrace algorithm


package com.silverpeas.notification.mock;

import javax.inject.Named;

import com.silverpeas.admin.notification.AdminNotificationService;

@Named("adminNotificationService")
public class AdminNotificationServiceMock implements AdminNotificationService {

  @Override
  public void notifyOnDeletionOf(String spaceId, String userId) {

  }

}

Fix a test issue with the new event notification from the admin component


package com.haxademic.demo.camera;

import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.camera.CameraUtil;
import com.haxademic.core.draw.context.DrawUtil;

public class Demo_CameraUtil_setCameraDistance
extends PAppletHax {
	public static void main(String args[]) { PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); }

	protected String DIST = "DIST";
	protected String NEAR = "NEAR";

	public void setupFirstFrame() {
		p.prefsSliders.addSlider(DIST, 4000, 100, 20000, 100, false);
		p.prefsSliders.addSlider(NEAR, 100, 100, 10000, 10, false);
	}

	public void drawApp() {
		p.background(0);
		DrawUtil.setCenterScreen(p);
		DrawUtil.setDrawCenter(p);

		int maxDist = (int) p.prefsSliders.value(DIST);
		int minDist = (int) p.prefsSliders.value(NEAR);
		CameraUtil.setCameraDistance(p.g, minDist, maxDist);

		p.fill(255);
		p.stroke(0);
		p.strokeWeight(1);
		int zStep = 500;
		for (int i=0; i < 20000; i += zStep) {
			p.pushMatrix();
			p.translate(0, 0, -i);
			p.rotateX(i);
			p.rotateY(i);
			p.box(i/3);
			p.popMatrix();
		}

		CameraUtil.resetCamera(p.g);
		p.camera();
	}
}

Test to increase camera distance


/*
 * Copyright 2017 The Closure Compiler 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 com.google.javascript.jscomp;

Add @nocollapse to deps methods of [] objects. These deps method are called by the framework, so they shouldn't be collapsed.


package com.google.sps.servlets;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.UserRecord;
import com.google.sps.firebase.FirebaseAppManager;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

// Retrieve the number of visits per class from Visit entity and send to chart
@WebServlet("/visits")
public class Visits extends HttpServlet {
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    ArrayList<String> listOfClassNames = new ArrayList<String>();
    ArrayList<Integer> visitsPerClass = new ArrayList<Integer>();

    // Obtain visits from datastore and filter them into results query
    Query query = new Query("Visit");
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    PreparedQuery results = datastore.prepare(query);

    // Store the class name and number of visits into two separate lists
    for (Entity entity : results.asIterable()) {
      String className = entity.getProperty("???");
      Integer classVisits = entity.getProperty("numVisits");

      listOfClassNames.add(className);
      visitsPerClass.add(classVisits);
    }
  }
}

Create visits servlet and obtain visits queries from datastore.


package test.blog.distrib;

import static org.junit.Assert.assertEquals;

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

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

import blog.common.Util;
import blog.common.numerical.JamaMatrixLib;
import blog.common.numerical.MatrixLib;
import blog.distrib.Laplace;
import blog.model.BuiltInTypes;

/**
 * A test class to verify the Laplace distribution
 *
 * @author awong
 */
public class LaplaceTest {

	private static final double MEAN = 0.0;

	private static final double DIVERSITY = 1.0;
	//private static final double MAX_DIFF_DOUBLE = 1e-10;

	private Laplace distrib;
	private static final int NUM_OF_SAMPLES = 1000;

	@Before
	public void createLaplace() {
		distrib = new Laplace(MEAN, DIVERSITY);

	}

	@Test
	public void testSampleVal() {
		Util.initRandom(true);
		double sample, sample_mean = 0, sample_variance = 0;
		System.out.println("Number of samples: " + NUM_OF_SAMPLES);
		System.out.print("Samples: ");
		for(int i = 0; i < NUM_OF_SAMPLES; i++) {
			sample = distrib.sampleVal();
			System.out.print(sample + "\t");
			sample_mean += sample;
			sample_variance += sample * sample;
		}
		sample_mean /= NUM_OF_SAMPLES;
		sample_variance = (sample_variance - NUM_OF_SAMPLES * sample_mean * sample_mean) / (NUM_OF_SAMPLES - 1);
		System.out.println();
		System.out.println("Sample mean: " + sample_mean + ", true mean: " + distrib.getMean());
		System.out.println("Sample variance: " + sample_variance + ", true variance: " + distrib.getVariance());
	}

	@Test
	public void testToString() {
		System.out.println(distrib.toString());
	}
}

Add a test for Laplace distribution -- by Da Tang


/*
 * Copyright 2014 Open mHealth
 *
 * 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.openmhealth.schema.domain;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;

/**
 * A suite of unit tests for schema version objects.
 */
@RunWith(BlockJUnit4ClassRunner.class)
public class SchemaVersionUnitTests {

    @Test(expected = NullPointerException.class)
    public void stringConstructorShouldThrowExceptionOnUndefinedVersion() {

        new SchemaVersion(null);
    }

    @Test(expected = IllegalArgumentException.class)
    public void stringConstructorShouldThrowExceptionOnNegativeMajorVersion() {

        new SchemaVersion("-2.1");
    }

    @Test(expected = IllegalArgumentException.class)
    public void stringConstructorShouldThrowExceptionOnMalformedMajorVersion() {

        new SchemaVersion("a.1");
    }

    @Test(expected = IllegalArgumentException.class)
    public void stringConstructorShouldThrowExceptionOnNegativeMinorVersion() {

        new SchemaVersion("2.-1");
    }

    @Test(expected = IllegalArgumentException.class)
    public void stringConstructorShouldThrowExceptionOnMalformedMinorVersion() {

        new SchemaVersion("2.a");
    }

    @Test(expected = IllegalArgumentException.class)
    public void stringConstructorShouldThrowExceptionOnMalformedQualifier() {

        new SchemaVersion("2.1.%");
    }

    @Test
    public void stringConstructorShouldSupportZeroMajorVersion() {

        SchemaVersion schemaVersion = new SchemaVersion("0.1");

        assertThat(schemaVersion, notNullValue());
        assertThat(schemaVersion.getMajor(), equalTo(0));
        assertThat(schemaVersion.getMinor(), equalTo(1));
        assertThat(schemaVersion.getQualifier().isPresent(), equalTo(false));
    }

    @Test
    public void stringConstructorShouldSupportZeroMinorVersion() {

        SchemaVersion schemaVersion = new SchemaVersion("3.0");

        assertThat(schemaVersion, notNullValue());
        assertThat(schemaVersion.getMajor(), equalTo(3));
        assertThat(schemaVersion.getMinor(), equalTo(0));
        assertThat(schemaVersion.getQualifier().isPresent(), equalTo(false));
    }

    @Test
    public void stringConstructorShouldSupportQualifier() {

        SchemaVersion schemaVersion = new SchemaVersion("2.1.RELEASE");

        assertThat(schemaVersion, notNullValue());
        assertThat(schemaVersion.getMajor(), equalTo(2));
        assertThat(schemaVersion.getMinor(), equalTo(1));
        assertThat(schemaVersion.getQualifier().isPresent(), equalTo(true));
        assertThat(schemaVersion.getQualifier().get(), equalTo("RELEASE"));
    }

    // TODO add more tests
}

Add schema version unit tests.


package leetcode.implement_strstr;

public class Solution {
	public int[] build_table(char[] haystack){
		int length = haystack.length;
		int[] table = new int[length];
		int pos = 2;
		int cnd = 0;
		table[0] = -1;
		if(table.length > 1)
			table[1] = 0;
		while(pos < length){
			if(haystack[pos - 1] == haystack[cnd]){
				table[pos++] = ++cnd;
			}else if(cnd > 0){
				cnd = table[cnd];
			}else{
				table[pos++] = 0;
			}
		}
		return table;
	}

    public String strStr(String haystack, String needle) {
    	if(haystack == null) return null;
    	if(needle.length() == 0) return haystack;
    	if(haystack.length() == 0) return null;
    	char[] S = haystack.toCharArray();
    	char[] W = needle.toCharArray();
        int[] T = build_table(W);
        int m = 0;
        int i = 0;
        while(m + i < S.length){
        	if(W[i] == S[m + i]){
        		if(i == W.length - 1){
        			return new String(S, m, S.length - m);
        		}
        		i++;
        	}else{
        		m = m + i - T[i];
        		if(T[i] > -1){
        			i = T[i];
        		}else{
        			i = 0;
        		}
        	}
        }
        return null;
    }

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

Add java solution for 28. Implement strStr()


package org.hibernate.protean.substitutions;

import java.util.Map;
import javax.management.ObjectName;

import org.hibernate.jmx.spi.JmxService;
import org.hibernate.service.Service;
import org.hibernate.service.spi.Manageable;

import com.oracle.svm.core.annotate.Substitute;
import com.oracle.svm.core.annotate.TargetClass;

@TargetClass(className = "org.hibernate.jmx.internal.JmxServiceImpl")
@Substitute
public final class JmxServiceImpl implements JmxService {

	@Substitute
	public JmxServiceImpl(Map configValues) {
		//ignored but needs to exist
	}

	@Override
	public void registerService(Manageable service, Class<? extends Service> serviceRole) {
		//no-op
	}

	@Override
	public void registerMBean(ObjectName objectName, Object mBean) {
		//no-op
	}
}

Disable the Hibernate JMX integration


package com.ruigoncalo.marvin.utils;

import android.support.v4.view.ViewPager;
import android.view.View;

/**
 * Font: http://developer.android.com/training/animation/screen-slide.html
 *
 * Created by ruigoncalo on 28/04/16.
 */
public class ZoomOutPageTransformer implements ViewPager.PageTransformer {
    private static final float MIN_SCALE = 0.85f;
    private static final float MIN_ALPHA = 0.5f;

    public void transformPage(View view, float position) {
        int pageWidth = view.getWidth();
        int pageHeight = view.getHeight();

        if (position < -1) { // [-Infinity,-1)
            // This page is way off-screen to the left.
            view.setAlpha(0);

        } else if (position <= 1) { // [-1,1]
            // Modify the default slide transition to shrink the page as well
            float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
            float vertMargin = pageHeight * (1 - scaleFactor) / 2;
            float horzMargin = pageWidth * (1 - scaleFactor) / 2;
            if (position < 0) {
                view.setTranslationX(horzMargin - vertMargin / 2);
            } else {
                view.setTranslationX(-horzMargin + vertMargin / 2);
            }

            // Scale the page down (between MIN_SCALE and 1)
            view.setScaleX(scaleFactor);
            view.setScaleY(scaleFactor);

            // Fade the page relative to its size.
            view.setAlpha(MIN_ALPHA +
                    (scaleFactor - MIN_SCALE) /
                            (1 - MIN_SCALE) * (1 - MIN_ALPHA));

        } else { // (1,+Infinity]
            // This page is way off-screen to the right.
            view.setAlpha(0);
        }
    }
}

Create pager transformer for collections screen


package util;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Streaming;

/**
 * Retrofit wrapper interface to Filestack endpoints served by CDN.
 */
public interface CdnService {
    String URL = "https://cdn.filestackcontent.com/";

    @GET("{handle}")
    @Streaming
    Call<ResponseBody> get(@Path("handle") String handle);
}

Add wrapper for Filestack CDN endpoints.


/**
 * This Source Code Form is subject to the terms of the Mozilla Public License,
 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
 * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
 * the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
 *
 * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
 * graphic logo is a trademark of OpenMRS Inc.
 */
package org.openmrs.customdatatype.datatype;

import org.apache.commons.lang.StringUtils;
import org.openmrs.Concept;
import org.openmrs.api.context.Context;
import org.openmrs.customdatatype.CustomDatatype;

/**
 * This is a class for custom datatypes for concepts
 *
 * @since 2.0
 */
public class ConceptDatatype extends BaseOpenmrsDatatype<Concept> {

	/**
	 * @see org.openmrs.customdatatype.SerializingCustomDatatype#deserialize(String)
	 * @override
	 */
	public Concept deserialize(String uuid) {
		if (StringUtils.isBlank(uuid)) {
			return null;
		}
		return Context.getConceptService().getConceptByUuid(uuid);
	}

	/**
	 * @see BaseOpenmrsDatatype#doGetTextSummary(Object)
	 * @should use the name in summary instance
	 */
	@Override
	public Summary doGetTextSummary(Concept concept) {
		String name = "";
		if (concept.getName() != null) {
			name = concept.getName().getName();
		}
		return new CustomDatatype.Summary(name, true);
	}
}

Create a custom data type and its associated handler for concepts - TRUNK-3621


package org.reactivecouchbase.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class NamedExecutors {

    public static ScheduledExecutorService newFixedThreadPool(final int size, final String prefix) {
        return Executors.newScheduledThreadPool(size, new ThreadFactory() {
            AtomicInteger counter = new AtomicInteger(0);
            @Override
            public Thread newThread(Runnable runnable) {
                return new Thread(runnable, prefix + "-" + counter.incrementAndGet());
            }
        });
    }

    public static ExecutorService newCachedThreadPool(final String prefix) {
        return Executors.newCachedThreadPool(new ThreadFactory() {
            AtomicInteger counter = new AtomicInteger(0);
            @Override
            public Thread newThread(Runnable runnable) {
                return new Thread(runnable, prefix + "-" + counter.incrementAndGet());
            }
        });
    }

    public static ScheduledExecutorService newSingleThreadPool(final String prefix) {
        return Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
            AtomicInteger counter = new AtomicInteger(0);

            @Override
            public Thread newThread(Runnable runnable) {
                return new Thread(runnable, prefix + "-" + counter.incrementAndGet());
            }
        });
    }
}

Add API to easily create named Executors


package org.tapestry.objects;

public class DisplayedSurveyResult {
	private String questionId;
	private String questionAnswer;
	private String observerNotes;
	private String title;
	private String date;

	public DisplayedSurveyResult(){

	}

	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getDate() {
		return date;
	}
	public void setDate(String date) {
		this.date = date;
	}
	public String getQuestionId() {
		return questionId;
	}
	public void setQuestionId(String questionId) {
		this.questionId = questionId;
	}
	public String getQuestionAnswer() {
		return questionAnswer;
	}
	public void setQuestionAnswer(String questionAnswer) {
		this.questionAnswer = questionAnswer;
	}
	public String getObserverNotes() {
		return observerNotes;
	}
	public void setObserverNotes(String observerNotes) {
		this.observerNotes = observerNotes;
	}

}

Add new bean for survey


package com.google.sps.servlets;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.sps.data.User;
import com.google.sps.utilities.Constants;
import com.google.sps.utilities.DatabaseWrapper;
import java.io.IOException;
import java.util.HashSet;
import java.util.Arrays;
import java.util.Set;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Servlet that handles user profile edits. */
@WebServlet("/profile-update")
public class UserProfileUpdateServlet extends HttpServlet {
  private static final String email = UserServiceFactory.getUserService().getCurrentUser().getEmail();
  private DatabaseWrapper databaseWrapper = new DatabaseWrapper(Constants.DB_INSTANCEID, Constants.DB_DATABASEID);

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    User user = databaseWrapper.readUserFromEmail(email);
    String userJson = Json.createObjectBuilder()
        .add("name", user.getName())
        .add("email", email)
        .add("interests", createJsonArray(user.getInterests()))
        .add("skills", createJsonArray(user.getSkills()))
        .build()
        .toString();
    response.setContentType("application/json;");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().println(userJson);
  }

  public JsonArray createJsonArray(Set<String> elements) {
    JsonArrayBuilder builder = Json.createArrayBuilder();
    for (String element : elements) {
      builder.add(element);
    }
    return builder.build();
  }

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Get the input from the form.
    String name = request.getParameter("name");
    Set<String> interests = new HashSet<>(Arrays.asList(request.getParameter("interests")));
    Set<String> skills = new HashSet<>(Arrays.asList(request.getParameter("skills")));

    User updatedUser =
        new User.Builder(name, email)
            .setInterests(interests)
            .setSkills(skills)
            .build();
    databaseWrapper.insertOrUpdateUser(updatedUser);
    response.sendRedirect("/profile.html");
  }
}

Add user profile update servlet


package eu.danieldk.dictomaton.levenshtein;

interface ParametricTransitions
{
    /**
     * The number of edit operations this parametric transition table is for.
     * @return The number of edit operations.
     */
    public int nEditOperations();

    /**
     * The number of parametric states in the parametric transition table.
     * @return The number of parametric states.
     */
	public int nParametricStates();

    /**
     * The maximum allowed number of offset errors per parametric state.
     * @param parametricState The parametric state.
     * @return The allowed offset error.
     */
    public int maxOffsetErrors(int parametricState);

    /**
     * The transition function.
     * @param fromState The (non-parametric) from-state.
     * @param position The word position.
     * @param characteristicVector The characteristic vector.
     * @param len The length of the word.
     * @return
     */
    public int transition(int fromState, int position, int characteristicVector, int len);
}

Add the interface for parametric transitions.


package com.adenki.smpp.util;

/**
 * Some string utility methods.
 * @version $Id:$
 */
public final class StringUtil {

    private StringUtil() {
    }

    /**
     * Return a Java String with any non-ASCII characters escaped using "\u"
     * notation.
     * @param s The string to escape.
     * @return A new String with non-ASCII characters escaped.
     */
    public static final String escapeJava(String s) {
        StringBuilder b = new StringBuilder(s.length());
        for (char c : s.toCharArray()) {
            if (Character.isLetterOrDigit(c)) {
                b.append(c);
            } else {
                b.append(String.format("\\u%04x", (int) c));
            }
        }
    }
}

Add a String processing utility class


package com.cjm721.overloaded.storage.builder;

import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilityProvider;

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

public class CapabilityContainer implements ICapabilityProvider {

    @Nonnull
    private List<ICapabilityProvider> capabilityProviders;

    public CapabilityContainer() {
        capabilityProviders = new ArrayList<>();
    }

    public CapabilityContainer addCapability(ICapabilityProvider capabilityProvider) {
        capabilityProviders.add(capabilityProvider);
        return this;
    }

    public CapabilityContainer addCapability(Collection<ICapabilityProvider> capabilityProvider) {
        capabilityProviders.addAll(capabilityProvider);
        return this;
    }

    @Override
    public boolean hasCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing facing) {
        return capabilityProviders.stream().anyMatch(cap -> cap.hasCapability(capability, facing));
    }

    @Nullable
    @Override
    public <T> T getCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing) {
        return capabilityProviders.stream().map(cap -> cap.getCapability(capability, facing)).filter(o -> o != null).findAny().orElse(null);
    }
}

Create a way to add multiple Capabilities to a single item nicely


/**
 * @see Indexing and PSI Stubs in IntelliJ IDEA
 *
 * @see Lifecycle of stub creation
 */
package com.intellij.psi.stubs;

Package info with links to confluence added


package org.bitcoinj.core;

/**
 * Created by Hash Engineering on 6/26/2017.
 *
 * This is a wrapper to allow a message to be ignored that bitcoinj
 * will not process.  This will prevent the peer from being rejected.
 */
public class IgnoreThisMessage extends EmptyMessage {

    public IgnoreThisMessage(NetworkParameters params) {
        super(params);
        length = 0;
    }
}

Add class for messages that will be ignored.


package alluxio.master.block;

import alluxio.AlluxioURI;
import alluxio.client.WriteType;
import alluxio.client.file.FileSystem;
import alluxio.client.file.FileSystemTestUtils;
import alluxio.client.file.URIStatus;
import alluxio.exception.BlockInfoException;
import alluxio.master.LocalAlluxioCluster;
import alluxio.master.MasterRegistry;
import alluxio.master.MasterTestUtils;
import alluxio.wire.WorkerNetAddress;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.util.concurrent.ExecutorService;

import static org.junit.Assert.fail;

/**
 * Integration test for block master functionality.
 */
public class BlockMasterIntegrationTest {

  private ExecutorService mExecutorsForClient;
  private LocalAlluxioCluster mCluster;

  @Before
  public void before() throws Exception {
    mCluster = new LocalAlluxioCluster();
    mCluster.initConfiguration();
    mCluster.start();
  }

  @Test
  public void journalBlockDeletion() throws Exception {
    FileSystem fs = mCluster.getClient();
    BlockMaster blockMaster = mCluster.getLocalAlluxioMaster().getMasterProcess().getMaster(BlockMaster.class);
    AlluxioURI file = new AlluxioURI("/test");
    FileSystemTestUtils.createByteFile(fs, file, WriteType.MUST_CACHE, 10);
    URIStatus status = fs.getStatus(file);
    Long blockId = status.getBlockIds().get(0);
    Assert.assertNotNull(blockMaster.getBlockInfo(blockId));
    fs.delete(file);
    WorkerNetAddress workerAddress = mCluster.getWorkerAddress();
    try {
      blockMaster.getBlockInfo(blockId);
      fail("Expected the block to be deleted");
    } catch (BlockInfoException e) {
      // expected
    }
    mCluster.stop();
    MasterRegistry registry = MasterTestUtils.createLeaderFileSystemMasterFromJournal();
    try {
      registry.get(BlockMaster.class).getBlockInfo(blockId);
      fail("Expected the block to be deleted after restart");
    } catch (BlockInfoException e) {
      // expected
    }
    registry.stop();
  }
}

Add test for block deletion journaling


package ch.tkuhn.memetools;

import java.io.File;

import com.beust.jcommander.JCommander;
import com.beust.jcommander.ParameterException;

public class PrepareWosData {

	private File logFile;

	public static final void main(String[] args) {
		PrepareWosData obj = new PrepareWosData();
		JCommander jc = new JCommander(obj);
		try {
			jc.parse(args);
		} catch (ParameterException ex) {
			jc.usage();
			System.exit(1);
		}
		obj.run();
	}

	// Data format: semicolon-delimited with the following columns:
	//
    // 0 t9 (9 last digits)
    // 1 year
    // 2 documentType (one letter)
    // 3 doi (optional)
    // 4 subject (two letters, optional)
    // 5 iso journal (optional)
    // 6 volume
    // 7 issue
    // 8 pages
    // 9 title
    // 10 noOfAuthors
    // 11.. authors
    // 11+noOfAuthors noOfJournals
    // 12+noOfAuthors... journals (other journal labels)
    // 12+noOfAuthors+noOfJournals summary (optional)
    // 13+noOfAuthors+noOfJournals references (non-delimited t9)
    // 14+noOfAuthors+noOfJournals citations (non-delimited t9)

	public PrepareWosData() {
	}

	public void run() {
		init();
		log("Finished");
	}

	private void init() {
		logFile = new File(MemeUtils.getLogDir(), "prepare-aps.log");
		log("==========");
		log("Starting...");
	}

	private void log(Object obj) {
		MemeUtils.log(logFile, obj);
	}

}

Add stub class to process WoS data


package com.tlswe.awsmock.common.exception;

import org.junit.Test;

public class AwsMockExceptionTest {

    @Test(expected=AwsMockException.class)
    public void TestAwsMockExceptionMessageAndThrowable(){
        throw new AwsMockException("AWS Mock Exception", new Exception());
    }

    @Test(expected=AwsMockException.class)
    public void TestAwsMockExceptionMessageOnly(){
        throw new AwsMockException("AWS Mock Exception");
    }

    @Test(expected=AwsMockException.class)
    public void TestAwsMockExceptionThrowableOnly(){
        throw new AwsMockException(new Exception());
    }

}

Complete unit test for AwsMockException


package com.farmerbb.taskbar.util;

import android.content.Context;

import androidx.test.core.app.ApplicationProvider;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;

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

@RunWith(RobolectricTestRunner.class)
public class TopAppsTest {
    private Context context;
    private TopApps topApps;

    @Before
    public void setUp() {
        context = ApplicationProvider.getApplicationContext();
        topApps = TopApps.getInstance(context);
    }

    @Test
    public void testGetInstance() {
        assertNotNull(topApps);
        for (int i = 1; i <= 20; i++) {
            assertEquals(topApps, TopApps.getInstance(context));
        }
    }

    @Test
    public void testIsTopApp() {
        assertFalse(topApps.isTopApp(context.getPackageName()));
        addCurrentPackageToTopApps();
        assertTrue(topApps.isTopApp(context.getPackageName()));
        topApps.removeTopApp(context, context.getPackageName());
    }

    @Test
    public void testRemoveTopApp() {
        addCurrentPackageToTopApps();
        assertTrue(topApps.isTopApp(context.getPackageName()));
        topApps.removeTopApp(context, context.getPackageName());
        assertFalse(topApps.isTopApp(context.getPackageName()));
    }

    private void addCurrentPackageToTopApps() {
        String packageName = context.getPackageName();
        BlacklistEntry entry = new BlacklistEntry(packageName, packageName);
        topApps.addTopApp(context, entry);
    }
}

Add unit tests for TopApps


package com.vmware.loginsight.send;

import java.util.List;

public class LogUploadClient {
	public final String url;
	public final int port;
	public final LogInsigntProtocol proto;

	public LogUploadClient(String url, int port, LogInsigntProtocol proto) {
		this.url = url;
		this.port = port;
		this.proto = proto;

		assert (!proto.equals(LogInsigntProtocol.UNKNOWN));
	}

	private LogUploadClientReturnStatus sendMessageBySyslog(String msg, List<Field> fields, List<String> filters) {
		return null;
	}

	private LogUploadClientReturnStatus sendMessageByHttp(String msg, List<Field> fields, List<String> filters) {
		return null;
	}

	public LogUploadClientReturnStatus sendMessage(String msg, List<Field> fields, List<String> filters) {
		assert (msg != null);
		assert (fields != null);

		if (proto.isSyslog()) {
			return sendMessageBySyslog(msg, fields, filters);
		} else {
			return sendMessageByHttp(msg, fields, filters);
		}
	}

	public enum LogInsigntProtocol {
		SYSLOG_TCP(1), SYSLOG_UDP(2), SYSLOG_TLS(3), HTTP(4),

		UNKNOWN(0);

		private int value;

		private LogInsigntProtocol(int value) {
			this.value = value;
		}

		public int getValue() {
			return value;
		}

		public boolean isSyslog() {
			return (this.equals(SYSLOG_TCP) || this.equals(SYSLOG_UDP) || this
					.equals(SYSLOG_TLS));
		}
	}

	public enum LogUploadClientReturnStatus {
		FAIL(-1),
		SUCCESS(1);

		int value;
		private LogUploadClientReturnStatus(int value) {
			this.value = value;
		}

	}

	public static class Field {
		public String key;
		public String value;

		public Field(String key, String value) {
			this.key = key;
			this.value = value;
		}
	}
}

Add LogInsightClient.java as a starting point of message sending library


//
// Triple Play - utilities for use in PlayN-based games
// Copyright (c) 2011-2012, Three Rings Design, Inc. - All rights reserved.
// http://github.com/threerings/tripleplay/blob/master/LICENSE

package tripleplay.game.trans;

import tripleplay.game.Screen;
import tripleplay.game.ScreenStack;

/**
 * Fades the new screen in front of the old one.
 */
public class FadeTransition extends InterpedTransition<SlideTransition>
{
    public FadeTransition (ScreenStack stack) {
    }

    @Override public boolean update (Screen oscreen, Screen nscreen, float elapsed) {
        float nalpha = _interp.apply(0, 1, elapsed, _duration);
        nscreen.layer.setAlpha(nalpha);
        return elapsed >= _duration;
    }

    @Override public void complete (Screen oscreen, Screen nscreen) {
        super.complete(oscreen, nscreen);
        nscreen.layer.setAlpha(1);
    }
}

Add a really simple transition that fades in a new screen.


package VQVAD;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;

import Utils.Player;

import Frontend.VQVoiceActivityDetector;

public class PlaybackTest {

	private static AudioInputStream copyAis(AudioInputStream source, AudioFormat format) {
		boolean run = true;
		int i = 0;
		int buffer_size = 4000;
		byte tempBuffer[] = new byte[buffer_size];
		ByteArrayOutputStream debugStream = new ByteArrayOutputStream();

		while (run) {
			int cnt = -1;
			try {//read data from the audio input stream
				cnt = source.read(tempBuffer, 0, buffer_size);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			if (cnt > 0) {//if there is data
				try {
					debugStream.write(tempBuffer);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				run = false;
			}
		}

		return new AudioInputStream (new ByteArrayInputStream(debugStream.toByteArray()), format, debugStream.size());
	}

	/**
	 * @param args
	 * @throws MalformedURLException
	 */
	public static void main(String[] args) throws MalformedURLException {

		VQVoiceActivityDetector vac = new VQVoiceActivityDetector(null, "foo");

		AudioInputStream debugAis = copyAis(vac, vac.getFormat());

		Player.playStream(debugAis);

	}

}

Test class for playing back VAD stream


package br.com.bloder.better_migrations.migrations;

import br.com.bloder.migration.Migration;
import io.realm.DynamicRealm;

/**
 * Created by bloder on 25/09/16.
 */
public class VersionOne extends Migration {

  @Override
  public void up(DynamicRealm realm) {
    realm.getSchema().get("User").addField("age", Integer.class);
  }

  @Override
  public void down(DynamicRealm realm) {
    realm.getSchema().get("User").removeField("age");
  }
}

Create example realm config version one migration


package net.imagej.ops.views;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.Offset;
import net.imglib2.RandomAccessible;
import net.imglib2.view.MixedTransformView;
import net.imglib2.view.Views;

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

@Plugin(type = ViewOps.Offset.class, name = ViewOps.Offset.NAME)
public class DefaultOffset<T> extends
		AbstractView<RandomAccessible<T>, MixedTransformView<T>> implements
		Offset<RandomAccessible<T>, MixedTransformView<T>> {

	@Parameter(type = ItemIO.INPUT)
	private long[] offset;

	@Override
	public MixedTransformView<T> compute(RandomAccessible<T> input) {
		return Views.offset(input, offset);
	}

}

Add default implementation of Offset interface.


import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

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

@RunWith(MockitoJUnitRunner.class)
public class TennisGameTest {

    @InjectMocks
    private TennisGame tennisGame;

    @Mock
    private TennisGameScore tennisGameScore;

    @Before
    public void setUp() {
        initTennisGameScore();
    }

    @Test
    public void should_federer_wins_point_when_it_has_an_even_number() {
        assertThat(tennisGame.isFedererWinPoint(2)).isTrue();
    }

    private void initTennisGameScore() {
        tennisGameScore.init();
        tennisGameScore.addPoint(0, 1, "Nadal");
        tennisGameScore.addPoint(0, 2, "Nadal");
        tennisGameScore.addPoint(0, 3, "Nadal");
        tennisGameScore.addPoint(0, 4, "Nadal");
    }

}

Test on winning point for Federer


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.new_liberty.itemconomy.commands;

import net.new_liberty.itemconomy.BankAccount;
import net.new_liberty.itemconomy.CurrencyInventory;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

/**
 *
 * @author simplyianm
 */
public class ICBalance implements CommandExecutor {

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!sender.hasPermission("itemconomy.console")) {
            sender.sendMessage(ChatColor.RED + "Not allowed...");
            return true;
        }

        if (args.length < 1) {
            sender.sendMessage(ChatColor.RED + "Usage: /icbalance <player>");
            return true;
        }

        BankAccount b = new BankAccount(args[0]);

        sender.sendMessage(ChatColor.YELLOW + args[0] + "'s balance is " + b.balance() + " emeralds.");
        return true;
    }

}

Add command to check player balance.


package info.maccac.recorder;

import com.intellij.execution.testframework.AbstractTestProxy;

import java.util.List;
import java.util.stream.Collectors;

final class TestResultsConverter {

    private TestResultsConverter() {
    }

    static TestResults breakdown(String projectName, AbstractTestProxy testProxy) {
        return new TestResults(projectName, new TestResult(null, testProxy.getName(), testProxy.getDuration(), getChildren(testProxy)));
    }

    private static List<TestResult> getChildren(AbstractTestProxy testProxy) {
        return testProxy
                .getChildren().stream()
                .map(p -> new TestResult(p.getParent().getName(), p.getName(), p.getDuration(), getChildren(p)))
                .collect(Collectors.toList());
    }
}

Add TestResultConverter to assist in changing intelliJ type