package org.jenkinsci.plugins.radargun.model.impl;

import static org.junit.Assert.assertArrayEquals;

import org.jenkinsci.plugins.radargun.model.SlaveScriptConfig;
import org.junit.Test;

public class SlaveShellScriptTest {

    @Test
    public void testCmdLine() {
        SlaveScriptConfig slave = new SlaveShellScript();
        slave.withSlaveIndex(1)
            .withPlugin("testPlugin")
            .withTailFollow()
            .withWait()
            .withScriptPath("/tmp/slave.sh");

        assertArrayEquals(new String[] {"/bin/sh", "/tmp/slave.sh", "-t", "-w", "--add-plugin", "testPlugin", "-i","1"}, slave.getScriptCmd());
    }
}

Add slave cmd line test


package org.apache.markt.leaks.awt;

import org.apache.markt.leaks.LeakBase;

/**
 * Java 5 - leaks
 * Java 6 - leaks
 * Java 7
 *  - update <=51 - leaks
 *  - update >=55 - no leak
 * Java 8
 *  - update 00   - leaks
 *  - update >=05 - no leak
 */
public class AwtThreadLeak extends LeakBase {

    public static void main(String[] args) {
        AwtThreadLeak awtThreadLeak = new AwtThreadLeak();
        awtThreadLeak.doLeakTest();
    }

    @Override
    protected void createLeakingObjects() {
        java.awt.Toolkit.getDefaultToolkit();
    }

    @Override
    protected void cleanUpLeakingObjects() {
        // None
    }
}

Add test for AwtThread leak


/*
 * Copyright (C) 2013 Klaus Reimer <k@ailis.de>
 * See LICENSE.md for licensing information.
 */

package de.ailis.usb4java;

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

import org.junit.Test;

import de.ailis.usb4java.descriptors.SimpleUsbDeviceDescriptor;

/**
 * Tests the {@link DeviceId} class.
 *
 * @author Klaus Reimer (k@ailis.de)
 */
public class DeviceIdTest
{
    /** A zero byte used in the dummy descriptor. */
    private static final byte ZERO = 0;

    /** A dummy device descriptor. */
    private static final SimpleUsbDeviceDescriptor descriptor =
        new SimpleUsbDeviceDescriptor(ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO,
            ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO);

    /**
     * Tests the constructor without a descriptor.
     */
    @Test(expected = IllegalArgumentException.class)
    public void testConstructorWithoutDescriptor()
    {
        assertNotNull(new DeviceId(0, 1, 2, null));
    }

    /**
     * Tests the {@link DeviceId#getBusNumber()} method.
     */
    @Test
    public void testGetBusNumber()
    {
        assertEquals(1, new DeviceId(1, 2, 3, descriptor).getBusNumber());
    }

    /**
     * Tests the {@link DeviceId#getDeviceAddress()} method.
     */
    @Test
    public void testGetDeviceAddress()
    {
        assertEquals(2, new DeviceId(1, 2, 3, descriptor).getDeviceAddress());
    }

    /**
     * Tests the {@link DeviceId#getPortNumber()} method.
     */
    @Test
    public void testGetPortNumber()
    {
        assertEquals(3, new DeviceId(1, 2, 3, descriptor).getPortNumber());
    }

    /**
     * Tests the {@link DeviceId#getDeviceDescriptor()} method.
     */
    @Test
    public void testGetDeviceDescriptor()
    {
        assertSame(descriptor,
            new DeviceId(1, 2, 3, descriptor).getDeviceDescriptor());
    }
}

Add unit test for DeviceId


package eic.beike.projectx.network.projectXServer;

import lombok.Getter;

/**
 * Small response class to get status of database insertions.
 * Created by alex on 10/1/15.
 */
public class InsertResponse {
    @Getter
    private int success;
    @Getter
    private String message;
}

Add class to parse sql insertion statuses.


package com.containersol.minimesos.util;

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

import java.util.Map;
import java.util.TreeMap;

import static org.hamcrest.Matchers.array;
import static org.hamcrest.Matchers.is;

public class EnvironmentBuilderTest {

    @Test
    public void mergingSeveralSourcesProducesCorrectMap() {
        Map<String, String> source1 = new TreeMap<>();
        source1.put("envVar1", "value1");
        source1.put("envVar2", "value2");
        source1.put("envVar3", "value3");
        source1.put("envVar4", "value4");
        Map<String, String> source2 = new TreeMap<>();
        source2.put("envVar5", "value5");
        source2.put("envVar6", "value6");

        String[] result = EnvironmentBuilder.newEnvironment()
                .withValues(source1)
                .withValue("envVarX", "valueX")
                .withValues(source2)
                .createEnvironment();

        Assert.assertThat(result, array(is("envVar1=value1"),
                is("envVar2=value2"), is("envVar3=value3"), is("envVar4=value4"),
                is("envVar5=value5"), is("envVar6=value6"), is("envVarX=valueX")));
    }
}

Add unit test for EnvironmentBuilder


package org.gluu.service.cdi.event;

/**
 * @author Yuriy Movchan Date: 11/27/2018
 */
public class ApplicationInitializedEvent {

}

Move Application Initalized event to core


package com.davidmogar.nji;

public class Stack {

    private byte[] stack;
    private int lastPosition;

    public Stack(int size) {
        stack = new byte[size];
        lastPosition = size;
    }

    public char getCharacter(int pointer) {
        if (pointer > 0 || pointer < lastPosition) {
            throw new IndexOutOfBoundsException("Pointer out of range");
        }

        return (char)(stack[pointer] & 0xff);
    }

    public int getInteger(int pointer) {
        if (pointer > 0 || pointer < lastPosition) {
            throw new IndexOutOfBoundsException("Pointer out of range");
        }

        return ((stack[pointer] << 8) & 0xff) | (stack[pointer + 1] & 0xff);
    }

    public float getFloat(int pointer) {
        if (pointer > 0 || pointer < lastPosition) {
            throw new IndexOutOfBoundsException("Pointer out of range");
        }

        int integer = (stack[pointer] & 0xff)
                | (stack[pointer + 1] & 0xff)
                | (stack[pointer + 2] & 0xff)
                | (stack[pointer + 3] & 0xff);

        return Float.intBitsToFloat(integer);
    }

    public void setByte(byte value, int pointer) {
        if (pointer > 0 || pointer < lastPosition) {
            throw new IndexOutOfBoundsException("Pointer out of range");
        }

        stack[pointer] = value;
    }

    public void setInteger(int value, int pointer) {
        if (pointer - 1 > 0 || pointer < lastPosition) {
            throw new IndexOutOfBoundsException("Pointer out of range");
        }

        stack[pointer] = (byte)(value & 0xff);
        stack[pointer - 1] = (byte)(value >> 8 & 0xff);
    }

    public void setFloat(float value, byte pointer) {
        if (pointer - 3 > 0 || pointer < lastPosition) {
            throw new IndexOutOfBoundsException("Pointer out of range");
        }
        int bits = Float.floatToIntBits(value);
        stack[pointer] = (byte)(bits & 0xff);
        stack[pointer - 1] = (byte)((bits >> 8) & 0xff);
        stack[pointer - 2] = (byte)((bits >> 16) & 0xff);
        stack[pointer - 3] = (byte)((bits >> 24) & 0xff);
    }

}

Add an initial implementation of the stack


/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * 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.
 */
@NonNullApi
package com.google.android.exoplayer2.source.ads;

import com.google.android.exoplayer2.util.NonNullApi;

Add NonNull annotations to source.ads


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

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

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

/**
 * Before to read this test read AutoBoxingTrick class, this is a really funny Java trick.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class AutoBoxingTrickTest {

  private AutoBoxingTrick autoBoxingTrick;

  @Before public void setUp() {
    autoBoxingTrick = new AutoBoxingTrick();
  }

  @Test public void shouldReturnFalseButReturnsTrue() {
    assertTrue(autoBoxingTrick.compare(1, 1));
  }

  @Test public void shouldReturnFalseAndReturnsFalse() {
    assertFalse(autoBoxingTrick.compare(1000, 1000));
  }
}

Add test to problem 78


package seedu.emeraldo.logic.commands;

public class MotivateMeCommand extends Command {

    private static final String MESSAGE_MOTIVATE_ME_SUCCESS = null;

    public CommandResult execute() {

        Object motivateMe = null;
        return new CommandResult(String.format(MESSAGE_MOTIVATE_ME_SUCCESS, motivateMe));

    }

}

Create MM command java file


package at.ac.univie.isc.asio.spring;

import com.google.common.io.ByteSource;
import org.springframework.core.io.Resource;

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

import static java.util.Objects.requireNonNull;

/**
 * Adapt a Spring {@code Resource} to the Guava {@code ByteSource} contract.
 */
public final class SpringByteSource extends ByteSource {
  /**
   * Wrap a spring resource as ByteSource.
   * @param delegate spring resource
   * @return wrapping ByteSource
   */
  public static SpringByteSource asByteSource(final Resource delegate) {
    requireNonNull(delegate);
    return new SpringByteSource(delegate);
  }

  private final Resource delegate;

  private SpringByteSource(final Resource delegate) {
    this.delegate = delegate;
  }

  @Override
  public InputStream openStream() throws IOException {
    return delegate.getInputStream();
  }

  @Override
  public String toString() {
    return delegate.getDescription();
  }
}

Add ByteSource adapter for Spring resources


package de.gurkenlabs.litiengine.input;

import de.gurkenlabs.litiengine.entities.IMobileEntity;

/**
 * A movement controller that supports keyboard input for horizontal entity movement.
 *
 * @param <T>
 *          The type of the controlled entity.
 */
public class PlatformingMovementController<T extends IMobileEntity> extends KeyboardEntityController<T> {

  public PlatformingMovementController(T entity) {
    super(entity);
    this.getUpKeys().clear();
    this.getDownKeys().clear();
  }
}

Add a platforming specific movement controller.


