/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Yegor Bugayenko
 *
 * 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package org.cactoos.func;

import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;

/**
 * Test case for {@link False}.
 *
 * @author Vseslav Sekorin (vssekorin@gmail.com)
 * @version $Id$
 * @since 0.5
 * @checkstyle JavadocMethodCheck (500 lines)
 */
public final class FalseTest {

    @Test
    public void asValue() throws Exception {
        MatcherAssert.assertThat(
            new False().asValue(),
            Matchers.equalTo(false)
        );
    }

}

Add test case for False

Add test case for False


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

/**
 * A very simple main class to test the {@link RemoteUpdater} class.
 *
 * @author Johannes Schindelin
 */
public class RemoteUpdaterTestDrive {

	public static void main(String[] args) {
		System.setProperty("imagej.dir", System.getProperty("user.home") + "/Fiji.app");
		System.err.println(RemoteUpdater.runRemote());
	}

}

Add a test drive for the new remote updater feature

Signed-off-by: Johannes Schindelin <53fb8db7833fca1e1746dd8592f61048d350f64c@gmx.de>


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

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

/**
 * A no-op filter. Used for bindings that are whitelisted and do not require any authorization.
 *
 * @author bjorncs
 */
@SuppressWarnings("unused") // Injected
public class NoopFilter implements SecurityRequestFilter {

    @Override
    public void filter(DiscFilterRequest request, ResponseHandler handler) {}

}

Add noop security filter for controller

Add noop security filter for controller


package org.robockets.stronghold.robot.highgoalshooter;

import org.robockets.stronghold.robot.flipper.FireShooter;
import org.robockets.stronghold.robot.hood.MoveHood;

import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 *
 */
public class ShootPosition extends CommandGroup {

    public  ShootPosition() {
    	addSequential(new MoveHood(-70));
    	addSequential(new FireShooter()); // Unstick ball
    }
}

Add shoot position command that unsticks the ball


package org.helioviewer.plugins.eveplugin.view.linedataselector;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JPanel;
import javax.swing.JTable;

public class LineDateSelectorTablePanel extends JPanel {

    private static final int ROW_HEIGHT = 20;
    private static final int ICON_WIDTH = 16;

    private static final int VISIBLE_ROW = 0;
    private static final int TITLE_ROW = 1;
    public static final int LOADING_ROW = 2;
    private static final int REMOVE_ROW = 3;

    private final JTable grid;

    private final LineDataSelectorTableModel tableModel;

    GridBagConstraints gc = new GridBagConstraints();

    public LineDateSelectorTablePanel() {
        this.setLayout(new GridBagLayout());
        tableModel = new LineDataSelectorTableModel();
        grid = new JTable(tableModel);
        tableModel.addTableModelListener(grid);

        gc.gridx = 0;
        gc.gridy = 0;
        gc.weightx = 1;
        gc.weighty = 0;
        gc.fill = GridBagConstraints.BOTH;

    }
}

Introduce the line selector panel based on a table

git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@4241 b4e469a2-07ce-4b26-9273-4d7d95a670c7


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

//tag::snippet-in-doc[]
import static org.junit.jupiter.api.Assertions.assertTrue;

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

// tag::snippet-in-doc[]
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;

import io.github.bonigarcia.DriverCapabilities;
import io.github.bonigarcia.SeleniumExtension;

@ExtendWith(SeleniumExtension.class)
public class ChromeWithGlobalCapabilitiesJupiterTest {

    @DriverCapabilities
    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
    {
        Map<String, String> mobileEmulation = new HashMap<String, String>();
        mobileEmulation.put("deviceName", "Nexus 5");
        Map<String, Object> chromeOptions = new HashMap<String, Object>();
        chromeOptions.put("mobileEmulation", mobileEmulation);
        capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
    }

    @Test
    void webrtcTest1(ChromeDriver chrome) throws InterruptedException {
        chrome.get("https://bonigarcia.github.io/selenium-jupiter/");

        assertTrue(chrome.getTitle().startsWith("selenium-jupiter"));

        Thread.sleep(1500); // Wait 1.5 seconds to see the page
    }

}
// end::snippet-in-doc[]

Include test using Chrome and global capabilities (mobile emulation)


package edu.columbia.cs.psl.test.phosphor;

import static org.junit.Assert.*;

import org.junit.Test;

public class LambdaIntTagITCase {
	@Test
	public void testEmptyLambda() throws Exception {
		Runnable r = () -> {
		};
	}
}

Add empty lambda test case

Add empty lambda test case


package org.skife.jdbi.v2.sqlobject;

import junit.framework.TestCase;
import org.h2.jdbcx.JdbcDataSource;
import org.junit.Test;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.Something;
import org.skife.jdbi.v2.TransactionCallback;
import org.skife.jdbi.v2.TransactionStatus;
import org.skife.jdbi.v2.sqlobject.mixins.GetHandle;
import org.skife.jdbi.v2.tweak.HandleCallback;
import java.util.Random;

public class TestReentrancy extends TestCase
{
    private DBI    dbi;
    private Handle handle;

    interface TheBasics extends GetHandle
    {
        @SqlUpdate("insert into something (id, name) values (:id, :name)")
        int insert(@BindBean Something something);
    }

    @Test
    public void testHandleReentrant() throws Exception
    {
        final TheBasics dao = dbi.onDemand(TheBasics.class);

        dao.withHandle(new HandleCallback<Void>() {
            @Override
            public Void withHandle(Handle handle) throws Exception
            {
                dao.insert(new Something(7, "Martin"));

                handle.createQuery("SELECT 1").list();

                return null;
            }
        });
    }

    @Test
    public void testTxnReentrant() throws Exception
    {
        final TheBasics dao = dbi.onDemand(TheBasics.class);

        dao.withHandle(new HandleCallback<Void>() {
            @Override
            public Void withHandle(Handle handle) throws Exception
            {
                handle.inTransaction(new TransactionCallback<Void>() {
                    @Override
                    public Void inTransaction(Handle conn, TransactionStatus status) throws Exception
                    {
                        dao.insert(new Something(1, "x"));

                        conn.createQuery("SELECT 1").list();
                        return null;
                    }
                });

                return null;
            }
        });
    }

    @Override
    public void setUp() throws Exception
    {
        JdbcDataSource ds = new JdbcDataSource();
        // in MVCC mode h2 doesn't shut down immediately on all connections closed, so need random db name
        ds.setURL("jdbc:h2:mem:test" + new Random().nextInt() +";MVCC=TRUE");

        dbi = new DBI(ds);

        dbi.registerMapper(new SomethingMapper());

        handle = dbi.open();

        handle.execute("create table something (id int primary key, name varchar(100))");
    }

    @Override
    public void tearDown() throws Exception
    {
        handle.execute("drop table something");
        handle.close();
    }
}

Add a (failing) test to demonstrate confusing behavior when mixing SqlObject and GetHandle

You'd expect to be able to use the SqlObject from within, but if you do so it releases the handle, causing mass chaos.
If these constructs cannot coexist, then it should at least fail explicitly and quickly.


package com.zulip.android.util;

import android.animation.Animator;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.view.View;
import android.view.ViewPropertyAnimator;
import android.view.animation.Interpolator;

public class AnimationHelper {

    private static final Interpolator FAST_OUT_SLOW_IN_INTERPOLATOR = new FastOutSlowInInterpolator();

    public static void showView(final View view, int duration) {
        ViewPropertyAnimator slideOutAnimator = view.animate()
                .translationX(view.getWidth())
                .setInterpolator(FAST_OUT_SLOW_IN_INTERPOLATOR)
                .setDuration(duration);

        slideOutAnimator.setListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
            }

            @Override
            public void onAnimationEnd(Animator animator) {
                view.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationCancel(Animator animator) {
            }

            @Override
            public void onAnimationRepeat(Animator animator) {
            }
        });
        slideOutAnimator.start();
    }

    public static void hideView(final View view, int duration) {
        ViewPropertyAnimator slideOutAnimator = view.animate()
                .translationX(0)
                .setInterpolator(FAST_OUT_SLOW_IN_INTERPOLATOR)
                .setDuration(duration);

        slideOutAnimator.setListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
                view.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animator animator) {

            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {
            }
        });
        slideOutAnimator.start();
    }
}

Implement Animation Helper class to have methods for animation


/**
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for
 * license information.
 */

package com.microsoft.azure.management.resources.fluentcore.arm.collection;

import com.microsoft.azure.PagedList;
import com.microsoft.azure.management.apigeneration.LangDefinition;
import com.microsoft.azure.management.apigeneration.LangDefinition.MethodConversion;
import com.microsoft.azure.management.resources.fluentcore.arm.Region;

/**
 * Provides access to listing Azure resources of a specific type based on their tag.
 * <p>
 * (Note: this interface is not intended to be implemented by user code)
 *
 * @param <T> the fluent type of the resource
 */
