package leetcode.maximum_product_subarray;

public class Solution {
    public int maxProduct(int[] A) {
    	int max = A[0];
    	int start = 0, end = 0;
    	for(int i = 0; i < A.length; i++){
    		if(A[i] > max) max = A[i];
    		if(A[i] == 0){
    			end = i - 1;
    			if(start <= end){
    				int product_forward = 1;
    				int product_backward = 1;
    				for(int j = 0; j <= end - start; j++){
    					product_forward *= A[start + j];
    					product_backward *= A[end - j];
    					if(product_forward > max){
    						max = product_forward;
    					}
    					if(product_backward > max){
    						max = product_backward;
    					}
    				}
    			}
    			start = i + 1;
    		}
    	}
    	if(start < A.length){
    		end = A.length - 1;
			if(start <= end){
				int product_forward = 1;
				int product_backward = 1;
				for(int j = 0; j <= end - start; j++){
					product_forward *= A[start + j];
					product_backward *= A[end - j];
					if(product_forward > max){
						max = product_forward;
					}
					if(product_backward > max){
						max = product_backward;
					}
				}
			}
    	}
    	return max;
    }

    public static void main(String[] args){
    	int ans = new Solution().maxProduct(new int[]{-2, 0, -1});
    	System.err.println("ans = " + ans);
    }
}

Add java solution for 152. Maximum Product Subarray

152. Maximum Product Subarray: https://leetcode.com/problems/maximum-product-subarray/


package devopsdistilled.operp.client.abstracts;

import javax.swing.JComponent;
import javax.swing.JDialog;

import devopsdistilled.operp.server.data.entity.Entiti;

public abstract class Copy_2_of_AbstractEntityDetailsPane<E extends Entiti<?>> {

	protected final JDialog dialog;

	public Copy_2_of_AbstractEntityDetailsPane() {
		dialog = new JDialog();
		dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		dialog.setTitle(getTitle());
		dialog.setSize(400, 300);
	}

	public abstract JComponent getPane();

	public abstract void show(E entity);

	public abstract String getTitle();

	public JDialog getDialog() {
		return dialog;
	}
}

Make copy of old AbstractDetailsPane

Make copy of old AbstractDetailsPane

OPEN - task 64: Create CRUD functionality for Brand entity
http://github.com/DevOpsDistilled/OpERP/issues/issue/64


// Handle error gracefully and continue.
class ExcDemo3 {
  public static void main(String args[]) {
    int numer[] = { 4, 8, 16, 32, 64, 128 };
    int denom[] = { 2, 0, 4, 4, 0, 8 };

    for(int i=0; i<numer.length; i++) {
      try {
        System.out.println(numer[i] + " / " + denom[i] + " is " + numer[i]/denom[i]);
      }
      catch (ArithmeticException exc) {
        // catch the exception
        System.out.println("Can't divide by Zero!");
      }
    }
  }
}

Handle error gracefully and continue

Handle error gracefully and continue

http://ideone.com/JOIAfB


package io.sigpipe.sing.util;

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

import io.sigpipe.sing.dataset.Quantizer;
import io.sigpipe.sing.dataset.feature.Feature;

public class TestConfiguration {

    public static final String[] FEATURE_NAMES = {
        "temperature_surface",
        "temperature_tropopause",
        "relative_humidity_zerodegc_isotherm", // 0-100 range
        "snow_depth_surface",
        "snow_cover_surface", // 0-100 range
        "pressure_tropopause",
        "precipitable_water_entire_atmosphere",
        "visibility_surface",
        "upward_short_wave_rad_flux_surface",
        "surface_wind_gust_surface",
        "total_cloud_cover_entire_atmosphere", // 0-100 range
        "upward_long_wave_rad_flux_surface",
        "vegitation_type_as_in_sib_surface",
        "albedo_surface",
        "pressure_surface",
        "vegetation_surface",
        "downward_long_wave_rad_flux_surface",
        "planetary_boundary_layer_height_surface",
        "lightning_surface", // boolean
        "ice_cover_ice1_no_ice0_surface", // boolean
        "categorical_snow_yes1_no0_surface", // boolean
    };

    /* Temporarily disabled features:
     * ------------------------------
     *  "convective_inhibition_surface",
     *  "transpiration_stress-onset_soil_moisture_surface",
     *  "soil_porosity_surface",
     *  "total_precipitation_surface_3_hour_accumulation", // not in all files
     */

    public static final Map<String, Quantizer> quantizers = new HashMap<>();

    static {
        quantizers.put("temp", new Quantizer(
                    new Feature(0.0),
                    new Feature(221.1)));
    }
}

Create test configuration for experiments


package me.haosdent.cgroup.subsystem;

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

public class TestDevices {

  @Before
  public void setUp() {}

  @After
  public void tearDown() {}

  @Test
  public void testSetAllow() {}

  @Test
  public void testSetDeny() {}

  @Test
  public void testGetList() {}
}

Add devices subsystem test class.

Add devices subsystem test class.


/*******************************************************************************
 * Copyright 2016 Friedrich-Schiller-Universität Jena
 *
 * 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.
 *
 * Contributors:
 *     Stephan Druskat - initial API and implementation
 *******************************************************************************/
package org.corpus_tools.atomic.projects;

import static org.junit.Assert.*;

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

/**
 * Unit test for {@link SaltProjectCompiler}.
 *
 * <p>@author Stephan Druskat <stephan.druskat@uni-jena.de>
 *
 */
public class SaltProjectCompilerTest {

	private SaltProjectCompiler fixture = null;

	/**
	 * Set up the fixture.
	 *
	 * @throws java.lang.Exception
	 */
	@Before
	public void setUp() throws Exception {
//		setFixture(new SaltProjectCompiler(projectData));
	}

	/**
	 * Test method for {@link org.corpus_tools.atomic.projects.SaltProjectCompiler#SaltProjectCompiler(org.corpus_tools.atomic.projects.ProjectData)}.
	 */
	@Test
	public void testSaltProjectCompiler() {
		fail("Not yet implemented"); // TODO
	}

	/**
	 * Test method for {@link org.corpus_tools.atomic.projects.SaltProjectCompiler#run()}.
	 */
	@Test
	public void testRun() {
		fail("Not yet implemented"); // TODO
	}

	/**
	 * Test method for {@link org.corpus_tools.atomic.projects.SaltProjectCompiler#setProjectData(org.corpus_tools.atomic.projects.ProjectData)}.
	 */
	@Test
	public void testSetProjectData() {
		fail("Not yet implemented"); // TODO
	}

	/**
	 * @return the fixture
	 */
	private SaltProjectCompiler getFixture() {
		return fixture;
	}

	/**
	 * @param fixture the fixture to set
	 */
	private void setFixture(SaltProjectCompiler fixture) {
		this.fixture = fixture;
	}

}

Add test class for SaltProjectCompiler

Add test class for SaltProjectCompiler


package co.phoenixlab.common.lang;

import java.util.ListIterator;

/**
 * Provides a reversed view of a ListIterator, starting from the last element.
 * @param <E>
 */
public class ReverseListIterator<E> implements ListIterator<E> {

    private final ListIterator<E> parent;

    public ReverseListIterator(ListIterator<E> parent) {
        this.parent = parent;
        //  Wind the iterator to the end
        while (parent.hasNext()) {
            parent.next();
        }
    }

    @Override
    public boolean hasNext() {
        return parent.hasPrevious();
    }

    @Override
    public E next() {
        return parent.previous();
    }

    @Override
    public boolean hasPrevious() {
        return parent.hasNext();
    }

    @Override
    public E previous() {
        return parent.next();
    }

    @Override
    public int nextIndex() {
        return parent.previousIndex();
    }

    @Override
    public int previousIndex() {
        return parent.nextIndex();
    }

    @Override
    public void remove() {
        parent.remove();
    }

    @Override
    public void set(E e) {
        parent.set(e);
    }

    @Override
    public void add(E e) {
        parent.add(e);
    }
}

Add a reverse view ListIterator

Add a reverse view ListIterator


package com.sentibrand;

import org.junit.Test;
import org.springframework.http.HttpStatus;
import org.springframework.web.client.RestTemplate;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;

public class SentimentProcessingStarterTest {

    @Test
    public void shouldStartWebApp() throws Exception {
        SentimentProcessingStarter.main();

        HttpStatus statusCode = new RestTemplate()
                .getForEntity("http://localhost:8080/health", String.class)
                .getStatusCode();

        assertThat(statusCode.value(), is(200));
    }
}

Test to ensure webapp starts up.

Test to ensure webapp starts up.


/*
 * Copyright (C) 2014-2015 the original authors 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 io.sarl.lang.tests.bugs;

import static org.junit.Assert.assertEquals;
import io.sarl.lang.SARLInjectorProvider;
import io.sarl.lang.sarl.SarlScript;
import io.sarl.tests.api.AbstractSarlTest;

import org.eclipse.xtext.junit4.InjectWith;
import org.eclipse.xtext.junit4.XtextRunner;
import org.eclipse.xtext.junit4.util.ParseHelper;
import org.eclipse.xtext.junit4.validation.ValidationTestHelper;
import org.eclipse.xtext.util.IAcceptor;
import org.eclipse.xtext.xbase.XbasePackage;
import org.eclipse.xtext.xbase.compiler.CompilationTestHelper;
import org.eclipse.xtext.xbase.compiler.CompilationTestHelper.Result;
import org.eclipse.xtext.xbase.validation.IssueCodes;
import org.junit.Test;
import org.junit.runner.RunWith;

import com.google.inject.Inject;

/**
 * @author $Author: sgalland$
 * @version $FullVersion$
 * @mavengroupid $GroupId$
 * @mavenartifactid $ArtifactId$
 */
@SuppressWarnings("all")
public class Bug295 extends AbstractSarlTest {

	private String snippet = multilineString(
			"capacity C1 {",
			"    def fct(a : Object=null, b : int=0, c : Object*)",
			"}",
			"agent A1 {",
			"    uses C1",
			"    def mytest {",
			"        fct(new Object)",
			"    }",
			"}",
			"");