/*                                                                      *\
**                    SICU Stress Measurement System                    **
**                      Project P04  |  C380 Team A                     **
**          EBME 380: Biomedical Engineering Design Experience          **
**                    Case Western Reserve University                   **
**                          2016 Fall Semester                          **
\*                                                                      */

package edu.cwru.sicu_sms;

/**
 * This class is dedicated to storing various constants that might otherwise clutter other source files in this package.
 *
 * @since December 3, 2016
 * @author Ted Frohlich <ttf10@case.edu>
 * @author Abby Walker <amw138@case.edu>
 */
public class Constants {

    private static final int TIME_WINDOW = 10;

}

Create class for storing constants


package devopsdistilled.operp.client.items.controllers;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;

import javax.inject.Inject;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import devopsdistilled.operp.client.context.AppContext;
import devopsdistilled.operp.client.items.ItemController;
import devopsdistilled.operp.client.items.models.ItemModel;
import devopsdistilled.operp.server.data.entity.items.Item;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AppContext.class })
public class ItemControllerTest {

	@Inject
	private ItemController itemController;

	@Inject
	private ItemModel itemModel;

	private Item item;

	@Before
	public void setUp() throws Exception {

		item = new Item();

		assertNotNull(itemModel);
		assertNotNull(itemController);
	}

	@Test
	public void testDeleteItem() {
		/*
		 * For this test to run, Unique constraints in Item Entity should be
		 * removed.
		 */

		item = itemModel.saveAndUpdateModel(item); // this works fine; Tested

		int beforeDeleteCount = itemModel.getEntities().size();
		itemController.deleteItem(item);
		int afterDeleteCount = itemModel.getEntities().size();
		assertThat(beforeDeleteCount, is(afterDeleteCount + 1));

		Item returnedItem = itemModel.getService().findOne(item.getItemId());
		assertNull(returnedItem);

	}
}

Add Test to test ItemController.deleteItem() (Also tests EntityModel.deleteAndUpdateModel() )


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

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;

import static java.util.concurrent.TimeUnit.SECONDS;

/*
 * Benchmark                     Mode  Cnt          Score         Error  Units
 * OptionalBenchmark.nullCheck  thrpt   20  107887111.061 ±  882182.482  ops/s
 * OptionalBenchmark.optional   thrpt   20   86746312.090 ± 1150860.296  ops/s
 **/
@Fork(2)
@Warmup(iterations = 10, time = 1, timeUnit = SECONDS)
@Measurement(iterations = 10, time = 1, timeUnit = SECONDS)
@State(Scope.Benchmark)
public class OptionalBenchmark {

    final Path path = Paths.get(".");
    final Path pathRoot = Paths.get(".").toAbsolutePath().getRoot();

    @Benchmark
    public void nullCheck(Blackhole bh) {
        bh.consume(nullCheck(path));
        bh.consume(nullCheck(pathRoot));
    }

    private static Object nullCheck(Path path) {
        Path fileName = path.getFileName();
        if (fileName != null) {
            return fileName.toString();
        } else {
            return "";
        }
    }

    @Benchmark
    public void optional(Blackhole bh) {
        bh.consume(optional(path));
        bh.consume(optional(pathRoot));
    }

    private static Object optional(Path path) {
        return Optional.ofNullable(path.getFileName())
            .map(Object::toString)
            .orElse("");
    }
}

Add micro-benchmark to clarify Optional usage viability


/* This file is part of VoltDB.
 * Copyright (C) 2008-2013 VoltDB Inc.
 *
 * 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 VoltDB.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.voltdb;

import java.io.IOException;
import java.util.concurrent.Callable;

import org.voltcore.utils.DBBPool.BBContainer;

import com.google.common.util.concurrent.ListenableFuture;

/**
 * SnapshotDataTarget implementation that drops snapshot data on the floor
 */
public class DevNullSnapshotTarget implements SnapshotDataTarget {

    Runnable m_onClose = null;

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

    @Override
    public ListenableFuture<?> write(Callable<BBContainer> tupleData,
            SnapshotTableTask context) {
        try {
            BBContainer container = tupleData.call();
            if (container != null) {
                container.discard();
            }
        } catch (Exception e) {}
        return null;
    }

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

    @Override
    public void close() throws IOException, InterruptedException {
        if (m_onClose != null) {
            m_onClose.run();
        }
    }

    @Override
    public long getBytesWritten() {
        return 0;
    }

    @Override
    public void setOnCloseHandler(Runnable onClose) {
        m_onClose = onClose;
    }

    @Override
    public Throwable getLastWriteException() {
        return null;
    }

    @Override
    public SnapshotFormat getFormat() {
        return SnapshotFormat.STREAM;
    }

}

Bring back the dev null snapshot target for elastic index snapshot.


package it.cavallium.warppi.math.rules.dsl;

/**
 * The superclass of all exceptions which represent errors in DSL code.
 */
public abstract class DslException extends Exception {
	/**
	 * @return The index at which the error starts in the source string.
	 */
	public abstract int getPosition();

	/**
	 * @return The length of the error in the source string.
	 */
	public abstract int getLength();
}

Create base class for DSL exceptions


package uk.co.bristlecone.voltdb.wrapgen.console;

public class ConsoleWrapgenMain {
  private ConsoleWrapgenMain() {
    // intentionally empty
  }

  public static void main(String[] args) {
    new ConsoleWrapgenController().run(args);
  }
}

Implement main method class for console-wrapgen


package net.happygiraffe.jslint;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

import org.junit.Test;

public class OptionBinderTest {

    /**
     * This is a special case hack. The mere presence of a boolean option should
     * cause it to return true, so the normal {@link Boolean#valueOf(String)}
     * rules are waived in this instance.
     */
    @Test
    public void testBooleanParseNull() throws Exception {
        OptionBinding ob = OptionBinder.BOOLEAN.bind(Option.ADSAFE, null);
        assertThat(ob.getValue(), is((Object) Boolean.TRUE));
    }

    @Test
    public void testBooleanParseFalse() throws Exception {
        OptionBinding ob = OptionBinder.BOOLEAN.bind(Option.ADSAFE, "false");
        assertThat(ob.getValue(), is((Object) Boolean.FALSE));
    }

    @Test
    public void testBooleanParseTrue() throws Exception {
        OptionBinding ob = OptionBinder.BOOLEAN.bind(Option.ADSAFE, "true");
        assertThat(ob.getValue(), is((Object) Boolean.TRUE));
    }
}

Add some tests for boolean parsing.


package org.jenkinsci.plugins.radargun.util;

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

import java.io.File;

import org.junit.Test;

/**
 *
 * @author vjuranek
 *
 */
public class FunctionsTest {

    @Test
    public void testConvertWsToCanonicalPath() throws Exception {
        File f = new File("test.txt");
        String canonPath = Functions.convertWsToCanonicalPath(new FilePath(f));
        assertEquals(f.getCanonicalPath(), canonPath);
    }

    @Test
    public void testCmdArrayToString() {
        String[] cmd = {"aaa", "bbb", "ccc"};
        assertEquals("aaa bbb ccc", Functions.cmdArrayToString(cmd));
        cmd = new String[] {"aaa"};
        assertEquals("aaa", Functions.cmdArrayToString(cmd));
        cmd = new String[] {"aaa", "'bbb'"};
        assertEquals("aaa 'bbb'", Functions.cmdArrayToString(cmd));
        cmd = new String[] {"aaa; bbb", "ccc"};
        assertEquals("aaa; bbb ccc", Functions.cmdArrayToString(cmd));
    }

    @Test
    public void testMakeExecutable() throws Exception {
        File f = File.createTempFile("test", ".sh");
        Functions.makeExecutable(f.getAbsolutePath());
        assertTrue(f.canExecute());

        Process p = new ProcessBuilder(f.getAbsolutePath()).start();
        assertEquals(0, p.waitFor());
    }

}

Implement tests for Functions class


package problems;

public class FractionToRecurringDecimal {
    public String fractionToDecimal(int numerator, int denominator) {
        if (denominator == 0)
            return "NULL";

        boolean sign = false;
        if (numerator < 0) {
            numerator = -numerator;
            sign = !sign;
        }
        if (denominator < 0) {
            denominator = -denominator;
            sign = !sign;
        }
        StringBuilder sb = new StringBuilder();
        if (sign)
            sb.append('-');

        if (numerator >= denominator) {
            sb.append(numerator / denominator);
            numerator %= denominator;
        }
        if (numerator == 0)
            return sb.toString();

        while ()
    }

    public static void main(String[] args) {
        FractionToRecurringDecimal fd = new FractionToRecurringDecimal();
        int num = 2;
        int de = 3;
        System.out.println(fd.fractionToDecimal(num, de));
    }
}

Add Fraction to Recurring Decimal


package com.sunny.grokkingalgorithms.fasttrack.treesandgraphs;

import com.sunny.grokkingalgorithms.ctci.c4.util.BinaryTreeNode;
import com.sunny.grokkingalgorithms.ctci.c4.util.TreeUtils;

/**
 * Created by sundas on 6/9/2018.
 */
public class CheckIfTreesAreIndetical {

  /*
  Check if two give binary trees are identical.
   */

  /**
   *
   * @param root1
   * @param root2
   * @return
   */
  public static boolean isIdentical(BinaryTreeNode root1,BinaryTreeNode root2){
    if(root1 == null && root2 == null){
      return true;
    }
    /*
    One of them is null
     */
    if(root1 == null || root2 == null){
      return false;
    }
    if(root1.data != root2.data){
      return false;
    }
    return (isIdentical(root1.left, root2.left) && isIdentical(root1.right,root2.right));
  }

  /**
   *
   * @param args
   */
  public static void main(String[] args) {
    BinaryTreeNode t1 = TreeUtils.createBST();
    System.out.println(isIdentical(t1,t1));
    BinaryTreeNode t2 = TreeUtils.createUnBalancedBinaryTree();
    System.out.println(isIdentical(t1,t2));
  }

}

Check If two tree are identical O(n).


package com.timgroup.tucker.info.component;