@LangDefinition(ContainerName = "CollectionActions", MethodConversionType = MethodConversion.OnlyMethod)
public interface SupportsListingByTag<T> {
    /**
     * Lists all the resources of the specified type in the specified tag.
     *
     * @param tag the tag value
     * @return list of resources
     */
    PagedList<T> listByTag(String resourceGroupName, String tag);
}

Add supporting by tag interface

Add supporting by tag interface


// 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.data;

import com.google.appengine.api.datastore.Entity;

/**
 * A class to make a Trip type, containing
 * a specific id, destinations, interests and routes
 * to be used when updating a trip.
 */
public final class Trip{

  private long id;
  private final ArrayList<String> destinations;
  private final ArrayList<String> interests;
  private final ArrayList<String> route;

  public Trip(long id, ArrayList<String> destinations) {
    this.id = id;
    this.destinations = destinations;
    this.interests = null;
    this.route = null;
  }

  public void setInterestsFor(long id, ArrayList<String> interests){
    if(this.id == id) {
      this.interests = interests;
    } else {
      // Indicate illegal action somehow?
      return;
    }
  }

  public void setRouteFor(long id, ArrayList<String> route) {
    if(this.id == id) {
      this.route = route;
    } else {
      // Indicate illegal action somehow?
      return;
    }
  }

  public ArrayList<String> getInterests() {
      return this.interests;
  }

  public ArrayList<String> getRoute() {
      return this.route;
  }
}

Make Trip class to use throughout servlets


package leetcode.search_a_2d_matrix;

public class Solution {
	public boolean searchMatrix(int[][] matrix, int target) {
		if(matrix == null) return false;
		if(matrix.length == 0) return false;
		if(matrix[0].length== 0) return false;
		int height = matrix.length;
		int width = matrix[0].length;
		int U = height * width;
		int L = 0;
		if(matrix[0][0] == target) return true;
		if(matrix[0][0] > target || matrix[height - 1][width - 1] < target) return false;
		while(L + 1 < U){
			int mid = (L + U) / 2;
			int x = mid / width;
			int y = mid % width;
			if(matrix[x][y] == target) return true;
			if(matrix[x][y] > target) U = mid;
			else L = mid;
		}
		return false;
    }

	public static void main(String[] args){
		final int height = 5;
		final int width = 3;
		int[][] matrix = new int[height][width];
		for(int i = 0; i < height; i++){
			for(int j = 0; j < width; j++){
				matrix[i][j] = (i * width + j) * 2;
			}
		}
		for(int i = -1; i < (height * width) * 2 + 1; i++){
			System.err.println("" + new Solution().searchMatrix(matrix, i));
		}
	}
}

Add java solution for 74. Search a 2D Matrix

74. Search a 2D Matrix: https://leetcode.com/problems/search-a-2d-matrix/


public class Solution {

    public String convertToBase7(int num) {

        if (num < 0) {
            return '-' + convertToBase7(-num);
        }

        if (num < 7) {
            return Integer.toString(num);
        }

        return convertToBase7(num / 7) + num % 7;

    }

}

Create : 504 Base 7

Create : 504 Base 7


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// This file is a part of the 'esoco-common' project.
// Copyright 2016 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany
//
// 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 de.esoco.lib.property;

/********************************************************************
 * Enumeration of abstract event types for user interface interactions. The
 * values are:
 *
 *

 *
<l>{@link #UPDATE}: The value of an element has been updated.

 *
<l>{@link #ACTION}: An action has been triggered for an element.

 *
<l>{@link #FOCUS_LOST}: An element has lost the input focus.

 *

 */
public enum InteractionEventType { UPDATE, ACTION, FOCUS_LOST }

Add support for arbitrary client events

SDACK-18: Add support for arbitrary client events


package net.imagej.ops.filter.min;

import net.imagej.ops.ComputerOp;
import net.imagej.ops.Ops;
import net.imagej.ops.filter.AbstractNonLinearFilter;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.type.numeric.RealType;

import org.scijava.Priority;
import org.scijava.plugin.Plugin;

/**
 * Default implementation of {@link MinFilterOp}.
 *
 * @author Jonathan Hale (University of Konstanz)
 * @param <T> type
 */
@Plugin(type = Ops.Filter.Min.class, name = Ops.Filter.Min.NAME,
	priority = Priority.LOW_PRIORITY)
public class DefaultMinFilter<T extends RealType<T>> extends
	AbstractNonLinearFilter<T, T> implements
	MinFilterOp<RandomAccessibleInterval<T>>
{

	@SuppressWarnings("unchecked")
	@Override
	protected ComputerOp<Iterable<T>, T> getComputer(Class<?> inClass,
		Class<?> outClass)
	{
		return (ComputerOp<Iterable<T>, T>) ops.op(Ops.Stats.Min.class, Iterable.class,
			inClass);
	}

}

Add default implementation of MinFilterOp

Signed-off-by: squareys <b4e1335d2c774058f7a95112f52894dcc752fd3f@googlemail.com>


package net.chrizzly.csharp4netbeans.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.IntStream;

/**
 *
 * @author pedrohidalgo
 */
public class MiscUtil {
    public static final String LINE_SEPARATOR = System.getProperty("line.separator");

    public static List<String> getLinesFromFileContent(String fileContent) {
        List<String> result = new ArrayList<>();
        try (Scanner scanner = new Scanner(fileContent)) {
            while (scanner.hasNextLine()) {
                result.add(scanner.nextLine());
            }
        }

        return result;
    }

    public static int getOpenSymbolsAmount(String line) {
        int result = 0;
        char[] chars = line.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char ch = chars[i];
            if (ch == '{' || ch == '(') {
                result++;
            } else if (ch == '}' || ch == ')') {
                result--;
            }
        }
        return result;
    }

    public static String getAmountSeparatorChars(int amount) {
        if (amount <= 0) {
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder();
        IntStream.rangeClosed(1, amount).forEach((int i) -> {
            stringBuilder.append(" ");
        });
        return stringBuilder.toString();
    }
}

Copy over the reformat code from a fork of pedro.


package com.pengrad.telegrambot;

import com.pengrad.telegrambot.model.Chat;
import com.pengrad.telegrambot.model.Message;
import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.model.User;
import com.pengrad.telegrambot.response.GetUpdatesResponse;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Properties;

/**
 * stas
 * 3/31/16.
 */
public class TestLoopGetUpdates {

    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        properties.load(new FileInputStream("local.properties"));
        TelegramBot bot = TelegramBotAdapter.build(properties.getProperty("TEST_TOKEN"));

        GetUpdatesResponse updatesResponse;
        int j = 0;
        while (true) {
            try {
                updatesResponse = bot.getUpdates(j, 100, 20);
                List<Update> updates = updatesResponse.updates();
                for (int z = 0; z < updates.size(); z++) {
                    j = updates.get(z).updateId() + 1;
                    Message message = updates.get(z).message();
                    //
                    Chat chat = message.chat();
                    User user = message.from();
                    //String mes=message.text();

                    // Base64.getEncoder().encodeToString(s.getBytes(StandardCharsets.UTF_8));
                    if (message.text() != null) {
                        System.out.println("New message: " + message.text() + " id: " + message.messageId() + " from " + chat);
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Test get updates in endless loop

Test get updates in endless loop


/*
 * StrUtils.java
 *
 * Author: Ming Tsang
 * Copyright (c) 2015 Ming Tsang
 * Refer to LICENSE for details
 */

package com.nkming.utils.str;

import java.util.Collection;

public class StrUtils
{
	/**
	 * Join multiple objects with toString(). @a glue will be inserted between
	 * each objects
	 *
	 * @param glue
	 * @param c
	 * @return
	 */
	public static <T> String Implode(String glue, Collection<T> c)
	{
		String product = null;
		for (T obj : c)
		{
			if (product == null)
			{
				product = obj.toString();
			}
			else
			{
				product += glue + obj.toString();
			}
		}
		return product;
	}
}

Add implode to join strings

Add implode to join strings


package sortingalgorithms;

/**
 *  An interface for sorting algorithms. A class must implement
 *  SortingAlgorithm to work with SortingTest.
 *
 *  @author  Joel Abrahamsson
 *  @version %G%
 */
public interface SortingAlgorithm
{
  public void sort(int[] array);
}

Create interface for sorting algorithms

Create interface for sorting algorithms


package ch.skymarshall.tcwriter.jupiter;

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

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIfSystemProperty;

@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Test
@DisabledIfSystemProperty(named = "java.awt.headless", matches = "true")
public @interface DisableIfHeadless {
	// noop
}

Use Jupiter annotation to skip gui tests, instead of using maven profile


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

import fi.helsinki.cs.tmc.cli.Application;
import fi.helsinki.cs.tmc.cli.CliContext;
import fi.helsinki.cs.tmc.cli.io.TestIo;

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

public class ShellHelperCommandTest {

    private Application app;
    private TestIo io;

    @Before
    public void setUp() {
        io = new TestIo();
        CliContext ctx = new CliContext(io);
        app = new Application(ctx);
    }

    @Test
    public void failWhenNoOptionsGiven() {
        String[] args = {"shell-helper"};
        app.run(args);
        io.assertContains("internal usage");
    }

    @Test
    public void getCommandList() {
        String[] args = {"shell-helper", "-c"};
        app.run(args);
        io.assertContains("help\n");
    }
}

Add unit tests for shell helper.

Add unit tests for shell helper.


package com.iesebre.dam2.roger.todos;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;

public class Main2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    Intent intent = new Intent(Main2Activity.this, MainActivity.class);
                    startActivity(intent);

                //Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                //        .setAction("Action", null).show();
            }
        });
    }

}

