package leetcode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeSet;

/**
 * https://leetcode.com/problems/reconstruct-itinerary/
 */
public class Problem332 {
    public List<String> findItinerary(String[][] tickets) {
        Map<String, TreeSet<Ticket>> map = new HashMap<>();
        for (String[] ticket : tickets) {
            String from = ticket[0];
            String to = ticket[1];
            if (!map.containsKey(from)) {
                Ticket t = new Ticket(from, to);
                TreeSet<Ticket> set = new TreeSet<>();
                set.add(t);
                map.put(from, set);
            } else {
                map.get(from).add(new Ticket(from, to));
            }
        }
        List<String> result = new ArrayList<>();
        String from = "JFK";
        result.add(from);
        TreeSet<Ticket> set = map.get(from);
        while (set != null && set.size() > 0) {
            Ticket ticket = set.pollFirst();
            from = ticket.to;
            result.add(from);
            set = map.get(from);
        }
        return result;
    }

    private static class Ticket implements Comparable<Ticket> {
        private final String from;
        private final String to;

        public Ticket(String from, String to) {
            this.from = from;
            this.to = to;
        }

        @Override
        public int compareTo(Ticket o) {
            return to.compareTo(o.to);
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Ticket ticket = (Ticket) o;
            return Objects.equals(from, ticket.from) &&
                Objects.equals(to, ticket.to);
        }

        @Override
        public int hashCode() {
            return Objects.hash(from, to);
        }

        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder();
            sb.append("[").append(from).append(", ").append(to).append("]");
            return sb.toString();
        }
    }

    public static void main(String[] args) {
        Problem332 prob = new Problem332();
//        System.out.println(prob.findItinerary(new String[][]{
//            {"MUC", "LHR"}, {"JFK", "MUC"}, {"SFO", "SJC"}, {"LHR", "SFO"}
//        }));
//        System.out.println(prob.findItinerary(new String[][]{
//            {"JFK", "SFO"}, {"JFK", "ATL"}, {"SFO", "ATL"}, {"ATL", "JFK"}, {"ATL", "SFO"}
//        }));
        System.out.println(prob.findItinerary(new String[][]{
            {"JFK", "KUL"}, {"JFK", "NRT"}, {"NRT", "JFK"}
        }));
    }
}

Create a skeleton for problem 332

Create a skeleton for problem 332


package node.client;

import node.data.ClientDataLoader;
import data.system.RouteToNodeMap;
import data.trainnetwork.Network;

/**
 * The main class, managing all threads on the client
 * @author Balazs Pete
 *
 */
public class Client {

	public void test() {
		return;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Network network = new Network();
		RouteToNodeMap map = new RouteToNodeMap();

		ClientDataLoader loader = new ClientDataLoader(network, map);
		loader.getData(null, null, true);

		System.out.println(network.edgeSet().size());
		System.out.println(network.vertexSet().size());
	}

}

Add a very simple client in order to test data loading functionality


package com.gofish.sentiment.newscrawler;

import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.RunTestOnContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author Luke Herron
 */
@RunWith(VertxUnitRunner.class)
public class NewsCrawlerVerticleTest {

    @Rule
    public final RunTestOnContext vertxRule = new RunTestOnContext();

    private Vertx vertx;
    private DeploymentOptions deploymentOptions;

    @Before
    public void setUp() {
        vertx = vertxRule.vertx();

        JsonObject config = new JsonObject().put("api", new JsonObject()
                .put("base.url", "localhost")
                .put("url.path", "/bing/v5.0/news/search")
                .put("port", 80)
                .put("result.count", 100)
                .put("freshness", "Day"));

        deploymentOptions = new DeploymentOptions().setConfig(config);
    }

    @Test
    public void testStartingVerticle(TestContext context) {
        vertx.deployVerticle(NewsCrawlerVerticle.class.getName(), deploymentOptions, context.asyncAssertSuccess(context::assertNotNull));
    }

    @Test
    public void testStoppingVerticle(TestContext context) {
        vertx.deployVerticle(NewsCrawlerVerticle.class.getName(), deploymentOptions, context.asyncAssertSuccess(result -> {
            vertx.close(context.asyncAssertSuccess());
        }));
    }

    @Test
    public void testNewsCrawlerServicePublishedStatus(TestContext context) {
        final AtomicReference<String> serviceDiscoveryStatus = new AtomicReference<>();

        vertx.eventBus().<JsonObject>consumer("vertx.discovery.announce", messageHandler -> {
            final JsonObject announce = messageHandler.body();
            serviceDiscoveryStatus.set(announce.getString("status"));
        });

        vertx.deployVerticle(NewsCrawlerVerticle.class.getName(), deploymentOptions, context.asyncAssertSuccess(result -> {
            context.assertEquals(serviceDiscoveryStatus.get(), "UP", "Service Discovery Status returned '" +
                    serviceDiscoveryStatus + "'. Expected 'UP'");
        }));
    }
}

Add unit tests for NewsCrawlerVerticle

Add unit tests for NewsCrawlerVerticle


package net.customware.gwt.presenter.client.place;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class ParameterTokenFormatterTest {

    @Test
    public void parameterValue() {

        assertPlaceIsRenderedAs(new PlaceRequest("test").with("name", "value"), "test;name=value");
    }

    @Test
    public void escapedParameterValue() {

        assertPlaceIsRenderedAs(new PlaceRequest("test").with("name", "value;value"), "test;name=value;;value");
    }

    @Test
    public void noParameterValue() {

        assertPlaceIsRenderedAs(new PlaceRequest("test"), "test");
    }

    private void assertPlaceIsRenderedAs(PlaceRequest placeRequest, String expectedHistoryToken) {

        ParameterTokenFormatter formatter = new ParameterTokenFormatter();

        assertEquals("PlaceRequest improperly rendered", expectedHistoryToken, formatter.toHistoryToken(placeRequest));
    }

}

Add a basic test for ParameterTokenFormatter

--HG--
branch : replace


package com.splicemachine.derby.impl.load;

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

public class SpliceImportCoprocessorTest {
	@Test
	public void testParseCsvLine() throws Exception {

		// arbitrary character as delimiter with trailing delimiter
		Assert.assertArrayEquals(new String[]{"a", "b", ""},
				SpliceImportCoprocessor.parseCsvLine("x", "axbx"));

		// delimiter in the data
		Assert.assertArrayEquals(new String[]{"joe", "billy, the kid", "jim"},
				SpliceImportCoprocessor.parseCsvLine(",", "\"joe\",\"billy, the kid\",jim"));

		// empty field in the middle
		Assert.assertArrayEquals(new String[]{"joe", "", "jim"},
				SpliceImportCoprocessor.parseCsvLine(",", "joe,,jim"));

		// tabs as delimiters
		Assert.assertArrayEquals(new String[]{"joe", "jim"},
				SpliceImportCoprocessor.parseCsvLine("\t", "joe\tjim"));
	}

	@Test(expected=IndexOutOfBoundsException.class)
	public void testParseCsvLineNoDelimiterSpecified() throws Exception {
		SpliceImportCoprocessor.parseCsvLine("", "joe\tjim");
	}

	@Test(expected=NullPointerException.class)
	public void testParseCsvLineNullDelimiterSpecified() throws Exception {
		SpliceImportCoprocessor.parseCsvLine(null, "joe\tjim");
	}
}

Use opencsv library for CSV parsing rather than just splitting on the delimiter. This handles delimiters quoted in the data.


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

package org.usb4java;

import static org.junit.Assert.assertEquals;

import java.lang.reflect.Constructor;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;

import org.junit.Test;
import org.usb4java.BufferUtils;

/**
 * Tests the {@link BufferUtils} class.
 *
 * @author Klaus Reimer (k@ailis.de)
 */
public class BufferUtilsTest
{
    /**
     * Tests the {@link BufferUtils#allocateByteBuffer(int)} method.
     */
    @Test
    public void testAllocateByteBuffer()
    {
        ByteBuffer buffer = BufferUtils.allocateByteBuffer(13);
        assertEquals(13, buffer.limit());
    }

    /**
     * Tests the {@link BufferUtils#allocateIntBuffer()} method.
     */
    @Test
    public void testAllocateIntBuffer()
    {
        IntBuffer buffer = BufferUtils.allocateIntBuffer();
        assertEquals(1, buffer.limit());
    }

    /**
     * Tests the {@link BufferUtils#allocateLongBuffer()} method.
     */
    @Test
    public void testAllocateLongBuffer()
    {
        LongBuffer buffer = BufferUtils.allocateLongBuffer();
        assertEquals(1, buffer.limit());
    }

    /**
     * Tests the {@link BufferUtils#slice(ByteBuffer, int, int)} method.
     */
    @Test
    public void testSlice()
    {
        ByteBuffer buffer = BufferUtils.allocateByteBuffer(10);
        buffer.put(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
        buffer.rewind();
        ByteBuffer sliced = BufferUtils.slice(buffer,  2, 3);
        assertEquals(3, sliced.remaining());
        assertEquals(3, sliced.get());
        assertEquals(4, sliced.get());
        assertEquals(5, sliced.get());
    }

    /**
     * Ensure constructor is private.
     *
     * @throws Exception
     *             When constructor test fails.
     */
    @Test
    public void testPrivateConstructor() throws Exception
    {
        assertEquals(0, BufferUtils.class.getConstructors().length);
        Constructor<?> c = BufferUtils.class.getDeclaredConstructor();
        c.setAccessible(true);
        c.newInstance();
    }
}

Add unit test for BufferUtils

Add unit test for BufferUtils


package com.aemreunal.config;

import org.springframework.orm.jpa.vendor.Database;

public class DatabaseSettings {
    // The address of the database you want to use
    // It can be a local or remote database
    public static final String DB_IP   = "";
    public static final String DB_PORT = "";