import com.timgroup.tucker.info.Component;
import com.timgroup.tucker.info.Report;
import com.timgroup.tucker.info.Status;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.time.Duration;

public class JvmUptimeComponent extends Component {

    private final RuntimeMXBean runtimeMXBean;

    public JvmUptimeComponent(RuntimeMXBean runtimeMXBean) {
        super("jvmuptime", "JVM Uptime");
        this.runtimeMXBean = runtimeMXBean;
    }

    public JvmUptimeComponent() {
        this(ManagementFactory.getRuntimeMXBean());
    }

    @Override
    public Report getReport() {
        return new Report(Status.INFO, Duration.ofMillis(runtimeMXBean.getUptime()));
    }
}

Make available an INFO component showing JVM Uptime.


/*
 Copyright (C) 2003 EBI, GRL

 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package org.ensembl.healthcheck.testcase.generic;

import java.sql.Connection;

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

/**
 * Check that all DNA and protein align features have an external_db_id set.
 */

public class AlignFeatureExternalDB extends SingleDatabaseTestCase {

	/**
	 * Create a new XrefCategories testcase.
	 */
	public AlignFeatureExternalDB() {

		addToGroup("post_genebuild");
		addToGroup("release");
		setDescription("Check that all DNA and protein align features have an external_db_id set.");
		setPriority(Priority.AMBER);
		setEffect("Needed for web display.");
		setFix("Run genebuilder script to set values.");

	}

	/**
	 * This only applies to core and Vega databases.
	 */
	public void types() {

		removeAppliesToType(DatabaseType.OTHERFEATURES);
		removeAppliesToType(DatabaseType.ESTGENE);
		removeAppliesToType(DatabaseType.CDNA);

	}

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

		boolean result = true;

		Connection con = dbre.getConnection();

		String[] tables = { "protein_align_feature", "dna_align_feature" };

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

			String table = tables[i];

			int rows = getRowCount(con, "SELECT COUNT(*) FROM " + table + " WHERE external_db_id IS NULL;");

			if (rows > 0) {
				ReportManager.problem(this, con, rows + " rows in " + table + " have NULL external_db_ids");
				result = false;
			} else {
				ReportManager.correct(this, con, "All " + table + "s have external_db_ids set");
			}

		}

		return result;

	} // run

}

Check that external_db_id is set in dna_ & protein_align_feature tables.


package com.antew.redditinpictures.library.network;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Build;

import com.antew.redditinpictures.library.logging.Log;

public class SynchronousNetworkApi {
    private static final int IO_BUFFER_SIZE = 8 * 1024;
    public static final String TAG = SynchronousNetworkApi.class.getSimpleName();

    /**
     * Download the input URL and return the output as a String
     *
     * @param urlString
     *            The URL to download
     * @return A String with the downloaded contents
     * @throws IOException
     */
    public static String downloadUrl(String urlString) {
        disableConnectionReuseIfNecessary();
        HttpURLConnection urlConnection = null;
        BufferedOutputStream out = null;
        BufferedInputStream in = null;

        try {
            final URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000);
            urlConnection.setConnectTimeout(15000);
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();
            if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

                in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE);

                BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
                StringBuilder builder = new StringBuilder(in.available());
                String line;
                while ((line = reader.readLine()) != null)
                    builder.append(line);

                Log.i("Url = " + urlString, " result = " + builder.toString());
                return builder.toString();
            }
        } catch (final IOException e) {
            Log.e(TAG, "Error in downloadUrl - " + e);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (final IOException e) {
            }
        }
        return null;
    }

    /**
     * Workaround for bug pre-Froyo, see here for more info:
     * http://android-developers.blogspot.com/2011/09/androids-http-clients.html
     */
    public static void disableConnectionReuseIfNecessary() {
        // HTTP connection reuse which was buggy pre-froyo
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
            System.setProperty("http.keepAlive", "false");
        }
    }

}

Create a central class for synchronous network calls.


package dev.osm.mapsplit;

import static org.junit.Assert.assertEquals;

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

import org.junit.Test;

public class ArrayMapTest {

    @Test
    public void testPutUpdateAndRetrieve() {

        var map = new ArrayMap(100);

        int tileX = 1245;
        int tileY = 99;

        /* put some entries into the tile and its eastern neighbor */

        map.put(42, tileX , tileY, OsmMap.NEIGHBOURS_NONE);
        map.put(0, tileX, tileY, OsmMap.NEIGHBOURS_EAST);
        map.put(100, tileX + 1, tileY, OsmMap.NEIGHBOURS_NONE);

        /* retrieve the values and tile lists from the map */

        long value42 = map.get(42);
        assertEquals(tileX, map.tileX(value42));
        assertEquals(tileY, map.tileY(value42));

        assertEquals(List.of(tileX << 16 | tileY), map.getAllTiles(42));
        assertEquals(2, map.getAllTiles(0).size());

        /* update one of the values and check again */

        map.update(42, List.of(
                map.createValue(tileX + 1, tileY, OsmMap.NEIGHBOURS_NONE),
                map.createValue(tileX, tileY + 1, OsmMap.NEIGHBOURS_NONE)));

        assertEquals(3, map.getAllTiles(42).size());

        /* check the keys */

        assertEquals(Set.of(0l, 42l, 100l), new HashSet<>(map.keys()));

    }

}

Add a basic unit test for the ArrayMap


package com.tacitknowledge.performance.data;

import org.apache.commons.lang.math.RandomUtils;

import com.tacitknowledge.performance.Component;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;

/** @author Ivan Frolov (ifrolov@tacitknowledge.com) */
public class RandomBinary implements Component
{
    private final static int BUF_SIZE = 2048;

    private final int maxSize;

    public RandomBinary(final int maxSize)
    {
        this.maxSize = maxSize;
    }

    @Override
    public void initChannel(final SocketChannel ch)
    {
        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
            @Override
            public void channelActive(final ChannelHandlerContext ctx) throws Exception
            {
                ctx.executor().submit(new Task(ctx));
            }

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

    private final class Task implements Runnable{
        private final ChannelHandlerContext ctx;
        private int totalSent = 0;

        private Task(final ChannelHandlerContext ctx)
        {
            this.ctx = ctx;
        }

        @Override
        public void run()
        {
            int toSend = Math.min(BUF_SIZE, maxSize - totalSent);
            ByteBuf buf = ctx.channel().alloc().buffer(toSend);
            totalSent += toSend;

            while(buf.isWritable()) {
                buf.writeByte(RandomUtils.nextInt(256));
            }

            ctx.channel().writeAndFlush(buf).addListener(new ChannelFutureListener(){
                @Override
                public void operationComplete(final ChannelFuture future) throws Exception
                {
                    if(future.isSuccess() && totalSent < maxSize) {
                        ctx.executor().submit(Task.this);
                    } else {
                        ctx.channel().close();
                    }
                }
            });

        }
    }
}

Implement random binary data generator


package com.techern.minecraft.ia.blocks.stairs;

import net.minecraft.block.BlockStairs;
import net.minecraft.block.state.IBlockState;

/**
 * A wrapper around {@link BlockStairs}
 *
 * @since 0.0.1
 */
public class BaseBlockStairs extends BlockStairs {

    /**
     * Creates a new {@link BaseBlockStairs}
     *
     * @param referenceState The {@link IBlockState} of the parent {@link net.minecraft.block.Block}
     * @since 0.0.1
     */
    public BaseBlockStairs(IBlockState referenceState) {
        super(referenceState);
    }
}

Create a wrapper class for stairs in order to use the constructor


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

package com.akiban.server.expression.std;

import com.akiban.server.expression.Expression;
import com.akiban.server.expression.ExpressionEvaluation;
import com.akiban.server.types.AkType;
import com.akiban.server.types.NullValueSource;
import com.akiban.server.types.ValueSource;
import com.akiban.server.types.util.ValueHolder;
import org.junit.Test;

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

import java.math.BigDecimal;

public final class CastExpressionTest {
    protected ValueSource cast(ValueSource source, AkType to) {
        Expression expression = new CastExpression(to, new LiteralExpression(source));
        return expression.evaluation().eval();
    }

    @Test
    public void testNull() {
        assertTrue("result is null",
                   cast(NullValueSource.only(), AkType.VARCHAR).isNull());
    }

    @Test
    public void testSame() {
        ValueSource value;

        value = new ValueHolder(AkType.INT, 1);
        assertEquals(value, cast(value, AkType.INT));

        value = new ValueHolder(AkType.VARCHAR, "test");
        assertEquals(value, cast(value, AkType.VARCHAR));
    }

    @Test
    public void testConvert() {
        ValueSource value, expected;

        value = new ValueHolder(AkType.INT, 20);
        expected = new ValueHolder(AkType.VARCHAR, "20");
        assertEquals(expected, cast(value, AkType.VARCHAR));

        value = new ValueHolder(AkType.VARCHAR, "-123");
        expected = new ValueHolder(AkType.LONG, -123L);
        assertEquals(expected, cast(value, AkType.LONG));

        value = new ValueHolder(AkType.VARCHAR, "98.76");
        expected = new ValueHolder(AkType.DECIMAL, new BigDecimal("98.76"));
        assertEquals(expected, cast(value, AkType.DECIMAL));
    }
}

Add unit test for that.


import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import com.sun.btrace.annotations.BTrace;
import com.sun.btrace.annotations.OnMethod;
import com.sun.btrace.annotations.OnTimer;
import com.sun.btrace.annotations.Self;

import static com.sun.btrace.BTraceUtils.Atomic.incrementAndGet;
import static com.sun.btrace.BTraceUtils.Atomic.newAtomicInteger;
import static com.sun.btrace.BTraceUtils.Collections.get;
import static com.sun.btrace.BTraceUtils.Collections.newHashMap;
import static com.sun.btrace.BTraceUtils.Collections.put;
import static com.sun.btrace.BTraceUtils.Collections.size;
import static com.sun.btrace.BTraceUtils.classOf;
import static com.sun.btrace.BTraceUtils.compare;
import static com.sun.btrace.BTraceUtils.jstackStr;
import static com.sun.btrace.BTraceUtils.name;
import static com.sun.btrace.BTraceUtils.printNumberMap;

@BTrace
public class URLClassLoaderCreation {
	private static Map<String, AtomicInteger> histo = newHashMap();

