/*
 * Copyright (C) 2016 Thinkenterprise
 *
 * 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.
 *
 *

 * @author Michael Schaefer
 */

package com.thinkenterprise;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Add Spring Boot JPA Start Sample


package org.springframework.mock.http.client;

/*
 *
 * Riptide
 *
 * Copyright (C) 2015 - 2016 Zalando SE
 *
 * 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.
 *
 */

import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.mock.http.MockHttpInputMessage;
import org.springframework.util.Assert;

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

public class MockClientHttpResponse extends MockHttpInputMessage implements ClientHttpResponse {

    private final HttpStatus status;

    /**
     * Constructor with response body as a byte array.
     */
    public MockClientHttpResponse(byte[] body, HttpStatus statusCode) {
        super(body);
        Assert.notNull(statusCode, "statisCode is required");
        this.status = statusCode;
    }

    /**
     * Constructor with response body as InputStream.
     */
    public MockClientHttpResponse(InputStream body, HttpStatus statusCode) {
        super(body);
        Assert.notNull(statusCode, "statisCode is required");
        this.status = statusCode;
    }

    @Override
    public HttpStatus getStatusCode() throws IOException {
        return this.status;
    }

    @Override
    public int getRawStatusCode() throws IOException {
        return this.status.value();
    }

    @Override
    public String getStatusText() throws IOException {
        return this.status.getReasonPhrase();
    }

    @Override
    public void close() {
        try {
            this.getBody().close();
        } catch (IOException e) {
        }
    }

}

Align mock mvc behaviour with real http client


/*
 * Copyright (c) 2016-2019 Chronicle Software Ltd
 */

package net.openhft.chronicle.wire;

public class WatermarkedMicroTimestampLongConverter extends MicroTimestampLongConverter {
    @Override
    public long parse(CharSequence text) {
        char letter = text.charAt(0);
        if (('A' <= letter && letter <= 'Z') || ('a' <= letter && letter <= 'z')) {
            int digit = text.charAt(1);
            if ('0' <= digit && digit <= '9') {
                long watermark = (long) (((letter & 0x31) - 1) * 10 + digit) << -8;
                long parse = super.parse(text.subSequence(2, text.length()));
                return parse | watermark;
            }
        }
        throw new IllegalArgumentException("Unknown watermark");
    }

    @Override
    public void append(StringBuilder text, long value) {
        long time = value & (~0L << -8);
        long watermark = value >>> -8;
        text.append((char) ('A' + watermark / 10));
        text.append(watermark % 10);
        super.append(text, time);
    }
}

Add Chronicle FIX 4.4. and use the LATEST build otherwise a specific version doesn't get updated.


/*
 * Copyright 2015-2016 the original author or authors.
 *
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution and is available at
 *
 * http://www.eclipse.org/legal/epl-v10.html
 */

package org.junit.jupiter.engine.vintage.rulesupport;

import org.junit.Rule;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.rules.ExternalResource;

@ExtendWith(ExternalResourceLegacySupport.class)
public class MultipleExternalResourceLegacySupportTests {

	private static boolean beforeOfRule1WasExecuted = false;
	private static boolean beforeOfRule2WasExecuted = false;

	private static boolean afterOfRule1WasExecuted = false;
	private static boolean afterOfRule2WasExecuted = false;

	@Rule
	public ExternalResource resource1 = new ExternalResource() {
		@Override
		protected void before() throws Throwable {
			beforeOfRule1WasExecuted = true;
		}

		@Override
		protected void after() {
			afterOfRule1WasExecuted = true;
		}
	};

	@Rule
	public ExternalResource resource2 = new ExternalResource() {
		@Override
		protected void before() throws Throwable {
			beforeOfRule2WasExecuted = true;
		}

		@Override
		protected void after() {
			afterOfRule2WasExecuted = true;
		}
	};

	@Test
	void beforeMethodsOfbothRulesWereExecuted() {
		assert beforeOfRule1WasExecuted;
		//		assert beforeOfRule2WasExecuted;
	}

	@AfterAll
	static void afterMethodsOfBothRulesWereExecuted() {
		assert afterOfRule1WasExecuted;
		//        assert afterOfRule2WasExecuted;
	}

}

Support rules of type ExternalResource


package com.github.gabrielruiu.spring.cloud.config.redis;

import org.springframework.cloud.config.environment.PropertySource;

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

/**
 * @author Gabriel Mihai Ruiu (gabriel.ruiu@mail.com)
 */
public class PropertySourceBuilder {

    private String name;
    private Map<String, String> propertyMap = new HashMap<>();

    public static PropertySourceBuilder aPropertySource() {
        return new PropertySourceBuilder();
    }

    public PropertySourceBuilder withName(String name) {
        this.name = name;
        return this;
    }

    public PropertySourceBuilder withProperty(String key, String value) {
        this.propertyMap.put(key, value);
        return this;
    }

    public PropertySource build() {
        return new PropertySource(name, propertyMap);
    }
}

Add builder to help prepare expected instances of PropertySource in tests It's better than doing everything (instantiating the PropertySource along with the Map) inside the test itself, which would occupy much space


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

package org.apache.harmony.tests.java.io;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

import junit.framework.TestCase;

public class RandomAccessFileTest extends TestCase {

	/**
	 * @tests java.io.RandomAccessFile#RandomAccessFile(java.io.File, java.lang.String)
	 */
	public void test_ConstructorLjava_io_FileLjava_lang_String() throws IOException {
		// Regression for HARMONY-50
        File f = File.createTempFile("xxx", "yyy");
        f.deleteOnExit();
        RandomAccessFile raf = new RandomAccessFile(f, "rws");
        raf.close();

        f = File.createTempFile("xxx", "yyy");
        f.deleteOnExit();
        raf = new RandomAccessFile(f, "rwd");
        raf.close();
    }
}

Test case for HARMONY-50 (rightly part of revision 389232)


package com.nitorcreations.willow.metrics;

import com.nitorcreations.willow.messages.event.EventMessage;

import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

@Named("/event")
public class EventMetric extends FullMessageMetric<EventMessage,Collection<EventMessage>> {

  @Override
  protected Collection<EventMessage> processData(long start, long stop, int step, HttpServletRequest req) {
    return rawData.values();
  }
}

Add metric endpoint for events


package net.spals.appbuilder.app.grpc;

import com.google.inject.Guice;
import com.google.inject.Module;
import io.grpc.*;
import net.spals.appbuilder.graph.model.ServiceGraph;
import org.testng.annotations.Test;

import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

/**
 * Unit tests for {@link GrpcWebServerModule}
 *
 * @author tkral
 */
public class GrpcWebServerModuleTest {

    @Test
    public void testCompressorRegistry() {
        final CompressorRegistry compressorRegistry = CompressorRegistry.newEmptyInstance();
        final ServerBuilder<?> grpcExternalServerBuilder = mock(ServerBuilder.class);

        final Module compressorRegistryModule = binder ->
            binder.bind(CompressorRegistry.class).toInstance(compressorRegistry);
        Guice.createInjector(
            createWebServerModule("testCompressorRegistry", grpcExternalServerBuilder),
            compressorRegistryModule
        );

        verify(grpcExternalServerBuilder).compressorRegistry(same(compressorRegistry));
    }

    @Test
    public void testDecompressorRegistry() {
        final DecompressorRegistry decompressorRegistry = DecompressorRegistry.emptyInstance();
        final ServerBuilder<?> grpcExternalServerBuilder = mock(ServerBuilder.class);

        final Module decompressorRegistryModule = binder ->
            binder.bind(DecompressorRegistry.class).toInstance(decompressorRegistry);
        Guice.createInjector(
            createWebServerModule("testDecompressorRegistry", grpcExternalServerBuilder),
            decompressorRegistryModule
        );

        verify(grpcExternalServerBuilder).decompressorRegistry(same(decompressorRegistry));
    }

    @Test
    public void testHandlerRegistry() {
        final HandlerRegistry handlerRegistry = mock(HandlerRegistry.class);
        final ServerBuilder<?> grpcExternalServerBuilder = mock(ServerBuilder.class);

        final Module handlerRegistryModule = binder ->
            binder.bind(HandlerRegistry.class).toInstance(handlerRegistry);
        Guice.createInjector(
            createWebServerModule("testHandlerRegistry", grpcExternalServerBuilder),
            handlerRegistryModule
        );

        verify(grpcExternalServerBuilder).fallbackHandlerRegistry(same(handlerRegistry));
    }

    @Test
    public void testServerTransportFilter() {
        final ServerTransportFilter serverTransportFilter = mock(ServerTransportFilter.class);
        final ServerBuilder<?> grpcExternalServerBuilder = mock(ServerBuilder.class);

        final Module serverTransportFilterModule = binder ->
            binder.bind(ServerTransportFilter.class).toInstance(serverTransportFilter);
        Guice.createInjector(
            createWebServerModule("testServerTransportFilter", grpcExternalServerBuilder),
            serverTransportFilterModule
        );

        verify(grpcExternalServerBuilder).addTransportFilter(same(serverTransportFilter));
    }