	@Test
	public void bug295() throws Exception {
		SarlScript mas = file(snippet);
		validate(mas).assertError(
				XbasePackage.eINSTANCE.getXFeatureCall(),
				IssueCodes.AMBIGUOUS_FEATURE_CALL,
				117, 3,
				"both match");
	}

}

[lang] Add unit test for ambiguous function calls.

see #295

Signed-off-by: Stéphane Galland <23860b554af9116d4237121086bd6767cdd4ff4b@arakhne.org>


package com.jetbrains.python;

import com.intellij.openapi.util.io.FileUtil;
import com.intellij.testFramework.UsefulTestCase;
import com.jetbrains.python.console.PyConsoleIndentUtil;

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

/**
 * @author traff
 */
public class PyConsoleIndentTest extends UsefulTestCase {
  public void testIndent1() {
    doTest();
  }

  public void testIndent2() {
    doTest();
  }

  public void testIndent3() {
    doTest();
  }

  public void testIndent4() {
    doTest();
  }

  public void testIndent5() {
    doTest();
  }

  public void testIndent6() {
    doTest();
  }

  public void testIndent7() {
    doTest(2);
  }

  private void doTest() {
    doTest(0);
  }

  private void doTest(int indent) {
    String name = getTestName(true);
    try {
      String fileText = FileUtil.loadFile(new File(getTestDataPath() + name + ".py"));
      String expected = FileUtil.loadFile(new File(getTestDataPath() + name + ".after.py"));
      assertEquals(expected, PyConsoleIndentUtil.normalize(fileText, indent));
    }
    catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public static String getTestDataPath() {
    return PythonTestUtil.getTestDataPath() + "/console/";
  }
}

package com.jetbrains.python;

import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.testFramework.UsefulTestCase;
import com.jetbrains.python.console.PyConsoleIndentUtil;

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

/**
 * @author traff
 */
public class PyConsoleIndentTest extends UsefulTestCase {
  public void testIndent1() {
    doTest();
  }

  public void testIndent2() {
    doTest();
  }

  public void testIndent3() {
    doTest();
  }

  public void testIndent4() {
    doTest();
  }

  public void testIndent5() {
    doTest();
  }

  public void testIndent6() {
    doTest();
  }

  public void testIndent7() {
    doTest(2);
  }

  private void doTest() {
    doTest(0);
  }

  private void doTest(int indent) {
    String name = getTestName(true);
    try {
      String fileText = FileUtil.loadFile(new File(getTestDataPath() + name + ".py"));
      String expected = FileUtil.loadFile(new File(getTestDataPath() + name + ".after.py"));
      assertEquals(StringUtil.convertLineSeparators(expected), StringUtil.convertLineSeparators(
        PyConsoleIndentUtil.normalize(fileText, indent)));
    }
    catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public static String getTestDataPath() {
    return PythonTestUtil.getTestDataPath() + "/console/";
  }
}

Convert line separators in test.

Convert line separators in test.


/*
 * This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
 *
 * Copyright 2008-2011 Geosparc nv, http://www.geosparc.com/, Belgium.
 *
 * The program is available in open source according to the GNU Affero
 * General Public License. All contributions in this program are covered
 * by the Geomajas Contributors License Agreement. For full licensing
 * details, see LICENSE.txt in the project root.
 */

package org.geomajas.puregwt.client.map.controller;

import org.geomajas.puregwt.client.map.ZoomOption;
import org.geomajas.puregwt.client.spatial.Bbox;

/**
 * Map controller that lets the user drag a rectangle on the map, after which it zooms to that rectangle.
 *
 * @author Pieter De Graef
 */
public class ZoomToRectangleController extends AbstractRectangleController {

	/**
	 * Effectively zoom to the bounds that the user drew on the map.
	 *
	 * @param worldBounds
	 *            The result of the user's dragging on the map, expressed in world space.
	 */
	protected void execute(Bbox worldBounds) {
		mapPresenter.getMapModel().getViewPort().applyBounds(worldBounds, ZoomOption.LEVEL_CHANGE);
	}
}

Create zoom to rectangle controller

PURE-8: Create zoom to rectangle controller


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

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

/**
 *
 * @author prog694
 */
public class AutonVomitFast extends CommandGroup {

    public AutonVomitFast() {
       addParallel(new ConveyReverseManual(.5));
       addSequential(new AcquirerReverse(.5));
       addParallel(new ConveyReverseManual(3));
       addSequential(new AcquirerReverse(3));
    }

}

Add new auton command for fast vomit

Add new auton command for fast vomit


package org.filteredpush.qc.georeference;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.MultiPolygon;
import com.vividsolutions.jts.geom.Point;
import org.filteredpush.qc.georeference.util.GEOUtil;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.filter.text.cql2.CQLException;
import org.geotools.filter.text.ecql.ECQL;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.filter.Filter;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by lowery on 6/12/17.
 */
public class GEOUtilTester {
    private URL countryShapeFile = GEOUtil.class.getResource("/org.filteredpush.kuration.services/ne_10m_admin_0_countries.shp");

    private final GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
    private Map<String, MultiPolygon> polys = new HashMap<>();

    public GEOUtilTester() throws IOException {
        FileDataStore store = null;
        try {
            store = FileDataStoreFinder.getDataStore(countryShapeFile);
            SimpleFeatureSource featureSource = store.getFeatureSource();

            SimpleFeatureIterator iter = featureSource.getFeatures().features();

            while (iter.hasNext()) {
                SimpleFeature feature = iter.next();
                String name = (String) feature.getAttribute("NAME");
                MultiPolygon poly = (MultiPolygon) feature.getAttribute("the_geom");

                polys.put(name, poly);
            }
        } catch (IOException e) {
            throw new RuntimeException("Error loading shapefile: " + countryShapeFile.getPath(), e);
        } finally {
            if (store!=null) { store.dispose(); }
        }

    }

    public boolean pointInCountry(String country, double latitude, double longitude) {
        MultiPolygon polygon = polys.get(country);
        return polygon.contains(geometryFactory.createPoint(new Coordinate(longitude, latitude)));
    }

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

        GEOUtilTester tester = new GEOUtilTester();

        // Barrow, Alaska
        double originalLng = -156.766389d;
        double originalLat = 71.295556d;

        long startTime = System.currentTimeMillis();

        //boolean result = GEOUtil.isPointInCountry("United States", originalLat, originalLng);
        boolean result = tester.pointInCountry("United States", originalLat, originalLng);

        System.out.println("result: " + result + ", time: " + (System.currentTimeMillis() - startTime));
    }
}

Test of using hashmap of country to polygon for geospatial queries

Trying to speed up queries in GEOUtil for the Georeference Validation actor


/**
 * Copyright 2011 Matthias Nuessler <m.nuessler@web.de>
 *
 * 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.nuessler.junit.util.rule;

import static org.hamcrest.core.IsEqual.equalTo;

import org.hamcrest.Matcher;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
import org.nuessler.junit.util.rule.FailureLogger.Callback;

public class FailureLoggerTest {

    @Rule
    public ErrorCollector collector = new ErrorCollector();

    @Rule
    public FailureLogger logger = new FailureLogger(new Callback<String>() {
        @Override
        public void call(String logMsg) {
            System.out.println(logMsg);
        }
    });

    @Test
    public void test() {
        collector.checkThat(1, equalTo(2));
        collector.addError(new Exception());
    }

    @Test
    public void test2() {
        assertThat(1, equalTo(2));
    }

    private <T> void assertThat(T value, Matcher<T> matcher) {
        collector.checkThat(value, matcher);
    }

}

Add simple test for FailureLogger.

Add simple test for FailureLogger.


package fi.evident.apina.model;

import fi.evident.apina.model.type.ApiType;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;

import java.util.Collection;

import static org.hamcrest.Matchers.containsInAnyOrder;

public final class ModelMatchers {

    private ModelMatchers() {
    }

    public static Matcher<PropertyDefinition> property(String name, ApiType type) {
        return new TypeSafeMatcher<PropertyDefinition>() {
            @Override
            protected boolean matchesSafely(PropertyDefinition item) {
                return name.equals(item.getName()) && type.equals(item.getType());
            }

            @Override
            public void describeTo(Description description) {
                description.appendText("PropertyDefinition{name=")
                        .appendValue(name)
                        .appendText(", type=")
                        .appendValue(type)
                        .appendText("}");
            }
        };
    }

    @SafeVarargs
    public static Matcher<? super Collection<PropertyDefinition>> hasProperties(Matcher<PropertyDefinition>... matchers) {
        return containsInAnyOrder(matchers);
    }
}

Add Hamcrest matchers for model

Add Hamcrest matchers for model


package io.undertow.util;

import io.undertow.UndertowLogger;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Executor;

/**
 * Executor that will continue to re-run tasks in a loop that are submitted from its own thread.
 *
 * @author Stuart Douglas
 */
public class ContinuingExecutor implements Executor {

    private final Executor executor;

    private static final ThreadLocal<LinkedList<Runnable>> THREAD_QUEUE = new ThreadLocal<LinkedList<Runnable>>();

    public ContinuingExecutor(Executor executor) {
        this.executor = executor;
    }

    @Override
    public void execute(final Runnable command) {
        List<Runnable> queue = THREAD_QUEUE.get();
        if (queue != null) {
            queue.add(command);
        } else {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    LinkedList<Runnable> queue = THREAD_QUEUE.get();
                    if (queue == null) {
                        THREAD_QUEUE.set(queue = new LinkedList<Runnable>());
                    }
                    try {
                        command.run();
                    } catch (Throwable t) {
                        UndertowLogger.REQUEST_LOGGER.debugf(t, "Task %s failed", command);
                    }
                    Runnable runnable = queue.poll();
                    while (runnable != null) {
                        try {
                            command.run();
                        } catch (Throwable t) {
                            UndertowLogger.REQUEST_LOGGER.debugf(t, "Task %s failed", command);
                        }
                        runnable = queue.poll();
                    }

                }
            });
        }
    }
}

Add executor that will continue to run tasks in a loop