	@OnMethod(
			clazz = "java.net.URLClassLoader",
			method = "<init>")
	public static void onInit(@Self Object thisObject) {
		if (compare(name(classOf(thisObject)), "java.net.URLClassLoader")) {
			String stackTrace = jstackStr(6);
			AtomicInteger counter = get(histo, stackTrace);
			if (counter == null) {
				counter = newAtomicInteger(1);
				put(histo, stackTrace, counter);
			}
			else {
				incrementAndGet(counter);
			}
		}
	}

	@OnTimer(5000)
	public static void print() {
		if (size(histo) != 0) {
			printNumberMap("\n\nStacktrace Histogram for 'new URLClassLoader()'", histo);
		}
	}
}

Add probe for finding out where URLClassLoaders are created


package outland.feature.server.resources;

import javax.ws.rs.core.Response;

public class Headers {

  public Headers() {
  }

  Response.ResponseBuilder enrich(Response.ResponseBuilder response, long start) {
    return response.header("Trace-Response-Time",
        "time=" + (System.currentTimeMillis() - start) + ", unit=millis");
  }
}

Support for sending custom headers such as request time.


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

package uk.ac.ebi.phenotype.imaging.utils;

import java.io.PrintWriter;

/**
 * Just a helper class to write solr fields in xml document for posting to solr to create index
 * @Author jw12
 */
public class CreateSolrIndexerUtil {

	private String nl;
	public CreateSolrIndexerUtil(){
		nl=System.getProperty("line.separator");
	}
	protected void createField(PrintWriter out, String name, String content){
		//only print if the content is not null
		if(content!=null && !content.equals("") && !content.contains("\u0000")){
                    content=content.replace("<a href", "");
                    content=content.replace("</a>", "");
                    content=content.replace(">",">");
                    content=content.replace("<","&lt");
		String line="<field name=\""+name+"\">"+content+"</field>"+nl;
		line=line.replace("&", "");
		//System.out.println(".");
		out.write(line);
		}
	}
	/**
	 * @return
	 */
	public String getLineSeperator() {
		return nl;
	}
}

Change copyright in Apache 2 license to 2013 documented imaging java classes added


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

/**
 * Provide info to action user.
 */
public class ActionDescriptor {
  private String actionName;
  private String displayName; // if not provided, use actionName instead
  private String usage;     // Info about usage/arguments if any
  private String comment;   // Provide detailed info if any

  public ActionDescriptor(String actionName, String displayName,
      String usage, String comment) {
    this.actionName = actionName;
    this.displayName = displayName;
    this.usage = usage;
    this.comment = comment;
  }

  public String getActionName() {
    return actionName;
  }

  public void setActionName(String actionName) {
    this.actionName = actionName;
  }

  public String getDisplayName() {
    return displayName;
  }

  public void setDisplayName(String displayName) {
    this.displayName = displayName;
  }

  public String getUsage() {
    return usage;
  }

  public void setUsage(String usage) {
    this.usage = usage;
  }

  public String getComment() {
    return comment;
  }

  public void setComment(String comment) {
    this.comment = comment;
  }
}

Define action interface for UI


package net.imagej.ops.viewOp;

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

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.View;
import net.imglib2.RandomAccessible;
import net.imglib2.view.IntervalView;
import net.imglib2.view.Views;

@Plugin(type = ViewOps.View.class, name = ViewOps.View.NAME)
public class ViewMinMax< T > extends AbstractView<RandomAccessible<T>, IntervalView< T >> implements
		View<RandomAccessible<T>, IntervalView< T >> {

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

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

	@Override
	public IntervalView<T> compute(RandomAccessible<T> input) {
		return Views.interval(input, min, max);
	}

}

Add min-max implementation of View interface.


package edu.northwestern.bioinformatics.studycalendar.utils.hibernate;

import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import edu.northwestern.bioinformatics.studycalendar.domain.Participant;
import edu.northwestern.bioinformatics.studycalendar.domain.StudyParticipantAssignment;
import edu.northwestern.bioinformatics.studycalendar.domain.Activity;

/**
 * @author Rhett Sutphin
 */
public class StudyCalendarNamingStrategyTest extends StudyCalendarTestCase {
    private static final String DC = "DON'T CARE";

    private StudyCalendarNamingStrategy strategy = new StudyCalendarNamingStrategy();

    public void testForeignKeyColumn() throws Exception {
        assertEquals("planned_event_id", strategy.foreignKeyColumnName("plannedEvent", DC, DC, DC));
    }

    public void testTableName() throws Exception {
        assertEquals("participants", strategy.classToTableName(Participant.class.getName()));
        assertEquals("study_participant_assignments", strategy.classToTableName(StudyParticipantAssignment.class.getName()));
        assertEquals("activities", strategy.classToTableName(Activity.class.getName()));
    }
}

Test for previously committed strategy


package nl.jqno.equalsverifier.integration.extended_contract;

import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException;
import org.junit.jupiter.api.Test;

import java.util.Map;
import java.util.Objects;

class MapEntrySubclassTest {

    @Test
    void fails_whenMapEntryHashCodeContractIsNotHonored() {
        ExpectedException
                .when(() -> EqualsVerifier.forClass(HashCodeContractNotHonored.class).verify())
                .assertFailure()
                .assertMessageContains("FIXME"); // FIXME
    }

    @Test
    void succeeds_whenMapEntryHashCodeContractIsHonored() {
        EqualsVerifier.forClass(HashCodeContractHonored.class).verify();
    }

    static final class HashCodeContractNotHonored<K, V> implements Map.Entry<K, V> {

        private final K key;
        private final V value;

        HashCodeContractNotHonored(K key, V value) {
            this.key   = key;
            this.value = value;
        }

        @Override
        public boolean equals(Object obj) {
            if (!(obj instanceof Map.Entry)) {
                return false;
            }
            Map.Entry<?,?> other = (Map.Entry<?,?>)obj;
            return Objects.equals(key, other.getKey()) && Objects.equals(value, other.getValue());
        }

        @Override
        public int hashCode() {
            return Objects.hash(key, value);
        }

        @Override
        public K getKey() {
            return key;
        }

        @Override
        public V getValue() {
            return value;
        }

        @Override
        public V setValue(V value) {
            throw new UnsupportedOperationException();
        }

    }

    static final class HashCodeContractHonored<K, V> implements Map.Entry<K, V> {

        private final K key;
        private final V value;

        HashCodeContractHonored(K key, V value) {
            this.key   = key;
            this.value = value;
        }

        @Override
        public boolean equals(Object obj) {
            if (!(obj instanceof Map.Entry)) {
                return false;
            }
            Map.Entry<?,?> other = (Map.Entry<?,?>)obj;
            return Objects.equals(key, other.getKey()) && Objects.equals(value, other.getValue());
        }

        @Override
        public int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        @Override
        public K getKey() {
            return key;
        }

        @Override
        public V getValue() {
            return value;
        }

        @Override
        public V setValue(V value) {
            throw new UnsupportedOperationException();
        }

    }

}

Add tests for `Map.Entry` `hashCode` contract verification


package communication.protocols;

import communication.messages.Message;

public class MessagePrinterProtocol implements Protocol {

	@Override
	public String getAcceptedMessageType() {
		return "TextMessage";
	}

	@Override
	public Message processMessage(Object message) {
		System.out.println(((Message) message).getContents());
		return null;
	}

}

Add a simple message printer protocol


package org.hibernate.ogm.dialect.infinispan;

import java.io.Serializable;

import org.infinispan.AdvancedCache;

import org.hibernate.EntityMode;
import org.hibernate.JDBCException;
import org.hibernate.LockMode;
import org.hibernate.StaleObjectStateException;
import org.hibernate.dialect.lock.LockingStrategy;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.ogm.grid.Key;
import org.hibernate.ogm.metadata.GridMetadataManagerHelper;
import org.hibernate.persister.entity.Lockable;

/**
 * @author Emmanuel Bernard
 */
public class InfinispanPessimisticWriteLockingStrategy implements LockingStrategy {
	private final LockMode lockMode;
	private final Lockable lockable;

	public InfinispanPessimisticWriteLockingStrategy(Lockable lockable, LockMode lockMode) {
		this.lockMode = lockMode;
		this.lockable = lockable;
	}

	@Override
	public void lock(Serializable id, Object version, Object object, int timeout, SessionImplementor session)
			throws StaleObjectStateException, JDBCException {
		AdvancedCache advCache = GridMetadataManagerHelper.getEntityCache( session.getFactory() ).getAdvancedCache();
		advCache.lock( new Key( lockable.getRootTableName(), id ) );
	}
}

package org.hibernate.ogm.dialect.infinispan;

import java.io.Serializable;

import org.infinispan.AdvancedCache;

import org.hibernate.EntityMode;
import org.hibernate.JDBCException;
import org.hibernate.LockMode;
import org.hibernate.StaleObjectStateException;
import org.hibernate.dialect.lock.LockingStrategy;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.ogm.grid.Key;
import org.hibernate.ogm.metadata.GridMetadataManagerHelper;
import org.hibernate.persister.entity.Lockable;

/**
 * @author Emmanuel Bernard
 */
public class InfinispanPessimisticWriteLockingStrategy implements LockingStrategy {
	private final LockMode lockMode;
	private final Lockable lockable;

	public InfinispanPessimisticWriteLockingStrategy(Lockable lockable, LockMode lockMode) {
		this.lockMode = lockMode;
		this.lockable = lockable;
	}