    private GrpcWebServerModule createWebServerModule(
        final String name,
        final ServerBuilder<?> grpcExternalServerBuilder
    ) {
        return new GrpcWebServerModule.Builder()
            .setApplicationName(name)
            .setServiceGraph(new ServiceGraph())
            .setGrpcExternalServerBuilder(grpcExternalServerBuilder)
            .build();
    }
}

Add unit tests for GrpcWebServerModule


package io.github.droidkaigi.confsched2017.debug;

import com.tomoima.debot.strategy.DebotStrategy;

import android.app.Activity;
import android.support.annotation.NonNull;

import javax.inject.Inject;

public class NotificationStrategy extends DebotStrategy {

    @Inject
    public NotificationStrategy() {
    }

    @Override
    public void startAction(@NonNull Activity activity) {
        // Do nothing
    }
}

Add notification strategy for release build


package org.oskari.control.userlayer;

import org.oskari.map.userlayer.service.UserLayerDbService;

import fi.nls.oskari.control.ActionConstants;
import fi.nls.oskari.control.ActionDeniedException;
import fi.nls.oskari.control.ActionException;
import fi.nls.oskari.control.ActionParameters;
import fi.nls.oskari.control.ActionParamsException;
import fi.nls.oskari.domain.map.userlayer.UserLayer;

public class UserLayerHandlerHelper {

    public static UserLayer getUserLayer(UserLayerDbService service, ActionParameters params) throws ActionException {
        params.requireLoggedInUser();
        long id = params.getRequiredParamLong(ActionConstants.KEY_ID);
        UserLayer userLayer = service.getUserLayerById(id);
        if (userLayer == null) {
            throw new ActionParamsException("UserLayer doesn't exist: " + id);
        }
        if (!userLayer.isOwnedBy(params.getUser().getUuid())) {
            throw new ActionDeniedException("UserLayer belongs to another user");
        }
        return userLayer;
    }

}

Add Helper class for common functionality


package leetcode;

/**
 * https://leetcode.com/problems/additive-number/
 */
public class Problem306 {
    public boolean isAdditiveNumber(String num) {
        // TODO:
        return false;
    }

    public static void main(String[] args) {
        Problem306 prob = new Problem306();
        System.out.println(prob.isAdditiveNumber("112358")); // true
        System.out.println(prob.isAdditiveNumber("199100199")); // true
    }
}

Create a skeleton for problem 306


package leetcode;

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

/**
 * https://leetcode.com/problems/minimum-height-trees/
 */
public class Problem310 {
    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        List<Integer> result = new ArrayList<>();
        // TODO:
        return result;
    }

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

Create a skeleton for problem 310


package org.jkiss.dbeaver.ui.controls;

import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.widgets.Composite;

/**
 * Advanced styled text control
 */
public class AdvancedStyledText {

    public static StyledText createControl(Composite parent, int style)
    {
        StyledText text = new StyledText(parent, style);

        return text;
    }

}

Use StyledText instead of Text in RSV editors


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

import com.github.pedrovgs.linkedlist.ListNode;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

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

  private GetTheElementInTheMiddleOfTheList getTheElementInTheMiddleOfTheList;

  @Before public void setUp() {
    getTheElementInTheMiddleOfTheList = new GetTheElementInTheMiddleOfTheList();
  }

  @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullListInstances() {
    getTheElementInTheMiddleOfTheList.get(null);
  }

  @Test public void shouldReturnTheElementInTheMiddleOfAListWithAnEvenNumberOfElements() {
    ListNode<Integer> list = createList(new int[] { 1, 2, 3 });

    ListNode<Integer> middleElement = getTheElementInTheMiddleOfTheList.get(list);

    assertEquals(Integer.valueOf(2), middleElement.getData());
  }

  @Test public void shouldReturnTheElementInTheMiddleOfTheListWithAnOddNumberOfElements() {
    ListNode<Integer> list = createList(new int[] { 1, 2, 3, 4 });

    ListNode<Integer> middleElement = getTheElementInTheMiddleOfTheList.get(list);

    assertEquals(Integer.valueOf(2), middleElement.getData());
  }

  private ListNode<Integer> createList(int[] integers) {
    ListNode<Integer> head = new ListNode<Integer>(integers[0]);
    if (integers.length > 1) {
      ListNode<Integer> prevNode = head;
      for (int i = 1; i < integers.length; i++) {
        ListNode<Integer> currentNode = new ListNode<Integer>(integers[i]);
        prevNode.setNext(currentNode);
        prevNode = currentNode;
      }
    }
    return head;
  }
}

Add some tests to problem 64


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

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

import org.junit.Test;

import nom.bdezonia.zorbage.algebras.G;
import nom.bdezonia.zorbage.type.data.int32.SignedInt32Member;
import nom.bdezonia.zorbage.type.storage.array.ArrayStorage;

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

	@Test
	public void test1() {

		SignedInt32Member value1 = G.INT32.construct();
		SignedInt32Member value2 = G.INT32.construct();

		IndexedDataSource<SignedInt32Member> a = ArrayStorage.allocateInts(
				new int[] {7, -99, 1, 0, 0, 121, 4000, 77, 91});
		IndexedDataSource<SignedInt32Member> ds = new ReadOnlyDataSource<>(a);

		assertEquals(a.size(), ds.size());
		for (int i = 0; i < ds.size(); i++) {
			ds.get(i, value1);
			a.get(i, value2);
			assertEquals(value2.v(), value1.v());
		}

		try {
			ds.set(0, value1);
			fail();
		} catch (Exception e) {
			assertTrue(true);
		}
	}
}

Define tests for the ReadOnlyDataSource class


package com.github.sormuras.bach.internal;

import java.lang.module.ModuleDescriptor;
import java.util.Optional;
import java.util.spi.ToolProvider;

public class ToolProviders {

  public static String describe(ToolProvider provider) {
    var name = provider.name();
    var module = provider.getClass().getModule();
    var by =
        Optional.ofNullable(module.getDescriptor())
            .map(ModuleDescriptor::toNameAndVersion)
            .orElse(module.toString());
    var info =
        switch (name) {
          case "jar" -> "Create an archive for classes and resources, and update or restore them";
          case "javac" -> "Read Java class and interface definitions and compile them into classes";
          case "javadoc" -> "Generate HTML pages of API documentation from Java source files";
          case "javap" -> "Disassemble one or more class files";
          case "jdeps" -> "Launch the Java class dependency analyzer";
          case "jlink" -> "Assemble and optimize a set of modules into a custom runtime image";
          case "jmod" -> "Create JMOD files and list the content of existing JMOD files";
          case "jpackage" -> "Package a self-contained Java application";
          case "junit" -> "Launch the JUnit Platform";
          default -> provider.toString();
        };
    return "%s (provided by module %s)\n%s".formatted(name, by, info.indent(2)).trim();
  }

  /** Hidden default constructor. */
  private ToolProviders() {}
}

Add tool provider related helper


/**
 * Copyright (c) 2015-present Jorge Díaz All rights reserved.
 *
 * 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.
 */

package jorgediazest.indexchecker.model;

import com.liferay.portal.kernel.security.permission.ActionKeys;

import jorgediazest.util.data.Data;

/**
 * @author Jorge Díaz
 */
public class CalendarBookingPermissionsHelper extends IndexCheckerPermissionsHelper {

	@Override
	protected String getPermissionsActionId(Data data) {
		return "VIEW_BOOKING_DETAILS";
	}

	@Override
	protected String getPermissionsClassName(Data data) {
		return "com.liferay.calendar.model.Calendar";
	}

	@Override
	protected long getPermissionsClassPK(Data data) {
		return data.get("calendarId", -1L);
	}
}

Fix CalendarBooking permissions bug (entries were detected as outdated)


/**
 *
 */
package zoo;

import java.io.IOException;

import shapegrammar.Node;
import turtle.TextualTurtle;
import turtle.Turtle;
import turtle.TurtleInterpreter;

/**
 * @author loic
 *
 */
public class SierpinskiTriangle {

	public static void main(final String[] args) throws IOException {
		final TurtleInterpreter<Turtle> interp = new TurtleInterpreter<>();
		interp.declareRule('A', "A−B+A+B−A", "F");
		interp.declareRule('B', "BB", "F");
		final Node<? super Turtle> axiom = interp.createAxiom("A-B-B");
		interp.evaluate(axiom, 1);
		axiom.render(new TextualTurtle());
		for(int i = 0; i < 5; i++) {
			System.out.println();
			interp.evaluate();
			axiom.render(new TextualTurtle());
		}
	}

}

Add Sierpinski example based on rule declaration.


package utils;

import java.util.HashMap;

import org.junit.Test;

import static org.fest.assertions.Assertions.assertThat;

public class RequestUtilTest {

    @Test
    public void getFirstValueFromQuery() {
        {
            HashMap<String, String[]> query = new HashMap<String, String[]>();
            String[] values = {"a", "b", "c"};
            query.put("test", values);
            String actual = RequestUtil.getFirstValueFromQuery(query, "test");
            assertThat(actual).isEqualTo("a");
        }

        {
            HashMap<String, String[]> query = new HashMap<String, String[]>();
            String[] values = {};
            query.put("test", values);
            String actual = RequestUtil.getFirstValueFromQuery(query, "test");
            assertThat(actual).isEqualTo(null);
        }

        {
            HashMap<String, String[]> query = new HashMap<String, String[]>();
            String actual = RequestUtil.getFirstValueFromQuery(query, "test");
            assertThat(actual).isEqualTo(null);
        }
    }

}