Create a Main2activity and buton to MainActivity


package commands;

import MovementAndImageAPI.*;

public class ActivityCommand extends CommandsTurtle {

    public enum CommandType {HIDE, SHOW, PICK_UP, PUT};
    private CommandType command;

    public ActivityCommand(Turtle turtle, CommandType command) {
        super(turtle);
        this.command = command;
    }

    @Override
    public void execute() {
        switch(command) {
            case HIDE:
                turtle().hide();
                break;
            case SHOW:
                turtle().show();
                break;
            case PICK_UP:
                turtle().pickUp();
                break;
            case PUT:
                turtle().put();
                break;
        }

    }

}

Implement turtle activity commands subset


package cl.fatman.capital.fund;

import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

public class ControllerFailTest {

	private Controller control;
	private PersistenceData persistence;

	@Before
	public void setUp() {
		control = Controller.getInstance();
		control.setUp();
		persistence = PersistenceData.getInstance();
	}

	@After
	public void tearDown() {
		control.tearDown();
	}

	@Test
	public void storeFundDataFailTest() {
		control.storeFundData();
		control.storeFundData();
		List<?> fundRateList = persistence.selectAllObjects("from FundRate", FundRate.class);
		assertEquals("Fund rate list size shold be 0.", 0, fundRateList.size());
	}
}

Create a junit class to test the fails in the Controller.


package javaDatatypes;

import java.util.*;

class Solution{

	public static void getNumberAndOutoutType(Scanner sc){
		try
        {
            long x = sc.nextLong();
            System.out.println(x+" can be fitted in:");
            if( x >= -128 && x <= 127 )
                System.out.println("* byte");
            if( x >= -32768 && x <= 32767 )
                System.out.println("* short");
            if( x >= -2147483648 && x <= 2147483647)
                System.out.println("* int");
            if( x >= -9223372036854775808L && x <= 9223372036854775807L)
                System.out.println("* long");
        }
        catch(Exception e)
        {
            System.out.println(sc.next() + " can't be fitted anywhere.");
        }
	}

    public static void main(String []argh)
    {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();

        for(int i = 0;i < t; ++i)
        	getNumberAndOutoutType(sc);

        sc.close();
    }
}

Add solution for problem Java Datatypes, HackerRank/Introduction/Java Datatypes


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

package org.openmhealth.shim.googlefit.mapper;

import com.fasterxml.jackson.databind.JsonNode;
import org.openmhealth.schema.domain.omh.DataPoint;
import org.openmhealth.schema.domain.omh.Geoposition;

import java.util.Optional;

import static org.openmhealth.schema.domain.omh.LengthUnit.METER;
import static org.openmhealth.schema.domain.omh.PlaneAngleUnit.DEGREE_OF_ARC;
import static org.openmhealth.shim.common.mapper.JsonNodeMappingSupport.*;

/**
 * A mapper from Google Fit "merged location samples" endpoint responses (derived:com.google.location.sample:com.google.android.gms:merge_location_samples)
 * to {@link Geoposition} objects.
 *
 * @author Emerson Farrugia
 * @see Google Fit Data Type Documentation
 */
public class GoogleFitGeopositionDataPointMapper extends GoogleFitDataPointMapper<Geoposition> {

    @Override
    protected Optional<DataPoint<Geoposition>> asDataPoint(JsonNode listNode) {

        JsonNode listValueNode = asRequiredNode(listNode, "value");
        double latitude = asRequiredDouble(listValueNode.get(0), "fpVal");
        double longitude = asRequiredDouble(listValueNode.get(1), "fpVal");
        // TODO add accuracy to geoposition
        Optional<Double> accuracyInM = asOptionalDouble(listValueNode.get(2), "fpVal");
        Optional<Double> altitudeInM = asOptionalDouble(listValueNode.get(3), "fpVal");

        Geoposition.Builder measureBuilder =
                new Geoposition.Builder(
                        DEGREE_OF_ARC.newUnitValue(latitude),
                        DEGREE_OF_ARC.newUnitValue(longitude),
                        getTimeFrame(listNode));

        altitudeInM.ifPresent((a) -> measureBuilder.setElevation(METER.newUnitValue(a)));

        Geoposition geoposition = measureBuilder.build();

        Optional<String> originDataSourceId = asOptionalString(listNode, "originDataSourceId");

        return Optional.of(newDataPoint(geoposition, originDataSourceId.orElse(null)));
    }
}

Add Google Fit geoposition mapper

Add Google Fit geoposition mapper


/*
 Copyright (C) 2003 EBI, GRL

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

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

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

import java.sql.Connection;

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

/**
 * Check for any xref.info_type that are blank ('') - they should be NULL for various other things to work.
 */

public class BlankInfoType extends SingleDatabaseTestCase {

	/**
	 * Create a new BlankInfoType testcase.
	 */
	public BlankInfoType() {

		addToGroup("post_genebuild");
		addToGroup("release");
		setDescription("Check for any xref.info_type that are blank ('') - they should be NULL for various other things to work.");

	}

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

		boolean result = true;

		Connection con = dbre.getConnection();

		int rows = getRowCount(con, "SELECT COUNT(*) FROM xref WHERE info_type = ''");

		if (rows > 0) {

			ReportManager.problem(this, con, rows + " rows in xref have a blank info_type - should be set to null");
			result = false;

		} else {

			ReportManager.correct(this, con, "No blank info_types in xref");

		}

		return result;

	} // run

} // BlankInfoType


package org.springframework.data.datastore.repository;

import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
import static org.junit.Assert.assertThat;

import java.util.Arrays;

import org.junit.Test;

import com.google.cloud.datastore.PathElement;

public class ContextTest {
    @Test
    public void testWith1() {
        // Exercise
        try (Context ctx = Context.with(Arrays.asList(
                PathElement.of("Kind", 1)))) {
            // Verify
            assertThat(Context.getAncestors(), contains(
                PathElement.of("Kind", 1)));
        }
    }

    @Test
    public void testWith2() {
        // Exercise
        try (Context ctx = Context.with(Arrays.asList(
                PathElement.of("Kind", 1),
                PathElement.of("Kind", 2)))) {
            // Verify
            assertThat(Context.getAncestors(), contains(
                PathElement.of("Kind", 1),
                PathElement.of("Kind", 2)));
        }
    }

    @Test
    public void testWithVararg1() {
        // Exercise
        try (Context ctx = Context.with(
                PathElement.of("Kind", 1))) {
            // Verify
            assertThat(Context.getAncestors(), contains(
                PathElement.of("Kind", 1)));
        }
    }

    @Test
    public void testWithVararg2() {
        // Exercise
        try (Context ctx = Context.with(
                PathElement.of("Kind", 1),
                PathElement.of("Kind", 2))) {
            // Verify
            assertThat(Context.getAncestors(), contains(
                PathElement.of("Kind", 1),
                PathElement.of("Kind", 2)));
        }
    }

    @Test
    public void testClose1() {
        // Setup, Exercise
        try (Context ctx = Context.with(
                PathElement.of("Kind", 1))) {
        }

        // Verify
        assertThat(Context.getAncestors(), empty());
    }

    @Test
    public void testClose2() {
        // Setup, Exercise
        try (Context ctx = Context.with(
                PathElement.of("Kind", 1),
                PathElement.of("Kind", 1))) {
        }

        // Verify
        assertThat(Context.getAncestors(), empty());
    }
}

Add tests for Context class

Add tests for Context class


package org.knowm.xchange.service.trade.params;

import org.knowm.xchange.currency.CurrencyPair;

public class DefaultCancelOrderByPairAndIfParams implements CancelOrderByIdParams, CancelOrderByCurrencyPair {

	private CurrencyPair currencyPair;
	private String orderId;

	public DefaultCancelOrderByPairAndIfParams(CurrencyPair currencyPair, String orderId) {
		this.currencyPair = currencyPair;
		this.orderId = orderId;
	}

	public void setCurrencyPair(CurrencyPair pair) {
		this.currencyPair = pair;
	}

	public void setOrderId(String orderId) {
		this.orderId = orderId;
	}

	@Override
	public CurrencyPair getCurrencyPair() {
		return currencyPair;
	}

	@Override
	public String getOrderId() {
		return orderId;
	}
}

[Core] Add DefaultCancelOrder with pair and id params


package npe;

public class CheckATHROW {
	public void doNotReport(Throwable obj) throws Throwable {
		throw obj;
	}