    // The name of the database you want to use
    public static final String DB_NAME = "";

    // The username and password for the database you want to use
    public static final String DB_USERNAME = "";
    public static final String DB_PASSWORD = "";

    // Don't change these.
    public static final String   DB_URL = "jdbc:mysql://" + DB_IP + ":" + DB_PORT + "/" + DB_NAME + "?useUnicode=true&characterEncoding=UTF-8";
    public static final Database DB_TYPE = Database.MYSQL;
    public static final String   DB_DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver";
}

Add sample Database Settings file

Add sample Database Settings file


package com.orbekk.same;

import org.codehaus.jackson.type.TypeReference;

public class Types {
    public final static TypeReference<String> STRING =
            new TypeReference<String>() {};
    public final static TypeReference<Integer> INTEGER =
            new TypeReference<Integer>() {};
    public static <T> TypeReference<T> fromType(Class<T> clazz) {
        return new TypeReference<T>() {};
    }
}

Add class for easy access to different TypeReferences.


package voldemort.utils;

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

import joptsimple.OptionSet;
import joptsimple.OptionSpec;

/**
 * Helper functions for command line parsing. Because jopt-simple is a little
 * too simple.
 *
 * @author jay
 *
 */
public class CmdUtils {

    public static Set<String> missing(OptionSet options, String... required) {
        Set<String> missing = new HashSet<String>();
        for(String arg: required)
            if(!options.has(arg))
                missing.add(arg);
        return missing;
    }

    public static Set<OptionSpec<?>> missing(OptionSet options, OptionSpec<?>... required) {
        Set<OptionSpec<?>> missing = new HashSet<OptionSpec<?>>();
        for(OptionSpec<?> opt: required)
            if(!options.has(opt))
                missing.add(opt);
        return missing;
    }

    @SuppressWarnings("unchecked")
    public static <T> T valueOf(OptionSet options, String opt, T defaultValue) {
        if(options.has(opt))
            return (T) options.valueOf(opt);
        else
            return defaultValue;
    }

    public static <T> T valueOf(OptionSet options, OptionSpec<T> opt, T defaultValue) {
        if(options.has(opt))
            return options.valueOf(opt);
        else
            return defaultValue;
    }

}

Add proper command line options to store builder.


package colector.co.com.collector.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.content.CursorLoader;

/**
 * @author http://hmkcode.com/android-display-selected-image-and-its-real-path/
 * @version 1.0
 */

public class RealPathUtil {

    public static String getRealPathFromUri(Context context, Uri uri) {
        if (Build.VERSION.SDK_INT < 11) return getRealPathFromURI_BelowAPI11(context, uri);
        if (Build.VERSION.SDK_INT < 19) return getRealPathFromURI_API11to18(context, uri);
        return getRealPathFromURI_API19(context, uri);
    }

    @SuppressLint("NewApi")
    public static String getRealPathFromURI_API19(Context context, Uri uri) {
        String filePath = "";
        String wholeID = DocumentsContract.getDocumentId(uri);

        // Split at colon, use second item in the array
        String id = wholeID.split(":")[1];

        String[] column = {MediaStore.Images.Media.DATA};

        // where id is equal to
        String sel = MediaStore.Images.Media._ID + "=?";

        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                column, sel, new String[]{id}, null);

        int columnIndex = cursor.getColumnIndex(column[0]);

        if (cursor.moveToFirst()) {
            filePath = cursor.getString(columnIndex);
        }
        cursor.close();
        return filePath;
    }

    @SuppressLint("NewApi")
    public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        String result = null;

        CursorLoader cursorLoader = new CursorLoader(
                context,
                contentUri, proj, null, null, null);
        Cursor cursor = cursorLoader.loadInBackground();

        if (cursor != null) {
            int column_index =
                    cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            result = cursor.getString(column_index);
        }
        return result;
    }

    public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index
                = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
}

:star: Add helper class to retrive real uri path from picked image


/* Copyright (c) 2018 Sambhav Kothari
 * All rights reserved.
 *
 * 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.
 * 3. Neither the name of the MusicBrainz project nor the names of the
 *    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
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.musicbrainz.search.solrwriter.moxy;

import org.musicbrainz.mmd2.SecondaryType;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class StringSecondaryTypeAdapter extends XmlAdapter<String, SecondaryType> {

    @Override
    public SecondaryType unmarshal(String v) throws Exception {
        throw new UnsupportedOperationException("Umarshalling json back to model not supported");
    }

    @Override
    public String marshal(SecondaryType v) throws Exception {
        return v.getContent();
    }

}

Fix json release-group secondary type output


package org.apache.aries.blueprint.plugin;

import org.apache.maven.model.Resource;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;

/**
 * Creates resource base dir where blueprint file will be generated for IDE support
 */
@Mojo(name="add-resource-dir",
    requiresDependencyResolution= ResolutionScope.COMPILE,
    defaultPhase= LifecyclePhase.GENERATE_RESOURCES,
    inheritByDefault=false, threadSafe = true)
public class AddResourceDirMojo extends AbstractMojo {

    @Parameter(defaultValue="${project}", required=true)
    protected MavenProject project;

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        String buildDir = project.getBuild().getDirectory();
        String generatedBaseDir = buildDir + "/generated-sources/blueprint";
        Resource resource = new Resource();
        resource.setDirectory(generatedBaseDir);
        project.addResource(resource);
    }
}

[ARIES-1599] Add add-resource-dir goal to blueprint maven plugin

git-svn-id: f3027bd689517dd712b868b0d3f5f59c3162b83d@1758096 13f79535-47bb-0310-9956-ffa450edef68


package util;

import okhttp3.*;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * Intercepts HTTP requests and returns mock responses for unit testing.
 */
public class MockInterceptor implements Interceptor {
    public static String TEST_FILENAME = "filestack_test.txt";
    public static String TEST_FILE_CONTENT = "Test content for handle: %s\n%s\n";
    public static String TEST_FILE_TYPE = "text/plain; charset=utf-8";

    public static String HEADER_FILENAME = "x-file-name";

    public static String MESSAGE_OK = "OK";

    @Override
    public Response intercept(Chain chain) throws IOException {
        HttpUrl url = chain.request().url();
        Response.Builder builder = null;

        String host = url.host();
        List<String> path = url.pathSegments();
        String query = url.query();

        if (CdnService.URL.contains(host)) {
            if (path.size() == 1) {
                String handle = path.get(0);
                builder = genGetResponse(handle);
            }
        }

        if (builder == null)
            throw new IOException("The request was not matched by the interceptor");

        return builder
                .protocol(Protocol.HTTP_1_1)
                .request(chain.request())
                .build();
    }

    /**
     * Generates a test response for get requests.
     * Response contains data for a simple text file.
     *
     * @param handle File handle / id
     */
    private Response.Builder genGetResponse(String handle) {
        String bodyText = String.format(TEST_FILE_CONTENT, handle, new Date());
        ResponseBody body = ResponseBody.create(MediaType.parse(TEST_FILE_TYPE), bodyText);
        return new Response.Builder()
                .addHeader(HEADER_FILENAME, TEST_FILENAME)
                .body(body)
                .code(200)
                .message(MESSAGE_OK);
    }
}

Add http interceptor for unit testing.

Add http interceptor for unit testing.

This class intercepts requests passing through the OkHttpClient
and returns mocks responses for offline unit testing.


package org.springframework.security.config;

/**
 * @author Luke Taylor
 * @version $Id$
 */
public class SecurityConfigurationException extends RuntimeException {
    public SecurityConfigurationException(String s) {
        super(s);
    }

    public SecurityConfigurationException(String s, Throwable throwable) {
        super(s, throwable);
    }
}

package org.springframework.security.config;

import org.springframework.security.SpringSecurityException;

/**
 * @author Luke Taylor
 * @author Ben Alex
 * @version $Id$
 */
public class SecurityConfigurationException extends SpringSecurityException {
    public SecurityConfigurationException(String s) {
        super(s);
    }

    public SecurityConfigurationException(String s, Throwable throwable) {
        super(s, throwable);
    }
}

Make extend Spring Security's exception, for consistency with all other Spring Security exceptions.


package com.vaadin.tests.components.select;

import java.util.LinkedHashMap;

import com.vaadin.terminal.Resource;
import com.vaadin.ui.TwinColSelect;

public class TwinColSelectTest extends AbstractSelectTestCase<TwinColSelect> {

    private Command<TwinColSelect, Integer> rowsCommand = new Command<TwinColSelect, Integer>() {
        public void execute(TwinColSelect c, Integer value, Object data) {
            c.setRows(value);
        }
    };

    private Command<TwinColSelect, Integer> colsCommand = new Command<TwinColSelect, Integer>() {
        public void execute(TwinColSelect c, Integer value, Object data) {
            c.setColumns(value);
        }
    };

    private Command<TwinColSelect, String> leftColumnCaptionCommand = new Command<TwinColSelect, String>() {

        public void execute(TwinColSelect c, String value, Object data) {
//            c.setLeftColumnCaption(value);
        }
    };