Add a test for RequestUtil.


package com.persado.oss.quality.stevia.selenium.core;

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

import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.internal.Locatable;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by manoskousteris on 12/8/16.
 */
public class CustomExpectedCondition {

    /**
     * The Constant LOG.
     */
    private static final Logger conditionsLogger = LoggerFactory.getLogger(CustomExpectedCondition.class);

    public static ExpectedCondition<Boolean> elementHasStoppedMoving(final WebElement element) {
        return new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver driver) {
                Point initialLocation = ((Locatable) element).getCoordinates().inViewPort();
                try {
                    Thread.sleep(50);
                }catch (InterruptedException e){
                    conditionsLogger.error(e.getMessage());
                }
                Point finalLocation = ((Locatable) element).getCoordinates().inViewPort();
                return initialLocation.equals(finalLocation);
            }
        };
    }
}

Create custom expected condition class. Add new expected condition for element has stopped moving


package io.particle.android.sdk.devicesetup;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

public class SimpleReceiver extends BroadcastReceiver {

    public interface LambdafiableBroadcastReceiver {
        void onReceive(Context context, Intent intent);
    }

    public static SimpleReceiver newReceiver(Context ctx, IntentFilter intentFilter,
                                             LambdafiableBroadcastReceiver receiver) {
        return new SimpleReceiver(ctx, intentFilter, receiver);
    }

    public static SimpleReceiver newRegisteredReceiver(Context ctx, IntentFilter intentFilter,
                                                       LambdafiableBroadcastReceiver receiver) {
        SimpleReceiver sr = new SimpleReceiver(ctx, intentFilter, receiver);
        sr.register();
        return sr;
    }

    private final Context appContext;
    private final IntentFilter intentFilter;
    private final LambdafiableBroadcastReceiver receiver;

    private boolean registered = false;

    private SimpleReceiver(Context ctx, IntentFilter intentFilter,
                           LambdafiableBroadcastReceiver receiver) {
        this.appContext = ctx.getApplicationContext();
        this.intentFilter = intentFilter;
        this.receiver = receiver;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        receiver.onReceive(context, intent);
    }

    public void register() {
        if (registered) {
            return;
        }
        appContext.registerReceiver(this, intentFilter);
        registered = true;
    }

    public void unregister() {
        if (!registered) {
            return;
        }
        appContext.unregisterReceiver(this);
        registered = false;
    }

}

Create util class to make broadcast receivers less awkward


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

import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.junit.Before;
import org.junit.Test;

public class ImmutableContextTest extends ContextTestSupport {

    @Override
    @Before
    public void setUp() throws Exception {
        setUseImmutableContext(true);
        super.setUp();
    }

    @Test
    public void testCBRCamel() throws Exception {
        getMockEndpoint("mock:other").expectedMessageCount(0);
        getMockEndpoint("mock:camel").expectedMessageCount(1);
        getMockEndpoint("mock:donkey").expectedMessageCount(0);

        template.sendBody("direct:start", "Camel rules");

        assertMockEndpointsSatisfied();
    }

    @Test
    public void testCBRDonkey() throws Exception {
        getMockEndpoint("mock:other").expectedMessageCount(0);
        getMockEndpoint("mock:camel").expectedMessageCount(0);
        getMockEndpoint("mock:donkey").expectedMessageCount(1);

        template.sendBody("direct:start", "Donkey kong");

        assertMockEndpointsSatisfied();
    }

    @Test
    public void testCBROther() throws Exception {
        getMockEndpoint("mock:other").expectedMessageCount(1);
        getMockEndpoint("mock:camel").expectedMessageCount(0);
        getMockEndpoint("mock:donkey").expectedMessageCount(0);

        template.sendBody("direct:start", "Hello World");

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start")
                        .choice()
                            .when(body().contains("Camel"))
                                .to("mock:camel")
                            .when(body().contains("Donkey"))
                                .to("mock:donkey")
                            .otherwise()
                                .to("mock:other");
            }
        };
    }
}

Add a test for the immutable context


package com.tom_e_white.set_game.preprocess;

import boofcv.io.image.UtilImageIO;
import com.tom_e_white.set_game.model.Card;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Takes a test image and a label file (ending in .txt) and creates a directory of test images with the
 * corresponding labels.
 */
public class CreateTestSetV2 {
    public static void main(String[] args) throws IOException {
        File testFile = new File("data/20170106_205743.jpg");
        CardDetector cardDetector = new CardDetector();
        List<CardImage> images = cardDetector.detect(testFile.getAbsolutePath(), false);
        List<Card> cards = Files.lines(Paths.get(testFile.getAbsolutePath().replace(".jpg", ".txt")))
                .map(Card::new)
                .collect(Collectors.toList());
        File outDir = new File("data/test-v2");;
        outDir.mkdirs();
        for (int i = 0; i < images.size(); i++) {
            CardImage image = images.get(i);
            Card card = cards.get(i);
            File labelledDirectory = new File(outDir, card.getDescription().replace(" ", "-"));
            labelledDirectory.mkdirs();
            File newFile = new File(labelledDirectory, testFile.getName().replace(".jpg", "_" + (i + 1) + ".jpg"));
            UtilImageIO.saveImage(image.getImage(), newFile.getAbsolutePath());
        }

    }
}

Add code to generate test data in same directory structure as training data


package info.u_team.u_team_test.container;

import info.u_team.u_team_core.container.UTileEntityContainer;
import info.u_team.u_team_test.init.TestContainers;
import info.u_team.u_team_test.tileentity.BasicFluidInventoryTileEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.network.PacketBuffer;

public class BasicFluidInventoryContainer extends UTileEntityContainer<BasicFluidInventoryTileEntity> {

	// Client
	public BasicFluidInventoryContainer(int id, PlayerInventory playerInventory, PacketBuffer buffer) {
		super(TestContainers.BASIC_FLUID_INVENTORY, id, playerInventory, buffer);
	}

	// Server
	public BasicFluidInventoryContainer(int id, PlayerInventory playerInventory, BasicFluidInventoryTileEntity tileEntity) {
		super(TestContainers.BASIC_FLUID_INVENTORY, id, playerInventory, tileEntity);
	}

	@Override
	protected void init(boolean server) {

	}

}

Add basic fluid inventory container


package org.springframework.roo.support.util;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * Very simple convenience Builder for XML {@code Element}s
 *
 * @author Stefan Schmidt
 * @since 1.0
 *
 */
public class XmlElementBuilder {

	private Element element;

	/**
	 * Create a new Element instance.
	 *
	 * @param name The name of the element (required, not empty)
	 * @param document The parent document (required)
	 */
	public XmlElementBuilder (String name, Document document) {
		Assert.hasText(name, "Element name required.");
		Assert.notNull(document, "Owner document required");
		element = document.createElement(name);
	}

	/**
	 * Add an attribute to the current element.
	 *
	 * @param qName The attribute name (required, not empty)
	 * @param value The value of the attribute (required)
	 * @return
	 */
	public XmlElementBuilder addAttribute(String qName, String value) {
		Assert.hasText(qName, "Attribute qName required.");
		Assert.notNull(value, "Attribute value required.");
		element.setAttribute(qName, value);
		return this;
	}

	/**
	 * Add a child element to the current element.
	 *
	 * @param element The new element (required)
	 * @return The builder for the current element
	 */
	public XmlElementBuilder addChild(Element element) {
		Assert.notNull(element, "Element required.");
		this.element.appendChild(element);
		return this;
	}

	/**
	 * Add text contents to the current element. This will overwrite
	 * any previous text content.
	 *
	 * @param element The text content (required, not empty)
	 * @return The builder for the current element
	 */
	public XmlElementBuilder setText(String text) {
		Assert.hasText(text, "Text content required.");
		element.setTextContent(text);
		return this;
	}

	/**
	 * Get the element instance.
	 *
	 * @return The element.
	 */
	public Element build() {
		return element;
	}
}

Introduce simple XML Element builder to improve DOM generation tasks


/*
 * Copyright 2020 Martin Winandy
 *
 * 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.
 */

/**
 * Runtime implementations for standard Java and Android.
 */
package org.tinylog.core.runtimes;

Add package for runtime implementations


package org.gbif.occurrence.hive.udf;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class GeoDistanceUDFTest {

  @Test
  public void evaluateTest() {

    // At the Equator, moving 0.04° is 4448m.
    assertTrue(contains(0d, 0d, "5km", 0d, 0.04d));
    // And 0.5° is 5560m.
    assertFalse(contains(0d, 0d, "5km", 0d, 0.05d));

    // At 80° north, moving 0.04° is only 772m.
    assertTrue(contains(80d, 0d, "5km", 80d, 0.04d));
    // But we can move 0.25° and still have moved only 4827m.
    assertTrue(contains(80d, 0d, "5km", 80d, 0.25d));
    // This is 5020m.
    assertFalse(contains(80d, 0d, "5km", 80d, 0.26d));
  }

  private boolean contains(Double latitude1, Double longitude1, String distance, Double latitude2, Double longitude2) {
    return new GeoDistanceUDF().evaluate(latitude1, longitude1, distance, latitude2, longitude2).get();
  }
}