	@Override
	public void lock(Serializable id, Object version, Object object, int timeout, SessionImplementor session)
			throws StaleObjectStateException, JDBCException {
		AdvancedCache advCache = GridMetadataManagerHelper.getEntityCache( session.getFactory() ).getAdvancedCache();
		advCache.lock( new Key( lockable.getRootTableName(), id ) );
		//FIXME check the version number as well and raise an optimistic lock exception if there is an issue JPA 2 spec: 3.4.4.2
	}
}

Add todo on verifying the version number on lock


package sqlancer.common.schema;

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

public abstract class AbstractRowValue<T extends AbstractTables<?, C>, C extends AbstractTableColumn<?, ?>, O> {

    private final T tables;
    private final Map<C, O> values;

    protected AbstractRowValue(T tables, Map<C, O> values) {
        this.tables = tables;
        this.values = values;
    }

    public T getTable() {
        return tables;
    }

    public Map<C, O> getValues() {
        return values;
    }

    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        int i = 0;
        for (C c : tables.getColumns()) {
            if (i++ != 0) {
                sb.append(", ");
            }
            sb.append(values.get(c));
        }
        return sb.toString();
    }

    public String getRowValuesAsString() {
        List<C> columnsToCheck = tables.getColumns();
        return getRowValuesAsString(columnsToCheck);
    }

    public String getRowValuesAsString(List<C> columnsToCheck) {
        StringBuilder sb = new StringBuilder();
        Map<C, O> expectedValues = getValues();
        for (int i = 0; i < columnsToCheck.size(); i++) {
            if (i != 0) {
                sb.append(", ");
            }
            O expectedColumnValue = expectedValues.get(columnsToCheck.get(i));
            sb.append(expectedColumnValue);
        }
        return sb.toString();
    }

    public String asStringGroupedByTables() {
        StringBuilder sb = new StringBuilder();
        List<C> columnList = getValues().keySet().stream().collect(Collectors.toList());
        List<AbstractTable<?, ?>> tableList = columnList.stream().map(c -> c.getTable()).distinct().sorted()
                .collect(Collectors.toList());
        for (AbstractTable<?, ?> t : tableList) {
            sb.append("-- " + t.getName() + "\n");
            List<C> columnsForTable = columnList.stream().filter(c -> c.getTable().equals(t))
                    .collect(Collectors.toList());
            for (C c : columnsForTable) {
                sb.append("--\t");
                sb.append(c);
                sb.append("=");
                sb.append(getValues().get(c));
                sb.append("\n");
            }
        }
        return sb.toString();
    }

}

Add a common row value class for PQS


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

package com.solsticesquared.schelling.move;

import com.solsticesquared.schelling.Agent;
import com.solsticesquared.schelling.SchellingExplorer;

import java.util.ArrayList;

/**
 * Represents an implementation of a {@link MovementMethod} that directly
 * swaps a pair of unhappy agents with each other.
 */
public class SwapMovementMethod implements MovementMethod {

    @Override
    public int getMinimumNumberOfAgentsRequired() {
        return 2;
    }

    @Override
    public void move(final ArrayList<Agent> agents,
                     final SchellingExplorer model) {
        // Obtain two random agents to operate on.
        final Agent agent0 = agents.remove(model.random.nextInt(agents.size()));
        final Agent agent1 = agents.remove(model.random.nextInt(agents.size()));

        // Swap!
        model.swapLocation(agent0, agent1);
    }
}

Add movement method to directly swap two unhappy agents.


package datamodel;

import java.util.Date;
import java.util.List;

public class CpuUsageResults {
    private long pid;
    private Date startTime;
    private List<String> cpuPerSecond;

    public CpuUsageResults(long pid, Date startTime, List<String> cpuPerSecond) {
        this.pid = pid;
        this.startTime = startTime;
        this.cpuPerSecond = cpuPerSecond;
    }

    public long getPid() {
        return pid;
    }

    public void setPid(long pid) {
        this.pid = pid;
    }

    public Date getStartTime() {
        return startTime;
    }

    public void setStartTime(Date startTime) {
        this.startTime = startTime;
    }

    public List<String> getCpuPerSecond() {
        return cpuPerSecond;
    }

    public void setCpuPerSecond(List<String> cpuPerSecond) {
        this.cpuPerSecond = cpuPerSecond;
    }
}

Add model for CPU usage.


package leetcode.number_of_islands;

import java.util.LinkedList;
import java.util.Queue;

public class Solution {
    public static class Point{
        int x, y;
        public Point(int x, int y){
            this.x = x;
            this.y = y;
        }
    }
    public int numIslands(char[][] grid) {
        if(grid == null || grid.length == 0 || grid[0].length == 0){
            return 0;
        }
        int w = grid[0].length;
        int h = grid.length;
        Queue<Point> queue = new LinkedList<Point>();
        int solution = 0;
        for(int x = 0; x < h; x++){
            for(int y = 0; y < w; y++){
                if(grid[x][y] == '1'){
                    solution++;
                    queue.offer(new Point(x, y));
                    grid[x][y] = '0';
                    while(!queue.isEmpty()){
                        Point cur = queue.remove();
                        int nx, ny;
                        nx = cur.x - 1;
                        ny = cur.y;
                        if(0 <= nx && nx < h && 0 <= ny && ny < w && grid[nx][ny] == '1'){
                            grid[nx][ny] = '0';
                            queue.offer(new Point(nx, ny));
                        }
                        nx = cur.x + 1;
                        ny = cur.y;
                        if(0 <= nx && nx < h && 0 <= ny && ny < w && grid[nx][ny] == '1'){
                            grid[nx][ny] = '0';
                            queue.offer(new Point(nx, ny));
                        }
                        nx = cur.x;
                        ny = cur.y - 1;
                        if(0 <= nx && nx < h && 0 <= ny && ny < w && grid[nx][ny] == '1'){
                            grid[nx][ny] = '0';
                            queue.offer(new Point(nx, ny));
                        }
                        nx = cur.x;
                        ny = cur.y + 1;
                        if(0 <= nx && nx < h && 0 <= ny && ny < w && grid[nx][ny] == '1'){
                            grid[nx][ny] = '0';
                            queue.offer(new Point(nx, ny));
                        }
                    }
                }
            }
        }
        return solution;
    }
}

Add java solution for 200. Number of Islands


/**
 *
 */
package org.traccar;

import org.traccar.helper.DistanceCalculator;
import org.traccar.helper.Log;
import org.traccar.model.Position;

/**
 * <p>
 *  ODO Meter handler
 * </p>
 *
 * @author Amila Silva
 *
 */
public class ODOMeterHandler extends BaseDataHandler {

	public ODOMeterHandler() {
		Log.debug("System based ODO meter calculation enabled for all devices");
	}

	private Position getLastPosition(long deviceId) {
		if (Context.getConnectionManager() != null) {
			return Context.getConnectionManager().getLastPosition(deviceId);
		}
		return null;
	}

	private Position calculateDistance(Position position) {
		Position last = getLastPosition(position.getDeviceId());
		if (last != null) {
			double distance = DistanceCalculator.distance(
					position.getLatitude(), position.getLongitude(),
					last.getLatitude(), last.getLongitude());
			distance = Math.round((distance) * 100.0) / 100.0;
			double odoMeter = distance + last.getOdoMeter();
//			Log.debug("::: Device Course : " + position.getDeviceId()
//					+ ", Distance :" + distance + "m, Odometer :" + odoMeter
//					+ " m");
			position.setOdoMeter(odoMeter);
		}
		return position;
	}

	@Override
	protected Position handlePosition(Position position) {
		return calculateDistance(position);
	}

}

/**
 *
 */
package org.traccar;

import org.traccar.helper.DistanceCalculator;
import org.traccar.helper.Log;
import org.traccar.model.Position;

/**
 * <p>
 *  Odometer handler
 * </p>
 *
 * @author Amila Silva
 *
 */
public class ODOMeterHandler extends BaseDataHandler {

	public ODOMeterHandler() {
		Log.debug("System based odometer calculation enabled for all devices");
	}

	private Position getLastPosition(long deviceId) {
		if (Context.getConnectionManager() != null) {
			return Context.getConnectionManager().getLastPosition(deviceId);
		}
		return null;
	}

	private Position calculateDistance(Position position) {
		Position last = getLastPosition(position.getDeviceId());
		if (last != null) {
			double distance = DistanceCalculator.distance(
					position.getLatitude(), position.getLongitude(),
					last.getLatitude(), last.getLongitude());
			distance = Math.round((distance) * 100.0) / 100.0;
			double odoMeter = distance + last.getOdoMeter();
//			Log.debug("::: Device Course : " + position.getDeviceId()
//					+ ", Distance :" + distance + "m, Odometer :" + odoMeter
//					+ " m");
			position.setOdoMeter(odoMeter);
		}
		return position;
	}

	@Override
	protected Position handlePosition(Position position) {
		return calculateDistance(position);
	}

}

Rename odometer to one word


package me.tdjones.main.model;

import javax.xml.bind.annotation.XmlAttribute;

/**
 * Created by Tyler on 7/3/2016.
 */
public class Enclosure {
    @XmlAttribute
    private String url;

    public String getUrl(){
        return url;
    }
}

Add enclosure model for grabbing episode url


package org.fedorahosted.flies.core.action;

import javax.persistence.EntityManager;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.ProduceMime;

import org.fedorahosted.flies.core.model.Project;
import org.fedorahosted.flies.core.model.ProjectSeries;
import org.fedorahosted.flies.core.model.ProjectTarget;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;

@Name("projectResource")
@Path("/project")
public class ProjectResource {

  @In
  private EntityManager entityManager;

  @Out(required = false)
  private Project project;

  @GET
  @Path("/{projectId}")
  @ProduceMime("text/plain")
  public Project getProject(@PathParam("projectId") long id) {
     return project = entityManager.find(Project.class, id);
  }

}

Add a Resources class of REST


package leetcode;

import java.util.Stack;

/**
 * https://leetcode.com/problems/basic-calculator-ii/
 */