    private Command<TwinColSelect, Resource> leftColumnIconCommand = new Command<TwinColSelect, Resource>() {

        public void execute(TwinColSelect c, Resource value, Object data) {
//            c.setLeftColumnIcon(value);
        }
    };
    private Command<TwinColSelect, String> rightColumnCaptionCommand = new Command<TwinColSelect, String>() {

        public void execute(TwinColSelect c, String value, Object data) {
//            c.setRightColumnCaption(value);
        }
    };

    private Command<TwinColSelect, Resource> rightColumnIconCommand = new Command<TwinColSelect, Resource>() {

        public void execute(TwinColSelect c, Resource value, Object data) {
//            c.setRightColumnIcon(value);
        }
    };

    @Override
    protected Class<TwinColSelect> getTestClass() {
        return TwinColSelect.class;
    }

    @Override
    protected void createActions() {
        super.createActions();
        createRowsAction(CATEGORY_FEATURES);
        createColsAction(CATEGORY_FEATURES);
        createCaptionActions(CATEGORY_FEATURES);
    }

    private void createRowsAction(String category) {
        LinkedHashMap<String, Integer> options = createIntegerOptions(20);
        createSelectAction("Rows", category, options, "0", rowsCommand);
    }

    private void createColsAction(String category) {
        LinkedHashMap<String, Integer> options = createIntegerOptions(20);
        createSelectAction("Columns", category, options, "0", colsCommand);
    }

    private void createCaptionActions(String category) {
//        createSelectAction("Left column caption", category,
//                createCaptionOptions(), "-", leftColumnCaptionCommand);
//        createSelectAction("Right column caption", category,
//                createCaptionOptions(), "-", rightColumnCaptionCommand);
//        createSelectAction("Left column icon", category,
//                createIconOptions(false), "-", leftColumnIconCommand);
//        createSelectAction("Right column icon", category,
//                createIconOptions(false), "-", rightColumnIconCommand);

    }
}

Test for TwinColSelect (commented out left and right caption for now)

svn changeset:16271/svn branch:6.5


/*
 * Copyright 2006-2015 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 com.consol.citrus.dsl.runner;

import com.consol.citrus.TestCase;
import com.consol.citrus.actions.SleepAction;
import com.consol.citrus.testng.AbstractTestNGUnitTest;
import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * @author Christoph Deppisch
 */
public class SleepTestRunnerTest extends AbstractTestNGUnitTest {

    @Test
    public void testSleepBuilder() {
        MockTestRunner builder = new MockTestRunner(getClass().getSimpleName(), applicationContext) {
            @Override
            public void execute() {
                sleep(200);
                sleep(150);
            }
        };

        TestCase test = builder.getTestCase();
        Assert.assertEquals(test.getActions().size(), 2);
        Assert.assertEquals(test.getActions().get(0).getClass(), SleepAction.class);
        Assert.assertEquals(test.getActions().get(1).getClass(), SleepAction.class);

        SleepAction action = (SleepAction)test.getActions().get(0);
        Assert.assertEquals(action.getName(), "sleep");
        Assert.assertEquals(action.getMilliseconds(), "200");

        action = (SleepAction)test.getActions().get(1);
        Assert.assertEquals(action.getName(), "sleep");
        Assert.assertEquals(action.getMilliseconds(), "150");
    }
}

Add further test runner Java DSL method unit tests


package leetcode.reverse_bits;

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        int out = 0;
        for(int i = 0; i < 32; i++){
            out <<= 1;
            out |= n & 1;
            n >>= 1;
        }
        return out;
    }
}

Add java solution for 190. Reverse Bits

Add java solution for 190. Reverse Bits

190. Reverse Bits: https://leetcode.com/problems/reverse-bits/


/**
 * Copyright © 2014
 * Hrfs Block Store API
 *
 * Defines what a block storage device for Hrfs should support. This will be
 * used by higher API's to store generic blocks of data to disk. Implementors
 * of this API may or may not specify the type of block they are using.
 *
 * @file BlockFactory.java
 * @author Will Dignazio <wdignazio@gmail.com>
 */
package edu.rit.cs.disk;

public interface BlockStore
{
	/**
	 * Create a new BlockStore, using the underlying hrfs configuration as
	 * the parameters for the location and specifications for the block
	 * storage unit.
	 * @return Whether the creation of the block store was successful.
	 */
	public boolean create();
}

Add block store base interface

blockstore: Add block store base interface

Add BlockStore interface, starting with a default creation method that uses the
underlying configuration.


package fi.helsinki.cs.tmc.cli.command;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import fi.helsinki.cs.tmc.cli.Application;
import fi.helsinki.cs.tmc.cli.command.core.CommandFactory;
import fi.helsinki.cs.tmc.cli.io.TerminalIo;

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

public class CommandFactoryTest {

    CommandFactory factory;
    Application app;

    @Before
    public void setUp() {
        factory = new CommandFactory();
        app = new Application(new TerminalIo());
    }

    @Test
    public void constructorAddsCommands() {
        assertTrue(!factory.getCommands().isEmpty());
    }

    @Test
    public void createCommandWorksWithRealCommand() {
        assertNotNull(factory.createCommand(app, "help"));
    }

    @Test
    public void createCommandWorksWithBadCommand() {
        assertNull(factory.createCommand(app, "foobar"));
    }
}

Add the command factory test back.

Add the command factory test back.

It was removed in previous merge. It's name was CommandMapTest in that commit.


package hudson.plugins.git;

import java.util.ArrayList;

import hudson.model.User;

import org.junit.Test;
import org.junit.Rule;
import static org.junit.Assert.*;

import org.jvnet.hudson.test.JenkinsRule;

public class GitChangeSetMalformedEmailTest {

    @Rule
    public JenkinsRule jenkins = new JenkinsRule();

    private final String badEmail = "@";

    private GitChangeSet genChangeSetWithBadEmail(boolean authorOrCommitter) {
        ArrayList<String> lines = new ArrayList<String>();
        lines.add("commit 1567861636cd854f4dd6fa40bf94c0c657681dd5");
        lines.add("tree 66236cf9a1ac0c589172b450ed01f019a5697c49");
        lines.add("parent e74a24e995305bd67a180f0ebc57927e2b8783ce");
        lines.add("author Bad Author <" + badEmail + "> 1363879004 +0100"); // Bad e-mail address
        lines.add("committer Bad Committer <" + badEmail + "> 1364199539 -0400"); // Bad e-mail address
        lines.add("");
        lines.add("    Committer and author have bad e-mail addresses.");
        lines.add("    ");
        lines.add("    Changes in this version:");
        lines.add("    - Committer has bad e-mail address.");
        lines.add("    - Author has bad e-mail address.");
        lines.add("    ");
        lines.add("");
        return new GitChangeSet(lines, authorOrCommitter);
    }

    @Test
    public void testFindOrCreateUserBadEmailAuthor() {
        assertEquals(User.getUnknown(), genChangeSetWithBadEmail(true).findOrCreateUser("Bad Author", badEmail, false));
    }

    @Test
    public void testFindOrCreateUserBadEmailCommitter() {
        assertEquals(User.getUnknown(), genChangeSetWithBadEmail(false).findOrCreateUser("Bad Committer", badEmail, false));
    }
}

Add test of invalid email

Add test of invalid email


/****************************************************************************
 * Copyright (C) 2018 ecsec GmbH.
 * All rights reserved.
 * Contact: ecsec GmbH (info@ecsec.de)
 *
 * This file is part of the Open eCard App.
 *
 * GNU General Public License Usage
 * This file may be used under the terms of the GNU General Public
 * License version 3.0 as published by the Free Software Foundation
 * and appearing in the file LICENSE.GPL included in the packaging of
 * this file. Please review the following information to ensure the
 * GNU General Public License version 3.0 requirements will be met:
 * http://www.gnu.org/copyleft/gpl.html.
 *
 * Other Usage
 * Alternatively, this file may be used in accordance with the terms
 * and conditions contained in a signed written agreement between
 * you and ecsec GmbH.
 *
 ***************************************************************************/

package org.openecard.plugins.pinplugin.gui;

import iso.std.iso_iec._24727.tech.schema.ConnectionHandleType;
import java.math.BigInteger;
import javax.annotation.Nonnull;
import org.openecard.common.event.EventType;
import org.openecard.common.event.IfdEventObject;
import org.openecard.common.interfaces.EventFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Sebastian Schuberth
 */
public class CardRemovedFilter implements EventFilter {

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

    private final String ifdName;
    private final BigInteger slotIdx;

    public CardRemovedFilter(@Nonnull String ifdName, @Nonnull BigInteger slotIdx) {
	this.ifdName = ifdName;
	this.slotIdx = slotIdx;
    }

    @Override
    public boolean matches(EventType t, Object o) {
	LOG.debug("Received event.");
	if (t.equals(EventType.CARD_REMOVED)) {
	    LOG.debug("Received CARD_REMOVED event.");
	    ConnectionHandleType conHandle = null;
	    boolean reset = false;
	    if (o instanceof IfdEventObject) {
		conHandle = ((IfdEventObject) o).getHandle();
		reset = ((IfdEventObject) o).cardWasReset();
	    } else if (o instanceof ConnectionHandleType) {
		conHandle = (ConnectionHandleType) o;
	    }

	    if(reset){
		LOG.info("Card was reset -> ignore");
	    } else {
		if (conHandle != null && ifdName.equals(conHandle.getIFDName()) && slotIdx.equals(conHandle.getSlotIndex())) {
		    LOG.info("Card removed during processing of PIN Management GUI.");
		    return true;
		} else {
		    LOG.debug("An unrelated card has been removed.");
		    return false;
		}
	    }
	}

	return false;
    }

}

Add filter for card removed event