Add test case for GeoDistanceUDF.


/*
 * Copyright 2008 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.openehealth.ipf.tutorials.ref.render;

import org.openehealth.ipf.platform.camel.flow.PlatformMessage;
import org.openehealth.ipf.platform.camel.flow.PlatformMessageRenderer;

/**
 * @author Martin Krasser
 */
public class DefaultRenderer implements PlatformMessageRenderer {

    @Override
    public String render(PlatformMessage message) {
        return message.getExchange().getIn().getBody(String.class);
    }

}

Use default renderer for all flow management interceptors


package uk.gov.dvla.services.authentication.exceptions;

public class DWPNegativeMatchException extends AuthenticationException {

    public DWPNegativeMatchException(String msg) {
        super(msg);
    }

    public DWPNegativeMatchException(String msg, Throwable t) {
        super(msg, t);
    }
}

Fix a couple of defects


/**
 * Copyright (C) 2009 - 2010 by OpenGamma Inc.
 *
 * Please see distribution for license.
 */
package com.opengamma.engine.view.calcnode;

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

import org.junit.Test;

/**
 *
 */
public class CalculationJobSpecificationTest {

  @Test
  public void testHashCode() {
    CalculationJobSpecification spec1 = new CalculationJobSpecification("view", "config", 1L, 1L);
    CalculationJobSpecification spec2 = new CalculationJobSpecification("view", "config", 1L, 1L);

    assertEquals(spec1.hashCode(), spec2.hashCode());

    spec2 = new CalculationJobSpecification("view2", "config", 1L, 1L);
    assertFalse(spec1.hashCode() == spec2.hashCode());
    spec2 = new CalculationJobSpecification("view", "config2", 1L, 1L);
    assertFalse(spec1.hashCode() == spec2.hashCode());
    spec2 = new CalculationJobSpecification("view", "config", 2L, 1L);
    assertFalse(spec1.hashCode() == spec2.hashCode());
    spec2 = new CalculationJobSpecification("view", "config", 1L, 2L);
    assertFalse(spec1.hashCode() == spec2.hashCode());
  }

  @Test
  public void testEquals() {
    CalculationJobSpecification spec1 = new CalculationJobSpecification("view", "config", 1L, 1L);
    assertTrue(spec1.equals(spec1));
    assertFalse(spec1.equals(null));
    assertFalse(spec1.equals("Kirk"));
    CalculationJobSpecification spec2 = new CalculationJobSpecification("view", "config", 1L, 1L);
    assertTrue(spec1.equals(spec2));

    spec2 = new CalculationJobSpecification("view2", "config", 1L, 1L);
    assertFalse(spec1.equals(spec2));
    spec2 = new CalculationJobSpecification("view", "config2", 1L, 1L);
    assertFalse(spec1.equals(spec2));
    spec2 = new CalculationJobSpecification("view", "config", 2L, 1L);
    assertFalse(spec1.equals(spec2));
    spec2 = new CalculationJobSpecification("view", "config", 1L, 2L);
    assertFalse(spec1.equals(spec2));
  }

}

Test of .hashCode and equals on CalculationJobSpecification.


package flyway.ptimigration;

import fi.nls.oskari.util.JSONHelper;
import org.json.JSONObject;

/**
 * Removes mapUrlPrefix config from toolbar if available
 */
public class V1_11__Remove_mapurl_from_toolbar_config extends ConfigMigration {

    public String getBundle() {
        return "toolbar";
    }

    public String getModifiedConfig(final String param) throws Exception {
        final JSONObject config = JSONHelper.createJSONObject(param);
        config.remove("mapUrlPrefix");
        return config.toString(2);
    }

}

Remove link config from toolbar


package ac.at.tuwien.infosys.visp.runtime.restAPI;

import java.util.List;

import ac.at.tuwien.infosys.visp.common.operators.Operator;
import ac.at.tuwien.infosys.visp.runtime.configuration.Configurationprovider;
import ac.at.tuwien.infosys.visp.runtime.reasoner.ReasonerUtility;
import ac.at.tuwien.infosys.visp.runtime.resourceManagement.ProcessingNodeManagement;
import ac.at.tuwien.infosys.visp.runtime.topology.TopologyManagement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/control")
@RestController
@DependsOn("configurationprovider")
public class ScalingAPI {

    @Autowired
    private TopologyManagement topologyMgmt;

    @Autowired
    private Configurationprovider config;

    @Autowired
    private ProcessingNodeManagement pcm;

    @Autowired
    private ReasonerUtility reasonerUtility;

    @RequestMapping(value = {"/scaleup/{operatorName}"}, method = RequestMethod.GET)
    public String scaleup(@PathVariable String operatorName) {

        List<Operator> operators = topologyMgmt.getOperatorsForAConcreteLocation(config.getRuntimeIP());

        Operator selectedOperator = null;

        for (Operator op : operators) {
            if (operatorName.equals(op.getName())) {
                selectedOperator = op;
                break;
            }
        }

        if (selectedOperator == null) {
            return "no operator with that name exists.";
        }

        pcm.scaleup(reasonerUtility.selectSuitableDockerHost(selectedOperator), selectedOperator);

        return "ok";
    }

}

Add scaling API for Operator instances


package com.googlecode.jslint4java.maven;

import static com.googlecode.jslint4java.maven.RootCauseMatcher.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class RootCauseMatcherTest {

    @Rule
    public ExpectedException kaboom = ExpectedException.none();

    private final RuntimeException exc = new RuntimeException(new IllegalArgumentException("foo"));

    @Test
    public void shouldMatchRootClauseByClass() {
        assertThat(exc, rootCause(IllegalArgumentException.class));
    }

    @Test
    public void shouldMatchRootClauseByMatcher() {
        assertThat(exc, rootCause(instanceOf(IllegalArgumentException.class)));
    }

    @Test
    public void shouldNotMatchNonException() {
        assertThat(new Object(), not(rootCause(IllegalArgumentException.class)));
    }

    @Test
    public void shouldDescribeFailure() {
        kaboom.handleAssertionErrors();
        kaboom.expect(AssertionError.class);
        kaboom.expectMessage(containsString("an exception with root cause"));

        // This should fail, and raise an AssertionErrror.
        assertThat(new Object(), rootCause(IllegalArgumentException.class));
    }
}

Add a test for RootCauseMatcher.


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

package com.uber.jenkins.phabricator;

import com.uber.jenkins.phabricator.utils.TestUtils;
import hudson.plugins.cobertura.targets.CoverageResult;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class CodeCoverageMetricsTest {
    @Test
    public void testInstantiateFromCoverageResult() {
        CoverageResult result = TestUtils.getDefaultCoverageResult();
        CodeCoverageMetrics metrics = new CodeCoverageMetrics(result);

        assertEquals(100.0f, metrics.getPackageCoveragePercent(), 0);
        assertEquals(100.0f, metrics.getFilesCoveragePercent(), 0);
        assertEquals(100.0f, metrics.getClassesCoveragePercent(), 0);
        assertEquals(100.0f, metrics.getMethodCoveragePercent(), 0);
        assertEquals(100.0f, metrics.getLineCoveragePercent(), 0);
        assertEquals(-1f, metrics.getConditionalCoveragePercent(), 0);
    }

    @Test
    public void testInstantiateFromNullResult() {
        CodeCoverageMetrics metrics = new CodeCoverageMetrics(null);
        assertEquals(-1f, metrics.getLineCoveragePercent(), 0);
    }
}

Add unit test for CodeCoverageMetrics


package org.grouplens.lenskit.knn.item;

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

import it.unimi.dsi.fastutil.longs.LongAVLTreeSet;
import it.unimi.dsi.fastutil.longs.LongSortedSet;
import org.grouplens.lenskit.collections.ScoredLongList;
import org.grouplens.lenskit.collections.ScoredLongListIterator;
import org.junit.Before;
import org.junit.Test;

/**
 * @author Michael Ekstrand
 */
public class TestItemItemModelAccumulator {
    LongSortedSet universe;
    /**
     * An accumulator with a size of 5 and universe of [1,10].
     */
    ItemItemModelAccumulator accum;

    @Before
    public void newAccumulator() {
        universe = new LongAVLTreeSet();
        for (long i = 1; i <= 10; i++) {
            universe.add(i);
        }
        accum = new ItemItemModelAccumulator(5, universe);
    }

    @Test
    public void testEmpty() {
        ItemItemModel model = accum.build();
        assertThat(model, notNullValue());
        assertThat(model.getItemUniverse(), equalTo(universe));
    }

    @Test
    public void testAccum() {
        accum.put(1, 2, Math.PI);
        accum.put(7, 3, Math.E);
        ItemItemModel model = accum.build();
        ScoredLongList nbrs = model.getNeighbors(1);
        assertThat(nbrs, hasSize(1));
        assertThat(nbrs.get(0), equalTo(2L));
        assertThat(nbrs.getScore(0), closeTo(Math.PI, 1.0e-6));
        nbrs = model.getNeighbors(7);
        assertThat(nbrs, hasSize(1));
        assertThat(nbrs.get(0), equalTo(3L));
        assertThat(nbrs.getScore(0), closeTo(Math.E, 1.0e-6));
    }