	public void throwNullValueReport(boolean b) throws Throwable {

		Throwable t = null;

		if (b) {
			System.out.println("Yeah");
		}

		throw t;
	}

	public void throwPossiblyNullReport(Throwable t) throws Throwable {
		if (t != null) {
			System.out.println("ok");
		}

		throw t;
	}
}

Test that ATHROW instructions are assumed to have a null check.

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@8609 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


package com.oriordank;

import com.oriordank.plist.MapDbPListStore;
import org.apache.activemq.broker.Broker;
import org.apache.activemq.broker.BrokerPlugin;

public class MapDbBrokerPlugin implements BrokerPlugin {
    @Override
    public Broker installPlugin(Broker broker) throws Exception {
        broker.getBrokerService().setTempDataStore(new MapDbPListStore());
        return broker;
    }
}

Add option of configuring using <plugins>


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

package org.zeroxlab.aster;

import java.util.*;
import javax.swing.event.*;

public class DefaultActionListModel implements ActionListModel {
    /** The listeners waiting for model changes. */
    protected EventListenerList listenerList = new EventListenerList();

    public void addChangeListener(ChangeListener l) {
        listenerList.add(ChangeListener.class, l);
    }

    public void removeChangeListener(ChangeListener l) {
        listenerList.remove(ChangeListener.class, l);
    }

    /**
     * Run each ChangeListener's stateChanged
     * method.
     */
    protected void fireStateChanged() {
        ChangeEvent ev = null;
        Object[] listeners = listenerList.getListenerList();
        for (int i = listeners.length-2; i >= 0; i -= 2) {
            if (listeners[i] == ChangeListener.class) {
                // Lazily create the event:
                if (ev == null)
                    ev = new ChangeEvent(this);
                ((ChangeListener)listeners[i+1]).stateChanged(ev);
            }
        }
    }

    /**
     * Returns an array of all the change listeners registered on this
     * DefaultActionListModel.
     *
     * @return all of this model's ChangeListeners or an empty
     *         arrary if no change listeners are currently registered
     *
     * @see #addchangeListener
     * @see #removeChangeListener
     */
    public ChangeListener[] getChangeListeners() {
        return (ChangeListener[]) listenerList.getListeners(ChangeListener.class);
    }

    /** The command stack */
    Deque actionList = new ArrayDeque<AsterCommand>();
    /** The recall command */
    AsterCommand recall;

    public DefaultActionListModel() {
    }

    public void setRecall(AsterCommand cmd) {
        recall = cmd;
        fireStateChanged();
    }

    public void pushCmd(AsterCommand cmd) {
        actionList.addFirst(cmd);
        fireStateChanged();
    }

    public void popCmd() {
        try {
            actionList.removeFirst();
            fireStateChanged();
        } catch (NoSuchElementException e) {
            // log.w("try to pop empty command list");
        }
    }
}

Add default action list model implementation.


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

package org.openmhealth.data.generator.service;

import org.joda.time.DateTime;
import org.openmhealth.data.generator.domain.MeasureGroup;
import org.openmhealth.schema.pojos.Activity;
import org.openmhealth.schema.pojos.DataPoint;
import org.openmhealth.schema.pojos.HeartRate;
import org.openmhealth.schema.pojos.Metadata;
import org.openmhealth.schema.pojos.builder.ActivityBuilder;
import org.openmhealth.schema.pojos.builder.HeartRateBuilder;
import org.openmhealth.schema.pojos.generic.DurationUnitValue;
import org.openmhealth.schema.pojos.generic.LengthUnitValue;
import org.springframework.stereotype.Service;

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

import static org.openmhealth.schema.pojos.generic.DurationUnitValue.DurationUnit.min;
import static org.openmhealth.schema.pojos.generic.LengthUnitValue.LengthUnit.m;

/**
 * @author Emerson Farrugia
 */
@Service
public class PhysicalActivityDataPointGenerationServiceImpl extends AbstractDataPointGenerationServiceImpl
        implements DataPointGenerationService {

    @Override
    public Iterable<DataPoint> generateDataPoints(Iterable<MeasureGroup> measureGroups) {

        List<DataPoint> dataPoints = new ArrayList<>();

        for (MeasureGroup measureGroup : measureGroups) {

            ActivityBuilder builder = new ActivityBuilder();

            double duration = measureGroup.getMeasureValue("duration");
            builder.withStartAndDuration(convert(measureGroup.getEffectiveDateTime()), duration, min);
            builder.setDistance(measureGroup.getMeasureValue("distance"), m);

            Metadata metadata = new Metadata();
            metadata.setTimestamp(DateTime.now());

            Activity dataPoint = builder.build();
            dataPoint.setMetadata(metadata);

            dataPoints.add(dataPoint);
        }

        return dataPoints;
    }
}

Add physical activity data generation service.


package ca.corefacility.bioinformatics.irida.web.controller.test.integration;

import com.google.common.net.HttpHeaders;
import com.jayway.restassured.response.Response;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

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

import static com.jayway.restassured.RestAssured.get;
import static com.jayway.restassured.RestAssured.given;
import static com.jayway.restassured.path.json.JsonPath.from;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

/**
 * Integration tests for project samples.
 *
 * @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>
 */
public class ProjectSamplesIntegrationTest {
    private static final Logger logger = LoggerFactory.getLogger(ProjectSamplesIntegrationTest.class);

    @Test
    public void testAddSampleToProject() {
        Map<String, String> sample = new HashMap<>();
        sample.put("sampleName", "sample 1");

        // load a project
        String projectsJson = get("/projects").asString();
        String projectUri = from(projectsJson).get("resource.resources[0].links[0].href");
        // get the uri for creating samples associated with the project.
        String projectJson = get(projectUri).asString();
        String samplesUri = from(projectJson).get("resource.links.find{it.rel == 'project/samples'}.href");

        // post that uri
        Response r = given().body(sample).expect().response().statusCode(HttpStatus.CREATED.value()).when().post(samplesUri);

        // check that the locations are set appropriately.
        String location = r.getHeader(HttpHeaders.LOCATION);
        String linkLocation = r.getHeader(HttpHeaders.LINK);

        assertNotNull(location);
        assertTrue(location.matches("^http://localhost:8080/api/samples/[a-f0-9\\-]+$"));

        assertNotNull(linkLocation);
        assertTrue(linkLocation.matches("^<http://localhost:8080/api/projects/[a-f0-9\\-]+/samples/[a-f0-9\\-]+>; rel=relationship$"));
    }
}

Test that samples can be added to a project without previously being persisted.


package org.apache.markt;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

class NoopFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // NO-OP
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        // NO-OP
    }

    @Override
    public void destroy() {
        // NO-OP
    }
}

Package private no-op filter for testing with.


package com.sequenceiq.environment.environment.repository.converter;

import java.util.Optional;

import com.sequenceiq.cloudbreak.converter.DefaultEnumConverter;
import com.sequenceiq.environment.environment.flow.deletion.event.EnvDeleteStateSelectors;

public class EnvDeleteStateSelectorsConverter extends DefaultEnumConverter<EnvDeleteStateSelectors> {
    @Override
    public EnvDeleteStateSelectors getDefault() {
        return EnvDeleteStateSelectors.FINALIZE_ENV_DELETE_EVENT;
    }

    @Override
    public Optional<EnvDeleteStateSelectors> tryConvertUnknownField(String attribute) {
        if ("START_PREREQUISITES_DELETE_EVENT".equals(attribute)) {
            return Optional.of(EnvDeleteStateSelectors.FINISH_ENV_DELETE_EVENT);
        }
        return Optional.empty();
    }
}

[ASRG] Implement resource group termination step - backward compatibility


/**
 * 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.
 *
 * Copyright 2012-2014 the original author or authors.
 */
package org.assertj.db.api.assertions.impl.constructor;

import org.assertj.db.api.assertions.impl.AssertionsOnColumnOfChangeType;
import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;

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

/**
 * Tests on {@link AssertionsOnColumnOfChangeType} class :
 * {@link AssertionsOnColumnOfChangeType#AssertionsOnColumnOfChangeType()} private constructor.
 *
 * @author Régis Pouiller
 *
 */
public class AssertionsOnColumnOfChangeType_Constructor_Test {

  /**
   * This method tests the private constructor of {@code Assertions} for the tests coverage..
   * @throws NoSuchMethodException
   * @throws SecurityException
   * @throws java.lang.reflect.InvocationTargetException
   * @throws IllegalAccessException
   * @throws InstantiationException
   * @throws IllegalArgumentException
   */
  @Test
  public void test_private_constructor_for_the_tests_coverage()
          throws SecurityException, NoSuchMethodException, IllegalArgumentException,
          InstantiationException, IllegalAccessException, InvocationTargetException {

    Constructor<AssertionsOnColumnOfChangeType> constructor = AssertionsOnColumnOfChangeType.class.getDeclaredConstructor();
    assertThat(Modifier.isPrivate(constructor.getModifiers())).isTrue();
    constructor.setAccessible(true);
    constructor.newInstance();
    constructor.setAccessible(false);
  }
}