package jamex.link;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith( Suite.class )
@Suite.SuiteClasses
  (
    {
      MessageTransformerTestCase.class,
      MessageVerifierTestCase.class
    }
  )
public class LinkSuite
{
  /** this ensures that there is one broker for the full suite */
  @BeforeClass
  public static void startupBroker()
    throws Exception
  {
    TestHelper.startupBroker();
  }

  @AfterClass
  public static void shutdownBroker()
    throws Exception
  {
    TestHelper.shutdownBroker();
  }
}

Add suite to ensure tests are run with single broker instance


package xml.commands;

import utility.Command;
import xml.Element;

public class ChangeTagCommand implements Command {
	private Element element;
	private String tag;
	private String oldTag;

	public ChangeTagCommand(Element element, String tag) {
		this.element = element;
		this.tag = tag;
		oldTag = new String(element.getTag());
	}

	@Override
	public void perform() {
		element.setTag(tag);
	}

	@Override
	public void undo() {
		element.setTag(oldTag);
	}

}

Add a Command to change a tag

Add a Command to change a tag


package openmods.utils;

public abstract class LazyValue<T> {

	private boolean initialized;

	private T value;

	protected abstract T initialize();

	public T get() {
		if (!initialized) {
			value = initialize();
			initialized = true;
		}

		return value;
	}

}

Add lazily initialized value (single threaded)


package ch.eiafr.cojac.unit.interval;

import ch.eiafr.cojac.interval.DoubleInterval;
import org.junit.Test;

import static org.junit.Assert.assertTrue;

public class DoubleIntervalTest
{

    @Test
    public void testCompareTo() throws Exception
    {
        double v1 = DoubleUtils.rDouble();
        double v2 = DoubleUtils.getBiggerDouble(v1);
        DoubleInterval a = new DoubleInterval(v1, v2);
        v1 = DoubleUtils.getBiggerDouble(v2);
        v2 = DoubleUtils.getBiggerDouble(v1);
        DoubleInterval b = new DoubleInterval(v1, v2);

        // Simple compare
        assertTrue(String.format("a > b  : %s > %s", a, b), a.compareTo(b) > 0);
        assertTrue(String.format("b < a  : %s < %s", b, a), b.compareTo(a) < 0);
        assertTrue(String.format("b == b : %s == %s", b, b), b.compareTo(b) == 0);
    }

    @Test
    public void testCompareTo1() throws Exception
    {

    }

    @Test
    public void testAdd() throws Exception
    {

    }

    @Test
    public void testSub() throws Exception
    {

    }

    @Test
    public void testMul() throws Exception
    {

    }

    @Test
    public void testDiv() throws Exception
    {

    }

    @Test
    public void testPow2() throws Exception
    {

    }

    @Test
    public void testPow() throws Exception
    {

    }

    @Test
    public void testPow1() throws Exception
    {

    }

    @Test
    public void testExp() throws Exception
    {

    }

    @Test
    public void testLog() throws Exception
    {

    }

    @Test
    public void testLog2() throws Exception
    {

    }

    @Test
    public void testLog10() throws Exception
    {

    }
}

Add skeleton test for the DoubleInterval class


package google.finder;

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

import google.model.Result;

class ConcurrentCache {

	// Possibly shared between threads.
	private final List<Result> cache = Collections.synchronizedList(new ArrayList<>());

	void add(Result result) {
		cache.add(result);
	}

	List<Result> getWholeCache() {
		return new ArrayList<>(cache);
	}

}

Add a thread safe cache class.

Add a thread safe cache class.


package org.dstadler.github;

import com.google.common.collect.Multimap;
import com.google.common.collect.TreeMultimap;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.dstadler.github.search.BaseSearch;
import org.dstadler.github.util.JSONWriter;
import org.dstadler.github.util.Stats;
import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GitHub;

import java.io.File;
import java.io.IOException;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ListStars {
    public static void main(String[] args) throws IOException {
        File[] files = Stats.getFiles();

        Set<String> repositories = readLines(files);
        System.out.println("Found " + repositories.size() + " repositories using Apache POI");

        Multimap<Integer, String> starsAndRepositories = createSortedMultimap();

        GitHub github = BaseSearch.connect();

        int count = 0;
        for (String repository : repositories) {
            try {
                GHRepository repo = github.getRepository(repository);
                starsAndRepositories.put(repo.getStargazersCount(), repository);

                count++;
                if (count % 10 == 0) {
                    System.out.println(count + ": " + repository + ": " + repo.getStargazersCount() + " - " +
                            StringUtils.abbreviate(starsAndRepositories.toString(), 1024));
                }
            } catch (IOException e) {
                starsAndRepositories.put(-1, repository);
                System.out.println(repository + ": " + e);
            }
        }

        System.out.println("Stars: " + starsAndRepositories + ": " +
                StringUtils.abbreviate(starsAndRepositories.toString(), 1024));
    }

    private static Multimap<Integer, String> createSortedMultimap() {
        Comparator<Integer> intSort = Comparator.naturalOrder();
        return TreeMultimap.create(intSort.reversed(), Comparator.naturalOrder());
    }

    private static Set<String> readLines(File[] files) throws IOException {
        Set<String> repositories = new HashSet<>();
        for(File file : files) {
            List<String> lines = FileUtils.readLines(file, "UTF-8");

            for (String line : lines) {
                JSONWriter.Holder holder = JSONWriter.mapper.readValue(line, JSONWriter.Holder.class);

                repositories.addAll(holder.getRepositoryVersions().values());
            }
        }

        return repositories;
    }
}

Add script which uses a simple loop of fetching stars of repositories

This stops after a few thousand results as Github starts to throttle
API requests, so should probably done with some search sorted by stars
instead...


package com.orm.andorm.test.implementation;

import android.test.AndroidTestCase;

import com.orm.androrm.Filter;
import com.orm.androrm.NoSuchFieldException;
import com.orm.androrm.impl.Brand;

public class FilterTest extends AndroidTestCase {

	public void testNoSuchFieldException() {
		Filter filter = new Filter();
		filter.is("no_such_field", "value");

		try {
			Brand.objects(getContext()).filter(filter);

			fail();
		} catch (NoSuchFieldException e) {

		}
	}

}

TEST - added test for NoSuchFieldException


package ch.hesso.master;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import ch.hesso.master.utils.StackoverflowPost;
import ch.hesso.master.utils.StackoverflowXMLInputFormat;

public class StackTest extends Configured implements Tool {

	private int numReducers;
	private Path inputPath;
	private Path outputPath;

	/**
	 * Stripes Constructor.
	 *
	 * @param args
	 */
	public StackTest(String[] args) {
		if (args.length != 3) {
			System.out.println("Usage: Ngram <num_reducers> <input_path> <output_path>");
			System.exit(0);
		}

		numReducers = Integer.parseInt(args[0]);
		inputPath = new Path(args[1]);
		outputPath = new Path(args[2]);
	}

	public static class StackTestMapper extends Mapper<LongWritable, StackoverflowPost, LongWritable, StackoverflowPost> {

	}

	public static class StackTestReducer extends Reducer<LongWritable, StackoverflowPost, LongWritable, StackoverflowPost> {

	}

	public int run(String[] args) throws Exception {

		Configuration conf = getConf();
		Job job = new Job(conf, "StackTest");

		job.setMapperClass(StackTestMapper.class);
		job.setReducerClass(StackTestReducer.class);

		job.setMapOutputKeyClass(LongWritable.class);
		job.setMapOutputValueClass(StackoverflowPost.class);

		job.setOutputKeyClass(LongWritable.class);
		job.setOutputValueClass(StackoverflowPost.class);

		StackoverflowXMLInputFormat.addInputPath(job, inputPath);
		job.setInputFormatClass(StackoverflowXMLInputFormat.class);

		FileOutputFormat.setOutputPath(job, outputPath);

		boolean useTextOutputFormat = !false;
		if (useTextOutputFormat) {
			job.setOutputFormatClass(TextOutputFormat.class);
		}
		else {
			job.setOutputFormatClass(SequenceFileOutputFormat.class);
		}

		job.setNumReduceTasks(numReducers);

		job.setJarByClass(StackTest.class);

		return job.waitForCompletion(true) ? 0 : 1;
	}

	public static void main(String[] args) throws Exception {
		int res = ToolRunner.run(new Configuration(), new StackTest(args), args);
		System.exit(res);
	}
}

Add a example mapreduce job using stackoverflow class


package org.beanmaker.util;

import org.dbbeans.sql.DBTransaction;

public interface LocalFileManager {

    DbBeanFile get(final long id);

    DbBeanFile getOrCreate(final long id);

    boolean isIdOK(final long id);

    boolean isIdOK(final long id, final DBTransaction transaction);

    String getFilename(final long id);

    String getDefaultUploadDir();

    DbBeanFileStoredFilenameCalculator getDefaultFileStoredFileNameCalculator();

}

Add interface for per project management of local files


package leetcode;

/**
 * https://leetcode.com/problems/number-of-digit-one/
 */
public class Problem233 {
    public int countDigitOne(int n) {
        int result = 0;
        for (int i = 1; i <= n; i++) {
        }
        return result;
    }

    public static void main(String[] args) {
        Problem233 prob = new Problem233();
        System.out.println(prob.countDigitOne(13));
        System.out.println(prob.countDigitOne(824883294));
    }
}

Create a skeleton for problem 233

Create a skeleton for problem 233


package leetcode;

/**
 * https://leetcode.com/problems/h-index/
 */
public class Problem274 {
    public int hIndex(int[] citations) {
        // TODO
        return 0;
    }

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

Add a skeleton for problem 274

Add a skeleton for problem 274


package replicant;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * A thin abstraction for scheduling callbacks that works in JVM and GWT environments.
 */
final class Scheduler
{
  private static final SchedulerSupport c_support = new SchedulerSupport();

  public static void schedule( @Nonnull final SafeFunction<Boolean> command )
  {
    c_support.schedule( command );
  }