    @Test
    public void testTruncate() {
        for (long i = 1; i <= 10; i++) {
            for (long j = 1; j <= 10; j += (i % 3) + 1) {
                accum.put(i, j, Math.pow(Math.E, -i) * Math.pow(Math.PI, -j));
            }
        }
        ItemItemModel model = accum.build();
        ScoredLongList nbrs = model.getNeighbors(1);
        assertThat(nbrs, hasSize(5));
        nbrs = model.getNeighbors(4);
        assertThat(nbrs, hasSize(5));
        ScoredLongListIterator iter = nbrs.iterator();
        while (iter.hasNext()) {
            long j = iter.nextLong();
            double s = iter.getScore();
            assertThat(s, closeTo(Math.pow(Math.E, -4) * Math.pow(Math.PI, -j), 1.0e-6));
        }
    }
}

Test the item-item model accumulator


package au.gov.ga.geodesy.domain.model;

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

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface EquipmentConfigurationRepository extends JpaRepository<EquipmentConfiguration, Integer> {

    @Override
    List<EquipmentConfiguration> findAll();

    @Query("select c from EquipmentConfiguration c" +
           " where c.equipmentId.id = :equipmentId and c.configurationTime = :configurationTime")
    EquipmentConfiguration findOne(@Param("equipmentId") Integer id, @Param("configurationTime") Date time);
}

Add generic equipment configuration repository.


/*
 * Copyright 2015 Michael Rozumyanskiy
 *
 * 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.michaelrocks.lightsaber.processor.commons;

import org.objectweb.asm.ClassVisitor;

import static org.objectweb.asm.Opcodes.ASM5;

public class JavaVersionChanger extends ClassVisitor {
    private final int newVersion;

    public JavaVersionChanger(final ClassVisitor classVisitor, final int newVersion) {
        super(ASM5, classVisitor);
        this.newVersion = newVersion;
    }

    @Override
    public void visit(final int version, final int access, final String name, final String signature,
            final String superName, final String[] interfaces) {
        super.visit(newVersion, access, name, signature, superName, interfaces);
    }
}

Implement a class visitor that changes JVM version of a class


package com.linkedin.clustermanager.controller;

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

import com.linkedin.clustermanager.core.ClusterDataAccessor.InstanceConfigProperty;
import com.linkedin.clustermanager.model.ZNRecord;

public class InstanceConfigHolder
{
  private List<ZNRecord> _instanceConfigList;

  private Map<String, Boolean> _instanceEnabledMap = new TreeMap<String, Boolean>();

  public void refresh(List<ZNRecord> instanceConfigs)
  {
    _instanceConfigList = instanceConfigs;
    updateEnableMap();
  }

  void updateEnableMap()
  {
    _instanceEnabledMap.clear();
    for(ZNRecord config : _instanceConfigList)
    {
      boolean enabled = Boolean.parseBoolean(config.getSimpleField(InstanceConfigProperty.ENABLED.toString()));
      _instanceEnabledMap.put(config.getId(), enabled);
    }
  }

  public boolean isEnabled(String instanceName)
  {
    if (!_instanceEnabledMap.containsKey(instanceName))
    {
        return false;
    }
    return _instanceEnabledMap.get(instanceName);
  }
}

Add instanceHolder class to keep the enabled / disabled instances


package com.github.sormuras.bach.lookup;

import java.net.URI;
import java.nio.file.Path;

/** A builder of external module objects. */
public class ExternalModuleLookupBuilder {

  /** The name of the module to link. */
  private final String module;

  /**
   * Constructs an instance of this class with the given components.
   *
   * @param module the name of the module to link
   */
  public ExternalModuleLookupBuilder(String module) {
    this.module = module;
  }

  /**
   * Returns a module link whose uri is determined by the given target string.
   *
   * @param target the target to parse into a uri
   * @return a module link
   */
  public ExternalModuleLookup to(String target) {
    var maven = target.indexOf('/') == -1 && target.chars().filter(ch -> ch == ':').count() >= 2;
    if (maven) return toMavenCentral(target);
    return toUri(target);
  }

  /**
   * Returns a module link pointing to local path.
   *
   * @param base the base directory
   * @param more the path to the file
   * @return an external module link
   */
  public ExternalModuleLookup toPath(String base, String more) {
    var first = base.equals("~") ? System.getProperty("user.home") : base;
    var path = Path.of(first, more);
    return toUri(path.normalize().toUri());
  }

  /**
   * Returns a module link pointing to an artifact hosted at the given Maven repository.
   *
   * @param repository Maven repository
   * @param coordinates Maven groupId + ':' + artifactId + ':' version [+ ':' + classifier]
   * @return a Maven-based {@code Link} instance
   */
  public ExternalModuleLookup toMaven(String repository, String coordinates) {
    var split = coordinates.split(":");
    if (split.length < 3) throw new IllegalArgumentException();
    var joiner = Maven.Joiner.of(split[0], split[1], split[2])
        .repository(repository)
        .classifier(split.length < 4 ? "" : split[3]);
    return toUri(joiner.toString());
  }

  /**
   * Returns a module link pointing to an artifact hosted at Maven Central.
   *
   * @param coordinates Maven groupId + ':' + artifactId + ':' version [+ ':' + classifier]
   * @return a Maven Central-based {@code Link} instance
   * @see search.maven.org
   */
  public ExternalModuleLookup toMavenCentral(String coordinates) {
    return toMaven(Maven.CENTRAL_REPOSITORY, coordinates);
  }

  /**
   * Returns a module link pointing to the given uniform resource identifier.
   *
   * @param uri uniform resource identifier of the module
   * @return a module link
   */
  public ExternalModuleLookup toUri(String uri) {
    return toUri(URI.create(uri));
  }

  /**
   * Returns a module link pointing to the given uniform resource identifier.
   *
   * @param uri uniform resource identifier of the module
   * @return a module link
   */
  public ExternalModuleLookup toUri(URI uri) {
    return new ExternalModuleLookup(module, uri.toString());
  }
}

Introduce external module lookup builder class


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

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

import org.junit.Test;
import org.onosproject.vtnrsc.TenantNetworkId;

import com.google.common.testing.EqualsTester;

/**
 * Unit tests for TenantNetworkId class.
 */
public class TenantNetworkIdTest {

    final TenantNetworkId networkId1 = TenantNetworkId.networkId("1");
    final TenantNetworkId sameAsnetworkId1 = TenantNetworkId.networkId("1");
    final TenantNetworkId networkId2 = TenantNetworkId.networkId("2");

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

    /**
     * Checks the operation of equals() methods.
     */
    @Test
    public void testEquals() {
        new EqualsTester().addEqualityGroup(networkId1, sameAsnetworkId1)
                .addEqualityGroup(networkId2).testEquals();
    }

    /**
     * Checks the construction of a TenantNetworkId object.
     */
    @Test
    public void testConstruction() {
        final String networkIdValue = "s";
        final TenantNetworkId networkId = TenantNetworkId.networkId(networkIdValue);
        assertThat(networkId, is(notNullValue()));
        assertThat(networkId.networkId(), is(networkIdValue));
    }
}

Add the junit test code of TenantNetworkId


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

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

import org.jboss.dmr.ModelNode;
import org.wildfly.swarm.container.runtime.AbstractServerConfiguration;
import org.wildfly.swarm.logstash.LogstashFraction;

/**
 * @author Bob McWhirter
 */
public class LogstashConfiguration extends AbstractServerConfiguration<LogstashFraction> {

    public LogstashConfiguration() {
        super(LogstashFraction.class);
    }

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

    @Override
    public LogstashFraction defaultFraction() {
        return (LogstashFraction) LogstashFraction.createDefaultLogstashFraction(false);
    }

    @Override
    public List<ModelNode> getList(LogstashFraction fraction) {
        return Collections.emptyList();
    }

}

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

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

import org.jboss.dmr.ModelNode;
import org.wildfly.swarm.container.runtime.AbstractServerConfiguration;
import org.wildfly.swarm.logstash.LogstashFraction;

/**
 * @author Bob McWhirter
 */
public class LogstashConfiguration extends AbstractServerConfiguration<LogstashFraction> {

    public LogstashConfiguration() {
        super(LogstashFraction.class);
    }

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

    @Override
    public LogstashFraction defaultFraction() {
        return (LogstashFraction) LogstashFraction.createDefaultLogstashFraction(false);
    }

}

Add some more *Configuration super-classes to simplify boiler-plate stuff.


package io.quarkus.spring.web.test;

import static io.restassured.RestAssured.when;
import static org.hamcrest.Matchers.is;

import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.test.QuarkusDevModeTest;

public class ControllerReloadTest {

    @RegisterExtension
    static QuarkusDevModeTest TEST = new QuarkusDevModeTest()
            .setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
                    .addClasses(SimpleSpringController.class));

    @Test
    public void testRepositoryIsReloaded() {
        when().get("/simple").then().body(is("hello"));

        TEST.modifySourceFile("SimpleSpringController.java", s -> s.replace("hello", "hi"));

        when().get("/simple").then().body(is("hi"));
    }
}

Add a dev-mode test for the Spring Web module