Add test on constructor of AssertionsOnColumnOfChangeType


package com.codemelon.graph.vertex.interfaces;

import com.codemelon.graph.common.Color;

/**
 * Vertex that supports colored edges
 * @author Marshall Farrier
 * @version Dec 10, 2012
 */
public interface ColoredEdgeVertex extends Vertex {
	/**
	 * Set the color of the given edge
	 * @param to head of the edge whose color is to be set
	 * @param color value to which to set the edge's color
	 */
	public void setEdgeColor(ColoredEdgeVertex to, Color color);
	/**
	 * Retrieve the color of the given edge
	 * @param to head of the edge whose color is to be retrieved
	 * @return the edge's color
	 */
	public Color getEdgeColor(ColoredEdgeVertex to);
}

Add vertex interface to support colored edges


package me.izstas.rfs.server.service;

import java.io.IOException;
import java.nio.file.*;

import me.izstas.rfs.server.RfsException;

class PathUtils {
    static RfsException wrapException(IOException e, String message) {
        if (e instanceof AccessDeniedException) {
            return new InaccessiblePathException(e);
        }

        if (e instanceof NoSuchFileException) {
            return new NonexistentPathException(e);
        }

        return new RfsException(message, e);
    }

    static void createDirectories(Path path, boolean parent) {
        try {
            Files.createDirectories(parent ? path.getParent() : path);
        }
        catch (FileAlreadyExistsException | NoSuchFileException e) { // While combination of these two may look weird,
                                                                     // on Windows we seem to get the latter one
                                                                     // if the problem is caused not by the immediate parent
                                                                     // but a further ascendant
            throw new NonexistentPathException("The path contains a file (not a directory) as one of the ascendants", e);
        }
        catch (IOException e) {
            throw wrapException(e, parent ? "Can't create ascendant directories" : "Can't create directories");
        }
    }

    private PathUtils() {
        throw new AssertionError();
    }
}

Add a class with some utility methods

Add a class with some utility methods


package org.jboss.jandex.test;

import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.Index;
import org.jboss.jandex.Indexer;
import org.jboss.jandex.Type;
import org.junit.Test;

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

import static org.junit.Assert.assertNotNull;

public class BoundedWildcardTestCase {

  public static class TestSubject<T extends Number> implements Comparable<T> {
    @Override
    public int compareTo(T o) {
      return 0;
    }
  }

  @Test
  public void testIndexer() throws IOException {
    Indexer indexer = new Indexer();
    InputStream stream = getClass().getClassLoader().getResourceAsStream(TestSubject.class.getName().replace('.', '/') + ".class");
    indexer.index(stream);
    Index index = indexer.complete();
    verifyMethodTypeVariable(index);
  }

  private void verifyMethodTypeVariable(Index index) {
    ClassInfo classInfo = index.getClassByName(DotName.createSimple(TestSubject.class.getName()));
    assertNotNull(classInfo.method("compareTo", Type.create(DotName.createSimple(Number.class.getName()), Type.Kind.CLASS)));
  }
}

Add test for method type variables that reference a class-level bounded wildcard generic


package com.dreamchain.skeleton.WS;

import com.dreamchain.skeleton.model.Customer;
import com.dreamchain.skeleton.model.User;
import com.dreamchain.skeleton.service.CustomerService;
import com.dreamchain.skeleton.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.jws.WebMethod;
import javax.jws.WebService;

/**
 * Created by LAPTOP DREAM on 11/4/2016.
 */

@WebService
public class CustomerWebService {

    @Autowired(required = true)
    private CustomerService customerService;

//    @WebMethod(exclude = true)
//    public void setCustomerService(CustomerService customerService) {
//        this.customerService = customerService;
//    }
    @WebMethod(operationName = "getCustomerById")
    public Customer getCustomerById(long id) {
        Customer customer = customerService.get(id);
        return customer;
    }

}

Add Customer soap web service

Add Customer soap web service


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

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

public class ChooseStoryActivityTestCases extends ActivityInstrumentationTestCase2<ChooseStoryActivity> {
	//declare activity and widgets
	private ChooseStoryActivity myChooseStoryActivity;
	private TextView myView;

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

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

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

	//Use Case 2, test 1/3
	public void testBrowseStoryList {
		addMultiStory();
		assertTrue(scrollable(mView.getText()));
	}

	//Use Case 2, test 2/3
	public void testBrowseNoScrollList {
		addOneStory();
		assertFalse(scrollable(mView.getText()));
	}

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

}

Put both test cases for use case 2 in here and changed the name so that it would potentially compile


package fr.tvbarthel.apps.simpleweatherforcast.fragments;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.widget.ArrayAdapter;

import java.security.InvalidParameterException;

public class TemperatureUnitPickerDialogFragment extends DialogFragment {

	private static final String BUNDLE_TEMPERATURE_UNIT_NAMES = "BundleTemperatureUnitNames";
	private static final String BUNDLE_TEMPERATURE_UNIT_SYMBOLS = "BundleTemperatureUnitSymbols";

	public static TemperatureUnitPickerDialogFragment newInstance(String[] temperatureUnitNames, String[] temperatureUnitSymbols) {
		final TemperatureUnitPickerDialogFragment instance = new TemperatureUnitPickerDialogFragment();
		final Bundle arguments = new Bundle();
		arguments.putStringArray(BUNDLE_TEMPERATURE_UNIT_NAMES, temperatureUnitNames);
		arguments.putStringArray(BUNDLE_TEMPERATURE_UNIT_SYMBOLS, temperatureUnitSymbols);
		instance.setArguments(arguments);
		return instance;
	}

	private TemperatureUnitPickerDialogFragment() {
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		final Bundle arguments = getArguments();

		final String[] temperatureUnitNames = arguments.getStringArray(BUNDLE_TEMPERATURE_UNIT_NAMES);
		final String[] temperatureUnitSymbols = arguments.getStringArray(BUNDLE_TEMPERATURE_UNIT_SYMBOLS);

		final ArrayAdapter<String> temperatureUnitNameAdapter = new ArrayAdapter<String>(getActivity(),
				android.R.layout.simple_expandable_list_item_1, temperatureUnitNames);

		final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		//TODO don't use a hard coded string
		builder.setTitle("Select a unit");
		builder.setAdapter(temperatureUnitNameAdapter, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Log.d("argonne",  temperatureUnitNames[which] + " -> " + temperatureUnitSymbols[which]);
				//TODO store the temperature unit chosen
			}
		});
		builder.setCancelable(true);
		//TODO don't use a hard coded string
		builder.setNegativeButton("Cancel", null);
		return builder.create();
	}
}

Add a dialog fragment skeleton for the temperature unit selection


package sfBugs;

public class Bug1908621 {
	public static Boolean get_bool() {
		Boolean test;

		if (1 == (int)Math.round(Math.random())) {
			test = null;
		} else {
			test = true;
		}

		return test;
	}

	/*
	 * Both alternatives do exactly the same. Alternative 1 gets the possible Null-Pointer-Dereference from the method "get_bool()",
	 * Alternative 2 gets the possible Null-Pointer-Dereference directly in the same method.
	 * FindBugs sends the alert only in alternative 2. It should also send the alert in alternative 1.
	 *
	 */

	public static void main (String[] args) {
		/**
		 * Alternative 1: Doesn't create a Null-Pointer-Dereference alert
		 */

		Boolean test = get_bool();

		if (test) {
			System.out.println("TRUE");
		}

		/**
		 * Alternative 2: Creates a Null-Pointer-Dereference alert
		 */

		//BEGIN: get_bool()
		Boolean test2;

		if (1 == (int)Math.round(Math.random())) {
			test2 = null;
		} else {
			test2 = true;
		}
		//END: get_bool()

		if (test2) {
			System.out.println("TRUE");
		}
	}
}

Test case for [ 1908621 ] Null Pointer Dereference

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@9385 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


package cpw.mods.fml.common.functions;

import java.util.Collection;
import java.util.List;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;

public class CollectionWrapperFactory {
    /**
     * Return a read only cast view of the supplied ungeneric collection, based on the element type given
     * @param coll The collection to cast
     * @param elementType the supertype contained in the collection
     * @return a collection asserting that type relationship
     */
    public static <T> Collection<T> wrap(@SuppressWarnings("rawtypes") Collection coll, Class<T> elementType)
    {
        Collection<?> asGeneric = coll;
        return Collections2.transform(asGeneric, new TypeCastFunction<T>(elementType));
    }

    /**
     * Return a read only cast view of the supplied ungeneric list, based on the element type given
     * @param list The list to cast
     * @param elementType the supertype contained in the list
     * @return a list asserting that type relationship
     */
    public static <T> List<T> wrap(@SuppressWarnings("rawtypes") List list, Class<T> elementType)
    {
        List<?> asGeneric = list;
        return Lists.transform(asGeneric, new TypeCastFunction<T>(elementType));
    }
}

Add a helper for casting some common collection types into generic form


package mesosphere.marathon.client.model.v2;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import mesosphere.marathon.client.Marathon;
import mesosphere.marathon.client.MarathonClient;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.Test;