  /**
   * JVM Compatible variant which will have fields and methods stripped out during GWT compile and thus fallback to GWT variant.
   */
  private static final class SchedulerSupport
    extends AbstractSchedulerSupport
  {
    @GwtIncompatible
    private final ScheduledExecutorService _executorService = Executors.newScheduledThreadPool( 1 );
    @GwtIncompatible
    @Nullable
    private ScheduledFuture<?> _future;

    @GwtIncompatible
    @Override
    void schedule( @Nonnull final SafeFunction<Boolean> command )
    {
      final Runnable action = () -> {
        if ( !command.call() && null != _future )
        {
          _future.cancel( false );
          _future = null;
        }
      };
      _future = _executorService.scheduleAtFixedRate( action, 0, 1, TimeUnit.MILLISECONDS );
    }
  }

  private static abstract class AbstractSchedulerSupport
  {
    void schedule( @Nonnull final SafeFunction<Boolean> command )
    {
      com.google.gwt.core.client.Scheduler.get().scheduleIncremental( command::call );
    }
  }
}

Add in simple abstraction for scheduling


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

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

import org.jsmpp.PDUStringException;
import org.testng.annotations.Test;

/**
 * @author uudashr
 *
 */
public class OctetStringValidationTest {
    private static final String FULL_LENGTH_TEXT = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor";
    private static final int MAX_SHORT_MESSAGE_LENGTH = 254;

    @Test
    public void zeroLength() throws Exception {
        String shortMessage = "";
        assertEquals(shortMessage.length(), 0);
        StringValidator.validateString(shortMessage.getBytes(), StringParameter.SHORT_MESSAGE);
    }

    @Test
    public void nonZeroBelow255Length() throws Exception {
        String shortMessage = "This is a simple message";
        assertTrue(shortMessage.length() > 0);
        assertTrue(shortMessage.length() <= MAX_SHORT_MESSAGE_LENGTH);
        StringValidator.validateString(shortMessage.getBytes(), StringParameter.SHORT_MESSAGE);
    }

    @Test
    public void fullLegth() throws Exception {
        assertEquals(FULL_LENGTH_TEXT.length(), MAX_SHORT_MESSAGE_LENGTH);
        StringValidator.validateString(FULL_LENGTH_TEXT.getBytes(), StringParameter.SHORT_MESSAGE);
    }

    @Test(expectedExceptions = PDUStringException.class)
    public void overLengthText() throws Exception {
        String shortMessage = FULL_LENGTH_TEXT + " ";
        assertTrue(shortMessage.length() > MAX_SHORT_MESSAGE_LENGTH);
        StringValidator.validateString(shortMessage.getBytes(), StringParameter.SHORT_MESSAGE);
    }
}

Add new test case for OctetString validation


package eu.nerro.wolappla.util;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

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

import static eu.nerro.wolappla.util.LogUtils.LOGV;
import static eu.nerro.wolappla.util.LogUtils.makeLogTag;

/**
 * Helper for building selection clauses for {@link SQLiteDatabase}. Each
 * appended clause is combined using AND.
 *

 * Note that this class is not thread safe.
 */
public class SelectionBuilder {
  private static final String TAG = makeLogTag(SelectionBuilder.class);

  private String mTable = null;
  private StringBuilder mSelection = new StringBuilder();
  private List<String> mSelectionArgs = new ArrayList<String>();

  public SelectionBuilder table(String table) {
    mTable = table;
    return this;
  }

  /**
   * Append the given selection clause to the internal state. Each clause
   * is surrounded with parenthesis and combined using AND.
   */
  public SelectionBuilder where(String selection, String... selectionArgs) {
    if (TextUtils.isEmpty(selection)) {
      if (selectionArgs != null && selectionArgs.length > 0) {
        throw new IllegalArgumentException("Valid selection required when including arguments");
      }
      return this;
    }

    if (mSelection.length() > 0) {
      mSelection.append(" AND ");
    }

    mSelection.append("(").append(selection).append(")");
    if (selectionArgs != null) {
      Collections.addAll(mSelectionArgs, selectionArgs);
    }

    return this;
  }

  /**
   * Execute query using current internal state as WHERE clause.
   */
  public Cursor query(SQLiteDatabase database, String[] columns, String orderBy) {
    return query(database, columns, null, null, orderBy, null);
  }

  /**
   * Execute query using current internal state as WHERE clause.
   */
  public Cursor query(SQLiteDatabase database, String[] columns, String groupBy, String having, String orderBy, String limit) {
    assertTable();
    LOGV(TAG, "query(columns=" + Arrays.toString(columns) + ") " + this);

    return database.query(mTable, columns, getSelection(), getSelectionArgs(), groupBy, having, orderBy, limit);
  }

  private void assertTable() {
    if (mTable == null) {
      throw new IllegalStateException("Table not specified");
    }
  }

  /**
   * Return selection string for current internal state.
   */
  public String getSelection() {
    return mSelection.toString();
  }

  /**
   * Return selection arguments for current internal state.
   */
  public String[] getSelectionArgs() {
    return mSelectionArgs.toArray(new String[mSelectionArgs.size()]);
  }

  @Override
  public String toString() {
    return "SelectionBuilder=[table=" + mTable + ", selection=" + getSelection()
        + ", " + Arrays.toString(getSelectionArgs()) + "]";
  }
}

Add helper for building selection clauses for sqlite database


package net.restlesscoder.sandbox;

/** Can you narrow the types of exceptions thrown in a subclass? Yes. */
public class ThrowException {

	public static class FooBase {
		public void go() throws Exception {}
	}

	public static class MyException extends Exception { }

	public static class FooExtension extends FooBase {
		@Override
		public void go() throws MyException { }
	}

	public static class FooSubExtension extends FooExtension {
		@Override
		public void go() { }
	}

	public static void main(final String... args) {
		FooExtension fooExt = new FooSubExtension();
		// Unhandled exception type ThrowException.MyException
		//fooExt.go();
	}
}

Add a quick test of exception type narrowing


/*
 * Project Info:  http://jcae.sourceforge.net
 *
 * This program 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 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 Lesser General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 *
 * (C) Copyright 2008, by EADS France
 */

package org.jcae.opencascade.test;

import org.jcae.opencascade.jni.STEPControl_Reader;
import org.jcae.opencascade.jni.TopAbs_ShapeEnum;
import org.jcae.opencascade.jni.TopExp_Explorer;
import org.jcae.opencascade.jni.TopoDS_Shape;

/**
 * Example which dump the label from the edges of a STEP file
 * @author Jerome Robert
 */
public class STEPLabel
{
	public static void main(final String[] args)
	{
		STEPControl_Reader aReader = new STEPControl_Reader();
		aReader.readFile("/tmp/Un_autre_essai.stp".getBytes());
		aReader.nbRootsForTransfer();
		aReader.transferRoots();
		TopoDS_Shape s = aReader.oneShape();
		TopExp_Explorer ex = new TopExp_Explorer(s, TopAbs_ShapeEnum.EDGE);
		int i = 0;
		while(ex.more())
		{
			i++;
			System.out.println(i+ " " + aReader.getLabel(ex.current()));
			ex.next();
		}
	}
}

Add an example to show how to dump the label from the edges of a STEP file

git-svn-id: f93d4e6abee5d08e50288ddf8295609b3b37a1b6@2264 9c4724a3-da1e-0410-bc68-88f18da35cd4


/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio;

import com.google.common.collect.ImmutableMap;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runners.model.Statement;

/**
 * Unit tests for {@link ConfigurationRule}.
 */
public final class ConfigurationRuleTest {

  @Test
  public void changeConfiguration() throws Throwable {
    Statement statement = new Statement() {
      @Override
      public void evaluate() throws Throwable {
        Assert.assertEquals("testValue", Configuration.get(Constants.MASTER_ADDRESS));
      }
    };
    new ConfigurationRule(ImmutableMap.of(Constants.MASTER_ADDRESS, "testValue"))
        .apply(statement, null).evaluate();
  }
}

Add unit test for ConfigurationRule

Add unit test for ConfigurationRule


/*
 * #%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.legacy.plugin;

import ij.ImagePlus;

import org.scijava.plugin.SciJavaPlugin;

/**
 * Extension point for actions to be executed after Help>Refresh
 * Menus.
 *
 * @author Johannes Schindelin
 */
public interface LegacyImageOpener extends SciJavaPlugin {

	/**
	 * Optionally override opening images via legacy hooks.
	 *

	 * This is intended as a "HandleExtraFileTypesPlus".
	 *

	 *
	 * @param path
	 *            the path to the image, or {@code null} if a dialog needs to be
	 *            shown
	 * @param sliceIndex
	 *            the index of the single slice to open, or -1 for all slices
	 * @return an image, or {@code null} to let ImageJ 1.x open the image
	 */
	ImagePlus openImage(final String path, final int sliceIndex);
}

Add a plugin type to intercept ImageJ 1.x' opening images

This plugin type will need to be implemented by all plugins wanting
to have a say how an image is opened.

It is our design to improve on HandleExtraFileTypes; Now developers
can extend ImageJ 1.x' image opening without stepping on each others
toes, badly.

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


/*
	Project 4-1

	Convert the help system from Project 3-3 into a Help class.
*/
class Help {
	void helpon(int what) {
		switch(what) {
			case '1':
				System.out.println("The if:\n");
				System.out.println("if(condition) statement;");
				System.out.println("else statement;");
				break;
			case '2':
				System.out.println("The switch:\n");
				System.out.println("switch(expression) {");
				System.out.println("  case constant:");
				System.out.println("    statement sequence");
				System.out.println("    break;");
				System.out.println("  // ...");
				System.out.println("}");
				break;
			case '3':
				System.out.println("The for:\n");
				System.out.println("for(initialization; condition; iteration) statement;");
				break;
			case '4':
				System.out.println("The while:\n");
				System.out.println("while(condition) statement;");
				break;
			case '5':
				System.out.println("The do-while:\n");
				System.out.println("do {");
				System.out.println("  statement;");
				System.out.println("} while (condition);");
				break;
			case '6':
				System.out.println("The break:\n");
				System.out.println("break; or break label;");
				break;
			case '7':
				System.out.println("The continue:\n");
				System.out.println("continue; or continue label;");
				break;
		}
		System.out.println();
	}