/*
 * Copyright 2016-2019 Talsma ICT
 *
 * 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 for context-aware java {@link java.util.concurrent.Future} code.
 *
 *
{@linkplain nl.talsmasoftware.context.futures.ContextAwareCompletableFuture}

 *

 * A {@linkplain java.util.concurrent.CompletableFuture} that applies a certain
 * {@linkplain nl.talsmasoftware.context.ContextSnapshot} to all
 * {@linkplain java.util.concurrent.CompletionStage completion stages} of the completable future.
 */
package nl.talsmasoftware.context.futures;

Add javadoc to the java 8 futures package


package com.github.conradoqg.studydsa.hackerrank.challenges.ctci;

import java.util.Scanner;

public class LonelyInteger {
    public static int lonelyInteger(int[] a) {
        int lonelyOne = 0;
        for (int nextNumber : a) {
            lonelyOne = lonelyOne ^ nextNumber;
        }
        return lonelyOne;
    }

    public static void main(String[] args) {
        try (Scanner in = new Scanner(System.in)) {
            int n = in.nextInt();
            int a[] = new int[n];
            for (int a_i = 0; a_i < n; a_i++) {
                a[a_i] = in.nextInt();
            }
            System.out.println(lonelyInteger(a));
        }
    }
}

Add lonely integer CTCI challenge


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

package enmasse.storage.controller.openshift;

import com.openshift.internal.restclient.model.ReplicationController;
import com.openshift.restclient.IClient;
import com.openshift.restclient.ResourceKind;
import enmasse.storage.controller.model.AddressType;
import enmasse.storage.controller.model.LabelKeys;
import org.jboss.dmr.ModelNode;
import org.junit.Test;

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

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class OpenshiftClientTest {
    @Test
    public void testListClusters() {
        IClient client = mock(IClient.class);
        OpenshiftClient osClient = new OpenshiftClient(client, "myspace");
        ReplicationController controller = new ReplicationController(new ModelNode(), client, Collections.emptyMap());
        controller.addLabel(LabelKeys.FLAVOR, "vanilla");
        controller.addLabel(LabelKeys.ADDRESS_TYPE, AddressType.QUEUE.value());
        controller.addLabel(LabelKeys.ADDRESS, "foo");
        when(client.list(ResourceKind.REPLICATION_CONTROLLER, "myspace")).thenReturn(Collections.singletonList(controller));

        List<StorageCluster> clusters = osClient.listClusters();
        verify(client).list(ResourceKind.REPLICATION_CONTROLLER, "myspace");
        assertThat(clusters.size(), is(1));
        StorageCluster cluster = clusters.get(0);
        assertThat(cluster.getDestination().address(), is("foo"));
        assertThat(cluster.getDestination().flavor(), is("vanilla"));
        assertTrue(cluster.getDestination().storeAndForward());
        assertFalse(cluster.getDestination().multicast());
    }
}

Add test for openshift client


package com.cyq7on.leetcode.linked_list;

/**
 * @author cyq7on
 * @description Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
 *

 * Example 1:
 *

 * Input: 1->2->3->3->4->4->5
 * Output: 1->2->5
 * Example 2:
 *

 * Input: 1->1->1->2->3
 * Output: 2->3
 * @create 2019/12/22
 **/
public class RemoveDuplicatesFromSortedListII {
    public ListNode deleteDuplicates(ListNode head) {
        return deleteDuplicates(head, Integer.MAX_VALUE);
    }

    public ListNode deleteDuplicates(ListNode head,int lastVal) {
        if (head == null) {
            return null;
        }

        //头结点值等于上个节点的值，移除头节点，从下个节点开始递归
        if (head.val == lastVal) {
            return deleteDuplicates(head.next, head.val);
        }

        if (head.next == null) {
            return head;
        }

        //头节点的值等于下个节点的值，则移除头结点和下一个节点，从下下个节点开始递归
        if (head.val == head.next.val) {
            return deleteDuplicates(head.next.next,head.val);
        }

        //头结点和下个节点都存在且值不相等，保留头节点，从下个节点开始递归
        head.next = deleteDuplicates(head.next,head.val);
        return head;
    }

    public static void main(String[] args) {
        RemoveDuplicatesFromSortedListII removeDuplicatesFromSortedListII = new RemoveDuplicatesFromSortedListII();
        System.out.println(removeDuplicatesFromSortedListII.deleteDuplicates(new ListNode(new int[]{-1,0,0,0,0,3,3})));
        System.out.println(removeDuplicatesFromSortedListII.deleteDuplicates(new ListNode(new int[]{1,2,2})));
        System.out.println(removeDuplicatesFromSortedListII.deleteDuplicates(new ListNode(new int[]{1,2,3,3,4,4,5})));
        System.out.println(removeDuplicatesFromSortedListII.deleteDuplicates(new ListNode(new int[]{1,1,1,2,3})));
        System.out.println(removeDuplicatesFromSortedListII.deleteDuplicates(new ListNode(new int[]{1,1,1,2,3,3})));
    }
}

Remove Duplicates from Sorted List II


package org.springframework.content.docx4j.config;

import internal.org.springframework.content.docx4j.JpegToPngRenditionProvider;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackageClasses = JpegToPngRenditionProvider.class)
public class Docx4jConfiguration {
}

Add a configuration that can be imported by applications to enable the docx4j renderers


package org.apache.solr.handler.dataimport;

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

import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakZombies;
import org.apache.solr.SolrTestCaseJ4;

import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

@ThreadLeakAction({ThreadLeakAction.Action.WARN})
@ThreadLeakLingering(linger = 0)
@ThreadLeakZombies(ThreadLeakZombies.Consequence.CONTINUE)
@ThreadLeakScope(ThreadLeakScope.Scope.NONE)
public class TestJdbcDataSourceConvertType extends AbstractDataImportHandlerTestCase {
  public void testConvertType() throws Throwable {
    // ironically convertType=false causes BigDecimal to String conversion
    convertTypeTest("false", String.class);

    // convertType=true uses the "long" conversion (see mapping of some_i to "long")
    convertTypeTest("true", Long.class);
  }

  private void convertTypeTest(String convertType, Class resultClass) throws Throwable {
    JdbcDataSource dataSource = new JdbcDataSource();
    Properties p = new Properties();
    p.put("driver", "org.apache.derby.jdbc.EmbeddedDriver");
    p.put("url", "jdbc:derby:memory:tempDB;create=true");
    p.put("convertType", convertType);

    List<Map<String, String>> flds = new ArrayList<>();
    Map<String, String> f = new HashMap<>();
    f.put("column", "some_i");
    f.put("type", "long");
    flds.add(f);

    Context c = getContext(null, null,
        dataSource, Context.FULL_DUMP, flds, null);
    dataSource.init(c, p);
    Iterator<Map<String, Object>> i = dataSource
        .getData("select 1 as id, CAST(9999 AS DECIMAL) as \"some_i\" from sysibm.sysdummy1");
    assertTrue(i.hasNext());
    Map<String, Object> map = i.next();
    Object val = map.get("some_i");
    assertEquals(resultClass, val.getClass());

    dataSource.close();
  }
}

Add tests for convertType and BigDecimal implicit conversion


package org.languagetool.rules.el;

import org.junit.Before;
import org.junit.Test;
import org.languagetool.JLanguageTool;
import org.languagetool.TestTools;
import org.languagetool.language.Greek;
import org.languagetool.rules.RuleMatch;
import java.io.IOException;
import static org.junit.Assert.assertEquals;

public class GreekRedundancyRuleTest {
	private GreekRedundancyRule rule;
	private JLanguageTool langTool;

	@Before
	public void setUp() throws IOException {
		rule = new GreekRedundancyRule(TestTools.getMessages("el"), new Greek());
		langTool = new JLanguageTool(new Greek());
	}

	// correct sentences
	@Test
	public void testRule() throws IOException {
		assertEquals(0, rule.match(langTool.getAnalyzedSentence("Τώρα μπαίνω στο σπίτι.")).length);
		assertEquals(0, rule.match(langTool.getAnalyzedSentence("Απόψε θα βγω.")).length);
	}

	// test for redundancy within the sentence
	@Test
	public void testRuleWithinSentence() throws IOException {
		RuleMatch[] matches = rule.match(langTool.getAnalyzedSentence("Τώρα μπαίνω μέσα στο σπίτι."));
		assertEquals(1, matches.length);
		assertEquals("μπαίνω", matches[0].getSuggestedReplacements().get(0));
	}

	// test for redundancy in the beggining of a sentence.
	@Test
	public void testRuleBegginingOfSentence() throws IOException {
		RuleMatch[] matches = rule.match(langTool.getAnalyzedSentence(
				"Απόψε το βράδυ θα βγω."));
		assertEquals(1, matches.length);
		assertEquals("Απόψε", matches[0].getSuggestedReplacements().get(0));
	}

	// test for redundancy with multiple suggestions
	@Test
	public void testRuleMultipleSuggestions() throws IOException {
		RuleMatch[] matches = rule.match(langTool.getAnalyzedSentence(
				"Το μαγαζί ήταν ωραίο, αλλά όμως δεν πέρασα καλά."));
		assertEquals(1, matches.length);
		assertEquals("αλλά,όμως", matches[0].getSuggestedReplacements().get(0));

	}

}

Add test cases for GreekRedundancyRule


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