Add filter for card removed event


package study.hard.javalib.hackerrank;

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

/**
 * Created by iandmyhand on 10/16/16.
 */

class Node {
    int data;
    Node next;
    Node(int data){
        this.data = data;
        this.next = null;
    }
}
public class SolutionLinkedListDeletion {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        Node head = null;
        int T = scan.nextInt();
        while(T-->0) {
            head = insert(head, scan.nextInt());
        }
        head = removeDuplicates(head);
        display(head);
    }

    static Node insert(Node head, int data) {
        if(null == head) return new Node(data);
        else {
            Node cur = head;
            while(true) {
                if(null == cur.next) {
                    cur.next = new Node(data);
                    return head;
                }
                cur = cur.next;
            }
        }
    }

    static Node removeDuplicates(Node head) {
        Set<Integer> set = new HashSet();
        Node cur = head;
        while(null != cur) {
            set.add(cur.data);
            cur = cur.next;
        }
        Integer[] sorted = set.toArray(new Integer[0]);
        quickSort(sorted, 0, sorted.length - 1);
        return toLinkedList(sorted);
    }

    private static void quickSort(Integer[] arr, Integer l, Integer r) {
        Integer i = partition(arr, l, r);
        if(l < i - 1) quickSort(arr, l, i - 1);
        if(r > i) quickSort(arr, i, r);
    }

    private static Integer partition(Integer[] arr, int l, int r) {
        Integer i = l, j = r;
        Integer pivot = arr[(l + r) / 2];
        while(i <= j) {
            while(pivot > arr[i]) i++;
            while(pivot < arr[j]) j--;
            if(i <= j) {
                swap(arr, i, j);
                i++;
                j--;
            }
        }
        return i;
    }

    private static void swap(Integer[] array, int l, int r) {
        int t = array[l];
        array[l] = array[r];
        array[r] = t;
    }

    private static Node toLinkedList(Integer[] arr) {
        Node head = new Node(arr[0]);
        Node cur = head;
        for(int i = 1; i < arr.length; i++) {
            cur.next = new Node(arr[i]);
            cur = cur.next;
        }
        return head;
    }

    static void display(Node cur) {
        if(null == cur) return;
        else {
            System.out.print(String.format("%d ", cur.data));
            display(cur.next);
        }
    }
}

Solve a problem that deletion of LinkedList.


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

/**
 * Given two binary trees, can you write a method to check if this trees are equals?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class BinaryTreeEquals {
}

Add statement for problem 17

Add statement for problem 17


package me.jesensky.dan.playertracker;

import me.jesensky.dan.playertracker.exceptions.InvalidPacketException;
import me.jesensky.dan.playertracker.net.Connection;
import me.jesensky.dan.playertracker.net.packets.DataResponsePacket;
import me.jesensky.dan.playertracker.net.packets.Packet;

import java.io.IOException;

public class RequestManager extends Thread {
    private Connection c;

    public RequestManager(Connection c) {
        super("Data Request Manager");
        this.c = c;
    }

    @Override
    public void run() {
        try {
            if (this.c.dataRemaining()) {
                Packet p = this.c.readData();

                switch (p.getType()) {
                    case LOGIN_RESPONSE:

                        break;
                    case DATA_RESPONSE:
                        DataResponsePacket packet = (DataResponsePacket) p;
                        String name, notes, violations;
                        UserViolationLevel vl;
                        name = packet.getName();
                        notes = packet.getNotes();
                        violations = packet.getViolations();
                        vl = packet.getViolationLevel();
                        //TODO show a new UI detailing the player whose details were received
                        break;
                    default:
                        break;
                }
            }
        } catch (IOException | InvalidPacketException e) {
            //TODO log exception
        }
        super.run();
    }
}

Implement ResponseManager, the client's equiv. to Server's ConnMgr.


/**
 * Copyright (C) 2012 - 2014 Xeiam LLC http://xeiam.com
 *
 * 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.xeiam.xchange.bitstamp.service.marketdata;

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

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;

import org.junit.Test;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xeiam.xchange.bitstamp.dto.marketdata.BitstampStreamingOrderBook;

/**
 * Test BitStamp Stream Depth JSON parsing
 */
public class StreamDepthJSONTest {

  @Test
  public void testUnmarshal() throws IOException {

    // Read in the JSON from the example resources
    InputStream is = StreamDepthJSONTest.class.getResourceAsStream("/marketdata/example-stream-depth-data.json");

    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    BitstampStreamingOrderBook orderBook = mapper.readValue(is, BitstampStreamingOrderBook.class);

    // Verify that the example data was unmarshalled correctly
    assertThat(orderBook.getBids().get(0).get(0)).isEqualTo(new BigDecimal("123.09"));
    assertThat(orderBook.getBids().get(0).get(1)).isEqualTo(new BigDecimal("0.16248274"));
    assertThat(orderBook.getAsks().get(0).get(0)).isEqualTo(new BigDecimal("123.39"));
    assertThat(orderBook.getAsks().get(0).get(1)).isEqualTo(new BigDecimal("0.60466812"));
    assertThat(orderBook.getTimestamp() > 0);
  }
}

Add Bitstamp stream depth test case

Add Bitstamp stream depth test case


/*
 * 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.aries.blueprint.uberbundle;

import org.apache.aries.blueprint.container.BlueprintExtender;
import org.apache.aries.proxy.impl.ProxyManagerActivator;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

public class UberActivator implements BundleActivator
{
  private BlueprintExtender blueprintActivator = new BlueprintExtender();
  private ProxyManagerActivator proxyActivator = new ProxyManagerActivator();

  public void start(BundleContext context)
  {
    proxyActivator.start(context);
    blueprintActivator.start(context);
  }

  public void stop(BundleContext arg0)
  {
    blueprintActivator.stop(arg0);
    proxyActivator.start(arg0);
  }
}

/*
 * 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.aries.blueprint.uberbundle;

import org.apache.aries.blueprint.container.BlueprintExtender;
import org.apache.aries.proxy.impl.ProxyManagerActivator;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

public class UberActivator implements BundleActivator
{
  private BlueprintExtender blueprintActivator = new BlueprintExtender();
  private ProxyManagerActivator proxyActivator = new ProxyManagerActivator();

  public void start(BundleContext context)
  {
    proxyActivator.start(context);
    blueprintActivator.start(context);
  }

  public void stop(BundleContext context)
  {
    blueprintActivator.stop(context);
    proxyActivator.stop(context);
  }
}

Fix problem with the proxy activator when using the blueprint bundle

git-svn-id: 212869a37fe990abe2323f86150f3c4d5a6279c2@1033177 13f79535-47bb-0310-9956-ffa450edef68


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

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

import io.nats.client.Connection;
import io.nats.client.Nats;
import io.nats.client.Options;

import org.apache.camel.EndpointInject;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Test;

public class NatsAuthConsumerLoadTest extends NatsAuthTestSupport {

    @EndpointInject(uri = "mock:result")
    protected MockEndpoint mockResultEndpoint;

    @Test
    public void testLoadConsumer() throws InterruptedException, IOException, TimeoutException {
        mockResultEndpoint.setExpectedMessageCount(100);
        Options options = new Options.Builder().server("nats://" + getNatsUrl()).build();
        Connection connection = Nats.connect(options);

        for (int i = 0; i < 100; i++) {
            connection.publish("test", ("test" + i).getBytes());
        }

        mockResultEndpoint.assertIsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("nats://"  + getNatsUrl() + "?topic=test").to(mockResultEndpoint);
            }
        };
    }

}

Camel-Nats: Add test for consuming also on Auth configuration


package org.realityforge.replicant.client.runtime;

import java.util.logging.Logger;
import javax.annotation.Nonnull;

public class DebugReplicantSystemListener
  implements ReplicantSystemListener
{
  private static final Logger LOG = Logger.getLogger( DebugReplicantSystemListener.class.getName() );

  /**
   * {@inheritDoc}
   */
  @Override
  public void stateChanged( @Nonnull final ReplicantClientSystem system,
                            @Nonnull final ReplicantClientSystem.State newState,
                            @Nonnull final ReplicantClientSystem.State oldState )
  {
    LOG.warning( "ReplicantSystem.stateChanged: NewState: " + newState + " OldState: " + oldState );
  }
}

Add ReplicantSystemListener usefulk for debugging


package at.ac.tuwien.dsg.salam.composer.algorithm;

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

import org.apache.commons.math3.distribution.UniformRealDistribution;
import org.apache.commons.math3.random.MersenneTwister;

import at.ac.tuwien.dsg.salam.common.model.ComputingElement;
import at.ac.tuwien.dsg.salam.composer.Composer;
import at.ac.tuwien.dsg.salam.composer.model.ConstructionGraph;
import at.ac.tuwien.dsg.salam.composer.model.Solution;
import at.ac.tuwien.dsg.salam.composer.model.SolutionComponent;

public class PriorityDistribution implements ComposerAlgorithmInterface {

    private static final int SEED_SELECTOR = 1001;
    private static UniformRealDistribution distSelector = new UniformRealDistribution(new MersenneTwister(SEED_SELECTOR), 0, 1);
    private ConstructionGraph cons;
    private Composer composer;

    @Override
    public void init(String configFile, ConstructionGraph cons, Composer composer) {
        this.cons = cons;
        this.composer = composer;
    }