	void showmenu() {
		System.out.println("Help on:");
		System.out.println("  1. if");
		System.out.println("  2. switch");
		System.out.println("  3. for");
		System.out.println("  4. while");
		System.out.println("  5. do-while");
		System.out.println("  6. break");
		System.out.println("  7. continue\n");
		System.out.print("Choose one (q to quit): ");
	}

	boolean isvalid(int ch) {
		if(ch < '1' | ch > '7' & ch != 'q') return false;
		else return true;
	}
}

class HelpClassDemo {
	public static void main(String args[]) throws java.io.IOException {
		char choice;
		Help hlpobj = new Help();

		for(;;) {
			do {
				hlpobj.showmenu();
				do {
					choice = (char) System.in.read();
				} while(choice == '\n' | choice == '\r');
			} while( !hlpobj.isvalid(choice) );

			if(choice == 'q') break;

			System.out.println("\n");

			hlpobj.helpon(choice);
		}
	}
}

Convert Help to a class

Convert Help to a class


package net.fushizen.invokedynamic.proxy;

import org.junit.Test;

import java.lang.invoke.ConstantCallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodType;

import static org.junit.Assert.assertEquals;

public class StatefulProxyTest {
    public abstract static class StateSuperclass {
        private int counter;

        protected void invokeIncrement() {
            counter++;
        }

        protected int invokeGet() {
            return counter;
        }
    }

    public interface Counter {
        public void increment();
        public int get();
    }

    @Test
    public void testStatefulProxy() throws Exception {
        DynamicInvocationHandler handler = (lookup, name, type, superMethod) -> {
            Class<?> proxyType = type.parameterArray()[0];
            MethodHandle mh;

            if (superMethod != null) {
                mh = superMethod.asType(type);
            } else if (name.equals("increment")) {
                mh = lookup.findSpecial(
                        StateSuperclass.class,
                        "invokeIncrement",
                        MethodType.methodType(Void.TYPE),
                        proxyType
                ).asType(type); // downcast the 'this' parameter
            } else if (name.equals("get")) {
                mh = lookup.findSpecial(
                        StateSuperclass.class,
                        "invokeGet",
                        MethodType.methodType(Integer.TYPE),
                        proxyType
                ).asType(type); // downcast the 'this' parameter
            } else {
                throw new UnsupportedOperationException();
            }

            return new ConstantCallSite(mh);
        };

        DynamicProxy proxy = DynamicProxy.builder()
                .withSuperclass(StateSuperclass.class)
                .withInterfaces(Counter.class)
                .withInvocationHandler(handler)
                .build();

        Counter counter1 = (Counter)proxy.supplier().get();
        Counter counter2 = (Counter)proxy.supplier().get();

        counter1.increment();

        assertEquals(1, counter1.get());
        assertEquals(0, counter2.get());
    }

}

Add a test demonstrating a stateful proxy


/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 hsz Jakub Chrzanowski <jakub@hsz.mobi>
 *
 * 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 mobi.hsz.idea.gitignore.actions;

import com.intellij.openapi.actionSystem.Presentation;
import mobi.hsz.idea.gitignore.Common;
import mobi.hsz.idea.gitignore.IgnoreBundle;
import mobi.hsz.idea.gitignore.file.type.IgnoreFileType;
import mobi.hsz.idea.gitignore.hideignoredfiles.HideIgnoredFilesAction;
import org.junit.Assert;

/**
 * @author Jakub Chrzanowski <jakub@hsz.mobi>
 * @since 1.5
 */
public class HideIgnoredFilesActionTest extends Common<AddTemplateAction> {
    public void testHideIgnoredFilesActionInvocation() {
        final HideIgnoredFilesAction action = new HideIgnoredFilesAction();
        Presentation presentation;

        presentation = myFixture.testAction(action);
        Assert.assertEquals(IgnoreBundle.message("action.hideIgnoredVisibility"), presentation.getText());
    }
}

Add unit test for HideIgnoredFilesAction


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

package edu.cwru.sicu_sms.util;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

/**
 * Test class for {@link PropertyOperator}.
 *
 * @since December 14, 2016
 * @author Ted Frohlich <ttf10@case.edu>
 * @author Abby Walker <amw138@case.edu>
 */
class PropertyOperatorTest {

    @BeforeEach
    void setUp() {

    }

    @AfterEach
    void tearDown() {

    }

    @Test
    void loadProperties() {

    }

    @Test
    void saveProperties() {

    }

}

Create test class for 'PropertyOperator'


package com.jetbrains.python.psi.impl;

import com.intellij.lang.ASTNode;
import com.jetbrains.python.PyElementTypes;
import com.jetbrains.python.psi.PyDecoratorList;
import com.jetbrains.python.psi.PyExpression;
import com.jetbrains.python.psi.stubs.PyDecoratorListStub;
import com.jetbrains.python.psi.PyDecorator;
import com.jetbrains.python.psi.PyElementVisitor;
import org.jetbrains.annotations.NotNull;

/**
 * @author dcheryasov
 */
public class PyDecoratorListImpl extends PyBaseElementImpl<PyDecoratorListStub> implements PyDecoratorList{

  public PyDecoratorListImpl(ASTNode astNode) {
    super(astNode);
  }

  @Override
  protected void acceptPyVisitor(PyElementVisitor pyVisitor) {
    pyVisitor.visitPyDecoratorList(this);
  }

  public PyDecoratorListImpl(final PyDecoratorListStub stub) {
    super(stub, PyElementTypes.DECORATOR_LIST);
  }

  @NotNull
  public PyDecorator[] getDecorators() {
    final PyDecorator[] decoarray = new PyDecorator[0];
    return getStubOrPsiChildren(PyElementTypes.DECORATOR_CALL, decoarray);
    //return decoarray;
  }

  @Override
  public PyDecorator findDecorator(String name) {
    final PyDecorator[] decorators = getDecorators();
    for (PyDecorator decorator : decorators) {
      final PyExpression callee = decorator.getCallee();
      if (callee != null && name.equals(callee.getText())) {
        return decorator;
      }
    }
    return null;
  }
}

package com.jetbrains.python.psi.impl;

import com.intellij.lang.ASTNode;
import com.jetbrains.python.PyElementTypes;
import com.jetbrains.python.psi.PyDecorator;
import com.jetbrains.python.psi.PyDecoratorList;
import com.jetbrains.python.psi.PyElementVisitor;
import com.jetbrains.python.psi.stubs.PyDecoratorListStub;
import org.jetbrains.annotations.NotNull;

/**
 * @author dcheryasov
 */
public class PyDecoratorListImpl extends PyBaseElementImpl<PyDecoratorListStub> implements PyDecoratorList{

  public PyDecoratorListImpl(ASTNode astNode) {
    super(astNode);
  }

  @Override
  protected void acceptPyVisitor(PyElementVisitor pyVisitor) {
    pyVisitor.visitPyDecoratorList(this);
  }

  public PyDecoratorListImpl(final PyDecoratorListStub stub) {
    super(stub, PyElementTypes.DECORATOR_LIST);
  }

  @NotNull
  public PyDecorator[] getDecorators() {
    final PyDecorator[] decoarray = new PyDecorator[0];
    return getStubOrPsiChildren(PyElementTypes.DECORATOR_CALL, decoarray);
    //return decoarray;
  }

  @Override
  public PyDecorator findDecorator(String name) {
    final PyDecorator[] decorators = getDecorators();
    for (PyDecorator decorator : decorators) {
      final PyQualifiedName qName = decorator.getQualifiedName();
      if (qName != null && name.equals(qName.toString())) {
        return decorator;
      }
    }
    return null;
  }
}

Use information from stub for finding decorator in decorators list


/*
 * ################################################################
 *
 * ProActive: The Java(TM) library for Parallel, Distributed,
 *            Concurrent computing with Security and Mobility
 *
 * Copyright (C) 1997-2002 INRIA/University of Nice-Sophia Antipolis
 * Contact: proactive-support@inria.fr
 *
 * 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 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
 *
 *  Initial developer(s):               The ProActive Team
 *                        http://www.inria.fr/oasis/ProActive/contacts.html
 *  Contributor(s):
 *
 * ################################################################
 */
package nonregressiontest;

/**
 * @author Alexandre di Costanzo
 *
 * Created on Jan 25, 2005
 */
public class TestCVSMessageLog {

}

Test cvs email message log.

Test cvs email message log.

git-svn-id: 9146c88ff6d39b48099bf954d15d68f687b3fa69@1991 28e8926c-6b08-0410-baaa-805c5e19b8d6


package org.trello4j;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.trello4j.model.Action;

/**
 * Created with IntelliJ IDEA.
 * User: joel
 * Date: 2012-04-15
 * Time: 11:00 AM
 */
public class TrelloURLTest {

    /**
     * Should build url with filter.
     *
     * @throws Exception the exception
     */
    @Test
    public void shouldBuildURLWithFilter() throws Exception {
        String url = TrelloURL.create("API_KEY", TrelloURL.ACTION_URL, "ID")
                .token("TOKEN")
                .filter(Action.TYPE.ADD_ATTACHMENT, Action.TYPE.ADD_CHECKLIST)
                .build();

        String expectedUrl = "https://api.trello.com/1/actions/ID?key=API_KEY&token=TOKEN&filter=" + Action.TYPE.ADD_ATTACHMENT + "," + Action.TYPE.ADD_CHECKLIST;

        assertEquals(expectedUrl, url);
    }
}

package org.trello4j;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.trello4j.model.Action;

/**
 * Created with IntelliJ IDEA.
 * User: joel
 * Date: 2012-04-15
 * Time: 11:00 AM
 */
public class TrelloURLTest {

    /**
     * Should build url with filter.
     *
     * @throws Exception the exception
     */
    @Test
    public void shouldBuildURLWithFilter() throws Exception {
        String url = TrelloURL.create("API_KEY", TrelloURL.ACTION_URL, "ID")
                .token("TOKEN")
                .filter(Action.TYPE.ADD_ATTACHMENT, Action.TYPE.ADD_CHECKLIST)
                .build();

        String expectedUrl = "https://api.trello.com/1/actions/ID?key=API_KEY&token=TOKEN&filter=" + Action.TYPE.ADD_ATTACHMENT + "," + Action.TYPE.ADD_CHECKLIST;

        assertEquals(expectedUrl, url);
    }