import java.util.ArrayList;

import static org.junit.Assert.*;

public class ExternalVolumeTest {

    @Test
    public void testExternalVolumes() throws Exception {
        final MockWebServer server = new MockWebServer();
        final String mockResponse = "{\"container\": {\"volumes\": [" +
                "{\"containerPath\":\"/data/db\",\"mode\":\"RW\",\"external\":" +
                "{\"name\":\"mongodb-testvol\",\"provider\":\"dvdi\",\"options\":" +
                "{\"dvdi/driver\":\"rexray\"}}}]}}";

        try {
            server.enqueue(new MockResponse().setBody(mockResponse));
            server.start();
            Marathon client = MarathonClient.getInstance(server.url("/").toString());

            App app = new App();
            app.setId("mongo");
            app.setCpus(1.0);
            app.setMem(256.0);
            app.setContainer(new Container());
            app.getContainer().setDocker(new Docker());
            app.getContainer().getDocker().setImage("mongo");
            app.getContainer().setVolumes(new ArrayList<Volume>());

            ExternalVolume externalVolume = new ExternalVolume();
            externalVolume.setName("mongodb-testvol");
            externalVolume.setMode("RW");
            externalVolume.setContainerPath("/data/db");
            externalVolume.setProvider("dvdi");
            externalVolume.setDriver("rexray");

            app.getContainer().getVolumes().add(externalVolume);

            final App appRes = client.createApp(app);
            assertFalse(appRes.getContainer().getVolumes().isEmpty());

            ExternalVolume responseVolume = (ExternalVolume) appRes.getContainer().getVolumes().iterator().next();
            assertEquals("mongodb-testvol", responseVolume.getExternalVolumeInfo().getName());

            RecordedRequest request = server.takeRequest();
            assertNotNull(request);

            final String requestBody = request.getBody().readUtf8();
            assertNotNull(requestBody);

            // request to JSON
            JsonObject requestPayload = new Gson().fromJson(requestBody, JsonObject.class);
            assertNotNull(requestPayload);
            JsonObject requestVolume = requestPayload.getAsJsonObject("container").getAsJsonArray("volumes").get(0).getAsJsonObject();
            assertNotNull(requestVolume);
            assertEquals("RW", requestVolume.get("mode").getAsString());
            assertEquals("/data/db", requestVolume.get("containerPath").getAsString());
        } finally {
            server.shutdown();
        }
    }

}

Add Test for External Volumes

Add Test for External Volumes

Add a test for External Volumes that verifies the rquest is proper
JSON and the response is parsed correctly.


package de.timroes;

import static org.junit.Assert.*;

import de.timroes.axmlrpc.ResponseParser;
import de.timroes.axmlrpc.XMLRPCClient;
import de.timroes.axmlrpc.XMLRPCServerException;
import de.timroes.axmlrpc.serializer.SerializerHandler;
import org.junit.Test;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

public class TestResponseParser {
    public final static String xmlDecl = "<?xml version=\"1.0\"?>";
    public final static SerializerHandler sh = new SerializerHandler(XMLRPCClient.FLAGS_NONE);

    @Test
    public void testSimpleResponse() throws Exception {
        ResponseParser sut = new ResponseParser();
        Object actual = sut.parse(sh, strToStream(xmlDecl +
                "<methodResponse>" +
                "  <params>" +
                "    <param>" +
                "      <value><string>toto</string></value>" +
                "    </param>" +
                "  </params>" +
                "</methodResponse>"), false);
        assertEquals("toto", actual);
    }

    @Test
    /**
     * I'm not sure it really makes sense to support this case. But since I'm adding tests on code which existed
     * for years, I guess it's better to avoid breaking retro compatibility.
     */
    public void testAcceptMissingHeader() throws Exception {
        ResponseParser sut = new ResponseParser();
        Object actual = sut.parse(sh, strToStream("<methodResponse>" +
                "  <params>" +
                "    <param>" +
                "      <value><string>toto</string></value>" +
                "    </param>" +
                "  </params>" +
                "</methodResponse>"), false);
        assertEquals("toto", actual);
    }

    @Test
    public void testXmlrpcError() throws Exception {
        ResponseParser sut = new ResponseParser();
        try {
            sut.parse(sh, strToStream("<methodResponse>" +
                    "  <fault>" +
                    "    <value>" +
                    "      <struct>" +
                    "        <member>" +
                    "          <name>faultCode</name>" +
                    "          <value><int>4</int></value>" +
                    "        </member>" +
                    "        <member>" +
                    "          <name>faultString</name>" +
                    "          <value><string>error X occurred</string></value>" +
                    "        </member>" +
                    "      </struct>" +
                    "    </value>" +
                    "  </fault>" +
                    "</methodResponse>"), false);
            fail("The previous call should have thrown");
        } catch (XMLRPCServerException e){
            assertEquals("error X occurred [4]", e.getMessage());
            assertEquals(4, e.getErrorNr());
        }
}

    private static InputStream strToStream(String str){
        return new ByteArrayInputStream(str.getBytes());
    }
}

Add basic tests on the parser

Add basic tests on the parser


package com.test.graphs;

import java.util.LinkedList;

import com.graphs.GraphAdjacencyListRepresentation;
import com.graphs.MostDirectPath;

import junit.framework.TestCase;

public class TestMostDirectPath extends TestCase {

    public void testMostDirectPath() {

        GraphAdjacencyListRepresentation graph = new GraphAdjacencyListRepresentation(13, true);
        graph.addEdge(0, 5);
        graph.addEdge(0, 1);

        graph.addEdge(2, 0);
        graph.addEdge(2, 3);

        graph.addEdge(3, 5);
        graph.addEdge(3, 2);

        graph.addEdge(4, 3);
        graph.addEdge(4, 2);

        graph.addEdge(5, 4);

        graph.addEdge(6, 4);
        graph.addEdge(6, 8);
        graph.addEdge(6, 0);
        graph.addEdge(6, 9);

        graph.addEdge(7, 6);

        graph.addEdge(8, 6);

        graph.addEdge(9, 11);
        graph.addEdge(9, 10);

        graph.addEdge(10, 12);

        graph.addEdge(11, 12);

        graph.addEdge(12, 9);

        MostDirectPath dp = new MostDirectPath(graph, 6);
        assertEquals(0, dp.getDistance(6));
        assertEquals(-1, dp.getDistance(7));
        assertEquals(2, dp.getDistance(2));
        assertEquals(2, dp.getDistance(5));

        LinkedList<Integer> pathTo3 = new LinkedList<>();
        pathTo3.add(6);
        pathTo3.add(4);
        pathTo3.add(3);

        System.out.println(dp.getMostDirectPath(3));

        assertEquals(true, pathTo3.equals(dp.getMostDirectPath(3)));

    }

}

Add JUnit test for MostDirectPath

Add JUnit test for MostDirectPath


package net.grinder.util;

import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;

import org.junit.Test;

public class NetworkUtilTest {
	@Test
	public void testLocalHostName() {
		String localHostAddress = NetworkUtil.getLocalHostAddress("www.google.com", 80);
		assertThat(localHostAddress, notNullValue());
		assertThat(localHostAddress, not("127.0.0.1"));
		localHostAddress = NetworkUtil.getLocalHostAddress("122.132.22.11", 80);
		assertThat(localHostAddress, notNullValue());
		assertThat(localHostAddress, not("127.0.0.1"));

	}
}

[NGRINDER-315] Add agent which is used for specific user.


/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.xwiki.refactoring.job;

import org.xwiki.job.Request;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.stability.Unstable;

/**
 * Define a request that can be processed by a user.
 *
 * @version $Id$
 * @since 10.10RC1
 */
@Unstable
public interface UserOrientedRequest extends Request
{
    /**
     * @return {@code true} in case the job should check if the user specified by {@link #getUserReference()} is
     *         authorized to perform the actions implied by this request, {@code false} otherwise
     */
    boolean isCheckRights();

    /**
     * Sets whether the job should check or not if the user specified by {@link #getUserReference()} is authorized to
     * perform the actions implied by this request.
     *
     * @param checkRights {@code true} to check if {@link #getUserReference()} is authorized to perform this request,
     *            {@code false} to perform this request without checking rights
     */
    void setCheckRights(boolean checkRights);

    /**
     * @return the user that should be used to perform this request; this user must be authorized to perform the actions
     *         implied by this request if {@link #isCheckRights()} is {@code true}.
     */
    DocumentReference getUserReference();

    /**
     * Sets the user that should be used to perform this request. This user must be authorized to perform the actions
     * implied by this request if {@link #isCheckRights()} is {@code true}.
     *
     * @param userReference the user reference
     */
    void setUserReference(DocumentReference userReference);
}

XWIKI-15787: Add a "Delete all" button on the recycle bin

  * Add the missing new interface


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

package org.mybatis.cdi;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({METHOD, FIELD, TYPE, PARAMETER})
public @interface MySpecialManager {
}