    @Override
    public Solution solve() {
        Solution solution = new Solution();
        List<ComputingElement> selectedElements = new ArrayList<ComputingElement>();
        for (int i=1; i<cons.getComponentList().size()-1; i++) {
            ArrayList<SolutionComponent> components = cons.getComponentList().get(i);
            // sum up priorities
            int prioritySum = 0;
            for (SolutionComponent comp: components) {
                int priority = (int)comp.getAssignee().getProvider().getProperties().getValue("assignment_priority", 1);
                prioritySum += priority;
            }
            // repeat until we have an element that has not been selected
        	int retry = 0;
        	SolutionComponent chosenComp = null;
            do {
            	double chosen = distSelector.sample() * prioritySum;
            	int pos = 0;
            	for (SolutionComponent comp: components) {
            		int priority = (int)comp.getAssignee().getProvider().getProperties().getValue("assignment_priority", 1);
            		pos += priority;
            		if (chosen <= pos) {
            			chosenComp = comp;
            			break;
            		}
            	}
            	if (chosenComp==null) {
            		System.out.println(chosen);
            		System.out.println(prioritySum);
            	}
            } while (retry++<20 && (chosenComp==null || selectedElements.contains(chosenComp.getAssignee().getProvider())));

            selectedElements.add(chosenComp.getAssignee().getProvider());
            solution.addSolutionComponent(chosenComp);
        }

        // measure objective values
        ArrayList<Solution> solutionList = new ArrayList<Solution>();
        solutionList.add(solution);
        composer.calculateObjectiveValues(solutionList);

        return solution;
    }

}

Add new composition algorithm: fair distribution with priority.


package won.matcher.service.common.mailbox;

import com.typesafe.config.Config;

import akka.actor.ActorSystem;
import akka.dispatch.PriorityGenerator;
import akka.dispatch.UnboundedStablePriorityMailbox;
import won.matcher.service.common.event.AtomEvent;

public class PriorityAtomEventMailbox extends UnboundedStablePriorityMailbox {
    // needed for reflective instantiation
    public PriorityAtomEventMailbox(ActorSystem.Settings settings, Config config) {
        // Create a new PriorityGenerator, lower prio means more important
        super(new PriorityGenerator() {
            @Override
            public int gen(Object event) {
                if (event instanceof AtomEvent) {
                    return ((AtomEvent) event).getPriority().getPriority();
                }
                return AtomEvent.Priority.LOWEST_PRIORTY;
            }
        });
    }
}

Add priority-aware mailbox for use by matchers


package am.extension.userfeedback.evaluation;

import am.extension.userfeedback.common.PrecisionRecallPlot;
import am.extension.userfeedback.experiments.UFLExperiment;

/**
 * A candidate selection evaluation that allows to run multiple candidate
 * selection evaluations as one.
 *
 * @author cosmin
 *
 */
public class MultiplexCandidateSelectionEvaluation extends CandidateSelectionEvaluation {

	private CandidateSelectionEvaluation[] evaluations;

	public MultiplexCandidateSelectionEvaluation() {
		super();

		// hardcoded for now
		evaluations = new CandidateSelectionEvaluation[2];
		evaluations[0] = new PrecisionRecallPlot();
		evaluations[1] = new RankingAccuracy();
	}

	@Override
	public void evaluate(UFLExperiment exp) {
		for( CandidateSelectionEvaluation eval : evaluations ) {
			eval.evaluate(exp);
		}
	}

}

Allow to use multiple candidate selection evaluations.


/**
 * Copyright (C) 2010-2011, FuseSource Corp.  All rights reserved.
 *
 *     http://fusesource.com
 *
 * The software in this package is published under the terms of the
 * CDDL license a copy of which has been included with this distribution
 * in the license.txt file.
 */

package org.fusesource.fabric.apollo.amqp.codec;

import org.fusesource.fabric.apollo.amqp.codec.interfaces.AMQPType;
import org.fusesource.hawtbuf.Buffer;
import org.fusesource.hawtbuf.DataByteArrayOutputStream;

/**
 *
 */
public class Codec {

    public static Buffer toBuffer(AMQPType type) throws Exception {
        DataByteArrayOutputStream out = new DataByteArrayOutputStream((int)type.size());
        type.write(out);
        return out.toBuffer();
    }
}

Add simple helper function to encode AMQP types


package info.u_team.u_team_core.data;

import java.nio.file.Path;

import net.minecraft.fluid.Fluid;
import net.minecraft.tags.*;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.registries.ForgeRegistries;

public abstract class CommonFluidTagsProvider extends CommonTagsProvider<Fluid> {

	public CommonFluidTagsProvider(GenerationData data) {
		super(data, ForgeRegistries.FLUIDS);
	}

	@Override
	protected Path makePath(ResourceLocation location) {
		return resolveData(location).resolve("tags").resolve("fluids").resolve(location.getPath() + ".json");
	}

	@Override
	protected void setCollection(TagCollection<Fluid> collection) {
		FluidTags.setCollection(collection);
	}

	@Override
	public String getName() {
		return "Fluid-Tags";
	}
}

Add common fluid tags provider

Add common fluid tags provider


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

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

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.opera.OperaDriver;
import org.openqa.selenium.opera.OperaOptions;

import io.github.bonigarcia.wdm.WebDriverManager;

@Disabled("Opera not available in CI")
class OperaOptionsTest {

    WebDriver driver;

    @BeforeAll
    static void setupClass() {
        WebDriverManager.operadriver().exportParameter("webdriver.opera.driver")
                .setup();
    }

    @SuppressWarnings("deprecation")
    @BeforeEach
    void setupTest() {
        OperaOptions operaOptions = new OperaOptions();
        operaOptions.setExperimentalOption("w3c", true);
        driver = new OperaDriver(operaOptions);
    }

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

    @Test
    void test() {
        // Exercise
        driver.get("https://bonigarcia.dev/selenium-webdriver-java/");
        String title = driver.getTitle();

        // Verify
        assertThat(title).contains("Selenium WebDriver");
    }

}

Include Opera test using w3c experimental option for OperaDriver


package de.uni_paderborn.fujaba.muml.allocation.algorithm.ilp.lpsolve.tests;

import de.uni_paderborn.fujaba.muml.allocation.algorithm.tests.qvto.QVToBasedAlgorithmTest;
import java.util.Collection;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

@RunWith(value = Parameterized.class)
@SuppressWarnings("all")
public class LPSolveBasedAlgorithmTest extends QVToBasedAlgorithmTest {
  public LPSolveBasedAlgorithmTest(final String expectedURI, final String transformationURI, final String... inputObjectURIs) {
    super(expectedURI, transformationURI, inputObjectURIs);
  }

  @Parameterized.Parameters
  public static Collection<Object[]> getTestData() {
    return QVToBasedAlgorithmTest.getTestData(
      "platform:/plugin/de.uni_paderborn.fujaba.muml.allocation.algorithm.ilp.lpsolve/transforms/LPSolveBasedAlgorithm.qvto");
  }
}

Check in xtend generated files

Check in xtend generated files


package wumpus;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;

import wumpus.Environment.*;

/**
 * The iteration of plays that the player can take until reaches its end.
 */
public class Runner implements Iterable<Player>, Iterator<Player> {
    private static final int DEFAULT_MAX_ITERATIONS = 200;

    private final World world;
    private int iterations = 0;

    /**
     * The runner constructor.
     * @param world The world instance.
     */
    public Runner(World world) {
        this.world = world;
    }

    /**
     * Returns the iterator that can be user in a loop.
     * @return Itself
     */
    public Iterator<Player> iterator() {
        return this;
    }

    /**
     * Check if the game has ended.
     * @return
     */
    public boolean hasNext() {
        Player player = world.getPlayer();
        return iterations < DEFAULT_MAX_ITERATIONS &&
                player.isAlive() && player.getResult() == Result.WIN;
    }

    /**
     * Get player instance to calculate the next iteration.
     * @return The current player instance
     */
    public Player next() {
        if (!hasNext()) throw new NoSuchElementException();
        iterations++;
        return world.getPlayer();
    }

    /**
     * Operation not supported, throws an error.
     */
    public void remove() {
        throw new UnsupportedOperationException();
    }

    /**
     * Get how many iterations have been made so far.
     * @return The amount of iterations
     */
    public int getDepth() {
        return iterations;
    }
}

Add a class to iterates plays until the game reachs its end


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

package com.google.gerrit.elasticsearch;

import com.google.gerrit.elasticsearch.ElasticTestUtils.ElasticNodeInfo;
import com.google.gerrit.server.query.project.AbstractQueryProjectsTest;
import com.google.gerrit.testing.ConfigSuite;
import com.google.gerrit.testing.InMemoryModule;
import com.google.gerrit.testing.IndexConfig;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.eclipse.jgit.lib.Config;
import org.junit.AfterClass;
import org.junit.BeforeClass;

public class ElasticV5QueryProjectsTest extends AbstractQueryProjectsTest {
  @ConfigSuite.Default
  public static Config defaultConfig() {
    return IndexConfig.createForElasticsearch();
  }

  private static ElasticNodeInfo nodeInfo;
  private static ElasticContainer<?> container;

  @BeforeClass
  public static void startIndexService() {
    if (nodeInfo != null) {
      // do not start Elasticsearch twice
      return;
    }

    container = ElasticContainer.createAndStart(ElasticVersion.V5_6);
    nodeInfo = new ElasticNodeInfo(container.getHttpHost().getPort());
  }

  @AfterClass
  public static void stopElasticsearchServer() {
    if (container != null) {
      container.stop();
    }
  }

  private String testName() {
    return testName.getMethodName().toLowerCase() + "_";
  }