	@Test
	public void shouldNotReturnNullBaseURL() {
		String url = TrelloURL
				.create("API_KEY", TrelloURL.CARD_POST_URL)
				.token("TOKEN")
				.build();

		String expectedUrl = "https://api.trello.com/1/cards?key=API_KEY&token=TOKEN";

		assertEquals(expectedUrl, url);
	}
}

Test for API url's without path parameters.

Signed-off-by: joelso <18eaca8d2012d90d448985477d4cb18b3fab3fa4@gmail.com>


package ml.alternet.util;

import java.lang.reflect.Field;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.function.UnaryOperator;
import java.util.logging.Logger;

import ml.alternet.misc.Thrower;

/**
 * Enum-related utilities.
 *
 * @author Philippe Poulard
 */
@Util
public class EnumUtil {

    /**
     * Replace the value of an enum instance by another value.
     *
     * Helpful for enum values that are made of characters that
     * are not Java names.
     *
     *
Example

     * An enum type made of values that contains a space.
     *
     *
public enum MyEnum {
     *    VALUE_1,
     *    VALUE_2,
     *    VALUE_3;
     *
     *    MyEnum() {
     *        // replace the "_" in the name by a " "
     *       EnumUtil.replace(MyEnum.class, this, s -> s.replace('_', ' '));
     *    }
     *}

     * Usage :
     *
 MyEnum val = MyEnum.valueOf("VALUE 2");

     *
     * @param enumClass The enum class to patch
     * @param enumValue The instance to change
     * @param transformer Apply a transformation on the name of the instance
     */
    public static void replace(Class<? extends Enum<?>> enumClass, Object enumValue, UnaryOperator<String> transformer) {
        try {
            Field fieldName = enumClass.getSuperclass().getDeclaredField("name");
            AccessController.doPrivileged((PrivilegedAction<Void>) (() -> {
                fieldName.setAccessible(true);
                return null;
            }));
            String value = (String) fieldName.get(enumValue);
            value = transformer.apply(value);
            fieldName.set(enumValue, value);
            AccessController.doPrivileged((PrivilegedAction<Void>) (() -> {
                fieldName.setAccessible(false);
                return null;
            }));
        } catch (Exception e) {
            Logger.getLogger(enumClass.getName())
            .severe("Unable to access to \"name\" field of class " + enumClass.getName());
            Thrower.doThrow(e);
        }
    }

}

Add replacement facility of enum values

Add replacement facility of enum values


// Copyright (c) 2003 Brian Wellington (bwelling@xbill.org)

package org.xbill.DNS;

/**
 * Helper functions for doing serial arithmetic.  These should be used when
 * setting/checking SOA serial numbers.
 *
 * @author Brian Wellington
 */

public final class Serial {

private static final long MAX32 = 0xFFFFFFFFL;

private
Serial() {
}

/**
 * Compares two numbers using serial arithmetic.  The numbers are assumed
 * to be 32 bit unsigned integers stored in longs.
 * @param serial1 The first integer
 * @param serial2 The second integer
 * @return 0 if the 2 numbers are equal, a positive number if serial1 is greater
 * than serial2, and a negative number if serial2 is greater than serial1.
 * @throws IllegalArgumentException serial1 or serial2 is out of range
 */
public static int
compare(long serial1, long serial2) {
	if (serial1 < 0 || serial1 > MAX32)
		throw new IllegalArgumentException(serial1 + " out of range");
	if (serial2 < 0 || serial2 > MAX32)
		throw new IllegalArgumentException(serial2 + " out of range");
	long diff = serial1 - serial2;
	if (diff >= MAX32)
		diff -= (MAX32 + 1);
	else if (diff < -MAX32)
		diff += (MAX32 + 1);
	return (int)diff;
}

/**
 * Increments a serial number.  The number is assumed to be a 32 bit unsigned
 * integer stored in a long.  This basically adds 1 and resets the value to
 * 0 if it is 2^32.
 * @param val The serial number
 * @return The incremented serial number
 * @throws IllegalArgumentException serial is out of range
 */
public static long
increment(long serial) {
	if (serial < 0 || serial > MAX32)
		throw new IllegalArgumentException(serial + " out of range");
	if (serial == MAX32)
		return 0;
	return serial + 1;
}

}

Add a class for doing serial arithmetic.


package com.alexstyl.specialdates.events;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

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

@RunWith(MockitoJUnitRunner.class)
public class EventTypeTest {

    @Test
    public void mapsTypeBirthdayIdToBirthdayEvent() {
        EventType eventType = EventType.fromId(EventColumns.TYPE_BIRTHDAY);
        assertThat(eventType).isEqualTo(EventType.BIRTHDAY);
    }

    @Test
    public void mapsTypeNamedayIdToNamedayEvent() {
        EventType eventType = EventType.fromId(EventColumns.TYPE_NAMEDAY);
        assertThat(eventType).isEqualTo(EventType.NAMEDAY);
    }

    @Test(expected = IllegalArgumentException.class)
    public void throwExceptionOnInvalidId() {
        EventType.fromId(3);
    }
}

Add test to ensure correct creation of EventType


package com.hearthsim.card.minion.concrete;

import com.hearthsim.card.Card;
import com.hearthsim.card.minion.Minion;
import com.hearthsim.card.minion.MinionTargetableBattlecry;
import com.hearthsim.event.CharacterFilterTargetedBattlecry;
import com.hearthsim.event.effect.CardEffectCharacter;
import com.hearthsim.model.BoardModel;
import com.hearthsim.model.PlayerSide;
import com.hearthsim.util.tree.HearthTreeNode;

public class YouthfulBrewmaster extends Minion implements MinionTargetableBattlecry {

    private final static CharacterFilterTargetedBattlecry filter = new CharacterFilterTargetedBattlecry() {
        protected boolean includeOwnMinions() { return true; }
    };

    private final static CardEffectCharacter effect = CardEffectCharacter.BOUNCE;

    public YouthfulBrewmaster() {
        super();
    }

    @Override
    public boolean canTargetWithBattlecry(PlayerSide originSide, Card origin, PlayerSide targetSide, int targetCharacterIndex, BoardModel board) {
        return YouthfulBrewmaster.filter.targetMatches(originSide, origin, targetSide, targetCharacterIndex, board);
    }

    @Override
    public HearthTreeNode useTargetableBattlecry_core(PlayerSide originSide, Minion origin, PlayerSide targetSide, int targetCharacterIndex, HearthTreeNode boardState) {
        return YouthfulBrewmaster.effect.applyEffect(originSide, origin, targetSide, targetCharacterIndex, boardState);
    }
}

Implement Youthful Brewmaster. No tests necessary since it has the same functionality as Ancient Brewmaster.


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

package com.sambrannen.spring.events.service;

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

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.transaction.annotation.Transactional;

import com.sambrannen.spring.events.domain.Event;
import com.sambrannen.spring.events.repository.EventRepository;

/**
 * Integration tests for the {@link EventService}.
 *
 * @author Sam Brannen
 * @since 1.0
 */
@ExtendWith(SpringExtension.class)
@SpringBootTest
@Transactional
class EventsServiceTests {

	@Autowired
	EventService service;

	@Autowired
	EventRepository repo;

	@Test
	@WithMockUser(roles = "ADMIN")
	void save() throws Exception {
		service.save(new Event("new event", "integration test"));

		assertThat(repo.findAll().stream().filter(e -> e.getName().equals("new event")).findFirst()).isPresent();
	}

}

Introduce integration tests for the EventService


/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.retry;

import alluxio.util.CommonUtils;

import com.google.common.base.Preconditions;

import javax.annotation.concurrent.NotThreadSafe;

/**
 * An option which allows retrying based on a maximum retry timeout.
 */
@NotThreadSafe
public class TimeoutRetry implements RetryPolicy {

  private final long mRetryTimeoutMs;
  private final long mSleepMs;
  private long mStartMs = 0;
  private int mCount = 0;

  /**
   * Constructs a retry facility which allows a maximum retry timeout.
   *
   * @param retryTimeoutMs maximum period of time to retry for, in milliseconds
   * @param sleepMs time in milliseconds to sleep before retrying
   */
  public TimeoutRetry(long retryTimeoutMs, int sleepMs) {
    Preconditions.checkArgument(retryTimeoutMs > 0, "Retry timeout must be a positive number");
    Preconditions.checkArgument(sleepMs >= 0, "sleepMs cannot be negative");
    mRetryTimeoutMs = retryTimeoutMs;
    mSleepMs = sleepMs;
  }

  @Override
  public int getRetryCount() {
    return mCount;
  }

  @Override
  public boolean attemptRetry() {
    if (mCount == 0) {
      // first attempt
      mStartMs = CommonUtils.getCurrentMs();
      mCount++;
      return true;
    }

    if (mSleepMs > 0) {
      CommonUtils.sleepMs(mSleepMs);
    }
    if ((CommonUtils.getCurrentMs() - mStartMs) <= mRetryTimeoutMs) {
      mCount++;
      return true;
    }
    return false;
  }
}

Add a timeout retry class

Add a timeout retry class


package coding4fun;

import java.util.Arrays;

/**
 * Write an algorithm to perform a Tetris rotation.
 */
public class Problem24 {
    public static void rotate(char[][] block) {
        char[][] aux = new char[block.length][];
        for (int row = 0; row < block.length; row++) {
            aux[row] = new char[block[row].length];
            for (int col = 0; col < block[row].length; col++) {
                aux[row][col] = block[row][col];
            }
        }

        for (int row = 0; row < block.length; row++) {
            for (int col = 0; col < block[row].length; col++) {
                // TODO
            }
        }
    }

    private static void print(char[][] block) {
        for (char[] chars : block) {
            System.out.println(Arrays.toString(chars));
        }
        System.out.println("-----------------------------------------------------------");
    }