Test case for Mapper injection (fail)

Test case for Mapper injection (fail)


package no.ssb.vtl.test;

import com.google.common.collect.ForwardingObject;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import no.ssb.vtl.model.Component;
import no.ssb.vtl.model.DataPoint;
import no.ssb.vtl.model.DataStructure;
import no.ssb.vtl.model.Dataset;
import no.ssb.vtl.model.StaticDataset;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 *
 */
public class TestDataset extends ForwardingObject implements Dataset {

    private final Random random;
    private final StaticDataset delegate;

    private boolean variableSize;
    private boolean shuffleData;
    private boolean shuffleStructure;

    public TestDataset(Random random, StaticDataset dataset) {
        this.delegate = checkNotNull(dataset);
        this.random = checkNotNull(random);
    }

    @Override
    public Stream<DataPoint> getData() {
        Stream<DataPoint> stream = delegate().getData();

        if (shuffleStructure)
            // TODO

        if (!shuffleData)
            return stream;

        List<DataPoint> collect = stream.collect(Collectors.toList());
        Collections.shuffle(collect, this.random);
        return collect.stream();

    }

    @Override
    public Optional<Map<String, Integer>> getDistinctValuesCount() {
        return Optional.empty();
    }

    @Override
    public Optional<Long> getSize() {
        return Optional.empty();
    }

    @Override
    public DataStructure getDataStructure() {
        DataStructure structure = delegate().getDataStructure();
        if (!shuffleStructure)
            return structure;

        ArrayList<Map.Entry<String, Component>> entries = Lists.newArrayList(structure.entrySet());
        Collections.shuffle(entries, this.random);
        return DataStructure.copyOf(ImmutableMap.copyOf(entries)).build();
    }

    @Override
    protected StaticDataset delegate() {
        return this.delegate;
    }
}

Add a test utility that randomize datasets


package com.exp.tracker.services.impl;

import java.util.List;

import javax.faces.model.SelectItem;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import com.exp.tracker.services.api.RoleService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/root-applicationContext.xml")
@ActiveProfiles("demo")
@WebAppConfiguration
public class JpaRoleServiceTests {

	@Autowired
	private RoleService roleService;

	@Test
	public void roleServiceTests() {
		List<SelectItem> rsi = roleService.getRolesSelectItems();
		Assert.assertNotNull("Failed to get roles",rsi);
		Assert.assertTrue("Expected exactly 3 roles", rsi.size() == 3);
	}
}

Fix strage test failure in Travis environment


package com.xqbase.bn.schema;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Arrays;
import java.util.Collection;

@RunWith(Parameterized.class)
public class TestSchemaFullName {

    @Parameterized.Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
                new Object[]{"a", "o.a.h", "o.a.h.a"}
        });
    }

    private final String name;
    private final String namespace;
    private final String fullName;

    public TestSchemaFullName(String name, String namespace, String fullName) {
        this.name = name;
        this.namespace = namespace;
        this.fullName = fullName;
    }

    @Test
    public void testFullName() {
        SchemaName schemaName = new SchemaName(name, namespace);
        Assert.assertEquals(fullName, schemaName.getFullName());
    }
}

Add full name test case......

Add full name test case......


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

/**
 * Write code to remove duplicates from an unsorted linked list. How would you solve this problem
 * if
 * a temporary buffer is not allowed?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class RemoveListDuplicatedElements {

}

Add statement to problem 57

Add statement to problem 57


/*
 * The MIT License
 *
 * Copyright (c) 2012, Chris Johnson
 *
 * 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 hudson.plugins.git;

import hudson.model.FreeStyleProject;
import org.jvnet.hudson.test.HudsonTestCase;

import java.util.concurrent.Future;
import java.util.Collections;

/**
 * Tests for {@link RevisionParameterAction}
 *
 * @author Chris Johnson
 */
public class RevisionParameterActionTest extends HudsonTestCase {

    /**
     * Test covering the behaviour until 1.1.25 where passing different revision
     * actions to a job in the queue combines them and ignores the later revisions.
     */
    public void testCombiningScheduling() throws Exception {

        FreeStyleProject fs = createFreeStyleProject("freestyle");

        // scheduleBuild2 returns null if request is combined into an existing item. (no new item added to queue)
        Future b1 = fs.scheduleBuild2(20, null, Collections.singletonList(new RevisionParameterAction("DEADBEEF")));
        Future b2 = fs.scheduleBuild2(20, null, Collections.singletonList(new RevisionParameterAction("FREED456")));

        //System.out.println(b1);
        //System.out.println(b2);

        // Check that we have the correct futures.
        assertNotNull(b1);
        assertNull(b2);

        // Check that only one build occured
        waitUntilNoActivity();
        assertEquals(fs.getBuilds().size(),1);
    }

}

Create testcase for starting builds with RevisionParameterAction

Covering existing behaviour where later builds with different revisions are ignored.


package com.itmill.toolkit.tests.components.tabsheet;

import com.itmill.toolkit.terminal.ThemeResource;
import com.itmill.toolkit.tests.components.TestBase;
import com.itmill.toolkit.ui.Component;
import com.itmill.toolkit.ui.Label;
import com.itmill.toolkit.ui.TabSheet;
import com.itmill.toolkit.ui.TextField;

public class TabSheetIcons extends TestBase {

    @Override
    protected String getDescription() {
        return "Tests rendering of a Tabsheet with fixed/dynamic width when the TabSheet contains icons";
    }

    @Override
    protected Integer getTicketNumber() {
        return null;
    }

    @Override
    protected void setup() {
        TabSheet ts1 = createTabsheet();
        ts1.setHeight("100px");
        TabSheet ts2 = createTabsheet();
        ts2.setHeight("100px");
        ts2.setWidth("400px");

        addComponent(ts1);
        addComponent(ts2);
    }

    private TabSheet createTabsheet() {
        TabSheet tabsheet = new TabSheet();
        tabsheet.setSizeUndefined();

        Component[] tab = new Component[3];
        tab[0] = new Label("This is tab 1");
        tab[0].setIcon(new ThemeResource("icons/32/folder-add.png"));
        tab[0].setCaption("tab number 1");
        tab[1] = new TextField("This is tab 2", "Contents of tab 2 textfield");
        tab[2] = new Label("This is tab 3");
        tab[2].setIcon(new ThemeResource("icons/16/folder-add.png"));
        tab[2].setCaption("tab number 3");

        for (Component c : tab) {
            tabsheet.addTab(c);
        }

        return tabsheet;
    }

}

Test case for a TabSheet containing icons

svn changeset:6604/svn branch:trunk


/**
 * Sample file using the RiakClient#store(RiakObject, ...) API
 */

package com.trifork.riak_http;

import java.io.IOException;

import com.basho.riak.client.RiakClient;
import com.basho.riak.client.RiakObject;

public class HTTPPushLotsOfData {

	public static void main(String[] args) throws IOException {

		RiakClient riak = new RiakClient("http://127.0.0.1:8098/riak");

		long before = System.currentTimeMillis();

		byte[] val = new byte[419];

		for (int i = 0; i < 100; i++) {

			long before2 = System.currentTimeMillis();

			String cpr = "" + (1000000000+i);
			String cpr_key = cpr;

			for (int rid = 0; rid < 1000; rid++)  {

				String rid_key = "" + (200000+i);

				RiakObject ro = new RiakObject(riak, cpr_key, rid_key, val);
				riak.store(ro);

			}

			long after2 = System.currentTimeMillis();

			System.out.println(""+i+" x 1000 INSERTS: "+(after2-before2)+"ms");

		}

		long after = System.currentTimeMillis();

		System.out.println("TOTAL TIME: "+(1.0*(after-before)/1000.0)+"s");
	}

}

Test similar to push-lots-of-data but using the HTTP-based java client.


/*
 * This is a special marker class used to differentiate our special
 * version of BCEL used for running Daikon/Chicory from any other
 * version that may be on the classpath. (markro)
 */

package org.apache.commons.bcel6;

public class PLSEMarker
{
  public static final String marker = "PLSE version of BCEL6";
}

Add a marker class to identify our version of bcel6.


package fi.vincit.mutrproject.service;

import static fi.vincit.multiusertest.rule.expection.Expectations.call;
import static fi.vincit.multiusertest.util.UserIdentifiers.ifAnyOf;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import fi.vincit.multiusertest.annotation.TestUsers;
import fi.vincit.multiusertest.util.LoginRole;
import fi.vincit.mutrproject.AbstractConfiguredIT;

@TestUsers(
        creators = {"role:ROLE_SUPER_ADMIN", "role:ROLE_ADMIN", "role:ROLE_USER", "role:ROLE_USER"},
        users = {"role:ROLE_SUPER_ADMIN", "role:ROLE_ADMIN", "role:ROLE_USER", "role:ROLE_ANONYMOUS", TestUsers.CREATOR}
)
public class TodoServiceJava8IT extends AbstractConfiguredIT {

    @Autowired
    private TodoService todoService;