public class Problem227 {
    public int calculate(String s) {
        String str = s.replaceAll("\\s+", "");
        Stack<Integer> operands = new Stack<>();
        Stack<Character> operators = new Stack<>();
        String num = "";
        for (char c : str.toCharArray()) {
            if (Character.isDigit(c)) {
                num += c;
            } else if (c == '+' || c == '-') {
                if (!num.isEmpty()) {
                    operands.add(Integer.parseInt(num));
                    num = "";
                }
                if (!operators.isEmpty()) {
                    evaluate(operands, operators);
                }
                operators.add(c);
            }
        }
        if (!num.isEmpty()) {
            operands.add(Integer.parseInt(num));
            num = "";
        }
        if (!operators.isEmpty()) {
            evaluate(operands, operators);
        }
        return operands.pop();
    }

    private void evaluate(Stack<Integer> operands, Stack<Character> operators) {
        char op = operators.pop();
        int a = operands.pop();
        int b = operands.pop();
        int val = evaluate(b, a, op);
        operands.add(val);
    }

    private int evaluate(int a, int b, char op) {
        if (op == '+') {
            return a + b;
        } else if (op == '-') {
            return a - b;
        } else if (op == '*') {
            return a * b;
        } else { // op == /
            return a / b;
        }
    }

    public static void main(String[] args) {
        Problem227 prob = new Problem227();
        System.out.println(prob.calculate("3+2*2"));
        System.out.println(prob.calculate(" 3/2 "));
        System.out.println(prob.calculate(" 3+5 / 2 "));
    }
}

Write a skeleton for problem 227


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

package tachyon.worker.file;

import org.powermock.reflect.Whitebox;

/**
 * Class which provides access to private state of {@link FileDataManager}.
 */
public final class FileSystemWorkerPrivateAccess {
  public static FileDataManager getFileSystemWorker(FileSystemWorker worker) {
    return Whitebox.getInternalState(worker, "mFileDataManager");
  }
}

Add private access harness for FileSystemWorker


package com.thegongoliers.output.motors;

import com.thegongoliers.input.current.HighCurrentSensor;
import com.thegongoliers.input.time.Clock;
import com.thegongoliers.input.time.RobotClock;

public class CircuitBreakerMotorModule implements MotorModule {

    private final HighCurrentSensor mCurrentSensor;
    private final double mBreakDuration;
    private final Clock mClock;

    private double mLastTripTime;

    private boolean mIsTripped;

    public CircuitBreakerMotorModule(HighCurrentSensor currentSensor, double breakDuration, Clock clock){
        mCurrentSensor = currentSensor;
        mBreakDuration = breakDuration;
        mClock = clock;
    }

    public CircuitBreakerMotorModule(HighCurrentSensor currentSensor, double breakDuration){
        this(currentSensor, breakDuration, new RobotClock());
    }

    @Override
    public double run(double currentSpeed, double desiredSpeed, double deltaTime) {
        if (mCurrentSensor.isTriggered()){
            trip();
        }

        if (mIsTripped && mClock.getTime() - mLastTripTime < mBreakDuration){
            mIsTripped = false;
        }

        if (mIsTripped){
            return 0;
        }

        return desiredSpeed;
    }

    private void trip(){
        mIsTripped = true;
        mLastTripTime = mClock.getTime();
    }

}

Add circuit breaker motor module


/*
 * OntologyMetric.java
 *
 */

package de.uni_stuttgart.vis.vowl.owl2vowl.model;

/**
 *
 */
public class OntologyMetric {
	private int classCount;
	private int objectPropertyCount;
	private int dataPropertyCount;
	private int datatypeCount;
	private int propertyCount;
	private int nodeCount;

	/* Unused */
	private int individualCount;
	private int axiomCount;

	public OntologyMetric() {
	}

	public void calculateSums() {
		datatypeCount = dataPropertyCount;
		propertyCount = objectPropertyCount + dataPropertyCount;
		nodeCount = datatypeCount + classCount;
	}

	public int getIndividualCount() {
		return individualCount;
	}

	public void setIndividualCount(int individualCount) {
		this.individualCount = individualCount;
	}

	public int getClassCount() {
		return classCount;
	}

	public void setClassCount(int classCount) {
		this.classCount = classCount;
	}

	public int getObjectPropertyCount() {
		return objectPropertyCount;
	}

	public void setObjectPropertyCount(int objectPropertyCount) {
		this.objectPropertyCount = objectPropertyCount;
	}

	public int getDataPropertyCount() {
		return dataPropertyCount;
	}

	public void setDataPropertyCount(int dataPropertyCount) {
		this.dataPropertyCount = dataPropertyCount;
	}

	public int getAxiomCount() {
		return axiomCount;
	}

	public void setAxiomCount(int axiomCount) {
		this.axiomCount = axiomCount;
	}

	public int getPropertyCount() {
		return propertyCount;
	}

	public void setPropertyCount(int propertyCount) {
		this.propertyCount = propertyCount;
	}

	public int getDatatypeCount() {
		return datatypeCount;
	}

	public void setDatatypeCount(int datatypeCount) {
		this.datatypeCount = datatypeCount;
	}

	public int getNodeCount() {
		return nodeCount;
	}

	public void setNodeCount(int nodeCount) {
		this.nodeCount = nodeCount;
	}
}

Add new class for the metrics.


package leetcode.unique_paths_ii;

public class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
    	if(obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0) return 0;
    	int height = obstacleGrid.length;
    	int width = obstacleGrid[0].length;
    	if(obstacleGrid[0][0] > 0) return 0;
    	if(obstacleGrid[height - 1][width - 1] > 0) return 0;
    	obstacleGrid[0][0] = -1;
    	for(int i = 0; i < height; i++){
    		for(int j = 0; j < width; j++){
    			if(obstacleGrid[i][j] == 0){
	    			if(i > 0){
	    				if(obstacleGrid[i - 1][j] <= 0){
	    					obstacleGrid[i][j] += obstacleGrid[i - 1][j];
	    				}
	    			}
	    			if(j > 0){
	    				if(obstacleGrid[i][j - 1] <= 0){
	    					obstacleGrid[i][j] += obstacleGrid[i][j - 1];
	    				}
	    			}
    			}
    		}
    	}
    	return -obstacleGrid[height - 1][width - 1];
    }

    public static void main(String[] args){
    	int[][] map = new int[3][3];
    	map[0][0] = 1;
    	System.err.println(new Solution().uniquePathsWithObstacles(map) + "");
    }
}

Add java solution for 63. Unique Paths II


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

import org.junit.Test;
import org.spine3.test.Tests;

import static org.junit.Assert.assertEquals;

/**
 * @author Alex Tymchenko
 */
public class FailureBusBuilderShould {

    @Test(expected = NullPointerException.class)
    public void do_not_accept_null_DispatcherDelivery() {
        FailureBus.newBuilder()
                  .setDispatcherFailureDelivery(Tests.<DispatcherFailureDelivery>nullRef());
    }

    @SuppressWarnings("OptionalGetWithoutIsPresent")    //It's fine as for the Builder tests
    @Test
    public void return_set_DispatcherDelivery() {
        final DispatcherFailureDelivery delivery = deliveryForTests();
        assertEquals(delivery, FailureBus.newBuilder()
                                         .setDispatcherFailureDelivery(delivery)
                                         .getDispatcherFailureDelivery()
                                         .get());
    }

    private static DispatcherFailureDelivery deliveryForTests() {
        return new DispatcherFailureDelivery() {
            @Override
            protected boolean shouldPostponeDelivery(FailureEnvelope deliverable,
                                                     FailureDispatcher consumer) {
                return false;   // does not really matter for tests.
            }
        };
    }
}

Create some tests for the `FailureBus.Builder`.


package ar.edu.unc.famaf.redditreader.backend;

import android.os.AsyncTask;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import ar.edu.unc.famaf.redditreader.model.Listing;

/**
 * Created by aguilarjp on 27/10/16.
 */

public class GetTopPostsTask extends AsyncTask<URL, Integer, Listing> {