  @Override
  protected void initAfterLifecycleStart() throws Exception {
    super.initAfterLifecycleStart();
    ElasticTestUtils.createAllIndexes(injector);
  }

  @Override
  protected Injector createInjector() {
    Config elasticsearchConfig = new Config(config);
    InMemoryModule.setDefaults(elasticsearchConfig);
    String indicesPrefix = testName();
    ElasticTestUtils.configure(elasticsearchConfig, nodeInfo.port, indicesPrefix);
    return Guice.createInjector(new InMemoryModule(elasticsearchConfig, notesMigration));
  }
}

Elasticsearch: Add tests for project queries against version 5

Bug: Issue 6094
Change-Id: I0be93b1597bf2f682a23a900e22bdf513cb888d9


package leetcode.subsets;

import java.util.ArrayList;
import java.util.Arrays;

public class Solution {
	public void dfs(ArrayList<ArrayList<Integer>> ans, ArrayList<Integer> cur, int[] S, int depth, int n){
		if(depth == n){
			ans.add(new ArrayList<Integer>(cur));
		}else{
			cur.add(S[depth]);
			dfs(ans, cur, S, depth + 1, n);
			cur.remove(cur.size() - 1);
			dfs(ans, cur, S, depth + 1, n);
		}
	}
    public ArrayList<ArrayList<Integer>> subsets(int[] S) {
		ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
		if(S == null) return ans;
		Arrays.sort(S);
		dfs(ans, new ArrayList<Integer>(), S, 0, S.length);
		return ans;
    }

    public static void main(String[] args){
    	for(ArrayList<Integer> ary : new Solution().subsets(new int[]{})){
    		for(int x : ary){
    			System.err.print(x + ", ");
    		}
    		System.err.println("");;
    	}
    }
}

Add java solution for 78. Subsets

Add java solution for 78. Subsets

78. Subsets: https://leetcode.com/problems/subsets/


// Copyright 2019 Google LLC
//
// 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
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.sps.servlets;

import com.google.sps.data.Tutor;
import com.google.sps.data.TimeRange;
import com.google.sps.data.TutorSession;
import com.google.sps.data.SampleData;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.Optional;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.*; // Can be deleted after hardcoded database is removed

@WebServlet("/confirmation")
public class ConfirmationServlet extends HttpServlet {
    SampleData hardcoded;

    public void init(ServletConfig servletconfig) throws ServletException {
        hardcoded = new SampleData();
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("plain/text");
        response.getWriter().println("To be implemented");
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // Get the id of the tutor whose availability will be displayed.
        String tutorID = request.getParameter("tutorID");

        List<TutorSession> scheduledSessions = new ArrayList<TutorSession>();

        for (Tutor tutor : hardcoded.getSampleTutors()) {
            if (tutorID.toLowerCase().equals(tutor.getEmail().toLowerCase())) {
                scheduledSessions = Arrays.asList(tutor.getScheduledSessions());
            }
        }

        String json = convertToJsonUsingGson(scheduledSessions);
        response.setContentType("application/json;");
        response.getWriter().println(json);
        return;
    }

    // Converts the time slot array into a JSON string using the Gson library.
    private String convertToJsonUsingGson(List<TutorSession> scheduledSessions) {
        Gson gson = new Gson();
        String json = gson.toJson(scheduledSessions);
        return json;
    }
}

Add the confirmation servlet which is responsible for getting the scheduled sessions for a given tutor and returning them when a session is confirmed.


package pete.metrics.adaptability.elements;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

class DetectionOnlyElements {

	private final Collection<AdaptableElement> elements;

	public DetectionOnlyElements() {
		elements = new HashSet<>();
	}

	private void addToSet(AdaptableElement element) {
		boolean success = elements.add(element);
		if (!success) {
			throw new IllegalStateException(element.getName()
					+ " was tried to be added twice");
		}
	}

	public List<String> getElementNames() {
		List<String> result = new ArrayList<>(elements.size());
		elements.forEach(element -> result.add(element.getName()));
		return result;
	}

	public List<AdaptableElement> getElements() {
		List<AdaptableElement> result = new ArrayList<>(elements.size());
		elements.forEach(element -> result.add(element));
		return result;
	}

	public Map<String, AdaptableElement> getElementsByName() {
		HashMap<String, AdaptableElement> result = new HashMap<>();
		elements.forEach(element -> result.put(element.getName(), element));
		return result;
	}

}

Add collection of elements that should only be detected

Former-commit-id: dbd2ce0422e2942b3c5265d3b0867dd9deae7b99


package se.embargo.core.graphics;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public abstract class Bitmaps {
	/**
	 * Decodes and sub-samples an image
	 * @param is		Stream to read image from
	 * @param maxWidth	Max height of returned image
	 * @param maxHeight	Max width of returned image
	 * @param config	Bitmap target coding
	 * @return			An image constrained by the given bounds, or null on failure
	 */
	public static Bitmap decodeStream(File file, int maxWidth, int maxHeight, Bitmap.Config config) {
		InputStream is;

		// Check the size of the image
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inPreferredConfig = config;
        options.inJustDecodeBounds = true;

		try {
			is = new FileInputStream(file);
	        BitmapFactory.decodeStream(is, null, options);
		}
		catch (IOException e) {
			return null;
		}

        if (options.outWidth < 0 || options.outHeight < 0) {
        	return null;
        }

        // Figure if sub-sampling should be used
        options.inJustDecodeBounds = false;

        if (options.outWidth > maxWidth) {
        	double ratio = (double)options.outWidth / (double)maxWidth;
        	int samples = (int)Math.ceil(ratio);
        	options.inSampleSize = Math.max(samples, options.inSampleSize);
        }

        if (options.outHeight > maxHeight) {
        	double ratio = (double)options.outHeight / (double)maxHeight;
        	int samples = (int)Math.ceil(ratio);
        	options.inSampleSize = Math.max(samples, options.inSampleSize);
        }

        // Reset the stream and decode the image
		try {
			is = new FileInputStream(file);
	        return BitmapFactory.decodeStream(is, null, options);
		}
		catch (IOException e) {
			return null;
		}
	}

	public static Bitmap decodeStream(File file, int maxWidth, int maxHeight) {
		return decodeStream(file, maxWidth, maxHeight, Bitmap.Config.ARGB_8888);
	}
}

Use bitmap sub-sampling to avoid out-of-memory


package utask.model.task;

import utask.commons.exceptions.IllegalValueException;

/**
 * Represents the boolean value of the isCompleted attribute in the uTask.
 * Guarantees: immutable; is valid as declared in
 * {@link #isValidBoolean(String)}
 */
// @@author A0138423J
public class IsCompleted {
    public static final String MESSAGE_NAME_CONSTRAINTS = "Task status should be true/false or "
            + "yes/no case insensitive, and it should not be blank";

    /*
     * The first character of the status must not be a whitespace, otherwise " "
     * (a blank string) becomes a valid input.
     */
    public static final String ISCOMPLETED_VALIDATION_REGEX = "^(YES|yes|Y|y|TRUE|true|T|t|NO|no|N|n|FALSE|false|F|f)$";
    //
    public final Boolean isCompleted;

    /**
     * Validates given name.
     *
     * @throws IllegalValueException
     *             if given name string is invalid.
     */
    public IsCompleted(String input) throws IllegalValueException {
        assert input != null;
        String trimmedName = input.trim();
        if (!isValidBoolean(trimmedName)) {
            throw new IllegalValueException(MESSAGE_NAME_CONSTRAINTS);
        }
        char value = input.toLowerCase().charAt(0);
        Boolean valToBool = false;
        switch (value) {
        case 't':
            valToBool = true;
            break;
        case 'y':
            valToBool = true;
            break;
        case 'f':
            valToBool = false;
            break;
        case 'n':
            valToBool = false;
            break;
        }
        this.isCompleted = valToBool;
    }

    /**
     * Returns true if a given string is a valid true/false or yes/no.
     */
    public static boolean isValidBoolean(String test) {
        return test.matches(ISCOMPLETED_VALIDATION_REGEX);
    }

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

    @Override
    public boolean equals(Object other) {
        return other == this // short circuit if same object
                || (other instanceof IsCompleted // instanceof handles nulls
                        && this.isCompleted
                                .equals(((IsCompleted) other).isCompleted)); // state
                                                                             // check
    }

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

Create isCompleted class for task status


package net.katsuster.strview.util;

/**
 * <p>
 * デバッグ用ユーティリティ関数群を定義するためのクラスです。
 * </p>
 *
 * @author katsuhiro
 */
public class DebugInfo {
    protected DebugInfo() {
        //do nothing
    }

    public static void printFunctionName(Object o) {
        System.err.print("Exception in "
                + "'" + o.getClass().getName() + "."
                + DebugInfo.getFunctionName(1) + "()': ");
    }

    public static String getFunctionName(int i) {
        return Thread.currentThread().getStackTrace()[2 + i].getMethodName();
    }
}

Add utils for debug info.

Add utils for debug info.


package nearenough.protocol;

/**
 * Constants and magic numbers of the Roughtime protocol
 */
public final class RtConstants {

  /** Minimum size of a client request */
  public static final int MIN_REQUEST_LENGTH_BYTES = 1024;

  /** Size of the client's nonce */
  public static final int NONCE_LENGTH_BYTES = 64;

  /** Size of server's timestamp value */
  public static final int TIMESTAMP_LENGTH_BYTES = 8;

  /** Size of server's time uncertainty value */
  public static final int RADIUS_LENGTH_BYTES = 4;