package io.spine.examples.todolist.server;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * An endpoint triggered by AppEngine when a new instance is being started.
 *
 * @see AppEngine doc
 */
@WebServlet("/_ah/warmup")
public class WarmupServlet extends HttpServlet {

    private static final long serialVersionUID = 0L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        Application application = Application.instance();
    }
}

Add warmup servlet for AppEngine instance start request.


package com.github.aureliano.damihilogs.config.input;

public enum InputConfigTypes {

	EXTERNAL_COMMAND,
	FILE_INPUT,
	FILE_TAILER,
	STANDARD_INPUT,
	URL,
	JDBC_INPUT,
	TWITTER_INPUT;
}

Create input config types enum.


package com.github.sparkcaller.preprocessing;

import com.github.sparkcaller.BaseGATKProgram;
import com.github.sparkcaller.Utils;
import org.apache.spark.api.java.function.Function;
import scala.Tuple2;

import java.io.File;

public class BQSRTargetGenerator extends BaseGATKProgram implements Function<File, Tuple2<File, File>> {
    public BQSRTargetGenerator(String pathToReference, String knownSites, String extraArgs) {
        super("BaseRecalibrator", extraArgs);
        setReference(pathToReference);
        addArgument("-knownSites", knownSites);
    }

    public Tuple2<File, File> call(File file) throws Exception {
        setInputFile(file.getPath());
        String outputTableFilename = Utils.removeExtenstion(file.getPath(), "bam") + "-recal_data.table";
        File outputTable = new File(outputTableFilename);

        setOutputFile(outputTable.getPath());

        executeProgram();
        return new Tuple2<File, File>(file, outputTable);
    }
}

Add the class used to find which parts of the BAM file which requires BQSR.


package org.roklib.urifragmentrouting.parameter.converter;

import org.junit.Test;
import org.roklib.urifragmentrouting.exception.ParameterValueConversionException;

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

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

public class StringListParameterValueConverterTest {

    @Test
    public void testConversion() throws ParameterValueConversionException {
        final List<String> stringList = Arrays.asList("foo", "bar/baz", "foo;bar");
        StringListParameterValueConverter converter = StringListParameterValueConverter.INSTANCE;
        final String convertedString = converter.convertToString(stringList);
        assertThat(convertedString, is("foo;bar%2Fbaz;foo%3Bbar"));

        final List<String> convertedList = converter.convertToValue(convertedString);
        assertThat(convertedList, is(stringList));
    }
}

Add unit test for StringListParameterValueConverter


// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.maintenance.servicedump;

import java.nio.file.Path;

/**
 * An artifact file produced by a {@link ArtifactProducer}.
 *
 * @author bjorncs
 */
class Artifact {

    enum Classification {
        CONFIDENTIAL("confidential"),
        INTERNAL("internal");

        private final String value;
        Classification(String value) { this.value = value; }
        public String value() { return value; }
    }

    private final Classification classification;
    private final Path file;
    private final boolean compressOnUpload;

    private Artifact(Builder builder) {
        this.file = builder.file;
        this.classification = builder.classification;
        this.compressOnUpload = builder.compressOnUpload != null ? builder.compressOnUpload : false;
    }

    static Builder newBuilder(Classification classification, Path file) {
        return new Builder(classification, file);
    }

    Classification classification() { return classification; }
    Path file() { return file; }
    boolean compressOnUpload() { return compressOnUpload; }

    static class Builder {
        private Classification classification;
        private Path file;
        private Boolean compressOnUpload;

        private Builder(Classification classification, Path file) {
            this.classification = classification;
            this.file = file;
        }

        Builder compressOnUpload() { this.compressOnUpload = true; return this; }
        Artifact build() { return new Artifact(this); }
    }
}

Add type representing a produced artifact


package com.sunny.grokkingalgorithms.boot2019.phleps;

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

public class RemoveDuplicateElementsFromString {

    public static char[] removeDuplicates(char[] input){
        Set<Character> trackerSet = new HashSet<>();
        StringBuilder stringBuilder = new StringBuilder();
        for(int i = 0 ; i < input.length ; i++){
            if(!trackerSet.contains(input[i])){
                stringBuilder.append(input[i]);
                trackerSet.add(input[i]);
            }
        }
        return stringBuilder.toString().toCharArray();
    }

    public static void main(String[] args) {
        char str[] = "geeksforgeeks".toCharArray();
        System.out.println(String.valueOf(removeDuplicates(str)));
    }
}

Remove duplicate elements using hashig.


/*
 * Copyright (c) 2012-2018 Red Hat, Inc.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Red Hat, Inc. - initial API and implementation
 */
package org.eclipse.che.api.workspace.server.wsnext;

import com.google.common.annotations.Beta;
import java.util.Collection;
import org.eclipse.che.api.workspace.server.spi.InfrastructureException;
import org.eclipse.che.api.workspace.server.spi.environment.InternalEnvironment;
import org.eclipse.che.api.workspace.server.wsnext.model.CheService;

/**
 * Applies Workspace.Next configuration to an internal runtime object that represents workspace
 * runtime configuration on an infrastructure level.
 *
 * @author Oleksander Garagatyi
 */
@Beta
public interface WorkspaceNextApplier {

  /**
   * Applies Workspace.Next configuration to internal environment.
   *
   * @param internalEnvironment infrastructure specific representation of workspace runtime
   *     environment
   * @param cheServices Workspace.Next configuration to apply to {@code internalEnvironment}
   * @throws InfrastructureException when applying Workspace.Next objects fails
   */
  void apply(InternalEnvironment internalEnvironment, Collection<CheService> cheServices)
      throws InfrastructureException;
}

Add an interface to apply Workspace.Next objects to internal environment


package org.verapdf.model.impl.pb.pd;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.verapdf.model.baselayer.Object;
import org.verapdf.model.impl.BaseTest;
import org.verapdf.model.pdlayer.PDFormField;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;

/**
 * @author Evgeniy Muravitskiy
 */
public class PBoxPDFormFieldTest extends BaseTest {

	public static final String FILE_RELATIVE_PATH = "pd/InteractiveObjects.pdf";
	public static final String FORM_TYPE = "Btn";

	@BeforeClass
	public static void setUp() throws URISyntaxException, IOException {
		expectedType = PBoxPDFormField.FORM_FIELD_TYPE;
		expectedID = null;

		setUp(FILE_RELATIVE_PATH);
		actual = new PBoxPDFormField(document.getDocumentCatalog().getAcroForm().getFields().get(0));
	}

	@Test
	public void testFTMethod() {
		Assert.assertEquals(FORM_TYPE, ((PDFormField) actual).getFT());
	}

	@Test
	public void testAdditionalActionLink() {
		List<? extends Object> additionalActions = actual.getLinkedObjects(PBoxPDFormField.ADDITIONAL_ACTION);
		Assert.assertEquals(0, additionalActions.size());
		for (Object object : additionalActions) {
			Assert.assertTrue("PDAction".equals(object.getType()) || "PDNamedAction".equals(object.getType()));
		}
	}

	@AfterClass
	public static void tearDown() throws IOException {
		expectedType = null;
		expectedID = null;
		actual = null;

		document.close();
	}
}

Add test for form fields


package arez.integration.observable;

import arez.annotations.ArezComponent;
import arez.annotations.Feature;
import arez.annotations.Observable;
import arez.integration.AbstractArezIntegrationTest;
import arez.integration.util.SpyEventRecorder;
import java.util.concurrent.atomic.AtomicInteger;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class ObservableDefaultReadAndWriteOutsideTransactionTest
  extends AbstractArezIntegrationTest
{
  @ArezComponent( defaultReadOutsideTransaction = Feature.ENABLE, defaultWriteOutsideTransaction = Feature.ENABLE )
  static abstract class MyComponent
  {
    @Observable
    abstract long getTime();

    abstract void setTime( long value );
  }

  @Test
  public void scenario()
    throws Throwable
  {
    final SpyEventRecorder recorder = SpyEventRecorder.beginRecording();

    final MyComponent component = new ObservableDefaultReadAndWriteOutsideTransactionTest_Arez_MyComponent();

    // Read outside a transaction
    assertEquals( component.getTime(), 0L );

    final AtomicInteger callCount = new AtomicInteger();

    observer( () -> {
      component.getTime();
      callCount.incrementAndGet();
    } );

    assertEquals( callCount.get(), 1 );

    component.setTime( 37L );

    // If gets here it reportObserved so observed re-ran
    assertEquals( callCount.get(), 2 );
    assertEquals( component.getTime(), 37L );

    component.setTime( 42L );

    assertEquals( callCount.get(), 3 );
    assertEquals( component.getTime(), 42L );

    assertMatchesFixture( recorder );
  }
}

Add an integration test that has default read and write outside transaction set


package org.apache.commons.jcs.engine.memory.util;

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

import org.apache.commons.jcs.engine.behavior.ICacheElement;

/**
 * This wrapper is needed for double linked lists.
 */