    public static void main(String[] args) {
        char[][] block = new char[][]{
            {' ', ' ', ' '},
            {'*', '*', '*'},
            {' ', '*', ' '},
        };
        print(block);

        rotate(block);
        print(block);

        rotate(block);
        print(block);

        rotate(block);
        print(block);
    }
}

Add skeleton for problem 24

Add skeleton for problem 24


package org.jgroups.demos;

import org.jgroups.*;
import org.jgroups.blocks.MethodCall;
import org.jgroups.blocks.Request;
import org.jgroups.blocks.RequestOptions;
import org.jgroups.blocks.RpcDispatcher;
import org.jgroups.util.ProxyAddress;
import org.jgroups.util.Rsp;
import org.jgroups.util.RspList;
import org.jgroups.util.Util;

import java.lang.reflect.Method;

/** Demos RELAY. Create 2 *separate* clusters with RELAY as top protocol. Each RELAY has bridge_props="tcp.xml" (tcp.xml
 * needs to be present). Then start 2 instances in the first cluster and 2 instances in the second cluster. They should
 * find each other, and typing in a window should send the text to everyone, plus we should get 4 responses.
 * @author Bela Ban
 */
public class RelayDemoRpc extends ReceiverAdapter {
    JChannel ch;
    RpcDispatcher disp;
    Address local_addr;

    public static void main(String[] args) throws Exception {
        String props="udp.xml";
        String name=null;

        for(int i=0; i < args.length; i++) {
            if(args[i].equals("-props")) {
                props=args[++i];
                continue;
            }
            if(args[i].equals("-name")) {
                name=args[++i];
                continue;
            }
            System.out.println("RelayDemo [-props props] [-name name]");
            return;
        }
        RelayDemoRpc demo=new RelayDemoRpc();
        demo.start(props, name);
    }

    public void start(String props, String name) throws Exception {
        ch=new JChannel(props);
        if(name != null)
            ch.setName(name);
        disp=new RpcDispatcher(ch, null, this, this);
        ch.connect("RelayDemo");
        local_addr=ch.getAddress();

        MethodCall call=new MethodCall(getClass().getMethod("handleMessage", String.class, Address.class));
        for(;;) {
            String line=Util.readStringFromStdin(": ");
            call.setArgs(new Object[]{line, local_addr});
            RspList rsps=disp.callRemoteMethods(null, call, new RequestOptions(Request.GET_ALL, 5000).setAnycasting(true));
            for(Rsp rsp: rsps.values())
                System.out.println("<< " + rsp.getValue() + " from " + rsp.getSender());
        }
    }

    public static String handleMessage(String msg, Address sender) {
        System.out.println("<< " + msg + " from " + sender);
        return "this is a response";
    }

    public void viewAccepted(View new_view) {
        System.out.println("view: " + print(new_view));
    }

    static String print(View view) {
        StringBuilder sb=new StringBuilder();
        boolean first=true;
        sb.append(view.getViewId()).append(": ");
        for(Address mbr: view.getMembers()) {
            if(first)
                first=false;
            else
                sb.append(", ");
            sb.append(mbr);
            if(mbr instanceof ProxyAddress)
               sb.append("(p)");
        }
        return sb.toString();
    }
}

Copy of RelayDemo using RPCs instead of messages


/*
 * Copyright (C) 2010 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.sonatype.gshell.logging;

import java.util.Collection;
import java.util.Collections;

/**
 * Provides generic access to the underlying logging system.
 *
 * @author Jason Dillon
 * @since 2.5
 */
public class NopLoggingSystem
    implements LoggingSystem
{
    public Level getLevel(String name) {
        return new Level()
        {
            public String getName() {
                return null;
            }
        };
    }

    public Collection<? extends Level> getLevels() {
        return Collections.emptyList();
    }

    public Logger getLogger(String name) {
        return new Logger()
        {
            public String getName() {
                return null;
            }

            public Level getLevel() {
                return null;
            }

            public void setLevel(Level level) {
            }

            public void setLevel(String level) {
            }

            public Logger parent() {
                return null;
            }

            public boolean isRoot() {
                return false;
            }
        };
    }

    public Collection<String> getLoggerNames() {
        return Collections.emptyList();
    }

    public Collection<? extends Component> getComponents() {
        return Collections.emptyList();
    }
}

Add crude nop logging system component

Add crude nop logging system component


package com.backendless.servercode;

/**
 * Created with IntelliJ IDEA.
 * User: Eugene Chipachenko
 * Date: 05.06.14
 * Time: 11:53
 */
public interface IBackendlessBootstrap
{
  /**
   * Receives notification that the classes initialization process is starting.
   */
  public void onStart();

  /**
   * Receives notification that the CodeRunner is about to be shut down.
   */
  public void onStop();
}

Add boot strap for custom code

Add boot strap for custom code


package com.vaadin.addon.audio.shared;

import java.io.Serializable;

/**
 * Format parameters for PCM data
 */
@SuppressWarnings("serial")
public class PCMFormat implements Serializable {

	private int numChannels;   // 1: mono, 2: stereo
	private int sampleRate;    // samples (values) per second of audio
	private int byteRate;      // sampleRate * numChannels * (bitsPerSample / 8)
	private int blockAlign;    // numChannels * (bitsPerSample / 8)
	private int bitsPerSample; // usually either 8 or 16

	public int getNumChannels() {
		return numChannels;
	}

	public int getSampleRate() {
		return sampleRate;
	}

	public int getByteRate() {
		return byteRate;
	}

	public int getBlockAlign() {
		return blockAlign;
	}

	public int getBitsPerSample() {
		return bitsPerSample;
	}

	public void setNumChannels(int numChannels) {
		this.numChannels = numChannels;
	}

	public void setSampleRate(int sampleRate) {
		this.sampleRate = sampleRate;
	}

	public void setByteRate(int byteRate) {
		this.byteRate = byteRate;
	}

	public void setBlockAlign(int blockAlign) {
		this.blockAlign = blockAlign;
	}

	public void setBitsPerSample(int bitsPerSample) {
		this.bitsPerSample = bitsPerSample;
	}

}

Add PCM format descriptor object

Add PCM format descriptor object


/*
 * 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 rationals;

import rationals.properties.TraceEquivalent;
import junit.framework.TestCase;

public class TraceEquivalentTest extends TestCase {

    /**
     * Constructor for TraceEquivalentTest.
     * @param arg0
     */
    public TraceEquivalentTest(String arg0) {
        super(arg0);
    }

    public void testTraceEquivalentAutomata() {

    }

    public void testNonTraceEquivalentAutomata() throws NoSuchStateException {
    	Automaton<String, Transition<String>, TransitionBuilder<String>> a1 = new Automaton<>();
    	State s10 = a1.addState(true, false);
    	State s11 = a1.addState(false, true);
    	State s12 = a1.addState(false, false);
    	a1.addTransition(new Transition<>(s10, "P", s11));
    	a1.addTransition(new Transition<>(s11, "Q", s12));
    	a1.addTransition(new Transition<>(s11, "S", s11));
    	a1.addTransition(new Transition<>(s12, "R", s11));

    	Automaton<String, Transition<String>, TransitionBuilder<String>> a2 = new Automaton<>();
    	State s20 = a2.addState(true, false);
    	State s21 = a2.addState(false, true);
    	State s22 = a2.addState(false, false);
    	State s23 = a2.addState(false, false);
    	State s24 = a2.addState(false, false);
    	a2.addTransition(new Transition<>(s20, "P", s21));
    	a2.addTransition(new Transition<>(s21, "Q", s22));
    	a2.addTransition(new Transition<>(s23, "Q", s24));
    	a2.addTransition(new Transition<>(s22, "R", s23));
    	a2.addTransition(new Transition<>(s21, "S", s21));
    	a2.addTransition(new Transition<>(s23, "S", s21));
    	a2.addTransition(new Transition<>(s24, "R", s21));

    	TraceEquivalent<String, Transition<String>, TransitionBuilder<String>> equiv = new TraceEquivalent<>();
        assertFalse(equiv.test(a1, a2));
    }

}

Add MWE that shows bug in TraceEquivalent as unit test.


package org.jets3t.samples;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;

public class S3PostFormBuilder {

    public static void main(String[] args) throws Exception {
        String aws_access_key = "YOUR AWS ACCESS KEY GOES HERE";
        String aws_secret_key = "YOUR AWS SECRET KEY GOES HERE";

        String policy_document =
          "{\"expiration\": \"2009-01-01T00:00:00Z\"," +
            "\"conditions\": [" +
              "{\"bucket\": \"s3-bucket\"}," +
              "[\"starts-with\", \"$key\", \"uploads/\"]," +
              "{\"acl\": \"private\"}," +
              "{\"success_action_redirect\": \"http://localhost/\"}," +
              "[\"starts-with\", \"$Content-Type\", \"\"]," +
              "[\"content-length-range\", 0, 1048576]" +
            "]" +
          "}";

        // Calculate policy and signature values from the given policy document and AWS credentials.
        String policy = (new BASE64Encoder()).encode(
            policy_document.getBytes("UTF-8")).replaceAll("\n","").replaceAll("\r","");

        Mac hmac = Mac.getInstance("HmacSHA1");
        hmac.init(new SecretKeySpec(
            aws_secret_key.getBytes("UTF-8"), "HmacSHA1"));
        String signature = (new BASE64Encoder()).encode(
            hmac.doFinal(policy.getBytes("UTF-8")))
            .replaceAll("\n", "");

        // Build an S3 POST HTML document
        String html_document =
            "\n" +
                "\n" +
                "  <title>S3 POST Form</title>\n" +
                "  <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n" +
                "\n" +

                "\n" +
                "  <form action=\"https://s3-bucket.s3.amazonaws.com/\" method=\"post\" enctype=\"multipart/form-data\">\n" +
                "    <input type=\"hidden\" name=\"key\" value=\"uploads/${filename}\">\n" +
                "    <input type=\"hidden\" name=\"AWSAccessKeyId\" value=\"" + aws_access_key + "\">\n" +
                "    <input type=\"hidden\" name=\"acl\" value=\"private\">\n" +
                "    <input type=\"hidden\" name=\"success_action_redirect\" value=\"http://localhost/\">\n" +
                "    <input type=\"hidden\" name=\"policy\" value=\"" + policy + "\">\n" +
                "    <input type=\"hidden\" name=\"signature\" value=\"" + signature + "\">\n" +
                "    <input type=\"hidden\" name=\"Content-Type\" value=\"image/jpeg\">\n" +

                "    File to upload to S3:\n" +
                "    <input name=\"file\" type=\"file\">\n" +
                "
\n" +
                "    <input type=\"submit\" value=\"Upload File to S3\">\n" +
                "  </form>\n" +
                "\n" +
            "";

        System.out.print(html_document);
    }

}