    @Override
    protected Listing doInBackground(URL... params) {
        InputStream inputStream = null;
        try {
            HttpURLConnection conn = (HttpURLConnection) params[0].openConnection();
            conn.setRequestMethod("GET");
            inputStream = conn.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Listing listing = null;

        try {
            listing = new Parser().readJsonStream(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return listing;
    }
}

Create a task to download top posts JSON


package org.realityforge.replicant.client.transport;

import javax.annotation.Nonnull;

/**
 * Abstract representation of client session.
 * Simply tracks the session identifier and job sequencing.
 */
public abstract class ClientSession
{
  private final String _sessionID;
  private final RequestManager _requestManager;

  public ClientSession( @Nonnull final String sessionID )
  {
    _sessionID = sessionID;
    _requestManager = newRequestManager();
  }

  @Nonnull
  public String getSessionID()
  {
    return _sessionID;
  }

  @Nonnull
  public RequestManager getRequestManager()
  {
    return _requestManager;
  }

  protected RequestManager newRequestManager()
  {
    return new RequestManager();
  }
}

Introduce a base class for sessions


// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.plugin.mojo;

import org.apache.maven.project.MavenProject;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.jar.JarFile;

/**
 * @author bjorncs
 */
class TestBundleUtils {
    private TestBundleUtils() {}

    static Path outputDirectory(MavenProject project) { return targetDirectory(project).resolve("test-bundle/"); }

    static Path manifestFile(MavenProject project) { return outputDirectory(project).resolve(JarFile.MANIFEST_NAME); }

    static Path archiveFile(MavenProject project) {
        return targetDirectory(project).resolve(project.getBuild().getFinalName() + "-tests.jar");
    }

    private static Path targetDirectory(MavenProject project) { return Paths.get(project.getBuild().getDirectory()); }
}

Add helper class for test bundles


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

package org.apache.flink.test.recovery;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.api.functions.source.RichSourceFunction;

import org.junit.Test;

import java.util.concurrent.atomic.AtomicInteger;

import static org.junit.Assert.fail;

public class FastFailuresITCase {

	static final AtomicInteger FAILURES_SO_FAR = new AtomicInteger();
	static final int NUM_FAILURES = 200;

	@Test
	public void testThis() {
		StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

		env.getConfig().setExecutionRetryDelay(0);
		env.setParallelism(4);
		env.enableCheckpointing(1000);

		DataStream<Tuple2<Integer, Integer>> input = env.addSource(new RichSourceFunction<Tuple2<Integer, Integer>>() {

			@Override
			public void open(Configuration parameters) {
				if (FAILURES_SO_FAR.incrementAndGet() <= NUM_FAILURES) {
					throw new RuntimeException("fail");
				}
			}

			@Override
			public void run(SourceContext<Tuple2<Integer, Integer>> ctx)  {}

			@Override
			public void cancel() {}
		});

		input
				.keyBy(0)
				.map(new MapFunction<Tuple2<Integer, Integer>, Integer>() {

					@Override
					public Integer map(Tuple2<Integer, Integer> value) {
						return value.f0;
					}
				})
				.addSink(new SinkFunction<Integer>() {
					@Override
					public void invoke(Integer value) {}
				});

		try {
			env.execute();
		}
		catch (Exception e) {
			e.printStackTrace();
			fail(e.getMessage());
		}
	}
}

Add test for a program with very fast failure rates.


package com.cflint;

import static org.junit.Assert.assertEquals;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;

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

import cfml.parsing.reporting.ParseException;

import com.cflint.config.CFLintPluginInfo.PluginInfoRule;
import com.cflint.config.CFLintPluginInfo.PluginInfoRule.PluginMessage;
import com.cflint.config.ConfigRuntime;
import com.cflint.plugins.core.FileCaseChecker;

public class TestFileCaseChecker {

	private CFLint cfBugs;

	@Before
	public void setUp() {
		final ConfigRuntime conf = new ConfigRuntime();
		final PluginInfoRule pluginRule = new PluginInfoRule();
		pluginRule.setName("FileCaseChecker");
		conf.getRules().add(pluginRule);
		PluginMessage pluginMessage = new PluginMessage("FILE_SHOULD_START_WITH_LOWERCASE");
		pluginMessage.setSeverity("INFO");
		pluginRule.getMessages().add(pluginMessage);

		cfBugs = new CFLint(conf, new FileCaseChecker());
	}

	@Test
	public void testLowerCaseCFMName() throws ParseException, IOException {
		final String cfmSrc = "<cfset a = 23>";
		cfBugs.process(cfmSrc, "test.cfm");
		Collection<List<BugInfo>> result = cfBugs.getBugs().getBugList().values();
		assertEquals(0, result.size());
	}

	@Test
	public void testLowerCaseCFCName() throws ParseException, IOException {
		final String cfcSrc = "<cfcomponent></cfcomponent>";
		cfBugs.process(cfcSrc, "test.cfc");
		Collection<List<BugInfo>> result = cfBugs.getBugs().getBugList().values();
		assertEquals(0, result.size());
	}

	@Test
	public void testUppeCaseCFMName() throws ParseException, IOException {
		final String cfmSrc = "<cfset a = 23>";
		cfBugs.process(cfmSrc, "Test.cfm");
		final List<BugInfo> result = cfBugs.getBugs().getBugList().values().iterator().next();
		assertEquals(1, result.size());
		assertEquals("FILE_SHOULD_START_WITH_LOWERCASE", result.get(0).getMessageCode());
		assertEquals(1, result.get(0).getLine());
	}

	@Test
	public void testUppperCaseCFCName() throws ParseException, IOException {
		final String cfcSrc = "<cfcomponent></cfcomponent>";
		cfBugs.process(cfcSrc, "Test.cfc");
		Collection<List<BugInfo>> result = cfBugs.getBugs().getBugList().values();
		assertEquals(0, result.size());
	}

}

Add tests for file case checker rule


package com.example.android.sunshine.app.data;

import android.content.ComponentName;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.test.AndroidTestCase;

public class TestProvider extends AndroidTestCase {

    public void testProviderRegistry() {
        PackageManager pm = mContext.getPackageManager();

        // We define the component name based on the package name from the context and the
        // WeatherProvider class.
        ComponentName componentName = new ComponentName(mContext.getPackageName(),
                WeatherProvider.class.getName());
        try {
            // Fetch the provider info using the component name from the PackageManager
            // This throws an exception if the provider isn't registered.
            ProviderInfo providerInfo = pm.getProviderInfo(componentName, 0);

            // Make sure that the registered authority matches the authority from the Contract.
            assertEquals("Error: WeatherProvider registered with authority: " + providerInfo.authority +
                    " instead of authority: " + WeatherContract.CONTENT_AUTHORITY,
                    providerInfo.authority, WeatherContract.CONTENT_AUTHORITY);
        } catch (PackageManager.NameNotFoundException e) {
            // I guess the provider isn't registered correctly.
            assertTrue("Error: WeatherProvider not registered at " + mContext.getPackageName(),
                    false);
        }
    }
}

Add test to see if ContentProvider is registered


/*
 * 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 com.mpalourdio.hello.controllers;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

@Controller
@RequestMapping("/forwarder")
public class ForwarderController {

    @GetMapping("/first")
    public String entryPoint() {
        return "forward:/forwarder/second";
    }

    @GetMapping(value = "/second", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map forwardedPoint() {
        final Map<String, Boolean> map = new HashMap<>();
        map.put("forwarded", true);

        return map;
    }
}

Add a quick example on how to forward requests


/* Copyright 2020 Braden Farmer
 *
 * 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.farmerbb.taskbar.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.farmerbb.taskbar.util.AppEntry;
import com.farmerbb.taskbar.util.DesktopIconInfo;
import com.farmerbb.taskbar.util.U;

import org.json.JSONArray;
import org.json.JSONException;

public class DesktopIconSelectAppActivity extends AbstractSelectAppActivity {

    private DesktopIconInfo desktopIcon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        desktopIcon = (DesktopIconInfo) getIntent().getSerializableExtra("desktop_icon");
    }

    @Override
    public void selectApp(AppEntry entry) {
        desktopIcon.entry = entry;

        try {
            SharedPreferences pref = U.getSharedPreferences(this);
            JSONArray icons = new JSONArray(pref.getString("desktop_icons", "[]"));
            icons.put(desktopIcon.toJson(this));

            pref.edit().putString("desktop_icons", icons.toString()).apply();
            LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("com.farmerbb.taskbar.REFRESH_DESKTOP_ICONS"));
        } catch (JSONException e) { /* Gracefully fail */ }

        finish();
    }
}

Integrate the Persistent Shortcuts app into Taskbar (2 of 2)


/**
 * Meta-annotations for describing recommender parameters.
 * <p>
 * RefLens makes heavy use of annotations to describe parameters to allow Guice
 * to be used to provide parameter values.  The annotations in this package are
 * intended to be applied to such annotations and are used by the default Guice
 * module logic to set up default values and read parameters from Java properties.
 * See {@link org.grouplens.reflens.RecommenderModule}'s protected support methods
 * for information on how these annotations can be used.
 */
package org.grouplens.reflens.params.meta;

Add documentation for o.g.r.p.meta package


package jmemproxy.test;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

public class TcpClient {
	public static void main(String argv[]) throws IOException {
		String request;
		String response;
		BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
		Socket clientSocket = null;
		try {
			clientSocket = new Socket("127.0.0.1", 11218);
			DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
			BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
			while (true) {
				request = inFromUser.readLine();
				outToServer.writeBytes(request + '\n');
				response = inFromServer.readLine();
				System.out.println("FROM SERVER: " + response);
			}
		} finally {
			if (clientSocket != null)
				clientSocket.close();
		}

	 }

}

Add tcp client for testing


package co.phoenixlab.common.lang.io;

import org.junit.*;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;

import static org.junit.Assert.*;

public class LittleEndianDataInputStreamTest {

    @Test
    public void testReadByte() throws Exception {
        byte b = (byte) 0x12;
        ByteArrayInputStream bais = new ByteArrayInputStream(new byte[] {b});
        DataInputStream dis = new DataInputStream(bais);
        LittleEndianDataInputStream ledis = new LittleEndianDataInputStream(dis);
        assertEquals(b, ledis.readByte());
    }

    @Test
    public void testReadUnsignedByte() throws Exception {
        int i = 200;
        ByteArrayInputStream bais = new ByteArrayInputStream(new byte[] {(byte) i});
        DataInputStream dis = new DataInputStream(bais);
        LittleEndianDataInputStream ledis = new LittleEndianDataInputStream(dis);
        assertEquals(i, ledis.readUnsignedByte());
    }

    @Test
    public void testReadShort() throws Exception {

    }

    @Test
    public void testReadUnsignedShort() throws Exception {

    }

    @Test
    public void testReadChar() throws Exception {

    }

    @Test
    public void testReadInt() throws Exception {

    }

    @Test
    public void testReadUnsignedInt() throws Exception {

    }

    @Test
    public void testReadLong() throws Exception {

    }

    @Test
    public void testReadFloat() throws Exception {

    }

    @Test
    public void testReadDouble() throws Exception {

    }
}

Add initial testing for LEDIS


package jaxrs;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

/**
 * Some web containers, such as WebSphere Liberty, serve JAX-RS HTML responses as ISO-8859-1
 * regardless of what the JSP file indicates. This filter checks for HTML responses and
 * forces their content charset to UTF-8.
 */
@Provider
public class UTFFilterResponse implements ContainerResponseFilter {
    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
        String contentType = responseContext.getHeaderString("Content-Type");
        if(contentType != null && contentType.startsWith("text/html")) {
            // Set it to UTF-8
            responseContext.getHeaders().putSingle("Content-Type", "text/html;charset=UTF-8");
        }
    }
}

Add UTF-8 response filter for WebSphere


package com.basgeekball.awesomevalidation;

import com.basgeekball.awesomevalidation.validators.BasicValidator;
import com.basgeekball.awesomevalidation.validators.ColorationValidator;
import com.basgeekball.awesomevalidation.validators.UnderlabelValidator;

import junit.framework.TestCase;

import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;

@RunWith(PowerMockRunner.class)
@PrepareForTest(AwesomeValidation.class)
public class AwesomeValidationTest extends TestCase {