  /** Prefixed to the server's certificate before generating or verifying certificate's signature */
  public static final String CERTIFICATE_CONTEXT = "RoughTime v1 delegation signature--\\x00";

  /** Prefixed to the server's response before generating or verifying the server's signature */
  public static final String SIGNED_RESPONSE_CONTEXT = "RoughTime v1 response signature\\x00";

  /** Value prepended to leaves prior to hashing */
  public static final byte TREE_LEAF_TWEAK = 0x00;

  /** Value prepended to nodes prior to hashing */
  public static final byte TREE_NODE_TWEAK = 0x01;
}

Add file containing protocol constant values


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

package io.spine.server.storage.jdbc.query;

import io.spine.server.storage.jdbc.DataSourceWrapper;
import io.spine.server.storage.jdbc.DatabaseException;
import io.spine.server.storage.jdbc.GivenDataSource;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Dmytro Dashenkov
 */
public class SimpleQueryShould {

    @Test(expected = DatabaseException.class)
    public void propagate_sql_exception() {
        final DataSourceWrapper dataSourceWrapper = GivenDataSource.whichIsStoredInMemory("foo");
        final SimpleQuery query = SimpleQuery.newBuilder()
                                             .setDataSource(dataSourceWrapper)
                                             .setLogger(log())
                                             .setQuery("invalid query")
                                             .build();
        query.execute();
    }

    private static Logger log() {
        return LogSingleton.INSTANCE.value;
    }

    private enum LogSingleton {
        INSTANCE;
        @SuppressWarnings("NonSerializableFieldInSerializableClass")
        private final Logger value = LoggerFactory.getLogger(SimpleQueryShould.class);
    }
}

Add a required test case.

Add a required test case.


package info.u_team.u_team_core.energy;

import net.minecraftforge.energy.IEnergyStorage;

public class BasicEnergyAcceptorDelegate implements IEnergyStorage {

	private final IEnergyStorage delegate;

	public BasicEnergyAcceptorDelegate(IEnergyStorage delegate) {
		this.delegate = delegate;
	}

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

	@Override
	public int receiveEnergy(int maxReceive, boolean simulate) {
		return delegate.receiveEnergy(maxReceive, simulate);
	}

	@Override
	public int getEnergyStored() {
		return delegate.getEnergyStored();
	}

	@Override
	public int getMaxEnergyStored() {
		return delegate.getMaxEnergyStored();
	}

	@Override
	public int extractEnergy(int maxExtract, boolean simulate) {
		return 0;
	}

	@Override
	public boolean canExtract() {
		return false;
	}
}

Add basic energy acceptor delegate

Add basic energy acceptor delegate


package org.codehaus.httpcache4j.payload;

import com.google.common.base.Charsets;
import com.google.common.io.ByteStreams;
import org.codehaus.httpcache4j.MIMEType;
import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.*;

public class PayloadTest {

    @Test
    public void generateByteArrayFromString() throws IOException {
        String s = String.format("abcdefghijklmnopqrstuvwxyz%s%s%s1234567890", (char)0x00E6, (char)0x00F8, (char)0x00E5);

        ByteArrayPayload bytes = new ByteArrayPayload(s.getBytes(Charsets.UTF_8), MIMEType.APPLICATION_OCTET_STREAM);
        assertEquals(42L, bytes.length());
        assertEquals(s, new String(ByteStreams.toByteArray(bytes.getInputStream()), Charsets.UTF_8));
    }

    @Test
    public void generateFromString() throws IOException {
        String s = String.format("abcdefghijklmnopqrstuvwxyz%s%s%s1234567890", (char)0x00E6, (char)0x00F8, (char)0x00E5);

        StringPayload bytes = new StringPayload(s, MIMEType.APPLICATION_OCTET_STREAM);
        assertEquals(42L, bytes.length());
        assertEquals(s, new String(ByteStreams.toByteArray(bytes.getInputStream()), Charsets.UTF_8));
    }
}

Add test to calculate the length and correctness of byte array payloads.


/*
 * Bach - Java Shell Builder
 * Copyright (C) 2020 Christian Stein
 *
 * 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
 *
 *     https://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 java.lang.module.ModuleDescriptor;
import java.nio.file.Path;

class BuildJigsawQuickStartWithBach {

  public static void main(String... args) {
    Bach.of(
            new Bach.Project.Builder()
                .base(Bach.Project.Base.of(Path.of("doc", "project", "JigsawQuickStart")))
                .title("Module System Quick-Start Guide Greetings")
                .version(ModuleDescriptor.Version.parse("47.11"))
                .walk()
                .build())
        .build()
        .assertSuccessful();
  }
}

Use project builder walker directly

Use project builder walker directly


package com.github.fluxw42.smappee.api.impl;

import org.junit.Test;

import java.util.ArrayList;

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

/**
 * Date: 6/16/17 - 11:46 PM
 *
 * @author Jeroen Meulemeester
 */
public class GetServiceLocationsResponseTest {

	@Test
	public void testNullName() throws Exception {
		assertEquals("", new GetServiceLocationsResponse(null, new ArrayList<>()).getAppName());
	}

	@Test
	public void testNullLocations() throws Exception {
		final GetServiceLocationsResponse response = new GetServiceLocationsResponse("appName", null);
		assertNotNull(response.getServiceLocations());
		assertTrue(response.getServiceLocations().isEmpty());
	}

}

Add Junit test for GetServiceLocationsResponse


package problems;

public class RecoverBinarySearchTree {

    public class TreeNode {
        int val;
        TreeNode left, right;

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

    // O(n) time and O(1) space, Morris traversal.
    public void recoverTree(TreeNode root) {
        TreeNode cur = root, pre = null, n1 = null, n2 = null;
        while (cur != null) {
            if (cur.left == null) {
                if (pre != null && pre.val > cur.val) {
                    if (n1 == null)
                        n1 = pre;
                    n2 = cur;
                }
                pre = cur;
                cur = cur.right;
            } else {
                TreeNode t = cur.left;
                while (t.right != null && t.right != cur)
                    t = t.right;
                if (t.right == null) {
                    t.right = cur;
                    cur = cur.left;
                } else {
                    t.right = null;
                    if (pre != null && pre.val > cur.val) {
                        if (n1 == null)
                            n1 = pre;
                        n2 = cur;
                    }
                    pre = cur;
                    cur = cur.right;
                }
            }
        }
        if (n1 != null && n2 != null) {
            int t = n1.val;
            n1.val = n2.val;
            n2.val = t;
        }
    }
}

Add Recovery Binary Search Tree

Add Recovery Binary Search Tree


/**
 *
 */
package com.humbughq.android;

/**
 * @author lfaraone
 *
 */
public enum MessageType {
    STREAM_MESSAGE("stream"), PRIVATE_MESSAGE("private");

    private String sendMessageType;

    MessageType(String sendMessageType) {
        this.sendMessageType = sendMessageType;
    }

    public String toString() {
        return this.sendMessageType;
    }
}

package com.humbughq.android;

public enum MessageType {
    STREAM_MESSAGE("stream"), PRIVATE_MESSAGE("private");

    private String jsonMessageType;

    MessageType(String sendMessageType) {
        this.jsonMessageType = sendMessageType;
    }

    public String toString() {
        return this.jsonMessageType;
    }
}

Remove spurious comments, rename variable for clarity.


package org.realityforge.arez;

import javax.annotation.Nonnull;
import org.realityforge.braincheck.BrainCheckTestUtil;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;

@SuppressWarnings( "Duplicates" )
public abstract class AbstractArezIntegrationTest
{
  @BeforeMethod
  protected void beforeTest()
    throws Exception
  {
    BrainCheckTestUtil.setVerboseErrorMessages( true );
    BrainCheckTestUtil.setCheckInvariants( true );
    BrainCheckTestUtil.setCheckApiInvariants( true );

    ArezConfigTestUtil.setEnableNames( true );
    ArezConfigTestUtil.setPurgeReactionsWhenRunawayDetected( false );
    ArezConfigTestUtil.setEnforceTransactionType( true );
    ArezConfigTestUtil.setEnableSpy( true );
    getProxyLogger().setLogger( null );
    Arez.setProvider( null );
  }

  @AfterMethod
  protected void afterTest()
    throws Exception
  {
    BrainCheckTestUtil.setVerboseErrorMessages( false );
    BrainCheckTestUtil.setCheckInvariants( false );
    BrainCheckTestUtil.setCheckApiInvariants( false );

    ArezConfigTestUtil.setEnableNames( false );
    ArezConfigTestUtil.setPurgeReactionsWhenRunawayDetected( true );
    ArezConfigTestUtil.setEnforceTransactionType( false );
    ArezConfigTestUtil.setEnableSpy( false );
    getProxyLogger().setLogger( null );
  }

  @Nonnull
  private ArezLogger.ProxyLogger getProxyLogger()
  {
    return (ArezLogger.ProxyLogger) ArezLogger.getLogger();
  }