Move this sample code into the official samples directory


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

import nom.bdezonia.zorbage.misc.LongUtils;
import nom.bdezonia.zorbage.type.algebra.Algebra;
import nom.bdezonia.zorbage.type.ctor.Allocatable;
import nom.bdezonia.zorbage.type.ctor.StorageConstruction;
import nom.bdezonia.zorbage.type.storage.Storage;
import nom.bdezonia.zorbage.type.storage.datasource.IndexedDataSource;

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

	/**
	 *
	 * @param dims
	 * @param type
	 * @return
	 */
	public static <T extends Algebra<T,U>, U extends Allocatable<U>>
		MultiDimDataSource<T,U> allocate(long[] dims, U type)
	{
		long numElements = LongUtils.numElements(dims);
		IndexedDataSource<U> data = Storage.allocate(numElements, type);
		return new MultiDimDataSource<>(dims, data);
	}

	/**
	 *
	 * @param strategy
	 * @param dims
	 * @param type
	 * @return
	 */
	public static <T extends Algebra<T,U>, U extends Allocatable<U>>
		MultiDimDataSource<T,U> allocate(StorageConstruction strategy, long[] dims, U type)
	{
		long numElements = LongUtils.numElements(dims);
		IndexedDataSource<U> data = Storage.allocate(strategy, numElements, type);
		return new MultiDimDataSource<>(dims, data);
	}
}

Define a multidim dataset allocator class


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

// https://www.hackerrank.com/challenges/ctci-ice-cream-parlor/problem
public class IceCreamParlor {

  private static final String SPACE = " ";
  private static final int SENTINEL = -1;

  private long[] getCosts(BufferedReader reader) throws IOException {
    String[] split = reader.readLine().split(SPACE);
    return Arrays.stream(split).mapToLong(Long::parseLong).toArray();
  }

  private Map<Long, List<Integer>> getFrequencies(long[] costs) {
    Map<Long, List<Integer>> frequencies = new HashMap<>();
    for (int i = 0; i < costs.length; i++) {
      long cost = costs[i];
      List<Integer> indexList = frequencies.getOrDefault(cost, new ArrayList());
      indexList.add(i);
      frequencies.put(cost, indexList);
    }
    return frequencies;
  }

  private int getDifferentIndex(int index, List<Integer> indices) {
    for (int indexFromList : indices) {
      if (indexFromList != index) {
        return indexFromList;
      }
    }
    return SENTINEL;
  }

  private String getIdsToSpendAllBudget(long budget, long[] costs) {
    Map<Long, List<Integer>> frequencies = getFrequencies(costs);
    for (int i = 0; i < costs.length; i++) {
      long cost = costs[i];
      long difference = budget - cost;
      List<Integer> secondCost = frequencies.getOrDefault(difference, null);
      if (secondCost != null) {
        int secondIndex = secondCost.get(0);
        if (cost == difference) {
          secondIndex = getDifferentIndex(i, secondCost);
          if (secondIndex == SENTINEL) {
            continue;
          }
        }
        return (i + 1) + SPACE + (secondIndex + 1);
      }
    }
    throw new IllegalStateException("There is no answer");
  }

  public static void main(String[] args) throws IOException {
    IceCreamParlor parlor = new IceCreamParlor();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
      int testCases = Integer.parseInt(reader.readLine());
      for (int i = 0; i < testCases; i++) {
        long budget = Long.parseLong(reader.readLine());
        reader.readLine(); // Skip the size of the array.
        long[] costs = parlor.getCosts(reader);
        String idsSeparatedBySpace = parlor.getIdsToSpendAllBudget(budget, costs);
        System.out.println(idsSeparatedBySpace);
      }
    }
  }
}

Add solution for Ice cream parlor problem.


package fc.lang;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import fc.lang.EvaluationException;
import fc.lang.Expression;
import fc.lang.Scope;

import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class ExitCommandTest {
    @Mock
    private Scope scope;

    @Test
    public void testExitCommand() throws EvaluationException {
        ExitCommand exitCommand = new ExitCommand();
        exitCommand.evaluate(scope);

        verify(scope).bind(eq("_exit"), any(Expression.class));
        verifyNoMoreInteractions(scope);
    }
}

Test case for exit command

Test case for exit command


package com.continuuity.passport.core.utils;

import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;

/**
 *
 */
public class PasswordUtils {
  private final static HashFunction hashFunction = Hashing.sha1();

  public static String generateHashedPassword(String password) {
    HashCode hashCode = hashFunction.newHasher().putString(password).hash();
    return hashCode.toString();
  }

}

Add sha1 hash to passwords

Add sha1 hash to passwords


/*
 * Copyright 2016 Lukáš Petrovický
 *
 * 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.triceo.robozonky;

import com.github.triceo.robozonky.remote.ZotifyApi;
import org.assertj.core.api.Assertions;
import org.junit.Test;

public class ApiProviderTest {

    @Test
    public void obtainAndDestroy() {
        final ApiProvider provider = new ApiProvider();
        // make sure API was provided
        final ZotifyApi cache = provider.cache();
        Assertions.assertThat(cache).isNotNull();
        Assertions.assertThat(cache.getLoans()).isNotEmpty();
        // make sure the API was destroyed
        provider.destroy();
        Assertions.assertThatThrownBy(cache::getLoans).isNotNull();
        // make sure the API can not be called again
        Assertions.assertThatThrownBy(provider::destroy).isNotNull();
    }

}

Increase mutation coverage in ApiProvider


/*
 * Copyright 2012-2017 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.springframework.boot.test;

import org.junit.AssumptionViolatedException;

import org.springframework.boot.system.JavaVersion;

/**
 * Provides utility methods that allow JUnit tests to {@link org.junit.Assume} certain
 * conditions hold {@code true}. If the assumption fails, it means the test should be
 * skipped.
 *
 * @author Stephane Nicoll
 * @since 2.0.0
 */
public abstract class Assume {

	/**
	 * Assume that the specified {@link JavaVersion} is the one currently available.
	 * @param version the expected Java version
	 * @throws AssumptionViolatedException if the assumption fails
	 */
	public static void javaVersion(JavaVersion version) {
		JavaVersion currentVersion = JavaVersion.getJavaVersion();
		boolean outcome = currentVersion.compareTo(JavaVersion.NINE) < 0;
		org.junit.Assume.assumeTrue(String.format(
				"This test should run on %s (got %s)", version, currentVersion), outcome);
	}

}

Add a way to run a test only with a certain Java version

Closes gh-9530


package com.github.aureliano.edocs.app.gui.menu;

import javax.swing.JMenuItem;

public class CloseTabMenuItem extends JMenuItem {

	private static final long serialVersionUID = -3834903211976535165L;

	public CloseTabMenuItem() {
		super.setText("Close");
	}
}

Create close tab menu item.

Create close tab menu item.


package org.openlmis.report.model.report;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.openlmis.report.model.ReportData;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class StockedOutFacility implements ReportData {

    private String id;
    private String code;
    private String name;
    private String facilityType;
    private String location;
}

Add the stocked out facility model

Add the stocked out facility model


package net.dempsy.util;

/**
 * This class will execute the Runnable provided to the constructor
 * once every so many calls to {@code run()}. It's meant to be used
 * in a high performance loop so it uses a mask rather than a mod
 * to determine when to actually do the call.
 */
public class OccasionalRunnable {

    private final long mask;
    private long callCount = 0;

    public OccasionalRunnable(final long frequency) {
        if(Long.bitCount(frequency) != 1)
            throw new IllegalArgumentException("When using an " + OccasionalRunnable.class.getSimpleName() + " the frequency must be a power of 2");
        this.mask = frequency - 1;
    }

    public void maybeRun(final Runnable work) {
        callCount++;
        if((callCount & mask) == 0)
            work.run();
    }

    public static Runnable staticOccasionalRunnable(final long frequency, final Runnable runnable) {
        final OccasionalRunnable partial = new OccasionalRunnable(frequency);
        return () -> partial.maybeRun(runnable);
    }

}

Add a utility to run anything (used in debug logging initially) on a periodic basis.


package org.om.core.impl.mapping;

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

import org.om.core.api.mapping.ItemMap;
import org.om.core.api.mapping.PropertyMapping;

/**
 *
 * @author tome
 *
 */
public class BasicPropertyMap implements ItemMap {

	/**
	 * properties
	 */
	private final Map<String, PropertyMapping> properties = new HashMap<String, PropertyMapping>();
	private final Map<String, PropertyMapping> fields = new HashMap<String, PropertyMapping>();

	public void add(PropertyMapping propertyMapping) {
		fields.put(propertyMapping.getFieldname(), propertyMapping);
		properties.put(propertyMapping.getPropertyName(), propertyMapping);

	}

	public Collection<PropertyMapping> getAll() {
		return properties.values();
	}

	public PropertyMapping getField(String fieldname) {
		return fields.get(fieldname);
	}

	public PropertyMapping getIdProperty() {
		return null;
	}

	public PropertyMapping getProperty(String name) {
		return properties.get(name);
	}

	public int getSize() {
		return properties.size();
	}

	public boolean hasField(String name) {
		return fields.containsKey(name);
	}

	public boolean hasProperty(String name) {
		return properties.containsKey(name);
	}

	public boolean isEmpty() {
		return getSize() == 0;
	}
}

Move mutable property map into jcr2pojo module