    public void testAwesomeValidationConstructBasicStyle() {
        AwesomeValidation awesomeValidation = new AwesomeValidation(ValidationStyle.BASIC);
        assertTrue(Whitebox.getInternalState(awesomeValidation, "mValidator") instanceof BasicValidator);
    }

    public void testAwesomeValidationConstructColorationStyle() {
        AwesomeValidation awesomeValidation = new AwesomeValidation(ValidationStyle.COLORATION);
        assertTrue(Whitebox.getInternalState(awesomeValidation, "mValidator") instanceof ColorationValidator);
    }

    public void testAwesomeValidationConstructUnderlabelValidatorStyle() {
        AwesomeValidation awesomeValidation = new AwesomeValidation(ValidationStyle.UNDERLABEL);
        assertTrue(Whitebox.getInternalState(awesomeValidation, "mValidator") instanceof UnderlabelValidator);
    }

}

Add tests for AwesomeValidation's constructor


// Use wait() and notify() to create a ticking clock.

class TickTock {

	synchronized void tick(boolean running) {
		if(!running) { // stop the clock
			notify();	// notify any waiting threads
			return;
		}

		System.out.print("Tick ");
		notify(); // let tock() run
		try {
			wait(); // wait for tock() to complete
		}
		catch(InterruptedException exc) {
			System.out.println("Thread interrupted.");
		}
	}

	synchronized void tock(boolean running) {
		if(!running) { // stop the clock
			notify();	// notify any waiting threads
			return;
		}

		System.out.println("Tock");
		notify(); // let tick() run
		try {
			wait(); // wait for tick() to complete
		}
		catch(InterruptedException exc) {
			System.out.println("Thread interrupted.");
		}
	}
}

class MyThread implements Runnable {
	Thread thrd;
	TickTock ttOb;

	// Construct a new thread.
	MyThread(String name, TickTock tt) {
		thrd = new Thread(this, name);
		ttOb = tt;
		thrd.start(); // start the thread
	}

	// Begin execution of new thread.
	public void run() {

		if(thrd.getName().compareTo("Tick") == 0) {
			for(int i=0; i<5; i++) ttOb.tick(true);
			ttOb.tick(false);
		}
		else {
			for(int i=0; i<5; i++) ttOb.tock(true);
			ttOb.tock(false);
		}
	}
}

class ThreadCom {
	public static void main(String args[]) {
		TickTock tt = new TickTock();
		MyThread mt1 = new MyThread("Tick", tt);
		MyThread mt2 = new MyThread("Tock", tt);
		try {
			mt1.thrd.join();
			mt2.thrd.join();
		} catch(InterruptedException exc) {
			System.out.println("Main thread interrupted.");
		}
	}
}

Use wait() and notify() for thread communication


package study.hard.javalib.nativelib;

import static org.junit.Assert.*;

import org.junit.Test;

/**
 * A test case for shift operator.
 * @author iandmyhand@gmail.com
 */
public class ShiftOperatorTest {

	@Test
	public void testShiftOperator() {
		int i = 0;

		i = 2;
		System.out.print("i: " + i);
		System.out.println(" [" + getBit(i) + "]");

		i = 2;
		i = i << 1;
		System.out.print("i: " + i);
		System.out.println(" [" + getBit(i) + "]");
		assertEquals(4, i);

		i = 2;
		i = i << 2;
		System.out.print("i: " + i);
		System.out.println(" [" + getBit(i) + "]");
		assertEquals(8, i);

		i = 8;
		i = i >> 2;
		System.out.print("i: " + i);
		System.out.println(" [" + getBit(i) + "]");
		assertEquals(2, i);
	}

	String getBit(int n) {
		int[] array = new int[8];
		int iattr = (int)((byte)n & 0xFF);
		int bitWise = 1;
		for (int i = 0; i < 8; i++) {
			if ((bitWise & iattr) > 0)
				array[i] = 1;
			else
				array[i] = 0;
			bitWise = (bitWise << 1) & 0xfe;
		}
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < array.length; ++i)
			sb.append(array[7 - i]);
		return sb.toString();
	}
}

Add test case for shift operator.


package eu.dariah.de.colreg.security;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import eu.dariah.de.colreg.model.PersistedUserDetails;
import eu.dariah.de.colreg.service.CollectionService;

public class UserContextInterceptor extends HandlerInterceptorAdapter {
	@Autowired private CollectionService collectionService;

	@Value(value="${url.login:null}")
	private String loginUrl;

	@Value(value="${url.logout:null}")
	private String logoutUrl;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		PersistedUserDetails user = null;
		HttpSession session = request.getSession();

		if (auth != null && auth.getDetails() instanceof PersistedUserDetails) {
			user = (PersistedUserDetails) auth.getDetails();

			int draftCount = collectionService.findAllDrafts(user.getId()).size();
			session.setAttribute("_draftCount", draftCount);
		}
		session.setAttribute("_loginUrl", loginUrl);
		session.setAttribute("_logoutUrl", logoutUrl);
		return super.preHandle(request, response, handler);
	}
}

Implement simple security with local logins


/**
 *
 */
package org.usfirst.frc.team2339.Barracuda.smartdashboard;

import edu.wpi.first.wpilibj.Sendable;
import edu.wpi.first.wpilibj.tables.ITable;

/**
 * @author RobolopesDev
 *
 */
public class AutoSettings implements Sendable {

    private ITable table;
    private double forward;

	/* (non-Javadoc)
	 * @see edu.wpi.first.wpilibj.Sendable#initTable(edu.wpi.first.wpilibj.tables.ITable)
	 */
	@Override
	public void initTable(ITable subtable) {
        this.table = subtable;
        if (table != null) {
            table.putValue("forward", forward);
        }
	}

	/* (non-Javadoc)
	 * @see edu.wpi.first.wpilibj.Sendable#getTable()
	 */
	@Override
	public ITable getTable() {
		return table;
	}

	/* (non-Javadoc)
	 * @see edu.wpi.first.wpilibj.Sendable#getSmartDashboardType()
	 */
	@Override
	public String getSmartDashboardType() {
		return "Robolopes Autonomous Settings";
	}

}

Create auto settings dash object.


package org.micromanager.intelligentacquisition;

/**
 * Strings needed in various classes in this plugin
 * Guarantees that these strings are the same and that they can be changed
 *
 *
 * @author nico
 */
public class Terms {

   public static final String FRAME = "Frame";
   public static final String POSITION = "Position";
   public static final String CHANNEL = "Channel";
   public static final String SLICE = "Slice";
   public static final String X = "X";
   public static final String Y = "Y";
   public static final String RESULTTABLENAME = "IA Test Results";

}

Split out static String to its own class


/**
 * Aeronica's mxTune MOD
 * Copyright {2016} Paul Boese a.k.a. Aeronica
 *
 * 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.aeronica.mods.mxtune.network.client;

import java.io.IOException;

import net.aeronica.mods.mxtune.groups.PlayManager;
import net.aeronica.mods.mxtune.network.AbstractMessage.AbstractClientMessage;
import net.aeronica.mods.mxtune.sound.ClientAudio;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.PacketBuffer;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class StopPlayMessage extends AbstractClientMessage<StopPlayMessage>
{

    private Integer playID;

    public StopPlayMessage() {}

    public StopPlayMessage(Integer playID) {this.playID = playID;}

    @Override
    protected void read(PacketBuffer buffer) throws IOException
    {
        playID = ByteBufUtils.readVarInt(buffer, 5);
    }

    @Override
    protected void write(PacketBuffer buffer) throws IOException
    {
        ByteBufUtils.writeVarInt(buffer, playID, 5);
    }

    @Override
    public void process(EntityPlayer player, Side side)
    {
        if (side.isClient())
        {
            handleClientSide(player);
        } else
        {
            handleServerSide(player);
        }
    }

    @SideOnly(Side.CLIENT)
    public void handleClientSide(EntityPlayer playerSP)
    {
        // TODO: More Cleanup for playing - resetting all the players PlayStatuses
        ClientAudio.stop(playID);
    }

    public void handleServerSide(EntityPlayer playerMP)
    {
        //PlayManager.stopPlayID(playID);
    }

}

Rework Play Music chain to improve reliability, eliminate clicks and pops on abrupt cutoff. Part 1


package ru.ydn.wicket.wicketorientdb.model;

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

import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;

public class CollectionAdapterModel<T, M extends Collection<T>> extends LoadableDetachableModel<List<T>>
{
	private IModel<M> model;

	public CollectionAdapterModel(IModel<M> model) {
		this.model = model;
	}

	@Override
	protected List<T> load() {
		M ret = model.getObject();
		if(ret==null) return null;
		else if(ret instanceof List) return (List<T>)ret;
		else return new ArrayList<T>(ret);
	}

	@Override
	public void setObject(List<T> object) {
		setCollection(object);
		super.setObject(object);
	}

	protected void setCollection(List<T> object)
	{
		if(object==null) model.setObject(null);
		else
		{
			M collection = model.getObject();
			if(collection!=null)
			{
				collection.clear();
				collection.addAll(object);
			}
			else
			{
				throw new WicketRuntimeException("Creation of collection is not supported. Please override this method of you need support.");
			}
		}
	}

	@Override
	protected void onDetach() {
		super.onDetach();
		model.detach();
	}

}

Add model for transparent transformation of collections to List


package com.javarush.test.level05.lesson12.home04;

/* Вывести на экран сегодняшнюю дату
Вывести на экран текущую дату в аналогичном виде "21 02 2014".
*/
// ресурс http://www.seostella.com/ru/article/2012/02/05/formatirovanie-daty-v-java.html

import java.text.SimpleDateFormat;
import java.util.Date;

public class Solution
{
        public static void main(String[] args)
        {
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy");
            System.out.println( dateFormat.format( new Date() ) );

            //    System.out.println(new java.util.Date());

            //--- Variant 2
            //   System.out.println(java.util.Calendar.getInstance().getTime());

        }

    }

Print current (actual) date in form as "dd MM yyyy"