  @SuppressWarnings( "SameParameterValue" )
  protected void setEnableNames( final boolean enableNames )
  {
    ArezConfigTestUtil.setEnableNames( enableNames );
  }
}

Introduce abstract test class so can modify global settings as part of testing


package ch.sheremet.dasfoo.rover.android.client.grpc.task;

import dasfoo.grpc.roverserver.nano.RoverServiceGrpc;

/**
 * Created by Katarina Sheremet on 5/23/16 11:12 AM.
 */
public abstract class AbstractGrpcTaskExecutor {
    public abstract String execute(RoverServiceGrpc.RoverServiceBlockingStub stub);
}

Add superclass for grpc tasks

Add superclass for grpc tasks


import org.testng.annotations.Test;

import static org.testng.Assert.*;

/**
 * Created by hajarboulhdir on 03/10/2016.
 */
public class Shape2DTest {
    @Test
    public void testPerimeter() throws Exception {

    }

}

Add Shape2Dtest, the test related to the class Shape2D.


/*
 *
 *  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.flex.compiler.internal.codegen.mxml.vf2js;

import org.apache.flex.compiler.internal.test.MXMLTestBase;
import org.apache.flex.compiler.internal.test.VF2JSTestBase;
import org.apache.flex.compiler.tree.mxml.IMXMLPropertySpecifierNode;
import org.junit.Test;

public class TestVF2JSMXMLAttributes extends VF2JSTestBase
{

    @Test
    public void testVF2JSAttribute()
    {
        String code = "label=\"hello\"";

        IMXMLPropertySpecifierNode node = (IMXMLPropertySpecifierNode) getNode(
                code, IMXMLPropertySpecifierNode.class,
                MXMLTestBase.WRAP_LEVEL_NODE);

        mxmlBlockWalker.visitPropertySpecifier(node);

        assertOut("label=\"hello\"");
    }
}

Add test class specifically for attribute tests.

Signed-off-by: Erik de Bruin <c195b508e6f0c57aeafdb5e96947e2b79e6a4b40@ixsoftware.nl>


package net.unicon.cas.mfa.authentication.defaultResolver;

import java.util.List;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentialsToPrincipalResolver;
import org.jasig.cas.authentication.principal.Credentials;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

/**
 * Initialize the application context with the needed webflow mfa configuration
 * as much as possible to simplify adding mfa into an existing overlay.
 *
 * @author Dan Hankins
 */
@Component
public class DefaultMultiFactorWebflowConfigurer implements InitializingBean {
    private static final Logger LOGGER = LoggerFactory.getLogger(DuoMultiFactorWebflowConfigurer.class);

    @Autowired
    private WebApplicationContext context;

    @PostConstruct
    @Override
    public void afterPropertiesSet() throws Exception {
        try {
            final List resolvers = this.context.getBean("mfaCredentialsToPrincipalResolvers", List.class);
            resolvers.add(new UsernamePasswordCredentialsToPrincipalResolver());
        } catch (final Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
}

Add class to put default credentials-principal resolver into resolver chain.


package examples;

import org.mapdb.*;

import java.util.Map;

/**
 * Keep tracks of number of items in map.
 * <p/>
 * Note: {@code Collections.size()} typically requires traversing entire collection in MapDB.
 */
public class Map_Size_Counter {

    public static void main(String[] args) {

        DB db = DBMaker.newTempFileDB().make();

        BTreeMap primary = db.getTreeMap("map");
        Atomic.Long sizeCounter = Atomic.getLong(db, "mapSize");

        Bind.size(primary, sizeCounter);

        primary.put("111", "some value");

    }

}

Add map size counter example

Add map size counter example


package io.quarkus.jdbc.postgresql.deployment;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

import java.sql.Connection;

import javax.inject.Inject;
import javax.inject.Named;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.agroal.api.AgroalDataSource;
import io.agroal.api.configuration.AgroalConnectionPoolConfiguration;
import io.quarkus.test.QuarkusUnitTest;

public class DevServicesPostgresqlDatasourceNamedWithUsernameTestCase {

    @RegisterExtension
    static QuarkusUnitTest test = new QuarkusUnitTest()
            .withEmptyApplication()
            .overrideConfigKey("quarkus.datasource.\"DB2\".db-kind", "postgresql")
            .overrideConfigKey("quarkus.datasource.\"DB2\".username", "foo")
            .overrideConfigKey("quarkus.datasource.\"DB2\".password", "foo");

    @Inject
    @Named("DB2")
    AgroalDataSource dataSource;

    @Test
    public void testDatasource() throws Exception {
        AgroalConnectionPoolConfiguration configuration = null;

        try {
            configuration = dataSource.getConfiguration().connectionPoolConfiguration();
        } catch (NullPointerException e) {
            // we catch the NPE here as we have a proxycd and we can't test dataSource directly
            fail("Datasource should not be null");
        }
        assertTrue(configuration.connectionFactoryConfiguration().jdbcUrl().contains("jdbc:postgresql:"));
        assertEquals("foo", configuration.connectionFactoryConfiguration().principal().getName());

        try (Connection connection = dataSource.getConnection()) {
        }
    }
}

Test JDBC Dev services on a named datasource with an explicit username/password


/**
 * Copyright 2009 Joe LaPenna
 */

package com.joelapenna.foursquared;

/**
 * @author Joe LaPenna (joe@joelapenna.com)
 */
public class FoursquaredSettings {

    public static final boolean USE_DEBUG_SERVER = false;

    public static final boolean DEBUG = false;
    public static final boolean API_DEBUG = false;
    public static final boolean PARSER_DEBUG = false;

    public static final boolean USE_DUMPCATCHER = true;
    public static final boolean DUMPCATCHER_TEST = false;

}

/**
 * Copyright 2009 Joe LaPenna
 */

package com.joelapenna.foursquared;

/**
 * @author Joe LaPenna (joe@joelapenna.com)
 */
public class FoursquaredSettings {

    public static final boolean USE_DEBUG_SERVER = false;

    public static final boolean DEBUG = false;
    public static final boolean API_DEBUG = false;
    public static final boolean PARSER_DEBUG = false;
    public static final boolean LOCATION_DEBUG = false;

    public static final boolean USE_DUMPCATCHER = true;
    public static final boolean DUMPCATCHER_TEST = false;

}

Update example settings file for LOCATION_DEBUG


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

package net.imagej.ops;

import org.scijava.AbstractContextual;
import org.scijava.Named;
import org.scijava.plugin.Parameter;

/**
 * A namespace is a collection of ops with related functions.
 *
 * @author Curtis Rueden
 */
public abstract class Namespace extends AbstractContextual implements Named {

	@Parameter
	protected OpService ops;

	// -- Named methods --

	@Override
	public void setName(final String name) {
		throw new UnsupportedOperationException();
	}

}

Add a superclass for working with namespaces


/*
 * Licensed to Metamarkets Group Inc. (Metamarkets) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  Metamarkets 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 io.druid.cli;

import com.google.common.collect.ImmutableList;
import com.google.inject.Injector;
import io.druid.guice.GuiceInjectors;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

@RunWith(Parameterized.class)
public class MainTest
{
  @Parameterized.Parameters(name = "{0}")
  public static Iterable<Object[]> constructorFeeder()
  {
    return ImmutableList.of(
        new Object[]{new CliOverlord()},
        new Object[]{new CliBroker()},

        // Takes arguments. Cannot be used in this test
        //new Object[]{new CliPeon()},

        new Object[]{new CliHistorical()},
        new Object[]{new CliCoordinator()},

        // Implements Runnable, not GuiceRunnable
        //new Object[]{new CliHadoopIndexer()},

        // Takes arguments. Cannot be used in this test
        //new Object[]{new CliInternalHadoopIndexer()},

        new Object[]{new CliMiddleManager()},
        new Object[]{new CliRealtime()},
        new Object[]{new CliRealtimeExample()},
        new Object[]{new CliRouter()}
    );
  }
  private final GuiceRunnable runnable;
  public MainTest(GuiceRunnable runnable)
  {
    this.runnable = runnable;
  }
  @Test
  public void testSimpleInjection()
  {
    final Injector injector = GuiceInjectors.makeStartupInjector();
    injector.injectMembers(runnable);
    Assert.assertNotNull(runnable.makeInjector());
  }
}

Add basic tests to some CliXXX classes

Add basic tests to some CliXXX classes


/*
 * Copyright (c) 2018. Real Time Genomics 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:
 *
 * 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
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.rtg.util;

import java.util.Arrays;

import junit.framework.TestCase;

public class PermutationTest extends TestCase {

  public void test3() {
    final Permutation p = new Permutation(2, 1, 0);
    assertEquals("[0, 1, 2]", Arrays.toString(p.next()));
    assertEquals("[0, 2, 1]", Arrays.toString(p.next()));
    assertEquals("[1, 0, 2]", Arrays.toString(p.next()));
    assertEquals("[1, 2, 0]", Arrays.toString(p.next()));
    assertEquals("[2, 0, 1]", Arrays.toString(p.next()));
    assertEquals("[2, 1, 0]", Arrays.toString(p.next()));
    assertNull(p.next());
  }

  public void testAA() {
    final Permutation p = new Permutation(1, 1);
    assertEquals("[1, 1]", Arrays.toString(p.next()));
    assertNull(p.next());
  }

  public void testAAB() {
    final Permutation p = new Permutation(1, 2, 1);
    assertEquals("[1, 1, 2]", Arrays.toString(p.next()));
    assertEquals("[1, 2, 1]", Arrays.toString(p.next()));
    assertEquals("[2, 1, 1]", Arrays.toString(p.next()));
    assertNull(p.next());
  }
}

Add unit test for Permutation

Add unit test for Permutation


package leetcode;

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

/**
 * https://oj.leetcode.com/problems/restore-ip-addresses/
 */
public class Problem93 {
    public List<String> restoreIpAddresses(String s) {
        List<String> result = new ArrayList<>();

        return result;
    }

    public static void main(String[] args) {
        Problem93 prob = new Problem93();
        System.out.println(prob.restoreIpAddresses("25525511135"));
    }
}

Put the skeleton for problem 93

Put the skeleton for problem 93