    @Test
    public void getPrivateTodoList() throws Throwable {
        long id = todoService.createTodoList("Test list", false);
        logInAs(LoginRole.USER);
        authorization().expect(
                call(() -> todoService.getTodoList(id))
                        .toFail(ifAnyOf("role:ROLE_USER", "role:ROLE_ANONYMOUS"))
        );
    }

    @Test
    public void getPublicTodoList() throws Throwable {
        long id = todoService.createTodoList("Test list", true);
        logInAs(LoginRole.USER);
        todoService.getTodoList(id);
    }

    @Test
    public void addTodoItem() throws Throwable {
        long listId = todoService.createTodoList("Test list", false);
        logInAs(LoginRole.USER);

        authorization().expect(
                call(() -> todoService.addItemToList(listId, "Write tests"))
                        .notToFail(ifAnyOf("role:ROLE_ADMIN", "role:ROLE_SUPER_ADMIN", TestUsers.CREATOR))
        );
    }

}

Add example test for Java8 style assertions


/*
 * Copyright (c) 2006-2016 DMDirc Developers
 *
 * 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.dmdirc.parser.irc.outputqueue;

import com.dmdirc.parser.common.QueuePriority;
import org.junit.Before;
import org.junit.Test;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

import static org.junit.Assert.assertEquals;

public class PriorityOutputQueueTest {

    private BufferedReader reader;
    private BufferedOutputStream outputStream;
    private PriorityOutputQueue outputQueue;

    @Before
    public void setup() throws IOException {
        PipedInputStream pipeInput = new PipedInputStream();
        reader = new BufferedReader(new InputStreamReader(pipeInput));
        outputStream = new BufferedOutputStream(new PipedOutputStream(pipeInput));
        outputQueue = new PriorityOutputQueue();
    }

    @Test(expected = IllegalStateException.class)
    public void testThrowsIfOutputStreamNotSet() {
        outputQueue.sendLine("testing", QueuePriority.IMMEDIATE);
    }

    @Test
    public void testSendsLinesToOutput() throws IOException {
        outputQueue.setOutputStream(outputStream);
        outputQueue.sendLine("test 123");
        outputQueue.sendLine("456...");
        assertEquals("test 123", reader.readLine());
        assertEquals("456...", reader.readLine());
    }

    @Test
    public void testDiscarding() throws IOException {
        outputQueue.setOutputStream(outputStream);
        outputQueue.setDiscarding(true);
        outputQueue.sendLine("test 123");
        outputQueue.setDiscarding(false);
        outputQueue.sendLine("456...");
        assertEquals("456...", reader.readLine());
    }

}

Add some super basic OutputQueue tests.

Add some super basic OutputQueue tests.


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

package org.spine3.string;

import com.google.protobuf.Duration;
import org.junit.Test;
import org.spine3.time.Durations2;

import static org.junit.Assert.assertEquals;

/**
 * @author Alexander Yevsyukov
 */
public class DurationStringifierShould {

    private static final Stringifier<Duration> stringifier = TimeStringifiers.forDuration();

    @Test
    public void convert_back_and_forth() {
        final Duration positive = Durations2.hoursAndMinutes(5, 37);
        final Duration negative = Durations2.hoursAndMinutes(-4, -31);

        assertEquals(positive, stringifier.reverse()
                                          .convert(stringifier.convert(positive)));
        assertEquals(negative, stringifier.reverse()
                                          .convert(stringifier.convert(negative)));
    }
}

Add test for duration stringifier

Add test for duration stringifier


/*
 * Copyright (C) 2003 EBI, GRL
 *
 * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
package org.ensembl.healthcheck.testcase.generic;

import java.util.Map;

import org.ensembl.healthcheck.DatabaseRegistryEntry;

/**
 * Compare the RepeatTypes in the current database with those from the equivalent
 * database on the secondary server.
 */

public class ComparePreviousVersionRepeatTypes extends ComparePreviousVersionBase {

	/**
	 * Create a new XrefTypes testcase.
	 */
	public ComparePreviousVersionRepeatTypes() {

		addToGroup("post_genebuild");
		addToGroup("release");
		setDescription("Compare the types of repeat features in the current database with those from the equivalent database on the secondary server");

	}

	// ----------------------------------------------------------------------

	protected Map getCounts(DatabaseRegistryEntry dbre) {

		return getCountsBySQL(dbre, "SELECT DISTINCT(rc.repeat_type), COUNT(*) FROM repeat_feature rf, repeat_consensus rc WHERE rf.repeat_consensus_id=rc.repeat_consensus_id GROUP BY rc.repeat_type");

	}

	// ------------------------------------------------------------------------

	protected String entityDescription() {

		return "Repeats of repeat consensus type";

	}

	// ------------------------------------------------------------------------

	protected double threshold() {

		return 0.75;

	}

	// ------------------------------------------------------------------------

} // ComparePreviousVersionRepeatTypes

Check types of repeat features against previous release.


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

package org.voltdb.sysprocs.saverestore;

import org.voltcore.utils.DBBPool;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

/**
 * A helper class to encapsulate the serialization of snapshot output buffers
 */
public class SnapshotOutputBuffers {
    private final List<DBBPool.BBContainer> m_containers = new ArrayList<DBBPool.BBContainer>();

    public void addContainer(DBBPool.BBContainer container)
    {
        m_containers.add(container);
    }

    public List<DBBPool.BBContainer> getContainers()
    {
        return m_containers;
    }

    public byte[] toBytes()
    {
        ByteBuffer buf = ByteBuffer.allocate(4 + // buffer count
                                             (8 + 4 + 4) * m_containers.size()); // buffer info

        buf.putInt(m_containers.size());
        for (DBBPool.BBContainer container : m_containers) {
            buf.putLong(container.address);
            buf.putInt(container.b.position());
            buf.putInt(container.b.remaining());
        }

        return buf.array();
    }
}

ENG-4568: Add a helper class to encapsulate serialization of multiple snapshot
buffers to EE.


package com.github.aureliano.achmed.os.pkg;

import com.github.aureliano.achmed.command.CommandResponse;
import com.github.aureliano.achmed.resources.properties.PackageProperties;

public class AptPackageManager implements IPackageManager {

	private PackageProperties properties;

	public AptPackageManager() {
		super();
	}

	public CommandResponse install() {
		throw new UnsupportedOperationException("Method not implemented yet.");
	}

	public CommandResponse uninstall() {
		throw new UnsupportedOperationException("Method not implemented yet.");
	}

	public String latest() {
		throw new UnsupportedOperationException("Method not implemented yet.");
	}

	public void setPackageProperties(PackageProperties properties) {
		this.properties = properties;
	}

	public PackageProperties getPackageProperties() {
		return this.properties;
	}
}

Create template of apt package manager.

Create template of apt package manager.


package com.jraska.vsb.or1.schedule;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Random;

import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;

public class SelfAdaptiveStrategyTest {
  //region Test Methods

  @Test
  public void testFillListAtStart() throws Exception {
    IObjectiveFunction objectiveFunction = mock(IObjectiveFunction.class);

    int size = 111;
    SelfAdaptiveSearchStrategy strategy = new SelfAdaptiveSearchStrategy(new Random(), objectiveFunction, size);

    strategy.getNext(new int[2]);

    assertThat(strategy.getNeighboursStrategies().size(), equalTo(size - 1)); //-1 because one is used
  }

  @Test
  public void testFillsWiningList() throws Exception {
    SelfAdaptiveSearchStrategy strategy = new SelfAdaptiveSearchStrategy(new GettingBetterFunction());

    for (int i = 0, size = strategy.getSize(); i < size; i++) {
      strategy.getNext(new int[2]);
    }

    assertThat(strategy.getWinningNeighbourStrategies().size(), equalTo(strategy.getSize())); //all should succeed
  }

  @Test
  public void testUsesWinningList() throws Exception {
    SelfAdaptiveSearchStrategy strategy = new SelfAdaptiveSearchStrategy(new GettingBetterFunction());

    for (int i = 0, size = strategy.getSize(); i < size; i++) {
      strategy.getNext(new int[2]);
    }

    ArrayList<ILocalSearchStrategy> winningStrategies = new ArrayList<ILocalSearchStrategy>(strategy.getWinningNeighbourStrategies());

    strategy.fillNeighboursList();

    assertThat(strategy.getWinningNeighbourStrategies().size(), equalTo(0));

    ArrayList<ILocalSearchStrategy> refilledStrategies = new ArrayList<ILocalSearchStrategy>(strategy.getNeighboursStrategies());
    for (int i = 0, size = strategy.getSize() / 2; i < size; i++) { // / 2 because only first part should fit
      assertThat(refilledStrategies.get(i), equalTo(winningStrategies.get(i)));
    }
  }

  //endregion

  //region Nested classes

  static class GettingBetterFunction implements IObjectiveFunction {
    private int _counter = Integer.MAX_VALUE;

    @Override
    public int evaluate(int[] solution) {
      return --_counter;
    }
  }

  //endregion
}

Add Self adaptive strategy test

Add Self adaptive strategy test