public class DefaultMemoryElementDescriptor<K, V>
    extends MemoryElementDescriptor<K, V>
{
    /** Don't change */
    private static final long serialVersionUID = -1905161209035522460L;

    /** The CacheElement wrapped by this descriptor */
    private final ICacheElement<K, V> ce;

    /**
     * Constructs a usable MemoryElementDescriptor.
     * <p>
     * @param ce
     */
    public DefaultMemoryElementDescriptor( ICacheElement<K, V> ce )
    {
        super( ce );
        this.ce = ce;
    }

    /**
     * @return the ce
     */
    @Override
    public ICacheElement<K, V> getCacheElement()
    {
        return ce;
    }
}

Make sure the SoftReference can actually be garbage collected.


package org.openmhealth.shim.misfit.mapper;

import com.fasterxml.jackson.databind.JsonNode;
import org.openmhealth.schema.domain.omh.*;
import org.openmhealth.shim.common.mapper.DataPointMapperUnitTests;
import org.springframework.core.io.ClassPathResource;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import java.io.IOException;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collections;
import java.util.List;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.openmhealth.schema.domain.omh.DurationUnit.SECOND;
import static org.openmhealth.schema.domain.omh.LengthUnit.MILE;
import static org.openmhealth.shim.misfit.mapper.MisfitDataPointMapper.RESOURCE_API_SOURCE_NAME;

/**
 * @author Emerson Farrugia
 */
public class MisfitPhysicalActivityDataPointMapperUnitTests extends DataPointMapperUnitTests {

    private final MisfitPhysicalActivityDataPointMapper mapper = new MisfitPhysicalActivityDataPointMapper();

    private JsonNode responseNode;

    @BeforeTest
    public void initializeResponseNode() throws IOException {

        ClassPathResource resource = new ClassPathResource("org/openmhealth/shim/misfit/sessions.json");
        responseNode = objectMapper.readTree(resource.getInputStream());
    }

    @Test
    public void asDataPointsShouldReturnCorrectNumberOfDataPoints() {

        List<DataPoint<PhysicalActivity>> dataPoints = mapper.asDataPoints(Collections.singletonList(responseNode));

        assertThat(dataPoints, notNullValue());
        assertThat(dataPoints.size(), equalTo(3));
    }

    @Test
    public void asDataPointsShouldReturnCorrectDataPoints() {

        List<DataPoint<PhysicalActivity>> dataPoints = mapper.asDataPoints(Collections.singletonList(responseNode));

        assertThat(dataPoints, notNullValue());
        assertThat(dataPoints.size(), greaterThan(0));

        TimeInterval effectiveTimeInterval = TimeInterval.ofStartDateTimeAndDuration(
                OffsetDateTime.of(2015, 4, 13, 11, 46, 0, 0, ZoneOffset.ofHours(-7)),
                new DurationUnitValue(SECOND, 1140.0));

        PhysicalActivity physicalActivity = new PhysicalActivity.Builder("Walking")
                .setDistance(new LengthUnitValue(MILE, 0.9371))
                .setEffectiveTimeFrame(effectiveTimeInterval)
                .build();

        DataPoint<PhysicalActivity> dataPoint = dataPoints.get(0);

        assertThat(dataPoint.getBody(), equalTo(physicalActivity));

        DataPointAcquisitionProvenance acquisitionProvenance = dataPoint.getHeader().getAcquisitionProvenance();

        assertThat(acquisitionProvenance, notNullValue());
        assertThat(acquisitionProvenance.getSourceName(), equalTo(RESOURCE_API_SOURCE_NAME));
        assertThat(acquisitionProvenance.getAdditionalProperty("external_id").isPresent(), equalTo(true));
        assertThat(acquisitionProvenance.getAdditionalProperty("external_id").get(),
                equalTo("552eab896c59ae1f7300003e"));
    }
}

Add Misfit physical activity mapper tests


/*
 * Copyright 2015-2016 the original author or authors.
 *
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution and is available at
 *
 * http://www.eclipse.org/legal/epl-v10.html
 */

package org.junit.jupiter.engine.vintage.rulesupport;

import org.junit.Rule;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.rules.ErrorCollector;

@ExtendWith(VerifierSupport.class)
public class VerifierSupportForErrorCollectorFieldTests {

	@Rule
	public ErrorCollector collector = new ErrorCollector();

	// TODO: this test does expose the correct behavior
	// - is there a way to formalize this in junit 5 without failing the test?
	// the expected org.junit.internal.runners.model.MultipleFailureException is only thrown
	// after the test method itself...
	// @Test
	void addingTwoThrowablesToErrorCollectorFailsLate() {
		collector.addError(new Throwable("first thing went wrong"));
		collector.addError(new Throwable("second thing went wrong"));
	}

}

Add integration test for Verifier-rules using ErrorCollector example from JUnit 4


package org.jenkinsci.plugins.relution_publisher.model;

import hudson.model.Result;

/**
 * Interface definition for a class that holds a {@link Result}.
 */
public interface ResultHolder {

    /**
     * @return The {@link Result}.
     */
    Result getResult();

    /**
     * Sets the result to the specified value.
     * @param result The {@link Result} to set.
     */
    void setResult(final Result result);
}

Add interface for classes that have a result.


package com.aviras.mrassistant.models;

import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;

/**
 * Represent medicine
 * <p/>
 * Created by ashish on 8/6/16.
 */
public class Medicine extends RealmObject {

    @PrimaryKey
    private int id;

    private String name;

    private Unit unit;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Unit getUnit() {
        return unit;
    }

    public void setUnit(Unit unit) {
        this.unit = unit;
    }
}

Add model to represent medicine


/*
 * Copyright 2009-2010 by The Regents of the University of California
 * 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 from
 *
 *     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 edu.uci.ics.hyracks.client.net;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

import edu.uci.ics.hyracks.comm.channels.IChannelConnectionFactory;
import edu.uci.ics.hyracks.net.exceptions.NetException;
import edu.uci.ics.hyracks.net.protocols.muxdemux.ChannelControlBlock;
import edu.uci.ics.hyracks.net.protocols.muxdemux.MultiplexedConnection;
import edu.uci.ics.hyracks.net.protocols.muxdemux.MuxDemux;
import edu.uci.ics.hyracks.net.protocols.muxdemux.MuxDemuxPerformanceCounters;

public class ClientNetworkManager implements IChannelConnectionFactory {
    private static final int MAX_CONNECTION_ATTEMPTS = 5;

    private final MuxDemux md;

    public ClientNetworkManager(int nThreads)
            throws IOException {
        md = new MuxDemux(nThreads, MAX_CONNECTION_ATTEMPTS);
    }

    public void start() throws IOException {
        md.start();
    }

    public void stop() {

    }

    public ChannelControlBlock connect(SocketAddress remoteAddress) throws InterruptedException, NetException {
        MultiplexedConnection mConn = md.connect((InetSocketAddress) remoteAddress);
        return mConn.openChannel();
    }

    public MuxDemuxPerformanceCounters getPerformanceCounters() {
        return md.getPerformanceCounters();
    }
}

Implement a network manager for the dataset clients to talk to the result distributing nodes.


package sfBugs;

import java.io.Serializable;
import java.util.List;

public class RFE2958584
    implements Serializable
{
  private static final long serialVersionUID = 1L;
  private List<NotSerializable> list; // Not findbugs warning here.
  private NotSerializable ns;// Findbugs gives a proper warning here.

  static class NotSerializable
  {

  }
}

Add testcase for RFE 2958584


// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.restapi.filter;

import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.handler.FastContentWriter;
import com.yahoo.jdisc.handler.ResponseDispatch;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.http.filter.DiscFilterRequest;
import com.yahoo.jdisc.http.filter.SecurityRequestFilter;

/**
 * @author bjorncs
 */
public class BlockingRequestFilter implements SecurityRequestFilter {

    @Override
    public void filter(DiscFilterRequest request, ResponseHandler handler) {
        Response response = new Response(Response.Status.FORBIDDEN);
        try (FastContentWriter writer = ResponseDispatch.newInstance(response).connectFastWriter(handler)) {
            writer.write("Forbidden to access this API");
        }
    }
}

Add simple security filters that returns 403 forbidden


package com.vladmihalcea.book.hpjp.hibernate.mapping.calculated;

import com.vladmihalcea.book.hpjp.util.AbstractPostgreSQLIntegrationTest;
import org.hibernate.annotations.Formula;
import org.junit.Test;

import javax.persistence.*;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;

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

/**
 * @author Vlad Mihalcea
 */
public class FormulaCurrentDateTest extends AbstractPostgreSQLIntegrationTest {

    @Override
    protected Class<?>[] entities() {
        return new Class<?>[] {
            Event.class,
        };
    }

    @Test
    public void test() {
        doInJPA(entityManager -> {
            Event event = new Event();
            event.setId(1L);

            entityManager.persist(event);
        });
        doInJPA(entityManager -> {
            Event event = entityManager.find(Event.class, 1L);

            assertNotNull(event.getCreatedOn());
        });
    }

    @Entity(name = "Event")
    @Table(name = "event")
    public static class Event {

        @Id
        private Long id;

        @Formula("(SELECT current_date)")
        @Temporal(TemporalType.TIMESTAMP)
        private Date createdOn;

        public Long getId() {
            return id;
        }

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

        public Date getCreatedOn() {
            return createdOn;
        }

        public void setCreatedOn(Date createdOn) {
            this.createdOn = createdOn;
        }
    }
}

Add @Formula test with currentdate