package com.beust.jcommander;

import org.testng.Assert;
import org.testng.annotations.Test;

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

/**
 *
Test that parameter order specified via order attributes is respected

 */
public class ParameterOrderTest {

  private static class ManualOrder1 {
    @Parameter(order=1, names = "--arg_b")
    public boolean isB;
    @Parameter(order=0, names = "--arg_a")
    public boolean isA;
    @Parameter(order=2, names = "--arg_c")
    public boolean isC;
  }

  @Test
  public void testOrder1() {
    testOrder(new ManualOrder1(), "--arg_a","--arg_b","--arg_c");
  }

  private static class ManualOrder2 {
    @Parameter(order=1, names = "--arg_b")
    public boolean isZ;
    @DynamicParameter(order=0, names = "--arg_a")
    public Map<String,String> mapA;
    @Parameter(order=2, names = "--arg_c")
    public boolean isC;
  }

  @Test
  public void testOrder2() {
    testOrder(new ManualOrder2(), "--arg_a","--arg_b","--arg_c");
  }

  private static class ManualOrder3 {
    @Parameter(order=1, names = "--arg_b")
    public boolean isB;
    @Parameter(order=0, names = "--arg_a")
    public boolean isA;
    @Parameter(names = "--arg_d")
    public boolean isD;
    @Parameter(order=2, names = "--arg_c")
    public boolean isC;
  }

  @Test
  public void testOrder3() {
    testOrder(new ManualOrder3(), "--arg_a","--arg_b","--arg_c", "--arg_d");
  }

  public void testOrder(Object cmd, String ... expected) {
    JCommander commander = new JCommander(cmd);

    StringBuilder out = new StringBuilder();
    commander.getUsageFormatter().usage(out);
    String output = out.toString();
    List<String> order = new ArrayList<>();
    for (String line : output.split("[\\n\\r]+")) {
      String trimmed = line.trim();
      if (!trimmed.contains(":")) {
        order.add(trimmed);
      }
    }
    Assert.assertEquals(order, Arrays.asList(expected));
  }
}

Add a test for Parameter order usage

Add a test for Parameter order usage

Test that usage or "order" with Parameter and DynamicParameter do result
in a properly ordered output in usage()


/**
 *
 */
package config;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Map;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

/**
 * @author Peter Vollmer
 *
 */
public class ConfigManager {

	private static ConfigManager instance = null;

	/**
	 * 	Parses the config file in JSON format.
	 */
	private final JSONParser parser = new JSONParser();

	/**
	 * Storage of configuration entries
	 */
	private Map<String, Object> confMap = null;

	/**
	 * Construct the ConfigManager for centralize all configurations of the server
	 *
	 * @param configPath
	 * @throws Exception
	 */
	private ConfigManager(String configPath) throws Exception {
		BufferedReader reader = null;
		reader = new BufferedReader(new InputStreamReader(
					new FileInputStream(configPath), Charset.forName("UTF-8")));
		JSONObject requestJSON = (JSONObject) parser.parse(reader);

		this.confMap = requestJSON;

	}

	/**
	 * Initialize the config management and construct the configManager.
	 * To do before getInstance
	 *
	 * @param configPath
	 *
	 * @throws Exception
	 */
	public static void Init (String configPath) throws Exception {
		instance = new ConfigManager(configPath);
	}

	/**
	 * Return the value of a given key or the given defaultValue
	 *
	 * @param key
	 * @param defaultValue
	 * @return value
	 *			 of a given key or the given defaultValue
	 */
	public String getEntry(String key, String defaultValue){
		String value = null;
		if (confMap.containsKey(key)){
			value = (String)confMap.get(key);
		} else {
			value = defaultValue;
		}
		return value;
	}

	/**
	 * Returns the value of the given key
	 *
	 * @param key
	 * 			to give the
	 * @return value (default value is null)
	 */
	public String getEntry (String key){
		String value = null;
		if (confMap.containsKey(key)){
			value = (String)confMap.get(key);
		}
		return value;
	}

	/**
	 * Return an instance of a constructed ConfigManager. Need Init before.
	 *
	 *
	 * @return instance of ConfigManager
	 */
	public static ConfigManager getInstance()	{
		return instance;
	}

}

Add the config manager funtionality to the server


package com.sunny.grokkingalgorithms.basic_2020.warmup;

import java.util.Stack;

public class DuplicateParenthesis {

	public static boolean duplicateParenthesis(String s) {
		Stack<Character> stack = new Stack<Character>();
		int i = 0;
		while(i < s.length()) {
			char current = s.charAt(i);
			if(current != ')') {
				stack.push(current);
			}else {
				if(stack.peek() == '(') {
					return true;
				}
				while(stack.peek() != '(') {
					stack.pop();
				}
				stack.pop();
			}
			i++;
		}
		return false;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
        String s = "((x+y))";
        System.out.println(duplicateParenthesis(s));
        s = "((x+y)+(y+z))";
        System.out.println(duplicateParenthesis(s));
	}

}

Duplicate parenthesis checking using stack.


package com.amitness.photon.utils;

/**
 * Provides a abstraction to the flashlight hardware
 */

class FlashLight {
    // TODO: Implement the methods

    public void turnOn() {
    }

    public void turnOff() {
    }

    public void release() {
    }
}

Make structure for utility classes

Make structure for utility classes


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

/**
 * Given two integers passed as argument, can you write a function to determine the number of bits
 * required to convert integer A to integer B.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class BitsToTransform {

}

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

/**
 * Given two integers passed as argument, can you write a function to determine the number of bits
 * required to convert integer A to integer B.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class BitsToTransform {

  /**
   * Iterative algorithm created to calculate a XOR using the input integers. Once you have the XOR
   * you can iterate through the XOR to count the number of bits equals to 1. To iterate over the
   * integer we are going to modify the value of the XOR integer using & operator with XOR & XOR
   * -1.
   *
   * For example:
   *
   * numA = 001
   * numB = 101
   * XOR  = 100
   *
   * Iteration 1 -> XOR = 100
   * Iteration 2 -> XOR = 100 & 011 = 000 // Loop body not executed.
   */
  public int calculate(int numA, int numB) {
    int differentBits = 0;
    for (int XOR = numA ^ numB; XOR != 0; XOR = XOR & (XOR - 1)) {
      differentBits++;
    }
    return differentBits;
  }
}

Add solution to problem 69

Add solution to problem 69


package com.google.sps.servlets;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Servlet that deletes the keywords.*/
@WebServlet("/delete-keywords")
public class DeleteKeywordsServlet extends HttpServlet {

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String keyString = request.getParameter("k");
    Key key = KeyFactory.stringToKey(keyString);
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    datastore.delete(key);
  }
}

Add Servlet to delete keywords

Add Servlet to delete keywords


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

package com.github.pedrovgs.nox;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import static org.junit.Assert.assertTrue;

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
@Config(emulateSdk = 18) @RunWith(RobolectricTestRunner.class) public class NoxItemCatalogTest {

  @Test public void test() {
    assertTrue(true);
  }
}

Create empty test case for NoxItemCatalog


/*
 * Copyright (c) 2012 Mateusz Parzonka, Eric Bodden
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Mateusz Parzonka - initial API and implementation
 */
package prm4j.indexing.realtime;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import prm4j.AbstractTest;
import prm4j.api.fsm.FSM;
import prm4j.api.fsm.FSMSpec;
import prm4j.indexing.BaseMonitor;
import prm4j.indexing.StatefulMonitor;
import prm4j.indexing.staticdata.StaticDataConverter;
import prm4j.spec.FiniteParametricProperty;
import prm4j.spec.FiniteSpec;

public class GarbageCollectionTest extends AbstractTest {

    protected StaticDataConverter converter;
    protected DefaultBindingStore bindingStore;
    protected DefaultNodeStore nodeStore;
    protected BaseMonitor prototypeMonitor;
    protected DefaultParametricMonitor pm;

    public void createDefaultParametricMonitorWithAwareComponents(FSM fsm, int cleaningInterval) {
	FiniteSpec finiteSpec = new FSMSpec(fsm);
	converter = new StaticDataConverter(new FiniteParametricProperty(finiteSpec));
	bindingStore = new DefaultBindingStore(finiteSpec.getFullParameterSet(), 1);
	nodeStore = new DefaultNodeStore(converter.getMetaTree());
	prototypeMonitor = new StatefulMonitor(finiteSpec.getInitialState());
	pm = new DefaultParametricMonitor(bindingStore, nodeStore, prototypeMonitor, converter.getEventContext());
    }

    @Test
    public void aliveBinding_nodeIsPersistent() throws Exception {

	FSM_obj_obj fsm = new FSM_obj_obj();
	createDefaultParametricMonitorWithAwareComponents(fsm.fsm, 1);

	// exercise
	Object object = new Object();
	LowLevelBinding[] bindings = bindingStore.getBindings(array(object));
	Node node = nodeStore.getOrCreateNode(bindings);

	// verify
	assertEquals(node, nodeStore.getNode(bindings));
    }

    @Test
    public void aliveBinding_bindingIsPersistent() throws Exception {

	FSM_obj_obj fsm = new FSM_obj_obj();
	createDefaultParametricMonitorWithAwareComponents(fsm.fsm, 1);

	// exercise
	Object object = new Object();
	LowLevelBinding[] bindings = bindingStore.getBindings(array(object));
	nodeStore.getOrCreateNode(bindings);

	// verify
	assertEquals(1, bindingStore.size());
    }

}

Add test for garbage collection

Add test for garbage collection

Tests interactions of Bindings, BindingStore, NodeStore and Nodes.


// ========================================================================
// Copyright 2011 NEXCOM Systems
// ------------------------------------------------------------------------
// 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.cipango.plus.sipapp;

import javax.servlet.sip.SipErrorEvent;
import javax.servlet.sip.SipErrorListener;

public class Listener implements SipErrorListener
{

	public void noAckReceived(SipErrorEvent arg0)
	{
	}

	public void noPrackReceived(SipErrorEvent arg0)
	{
	}

}

Fix CIPANGO-139: cipango-plus is broken

Fix CIPANGO-139: cipango-plus is broken

git-svn-id: a3e743b3c7f6e97b9a019791beffa901f5d7f1d1@662 657f710f-be33-0410-a596-71a6d81f68ef


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

package io.spine.server.command;

import org.junit.Test;

public class CommandShould {

    @Test
    public void be_applied() {

    }

    @Test
    public void not_be_applied_when_reused() {

    }
}

Declare tests to be implemented to test command idempotence.


package org.bouncycastle.crypto.tls;

/**
 * RFC 2246 7.4.4
 */
public class ClientCertificateType
{
    public static final short rsa_sign = 1;
    public static final short dss_sign = 2;
    public static final short rsa_fixed_dh = 3;
    public static final short dss_fixed_dh = 4;

    /*
     * RFC 4492 5.5
     */
    public static final short ecdsa_sign = 64;
    public static final short rsa_fixed_ecdh = 65;
    public static final short ecdsa_fixed_ecdh = 66;
}

Add another new TLS name space

Add another new TLS name space


package org.motechproject.uitest.page;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class DataServicesPage extends AbstractBasePage {

    public static final By ENTITY_NAME_FIELD = By.name("inputEntityName");
    public static final By NEW_ENTITY_BUTTON = By.id("newEntityButton");
    public static final By SAVE_ENTITY_BUTTON = By.id("saveNewEntityButton");
    public static final By DATA_SERVICES_BUTTON = By.id("data-services");
    public static final By SCHEMA_EDITOR_BUTTON = By.id("schemaEditor");
    public static final By BROWSE_INSTANCES_BUTTON = By.id("browseInstancesButton");
    public static final By ADD_NEW_INSTANCE_BUTTON = By.id("addNewInstanceButton");

    public static final String HOME_PATH = "/module/server/home#";

    public DataServicesPage(WebDriver driver) {
        super(driver);
    }

    public void createNewEntity(String entityName) throws InterruptedException {
        waitForElement(DATA_SERVICES_BUTTON);
        clickWhenVisible(DATA_SERVICES_BUTTON);
        waitForElement(SCHEMA_EDITOR_BUTTON);
        clickWhenVisible(SCHEMA_EDITOR_BUTTON);
        waitForElement(NEW_ENTITY_BUTTON);
        clickWhenVisible(NEW_ENTITY_BUTTON);
        waitForElement(ENTITY_NAME_FIELD);
        setTextToFieldNoEnter(ENTITY_NAME_FIELD, entityName);
        waitForElement(SAVE_ENTITY_BUTTON);
        clickOn(SAVE_ENTITY_BUTTON);
        waitForElement(BROWSE_INSTANCES_BUTTON);
    }

    public void goToEntityTable(String entityName) throws InterruptedException {
        waitForElement(DATA_SERVICES_BUTTON);
        clickWhenVisible(DATA_SERVICES_BUTTON);
        waitForElement(By.id(String.format("entity_%s", entityName)));
        clickWhenVisible(By.id(String.format("entity_%s", entityName)));
        waitForElement(ADD_NEW_INSTANCE_BUTTON);
    }

    @Override
    public String expectedUrlPath() {
        return HOME_PATH;
    }

    @Override
    public void goToPage() {
        getDriver().get(getMotechUrl() + HOME_PATH);
    }
}

MOTECH-2033: Add selenium test for adding a new entity in MDS


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

/**
 * Given an array full of integers implement a bubble sort algorithm to sort the content inside the
 * array.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class BubbleSort {

}

Add statement to problem 74

Add statement to problem 74


package net.restlesscoder.sandbox;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;

import net.imagej.ImageJ;

public class IJDispose {

	public static void main(final String... args) {
		final ImageJ ij = new ImageJ();
		ij.ui().showUI();

		final JFrame frame = new JFrame("Hello");
		final JButton b = new JButton("Close ImageJ");
		b.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(final ActionEvent e) {
				ij.thread().getExecutorService().shutdownNow();
				ij.getContext().dispose();
			}
		});
		frame.getContentPane().add(b);
		frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
	}

}

Add a little test of ImageJ2's context disposal

See: http://stackoverflow.com/a/33653331/1207769


package org.ethereum.net.shh;

import org.ethereum.crypto.ECKey;
import org.junit.Test;

import static org.junit.Assert.assertTrue;

/**
 * Created by kest on 6/26/15.
 */
public class FilterTest {

    byte[] to = new ECKey().decompress().getPubKey();
    byte[] from = new ECKey().decompress().getPubKey();
    String[] topics = {"topic1", "topic2", "topic3", "topic4"};

    @Test
    public void test1() {
        Filter matcher = new Filter(null, null, new TopicMatcher(new String[]{}));
        Filter message = new Filter(to, from, new TopicMatcher(topics));

        assertTrue(matcher.match(message));
    }

    @Test
    public void test2() {
        Filter matcher = new Filter(to, null, new TopicMatcher(new String[]{}));
        Filter message = new Filter(to, from, new TopicMatcher(topics));

        assertTrue(matcher.match(message));
    }

    @Test
    public void test3() {
        Filter matcher = new Filter(to, null, new TopicMatcher(new String[]{}));
        Filter message = new Filter(null, from, new TopicMatcher(topics));

        assertTrue(!matcher.match(message));
    }

    @Test
    public void test4() {
        Filter matcher = new Filter(null, from, new TopicMatcher(new String[]{}));
        Filter message = new Filter(to, from, new TopicMatcher(topics));

        assertTrue(matcher.match(message));
    }

    @Test
    public void test5() {
        Filter matcher = new Filter(null, from, new TopicMatcher(new String[]{}));
        Filter message = new Filter(to, null, new TopicMatcher(topics));

        assertTrue(!matcher.match(message));
    }

    @Test
    public void test6() {
        Filter matcher = new Filter(null, from, new TopicMatcher(topics));
        Filter message = new Filter(to, from, new TopicMatcher(topics));

        assertTrue(matcher.match(message));
    }

    @Test
    public void test7() {
        Filter matcher = new Filter(null, null, new TopicMatcher(topics));
        Filter message = new Filter(to, from, new TopicMatcher(new String[]{}));

        assertTrue(!matcher.match(message));
    }
}

Add the whisper filter tests

Add the whisper filter tests


package com.mycompany.lab3;

/**
 *
 * @author Burgy Benjamin
 */
public final class Settings_default
{
    public String OpenStack_user = "";
    public String OpenStack_tenant_name = "";
    public String OpenStack_service_region = "";
    public String OpenStack_auth_url = "";
    public String OpenStack_password = "";

    public String Amazon_accessKey = "";
    public String Amazon_secretKey = "";
}

Save the structure of the settings file.


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

package net.uncontended.precipice.metrics.registry;

import net.uncontended.precipice.PrecipiceFunction;
import net.uncontended.precipice.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MetricRegistry {

    private Map<String, Summary> services = new HashMap<>();
    private volatile PrecipiceFunction<Map<String, Summary>> callback;
    // TODO: Name thread
    private ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();

    public MetricRegistry() {
        executorService.scheduleAtFixedRate(new Task(), 0, 10, TimeUnit.SECONDS);
    }

    public void register(Service service) {
        services.put(service.getName(), new Summary(service));
    }

    public Summary getSummary(String name) {
        Summary summary = services.get(name);
        if (summary == null) {
            throw new IllegalArgumentException("Service: " + name + " not registered.");
        }
        return summary;
    }

    public void setUpdateCallback(PrecipiceFunction<Map<String, Summary>> callback) {
        this.callback = callback;
    }

    public void shutdown() {
        executorService.shutdown();
    }

    private static class Summary {
        private final Service service;

        private Summary(Service service) {
            this.service = service;
        }

        private void refresh() {

        }
    }

    private class Task implements Runnable {

        @Override
        public void run() {
            for (Summary summary : services.values()) {
                summary.refresh();
            }

            if (callback != null) {
                callback.apply(services);
            }
        }
    }
}

Add class for the new metric registry

Add class for the new metric registry


package co.nstant.in.cbor;

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

public class CborExceptionTest {

    @Test
    public void shouldHaveMessage() {
        CborException cborException = new CborException("message");
        Assert.assertEquals("message", cborException.getMessage());
    }

    @Test
    public void shouldHaveThrowable() {
        Throwable throwable = new Throwable();
        CborException cborException = new CborException(throwable);
        Assert.assertEquals(throwable, cborException.getCause());
    }

    @Test
    public void shouldHaveMessageAndThrowable() {
        Throwable throwable = new Throwable();
        CborException cborException = new CborException("message", throwable);
        Assert.assertEquals("message", cborException.getMessage());
        Assert.assertEquals(throwable, cborException.getCause());
    }

}

Add unit test for CborException

Add unit test for CborException


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

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import nom.bdezonia.zorbage.algebras.G;
import nom.bdezonia.zorbage.type.data.float64.real.Float64Member;
import nom.bdezonia.zorbage.type.data.float64.real.Float64VectorMember;

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

	@Test
	public void test1() {
		Float64Member value = G.DBL.construct();
		Float64VectorMember vec = new Float64VectorMember(new double[] {1,2,3,4});
		RModuleZero.compute(vec);
		for (long i = 0; i < vec.length(); i++) {
			vec.v(i, value);
			assertEquals(0, value.v(), 0);
		}
	}
}

Define a test for the RModuleZero algorithm


package agaricus.mods.oredupefix;

import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.Init;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.Mod.PostInit;
import cpw.mods.fml.common.Mod.PreInit;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkMod;

@Mod(modid = "OreDupeFix", name = "OreDupeFix", version = "1.0")
@NetworkMod(clientSideRequired = false, serverSideRequired = false)
public class OreDupeFix {
    @PostInit
    public static void postInit(FMLPostInitializationEvent event) {
        System.out.println("loading OreDupeFix!");
    }
}

Add new empty FML mod

Add new empty FML mod


package com.github.aureliano.achmed.os;

import com.github.aureliano.achmed.resources.types.OS;
import com.github.aureliano.achmed.resources.types.OperatingSystemFamily;

public interface IOperatingSystem {

	public abstract OS getOperatingSystem();

	public abstract OperatingSystemFamily getOperatingSystemFamily();
}

Create interface to operating system types.


package net.openhft.chronicle.logger;

import net.openhft.chronicle.Chronicle;
import net.openhft.chronicle.ExcerptAppender;
import net.openhft.chronicle.VanillaChronicle;
import net.openhft.chronicle.tools.ChronicleTools;
import org.apache.commons.lang3.StringUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by peter on 10/10/14.
 */
public class VanillChronicleQueuePerfTest {
    Chronicle chronicle;
    ExcerptAppender logger;

    @Before
    public void setUp() throws IOException {
        String baseDir = System.getProperty("java.io.tmpdir") + "/perf-binary-vanilla-chronicle";
        ChronicleTools.deleteDirOnExit(baseDir);
        chronicle = new VanillaChronicle(baseDir);
        logger = chronicle.createAppender();
    }

    @After
    public void tearDown() throws IOException {
        chronicle.close();
    }

    @Test
    public void testMultiThreadLogging() throws IOException, InterruptedException {

        final int RUNS = 2000000;
        final int THREADS = Runtime.getRuntime().availableProcessors();

        for (int size : new int[]{64, 128, 256}) {
            {
                final long start = System.nanoTime();

                ExecutorService es = Executors.newFixedThreadPool(THREADS);
                for (int t = 0; t < THREADS; t++) {
                    es.submit(new RunnableLogger(RUNS, size));
                }

                es.shutdown();
                es.awaitTermination(10, TimeUnit.SECONDS);

                final long time = System.nanoTime() - start;

                System.out.printf("ChronicleLog.MT (runs=%d, min size=%03d, elapsed=%.3f ms) took an average of %.3f us per entry\n",
                        RUNS,
                        size,
                        time / 1e6,
                        time / 1e3 / (RUNS * THREADS)
                );
            }
        }
    }

    protected final class RunnableLogger implements Runnable {
        private static final String fmtBase = " > val1={}, val2={}, val3={}";
        private final String fmt;
        private final int runs;

        public RunnableLogger(int runs, int pad) {
            this.runs = runs;
            fmt = StringUtils.rightPad(fmtBase, pad + fmtBase.length(), "X");
        }

        @Override
        public void run() {
            for (int i = 0; i < this.runs; i++) {
                logger.startExcerpt();
                logger.writeUTFΔ(fmt);
                logger.writeInt(i);
                logger.writeInt(i * 7);
                logger.writeInt(i / 16);
                logger.finish();
            }
        }
    }
}

Add performance test for Chronicle Queue


package com.intellij.execution.runners;

import com.intellij.execution.console.LanguageConsoleViewImpl;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;

public abstract class ConsoleRunnerWithHistory<T extends LanguageConsoleViewImpl> {
  protected final Project myProject;

  public ConsoleRunnerWithHistory(@NotNull Project project) {
    myProject = project;
  }
}

package com.intellij.execution.runners;

import com.intellij.execution.console.LanguageConsoleView;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;

public abstract class ConsoleRunnerWithHistory<T extends LanguageConsoleView> {
  protected final Project myProject;

  public ConsoleRunnerWithHistory(@NotNull Project project) {
    myProject = project;
  }
}

Implement get variable for console variables view.


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

/**
 * @author David BRASSELY (brasseld at gmail.com)
 */
public interface HttpHeadersValues {

    String CONNECTION_CLOSE = "close";

    String TRANSFER_ENCODING_CHUNKED = "chunked";

}

Add HTTP headers common values

Add HTTP headers common values


package fi.jgke.tagger.domain;

import java.util.UUID;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author jgke
 */
public class SourceParameterTest {

    @Test
    public void testSetGetTitle() {
        String title = UUID.randomUUID().toString();
        SourceParameter instance = new SourceParameter();
        instance.setTitle(title);
        assertEquals(title, instance.getTitle());
    }

    @Test
    public void testSetGetUrl() {
        String url = UUID.randomUUID().toString();
        SourceParameter instance = new SourceParameter();
        instance.setUrl(url);
        assertEquals(url, instance.getUrl());
    }

    @Test
    public void testSetGetTitleAndUrl() {
        String title = UUID.randomUUID().toString();
        String url = UUID.randomUUID().toString();
        SourceParameter instance = new SourceParameter();
        instance.setTitle(title);
        instance.setUrl(url);
        assertEquals(title, instance.getTitle());
        assertEquals(url, instance.getUrl());
    }

    @Test
    public void testSetGetSourceParametertype() {
        Long sourcetype = UUID.randomUUID().getLeastSignificantBits();
        SourceParameter instance = new SourceParameter();
        instance.setSourcetype(sourcetype);
        assertEquals(sourcetype, instance.getSourcetype());
    }

}

Add simple tests for SourceParameter

Add simple tests for SourceParameter


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

public class Main {
    public static void main(String args[]) throws IOException {
        InputStreamReader ir = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(ir);

        float a, b, c;

        a = Float.parseFloat(in.readLine());
        b = Float.parseFloat(in.readLine());
        c = Float.parseFloat(in.readLine());

        System.out.printf("MEDIA = %.1f\n", (a * 2.0 + b * 3.0 + c * 5.0) / 10.0);
    }
}

Solve Average 2 in java

Solve Average 2 in java


/*
 * Copyright 2017 MovingBlocks
 *
 * 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.destinationsol.game;

import com.badlogic.gdx.math.Vector2;
import org.destinationsol.game.item.ItemContainer;
import org.destinationsol.game.ship.FarShip;
import org.destinationsol.game.ship.ShipBuilder;
import org.destinationsol.game.ship.SolShip;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyFloat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class PlayerCreatorTest {

    private PlayerCreator playerCreator;

    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
    private SolGame solGame;
    @Mock
    private ShipConfig shipConfig;
    @Mock
    private ShipBuilder shipBuilder;
    private RespawnState respawnState;
    private Vector2 galaxySpawnPosition;
    @Mock
    private FarShip farShip;
    @Mock
    private SolShip solShip;

    @Before
    public void setUp() {
        playerCreator = new PlayerCreator();
        respawnState = new RespawnState();
        galaxySpawnPosition = new Vector2(42, 43);
        when(solGame.getGalaxyFiller().getPlayerSpawnPos(any())).thenReturn(galaxySpawnPosition);
        mockShipBuilding();
    }

    private void mockShipBuilding() {
        when(solGame.getShipBuilder()).thenReturn(shipBuilder);
        when(shipBuilder.buildNewFar(any(), any(), any(), anyFloat(), anyFloat(), any(), any(), any(), any(), anyBoolean(), anyFloat(), any(), anyBoolean())).thenReturn(farShip);
        when(farShip.toObject(any())).thenReturn(solShip);
        when(solShip.getItemContainer()).thenReturn(new ItemContainer());
    }

    @Test
    public void testSpawnOnGalaxySpawnPosition() {
        when(solGame.getTutMan()).thenReturn(null);
        playerCreator.createPlayer(shipConfig, true, respawnState, solGame, false, false);
        verify(shipBuilder).buildNewFar(any(), eq(galaxySpawnPosition), any(), anyFloat(), anyFloat(), any(), any(), any(), any(), anyBoolean(), anyFloat(), any(), anyBoolean());
    }
}

Test spawn on galaxy spawn position

Test spawn on galaxy spawn position


package com.fixture.generator.builder;

import static org.junit.Assert.assertEquals;

import java.util.List;

import org.junit.Test;

public class ClassInformationBuildersFactoryTest {

	@Test
	public void shouldCreateAListWithNecessaryBuilder() {
		List<ClassInformationBuilder> builders = ClassInformationBuildersFactory.get();

		assertEquals(5, builders.size());
		assertEquals(PackageBuilder.class, builders.get(0).getClass());
		assertEquals(ImportBuilder.class, builders.get(1).getClass());
		assertEquals(NameBuilder.class, builders.get(2).getClass());
		assertEquals(BaseFixtureBuilder.class, builders.get(3).getClass());
		assertEquals(MethodsBuilder.class, builders.get(4).getClass());
	}

}

Create class information builders favtory test


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

package com.google.sps;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** */
@RunWith(JUnit4.class)
public final class MeetingRequestTest {
  // Some people that we can use in our tests.
  private static final String PERSON_A = "Person A";
  private static final String PERSON_B = "Person B";
  private static final String PERSON_C = "Person C";

  private static final int DURATION_1_HOUR = 60;

  @Test
  public void CantAddOptionalAttendeeWhoIsAlsoMandatory() {
    MeetingRequest request = new MeetingRequest(Arrays.asList(PERSON_A), DURATION_1_HOUR);
    request.addOptionalAttendee(PERSON_A);

    int actual = request.getOptionalAttendees().size();
    int expected = 0;
    Assert.assertEquals(expected, actual);
  }
}

Add a basic test for MeetingRequest.java


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

/**
 * Mock rules that returns a leap second on day 1000.
 *
 * @author Stephen Colebourne
 */
public class MockUTCRulesLeapOn1000 extends UTCRules {

    @Override
    public String getName() {
        return "Mock1000";
    }

    @Override
    public int getLeapSecondAdjustment(long mjDay) {
        return (mjDay == 1000 ? 1 : 0);
    }

    @Override
    public int getTAIOffset(long mjDay) {
        return (mjDay <= 1000 ? 10 : 11);
    }

    @Override
    public long[] getLeapSecondDates() {
        return new long[] {1000};
    }

    @Override
    public TAIInstant convertToTAI(UTCInstant utcInstant) {
        return null;
    }

    @Override
    public UTCInstant convertToUTC(TAIInstant taiInstant) {
        return null;
    }

}

Add with methods to UTCInstant

Add with methods to UTCInstant

git-svn-id: d4c00b25eded7fd74432537d461d9a0ef86f0050@1437 291d795c-afe8-5c46-8ee5-bf9dd72e1864


//@author: A0138848M
package seedu.oneline.model.task;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;
import seedu.oneline.testutil.TestDataHelper;

public class TaskTest {
    Task taskDate0;
    Task taskDate1;
    Task taskNameA;
    Task taskNameB;

    @Before
    public void setUp() throws Exception {
        taskDate0 = TestDataHelper.generateTask(0);
        taskDate1 = TestDataHelper.generateTask(1);
        taskNameA = TestDataHelper.generateTaskWithName("A");
        taskNameB = TestDataHelper.generateTaskWithName("B");
    }

    @Test
    public void task_sortsByDate() {
        assertTrue(taskDate0.compareTo(taskDate1) < 0);
    }

    @Test
    public void task_sortsByName() {
        assertTrue(taskNameA.compareTo(taskNameB) < 0);
    }
}

Add initial test cases for task sorting

Add initial test cases for task sorting


package test;

import static org.junit.Assert.*;

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

import model.FixedTask;
import model.FloatingTask;
import model.TaskList;

import org.junit.BeforeClass;
import org.junit.Test;

public class TaskListTest {

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}

	@Test
	public void testAddingTask() {
		TaskList tasks = new TaskList();
		// generate 50 dummy task and add them
		 for (int i = 0; i < 50; i++) {
	            tasks.addToList(new FloatingTask("No." + i));
		}
		assertEquals(50, tasks.count());
	}

	@Test
	public void testDeletingTask() {
		TaskList tasks = new TaskList();
		// generate 50 dummy task and add them
		 for (int i = 0; i < 50; i++) {
	            tasks.addToList(new FloatingTask("No." + i));
		}
		assertEquals(50, tasks.count());

		// delete single task
		List<Integer> toDelete = new ArrayList<Integer>();
		toDelete.add(1);
		try {
			tasks.deleteFromList(toDelete);
		} catch (IndexOutOfBoundsException e) {
			System.out.println(e.getMessage());
		}
		assertEquals(49, tasks.count());

		//delete multiple task
		toDelete = new ArrayList<Integer>();
		for (int i = 1; i <=25; i++) {
            toDelete.add(i);
		}
		try {
			tasks.deleteFromList(toDelete);
		} catch (IndexOutOfBoundsException e) {
			System.out.println(e.getMessage());
		}
		assertEquals(24, tasks.count());

		// clear tasks
		tasks.clearList();
		assertEquals(0, tasks.count());
	}

	public void testEditingTask() {
		TaskList tasks = new TaskList();
		// editing floating task
		FloatingTask floatTask = new FloatingTask("lowercase");
		tasks.addToList(floatTask);
		tasks.editTaskDescription(1, "UPPERCASE");
		assertEquals("UPPERCASE", tasks.get(0).getDescription());

		tasks.clearList();
		// editing floating task
		Date dateA = new Date(100);
		Date dateB = new Date(200);
		Date dateC = new Date(300);
		FixedTask fixedTask = new FixedTask("lowercase", dateA, dateB);
		tasks.addToList(fixedTask);
		tasks.editTaskStartDate(1, dateC);
		assertEquals(dateC, tasks.get(0).getDeadline());
	}

}

Add unit test for TaskList class.

Add unit test for TaskList class.


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

package com.spotify.helios.system;

import com.spotify.helios.ZooKeeperTestManager;
import com.spotify.helios.ZooKeeperTestingClusterManager;
import com.spotify.helios.client.HeliosClient;

import org.junit.Test;

public class ZooKeeperBadNodeTest extends SystemTestBase {

  /**
   * This is a testing cluster that has one peer that can't be resolved. Note that this is different
   * from a cluster where a peer is down (that's tested in {@link ZooKeeperHeliosFailoverTest}).
   */
  private final ZooKeeperTestManager zkc = new ZooKeeperTestingClusterManager() {
    @Override
    public String connectString() {
      return super.connectString() + ",node-that-doesnt-exist:1738";
    }
  };

  @Test
  public void testGetJobsWithBadNode() throws Exception {
    startDefaultMaster("--zk-cluster-id=" + zkClusterId);

    final HeliosClient client = defaultClient();
    client.jobs().get();
  }

  @Override
  protected ZooKeeperTestManager zooKeeperTestManager() {
    return zkc;
  }

}

Add test for ZK cluster with unresolvable node

Note that this test currently fails. This is not a false negative, it's
because Helios actually fails in this scenario.


package org.cyclonedx.maven;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.cyclonedx.maven.model.Component;

import java.util.Set;
import java.util.stream.Collectors;

@Mojo(
        name = "makeAggregateBom",
        defaultPhase = LifecyclePhase.VERIFY,
        aggregator = true,
        requiresOnline = true,
        requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME
)
public class CycloneDxAggregateMojo extends BaseCycloneDxMojo {

    public void execute() throws MojoExecutionException{

        final Set<Component> components = getReactorProjects().stream()
                .flatMap(mavenProject -> mavenProject.getArtifacts().stream())
                .filter(this::shouldInclude)
                .map(this::convert)
                .collect(Collectors.toSet());

        super.execute(components);
    }
}

Add mojo for generating aggregate bom for multi module projects


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

/**
 * You are given two 32-bit numbers,N and M, and two bit positions, i and j. Write a method to
 * insert M into N such that M starts at bit j and ends at bit i. You can assume that the bits j
 * through i have enough space to fit all of M. That is,if M= 10011, you can assume that there are
 * at least 5 bits between j and i. You would not, for example, have j-3 and i=2, because M could
 * not fully fit between bit 3 and bit 2.
 *
 * EXAMPLE:
 *
 * Input:N=16000000000, M=10011, i =2, j =6 Output: N = 10001001100
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class MergeBinaryNumbers {

}

Add statement to problem 67

Add statement to problem 67


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

package org.hisp.dhis.android.core.enrollment.internal;

import androidx.annotation.NonNull;

import org.hisp.dhis.android.core.arch.handlers.internal.IdentifiableDataHandler;
import org.hisp.dhis.android.core.enrollment.Enrollment;

import java.util.List;

import javax.inject.Inject;

import dagger.Reusable;
import io.reactivex.Completable;

@Reusable
public final class EnrollmentPersistenceCallFactory {

    private final IdentifiableDataHandler<Enrollment> enrollmentHandler;

    @Inject
    EnrollmentPersistenceCallFactory(
            @NonNull IdentifiableDataHandler<Enrollment> enrollmentHandler) {
        this.enrollmentHandler = enrollmentHandler;
    }

    public Completable persistRelationships(final List<Enrollment> enrollments) {
        return persistEnrollmentsInternal(enrollments, true, false, false);
    }

    private Completable persistEnrollmentsInternal(
            final List<Enrollment> enrollments, boolean asRelationship, boolean isFullUpdate, boolean overwrite) {
        return Completable.defer(() -> {
            enrollmentHandler.handleMany(enrollments, asRelationship, isFullUpdate, overwrite);
            return Completable.complete();
        });
    }
}

Add enrollment persistence call factory

[androsdk-1165] Add enrollment persistence call factory


package utils;

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

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

import play.test.FakeApplication;
import play.test.Helpers;

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

public class ConfigTest {
    protected static FakeApplication app;
    private Map<String, String> additionalConfiguration;

    @Before
    public void before() {
        additionalConfiguration = new HashMap<String, String>(Helpers.inMemoryDatabase());
    }

    @Test
    public void getScheme() {
        additionalConfiguration.put("application.scheme", "http");
        app = Helpers.fakeApplication(additionalConfiguration);
        Helpers.start(app);
        assertThat(Config.getScheme("https")).isEqualTo("http");
        Helpers.stop(app);

        additionalConfiguration.put("application.scheme", "");
        app = Helpers.fakeApplication(additionalConfiguration);
        Helpers.start(app);
        assertThat(Config.getScheme("https")).isEqualTo("https");
        Helpers.stop(app);
    }

    @Test
    public void getHostname() {
        additionalConfiguration.put("application.hostname", "www.nforge.com");
        additionalConfiguration.put("application.port", "8080");
        app = Helpers.fakeApplication(additionalConfiguration);
        Helpers.start(app);
        assertThat(Config.getHostport("localhost")).isEqualTo("www.nforge.com:8080");
        Helpers.stop(app);

        additionalConfiguration.put("application.hostname", "www.nforge.com");
        additionalConfiguration.put("application.port", null);
        app = Helpers.fakeApplication(additionalConfiguration);
        Helpers.start(app);
        assertThat(Config.getHostport("localhost:9000")).isEqualTo("www.nforge.com");
        Helpers.stop(app);

        additionalConfiguration.put("application.hostname", null);
        additionalConfiguration.put("application.port", "8080");
        app = Helpers.fakeApplication(additionalConfiguration);
        Helpers.start(app);
        assertThat(Config.getHostport("localhost:9000")).isEqualTo("localhost:9000");
        Helpers.stop(app);

        additionalConfiguration.put("application.hostname", null);
        additionalConfiguration.put("application.port", null);
        app = Helpers.fakeApplication(additionalConfiguration);
        Helpers.start(app);
        assertThat(Config.getHostport("localhost:9000")).isEqualTo("localhost:9000");
        Helpers.stop(app);
    }

}

Add the test for Config.

config: Add the test for Config.


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

import nl.talsmasoftware.context.ContextSnapshot;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasToString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;

/**
 * @author Sjoerd Talsma
 */
public class ContextSnapshotHolderTest {
    private ExecutorService unawareThreadpool;

    @Before
    public void setUp() {
        unawareThreadpool = Executors.newCachedThreadPool();
    }

    @After
    public void tearDown() throws InterruptedException {
        unawareThreadpool.shutdown();
        unawareThreadpool.awaitTermination(5, TimeUnit.SECONDS);
    }

    @Test
    public void testSetGet() {
        ContextSnapshot snapshot = mock(ContextSnapshot.class);
        ContextSnapshotHolder holder = new ContextSnapshotHolder();

        holder.accept(snapshot);
        assertThat(holder.get(), is(sameInstance(snapshot)));
    }

    @Test
    public void testInterruption() throws InterruptedException {
        ContextSnapshot snapshot = mock(ContextSnapshot.class);
        ContextSnapshotHolder holder = new ContextSnapshotHolder();

        Future<ContextSnapshot> future = unawareThreadpool.submit(holder::get);
        unawareThreadpool.shutdownNow();
        unawareThreadpool.awaitTermination(5, TimeUnit.SECONDS);

        try {
            future.get();
            fail("Exception expected");
        } catch (ExecutionException expected) {
            assertThat(expected.getCause(), hasToString(containsString("Interrupted waiting for context snapshot")));
        }
    }

}

Add unit tests to ContextSnapshotHolder

Add unit tests to ContextSnapshotHolder


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

import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.container.jdisc.HttpResponse;

import java.util.function.Function;

/**
 * A {@link RuntimeException} that represents a http response.
 *
 * @author bjorncs
 */
public class RestApiException extends RuntimeException {
    private final int statusCode;
    private final HttpResponse response;

    public RestApiException(int statusCode, String errorType, String message) {
        this(new ErrorResponse(statusCode, errorType, message), message, null);
    }

    public RestApiException(HttpResponse response, String message) {
        this(response, message, null);
    }

    public RestApiException(int statusCode, String errorType, String message, Throwable cause) {
        this(new ErrorResponse(statusCode, errorType, message), message, cause);
    }

    public RestApiException(HttpResponse response, String message, Throwable cause) {
        super(message, cause);
        this.statusCode = response.getStatus();
        this.response = response;
    }

    private RestApiException(Function<String, HttpResponse> responseFromMessage, String message, Throwable cause) {
        this(responseFromMessage.apply(message), message, cause);
    }

    public int statusCode() { return statusCode; }
    public HttpResponse response() { return response; }

    public static class NotFoundException extends RestApiException {
        public NotFoundException() { super(ErrorResponse::notFoundError, "Not Found", null); }
    }

    public static class MethodNotAllowed extends RestApiException {
        public MethodNotAllowed() { super(ErrorResponse::methodNotAllowed, "Method not allowed", null); }
        public MethodNotAllowed(HttpRequest request) {
            super(ErrorResponse::methodNotAllowed, "Method '" + request.getMethod().name() + "' is not allowed", null);
        }
    }

    public static class BadRequest extends RestApiException {
        public BadRequest(String message) { super(ErrorResponse::badRequest, message, null); }
        public BadRequest(String message, Throwable cause) { super(ErrorResponse::badRequest, message, cause); }
    }

    public static class InternalServerError extends RestApiException {
        public InternalServerError(String message) { super(ErrorResponse::internalServerError, message, null); }
        public InternalServerError(String message, Throwable cause) { super(ErrorResponse::internalServerError, message, cause); }
    }
}

Add exception type for restapi error responses


package org.assertj.db.api;

import org.assertj.core.api.WritableAssertionInfo;
import org.assertj.core.description.Description;
import org.assertj.core.description.TextDescription;
import org.assertj.db.common.AbstractTest;
import org.assertj.db.type.Table;
import org.junit.Test;

import java.lang.reflect.Field;

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

/**
 * Test on {@code Descriptable} interface methods.
 *
 * @author Régis Pouiller
 *
 */
public class Descriptable_Test extends AbstractTest {

  /**
   * This method tests the {@code as} method to modify the description.
   */
  @Test
  public void test_as() throws Exception {
    Field field = AbstractAssert.class.getDeclaredField("info");
    field.setAccessible(true);
    Table table = new Table(source, "actor");

    TableRowAssert assertion = assertThat(table).row();
    WritableAssertionInfo info1 = (WritableAssertionInfo) field.get(assertion);
    assertThat(info1.descriptionText()).isEqualTo("Row at index 0 of actor table");

    TableRowAssert assertion2 = assertion.as("message %s with text", 1);
    WritableAssertionInfo info2 = (WritableAssertionInfo) field.get(assertion2);
    assertThat(info2.descriptionText()).isEqualTo("message 1 with text");

    Description description = new TextDescription("description %s %s", "with", "information");
    TableRowAssert assertion3 = assertion.as(description);
    WritableAssertionInfo info3 = (WritableAssertionInfo) field.get(assertion3);
    assertThat(info3.descriptionText()).isEqualTo("description with information");
  }
}

Add test on Descriptable interface method


package com.secondthorn.solitaireplayer.solvers.tripeaks;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

/**
 * Prints out solutions for the random decks.
 */
public class RandomDeckSolutions {
    public static void main(String[] args) {
        List<String> lines;
        try {
            lines = readLinesFromFile("random-decks.txt");
        } catch (IOException | URISyntaxException ex) {
            ex.printStackTrace();
            return;
        }
        System.out.println("Board Challenge Solver");
        printSolutions(lines, new BoardChallengeSolver());
        System.out.println("Score Challenge Solver");
        printSolutions(lines, new ScoreChallengeSolver(ScoreChallengeSolver.MAX_POSSIBLE_SCORE, 0));
        System.out.println("Card Challenge Solver");
        printSolutions(lines, new CardChallengeSolver(12, 'A', 0));
    }

    private static void printSolutions(List<String> lines, TriPeaksSolver solver) {
        for (int i=0; i<lines.size(); i++) {
            Solution solution = solver.solve(new Deck(lines.get(i)), State.INITIAL_STATE);
            System.out.println(String.format("(%d \"%s\" %s)",
                    i+1, solution.getDescription(), actionsToCardList(solution.getActions())));
        }
    }

    private static List<String> readLinesFromFile(String filename) throws IOException, URISyntaxException {
        return Files.readAllLines(Paths.get(ClassLoader.getSystemResource(filename).toURI()));
    }

    private static String actionsToCardList(List<Action> actions) {
        StringBuilder sb = new StringBuilder();
        sb.append("(");
        for (Action action : actions) {
            switch (action.getCommand()) {
                case DRAW:
                case REMOVE:
                    sb.append("\"");
                    sb.append(action.getCard());
                    sb.append("\" ");
                    break;
                default:
                    throw new RuntimeException("Only DRAW or REMOVE should be in the solution for fully known decks");
            }
        }
        int lastIndex = sb.length() - 1;
        if (sb.charAt(lastIndex) == ' ') {
            sb.setCharAt(lastIndex, ')');
        } else {
            sb.append(")");
        }
        return sb.toString();
    }
}

Add a tester to play through random decks.


package gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc;

import static org.junit.Assert.*;
import gov.nih.nci.ncicb.cadsr.common.dto.DesignationTransferObjectExt;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/applicationContext.xml"})
public class JDBCDesignationDAOTest {

	@Autowired
	JDBCDesignationDAO designationV2Dao;

	@Before
	public void setUp() throws Exception {
	}

	@Test
	public void testCreateDesignationForComponent() {
		String formSeqid = "F4E8EEE7-2DDB-0476-E040-BB8921B676BA";
		String createdBy = "FORMLOADER";
		String contextSeqid = "29A8FB18-0AB1-11D6-A42F-0010A4C1E842"; //"test" context
		DesignationTransferObjectExt desig = new DesignationTransferObjectExt();
		desig.setLanguage("ENGLISH");
		desig.setName("SY Testing");
		desig.setType("ABBREVIATION");

		int res = designationV2Dao.createDesignationForComponent(formSeqid, contextSeqid, createdBy, desig);
		assertTrue(res == 1);
	}

}

Test class for the new JDBCDesignationDAO


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

import nom.bdezonia.zorbage.predicate.Predicate;
import nom.bdezonia.zorbage.type.algebra.Algebra;
import nom.bdezonia.zorbage.type.storage.datasource.IndexedDataSource;

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

	public static <T extends Algebra<T,U>, U>
		void compute(T alg, Predicate<U> cond, IndexedDataSource<U> a, IndexedDataSource<U> b)
	{
		throw new IllegalArgumentException("not written yet");
	}

}

Make a placeholder for an algorithm

Make a placeholder for an algorithm


package org.telegram.telegrambots.api.commands;

import org.telegram.telegrambots.bots.AbsSender;

/**
 * Representation of a command, which can be executed
 *
 * @author tschulz
 */
public abstract class Command extends AbsSender {

    public final static String COMMAND_INIT_CHARACTER = "/";
    public final static String COMMAND_PARAMETER_SEPERATOR = " ";
    private final static int COMMAND_MAX_LENGTH = 32;

    private final String commandIdentifier;
    private final String description;
    private final String botToken;

    /**
     * construct a command
     *
     * @param commandIdentifier the unique identifier of this command (e.g. the command string to enter into chat)
     * @param description       the description of this command
     */
    public Command(String commandIdentifier, String description, String botToken) {

        if (commandIdentifier == null || commandIdentifier.isEmpty()) {
            throw new IllegalArgumentException("commandIdentifier for command cannot be null or empty");
        }

        if (commandIdentifier.startsWith(COMMAND_INIT_CHARACTER)) {
            commandIdentifier = commandIdentifier.substring(1);
        }

        if (commandIdentifier.length() + 1 > COMMAND_MAX_LENGTH) {
            throw new IllegalArgumentException("commandIdentifier cannot be longer than " + COMMAND_MAX_LENGTH + " (including " + COMMAND_INIT_CHARACTER + ")");
        }

        this.commandIdentifier = commandIdentifier.toLowerCase();
        this.description = description;
        this.botToken = botToken;
    }

    /**
     * get the identifier of this command
     *
     * @return the identifier
     */
    public final String getCommandIdentifier() {
        return commandIdentifier;
    }

    /**
     * get the description of this command
     *
     * @return the description as String
     */
    public String getDescription() {
        return description;
    }

    @Override
    public String getBotToken() {
        return botToken;
    }

    /**
     * execute the command
     *
     * @param arguments passed arguments
     * @param chatId    id of the chat, to be able to send replies
     */
    abstract void execute(String[] arguments, long chatId);
}

Create and implement basic command

Create and implement basic command


package com.mongodb;

import org.testng.annotations.Test;

/**
 *  Tests aspect of the DB - not really driver tests
 */
public class DBTests {

    /**
     *   This test will fail now.  Waiting for fix in DB.  Originally done to show the
     *   effect of removing "seen" in DBApiLayer
     *
     * @throws Exception
     */
    @Test
    public void testConcurrentUpdate()  throws Exception {

        Mongo m = new Mongo("com_mongodb_DBTests");

        DBCollection coll = m.getCollection("concurrentUpdate");

        coll.drop();

        for (int i = 0; i < 10000; i++) {
            coll.insert(new BasicDBObject("i", i).append("flarg", "ASDASDASDASDASDA)DA_)ASD_)IASD_OJASD_)AS_D)IAS_D)IAS_D)IA_S)DIA_S)DIA_S)DIA_S)DIA_S)DIA_S)DIA_S)DIA_S)DIA_S)DIA_S)DIA_S)"));
        }
        int count = 0;

        DBCursor c = coll.find();

        while(c.hasNext()) {

            DBObject o = c.next();

            if (count++ == 0) {
                o.put("woog", "12-3012-30123-0123-012312312-0312-012-01-203-012-0psaoija-0sid-as0daoisasoidas=0dias=0diapsodjasd");
                coll.update(new BasicDBObject("_id", o.get("_id")), o, false, false);
            }
        }

        System.out.println(count);
        assert(count == 10000);
    }

}

Test (not part of regular run) that shows DB update-during-iteration bug


package org.pdxfinder.web;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .headers()
                .xssProtection();

    }

    @Component
    public class PdxFinderURLFilter implements Filter {

        @Override
        public void destroy() {}

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterchain)
                throws IOException, ServletException {

            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;

            System.out.println("Query String:"+request.getQueryString());
            System.out.println("Remote Address:"+request.getRequestURL().toString());

            System.out.println("Remote Address SANITIZED:"+sanitize(request.getQueryString()));

            if (request.getRequestURI().contains("JAX")){
                response.sendRedirect("http://localhost:8080/data/search");
            }else {
                filterchain.doFilter(servletRequest, servletResponse);
            }

        }

        @Override
        public void init(FilterConfig filterconfig) throws ServletException {

        }

        public String sanitize(String string) {

            return string
                    .replaceAll("(?i)<script.*?>.*?</script.*?>", "")   // script tags
                    .replaceAll("(?i)<.*?.*?>.*?</.*?>", "") // js calls
                    .replaceAll("(?i)<.*?\\s+on.*?>.*?</.*?>", "");     // remove "font-size:11.0pt" lang="EN-U

        }
    }

}

Fix Potential XSS vulnerabilities : Added Spring Security Headers and Custom URL Filter Component


/* (C) 2017 kagix
** Some code is heavily based on stackoverflow DOT com
*/
package net.kagix.gtfs.ratptools.buslinecolor;
import java.lang.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;

public class HistogramCalculator
{
	private HashMap<Integer,Integer> histogram = null;

	public HistogramCalculator(BufferedImage image) {

		if (image != null) {
			histogram = new HashMap<Integer,Integer>();
			calculateHistogram(image);
		}
	}

	public HashMap<Integer,Integer> getHistogram() {
		return histogram;
	}

	private int calculateKey(int[] rgb) {
		int key = rgb[Image.RED]   * Image.RED_SHIFT
			 +rgb[Image.GREEN] * Image.GREEN_SHIFT
			 +rgb[Image.BLUE]  * Image.BLUE_SHIFT;
		return key;
	}

	private void addOrIncrementKeyCount( int key) {

		if (!histogram.containsKey(key)) {
			histogram.put(key,0);
		}

		histogram.put(key,histogram.get(key)+1);
	}

	private void processPixel( int[] pixel) {
		int key = calculateKey(pixel);

		addOrIncrementKeyCount( key );
	}

	private void calculateHistogram(BufferedImage image) {
		for (int row = 0; row < image.getHeight(null); row++) {
			for (int column = 0; column <image.getWidth(null); column++) {

				int[] pixel = image.getRaster().getPixel( column,
									  row,
									  new int[3]);
				processPixel( pixel );
			}
		}
	}

	public int getRedValue(int key) {

		return (key & Image.RED_MASK) / Image.RED_SHIFT;
	}

	public int getGreenValue(int key) {

		return (key & Image.GREEN_MASK) / Image.GREEN_SHIFT;
	}

	public int getBlueValue(int key) {

		return (key & Image.BLUE_MASK) / Image.BLUE_SHIFT;
	}

	public String getHexValue(int key) {

		return String.format("%06X",key);
	}

}

Build a histogram of pixel color repetitions


/*
 * (C) Copyright 2016 Boni Garcia (http://bonigarcia.github.io/)
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 */
package io.github.bonigarcia.wdm.test;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.openqa.selenium.phantomjs.PhantomJSDriver;

import io.github.bonigarcia.wdm.PhantomJsDriverManager;
import io.github.bonigarcia.wdm.base.BaseBrowserTst;

/**
 * Test with PhatomJS.
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 1.4.0
 */
@Ignore
public class PhantomJsBetaTest extends BaseBrowserTst {

    @BeforeClass
    public static void setupClass() {
        PhantomJsDriverManager.getInstance().useBetaVersions().setup();
    }

    @Before
    public void setupTest() {
        driver = new PhantomJSDriver();
    }

}

Include PhantomJS test forcing beta versions


package com.example.rx;

import android.test.AndroidTestCase;

public class ComposeMessageTest extends AndroidTestCase {

    public void testComposeMessage() {
        assertTrue(true); // it works!
    }
}

Include dummy test case signal for CI

Include dummy test case signal for CI


package org.stepic.droid.util;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.DrawableRes;

import org.stepic.droid.R;

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

import javax.inject.Singleton;

@Singleton
public class StepTypeResolver {

    private Map<String, Drawable> mapFromTypeToDrawable;
    private Context mContext;

    public StepTypeResolver(Context context) {

        mapFromTypeToDrawable = new HashMap<>();

        mapFromTypeToDrawable.put("text", getDrawable(context, R.drawable.ic_theory));
        mapFromTypeToDrawable.put("video", getDrawable(context, R.drawable.ic_video));
        mapFromTypeToDrawable.put("matching", getDrawable(context, R.drawable.ic_matching));
        mapFromTypeToDrawable.put("sorting", getDrawable(context, R.drawable.ic_sorting));
        mapFromTypeToDrawable.put("match", getDrawable(context, R.drawable.ic_math));
        mapFromTypeToDrawable.put("free-answer", getDrawable(context, R.drawable.ic_free_answer));
        mapFromTypeToDrawable.put("table", getDrawable(context, R.drawable.ic_table));
        mapFromTypeToDrawable.put("string", getDrawable(context, R.drawable.ic_string));
        mapFromTypeToDrawable.put("choice", getDrawable(context, R.drawable.ic_choice));
        mapFromTypeToDrawable.put("number", getDrawable(context, R.drawable.ic_number));
        mapFromTypeToDrawable.put("dataset", getDrawable(context, R.drawable.ic_dataset));
        mapFromTypeToDrawable.put("animation", getDrawable(context, R.drawable.ic_animation));
        mapFromTypeToDrawable.put("chemical", getDrawable(context, R.drawable.ic_chemical));
        mapFromTypeToDrawable.put("fill-blanks", getDrawable(context, R.drawable.ic_fill_blanks));
        mapFromTypeToDrawable.put("puzzle", getDrawable(context, R.drawable.ic_puzzle));
        mapFromTypeToDrawable.put("pycharm", getDrawable(context, R.drawable.ic_pycharm));

    }

    public Drawable getDrawableForType(String type) {
        Drawable drawable = mapFromTypeToDrawable.get(type);
        if (drawable != null)
            return drawable;
        else
            return getDrawable(mContext, R.drawable.ic_theory);
    }

    private Drawable getDrawable(Context context, @DrawableRes int drawableRes) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return context.getDrawable(drawableRes);
        } else {
            return context.getResources().getDrawable(drawableRes);
        }
    }

}

Add resolver for drawable item for step

Add resolver for drawable item for step


package org.realityforge.arez.api2;

import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class GuardsTest
  extends AbstractArezTest
{
  @Test
  public void fail()
    throws Exception
  {
    final IllegalStateException exception =
      expectThrows( IllegalStateException.class, () -> Guards.fail( () -> "My Failure Reason" ) );

    assertEquals( exception.getMessage(), "My Failure Reason" );
  }

  @Test
  public void fail_verboseErrorMessages_false()
    throws Exception
  {
    final ArezConfig.DynamicProvider provider = (ArezConfig.DynamicProvider) ArezConfig.getProvider();
    provider.setVerboseErrorMessages( false );

    final IllegalStateException exception =
      expectThrows( IllegalStateException.class, () -> Guards.fail( () -> "My Failure Reason" ) );

    assertEquals( exception.getMessage(), null );
  }

  @Test
  public void fail_checkInvariants_false()
    throws Exception
  {
    final ArezConfig.DynamicProvider provider = (ArezConfig.DynamicProvider) ArezConfig.getProvider();
    provider.setCheckInvariants( false );

    // No failure
    Guards.fail( () -> "My Failure Reason" );
  }

  @Test
  public void invariant_passed()
    throws Exception
  {
    Guards.invariant( () -> true, () -> "My Failure Reason" );
  }

  @Test
  public void invariant_failed()
    throws Exception
  {
    final IllegalStateException exception =
      expectThrows( IllegalStateException.class, () -> Guards.invariant( () -> false, () -> "My Failure Reason" ) );

    assertEquals( exception.getMessage(), "My Failure Reason" );
  }

  @Test
  public void invariant_condition_throws_exception()
    throws Exception
  {
    final IllegalStateException exception =
      expectThrows( IllegalStateException.class, () -> Guards.invariant( () -> {
        throw new RuntimeException( "X" );
      }, () -> "My Failure Reason" ) );

    final String message = exception.getMessage();
    assertTrue( message.startsWith( "Error checking condition.\n" +
                                    "Message: My Failure Reason\n" +
                                    "Throwable:\n" +
                                    "java.lang.RuntimeException: X" ) );
  }

  @Test
  public void invariant_verboseErrorMessages_false()
    throws Exception
  {
    final ArezConfig.DynamicProvider provider = (ArezConfig.DynamicProvider) ArezConfig.getProvider();
    provider.setVerboseErrorMessages( false );

    final IllegalStateException exception =
      expectThrows( IllegalStateException.class, () -> Guards.invariant( () -> false, () -> "My Failure Reason" ) );

    assertEquals( exception.getMessage(), null );
  }

  @Test
  public void invariant_checkInvariants_false()
    throws Exception
  {
    final ArezConfig.DynamicProvider provider = (ArezConfig.DynamicProvider) ArezConfig.getProvider();
    provider.setCheckInvariants( false );

    // No failure
    Guards.invariant( () -> false, () -> "My Failure Reason" );
  }
}

Add some tests for guards code

Add some tests for guards code


package org.graphstream.gama.extension.sender;

import msi.gama.precompiler.ISymbolKind;
import msi.gama.precompiler.GamlAnnotations.inside;
import msi.gama.precompiler.GamlAnnotations.symbol;
import msi.gama.runtime.IScope;
import msi.gama.runtime.exceptions.GamaRuntimeException;
import msi.gaml.descriptions.IDescription;
import msi.gaml.statements.AbstractStatement;
import msi.gaml.statements.IStatement;

import org.graphstream.gama.extension.GSManager;
import org.graphstream.gama.extension.IKeywordGSAdditional;

@symbol(name = IKeywordGSAdditional.CLEAR_SENDERS, kind = ISymbolKind.SINGLE_STATEMENT, with_sequence = false)
@inside(kinds = { ISymbolKind.BEHAVIOR, ISymbolKind.SINGLE_STATEMENT })
public class ClearSendersStatement extends AbstractStatement implements IStatement{

	public ClearSendersStatement(IDescription desc) {
		super(desc);
	}

	@Override
	protected Object privateExecuteIn(IScope scope) throws GamaRuntimeException {
		GSManager.clearSenders();
		return null;
	}

}

Add the 'clear senders' command

Add the 'clear senders' command


// Copyright 2008 Thiago H. de Paula Figueiredo
//
// 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 br.com.arsmachina.authentication.entity;

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

import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * Test class for {@link User}.
 *
 * @author Thiago H. de Paula Figueiredo (ThiagoHP)
 */
public class UserTest {

	@Test
	public void getRoles() {

		User user = new User();
		user.setName("Test");

		new ArrayList<Permission>();

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

			final PermissionGroup group = new PermissionGroup();
			group.setName("Group " + i);
			user.getPermissionGroups().add(group);

		}

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

			final Permission permission = new Permission();
			permission.setName("ROLE_" + i);

			user.getPermissionGroups().get(i % 2).getPermissions().add(permission);

			if (i % 4 == 0) {
				user.getRemovedPermissions().add(permission);
			}

		}

		List<Permission> permissions = user.getPermissions();

		Assert.assertEquals(permissions.size(), 6);

		for (Permission permission : permissions) {

			Assert.assertFalse(permission.getName().equals("ROLE_0"));
			Assert.assertFalse(permission.getName().equals("ROLE_4"));

		}

	}

}

Package change: from net.sf.arsmachina to br.com.arsmachina.


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

import static org.junit.Assert.assertEquals;

import java.math.BigInteger;

import org.junit.Test;

import nom.bdezonia.zorbage.tuple.Tuple2;
import nom.bdezonia.zorbage.type.data.rational.RationalMember;
import nom.bdezonia.zorbage.type.data.unbounded.UnboundedIntMember;

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

	@Test
	public void test1() {
		RationalMember value = new RationalMember(new UnboundedIntMember(14));
		Tuple2<BigInteger,BigInteger> tuple = new Tuple2<BigInteger,BigInteger>(null,null);
		SplatRational.toTuple(value, tuple);
		assertEquals(BigInteger.valueOf(14), tuple.a());
		assertEquals(BigInteger.valueOf(1), tuple.b());
	}

	@Test
	public void test2() {
		Tuple2<BigInteger,BigInteger> tuple = new Tuple2<BigInteger,BigInteger>(BigInteger.valueOf(7),BigInteger.valueOf(14));
		RationalMember value = new RationalMember();
		SplatRational.toValue(tuple, value);
		assertEquals(BigInteger.valueOf(1), value.n());
		assertEquals(BigInteger.valueOf(2), value.d());
	}
}

Define tests for the SpatRational algorithm


package org.cyclops.cyclopscore.helper;

import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.IBlockState;
import net.minecraftforge.common.property.IExtendedBlockState;
import net.minecraftforge.common.property.IUnlistedProperty;

import javax.annotation.Nullable;

/**
 * Contains helper methods for various block specific things.
 * @author rubensworks
 */
public final class BlockHelpers {

    /**
     * Safely get a block state property for a nullable state and value that may not have been set yet.
     * @param state The block state.
     * @param property The property to get the value for.
     * @param fallback The fallback value when something has failed.
     * @param <T> The type of value to fetch.
     * @return The value.
     */
    public static <T> T getSafeBlockStateProperty(@Nullable IBlockState state, IProperty property, T fallback) {
        Comparable value = state.getValue(property);
        if(value == null) {
            return fallback;
        }
        return (T) value;
    }

    /**
     * Safely get an extended block state property for a nullable state and value that may not have been set yet.
     * @param state The block state.
     * @param property The property to get the value for.
     * @param fallback The fallback value when something has failed.
     * @param <T> The type of value to fetch.
     * @return The value.
     */
    public static <T> T getSafeBlockStateProperty(@Nullable IExtendedBlockState state, IUnlistedProperty<T> property,
                                                  T fallback) {
        if(state == null) {
            return fallback;
        }
        T value = state.getValue(property);
        if(value == null) {
            return fallback;
        }
        return value;
    }

}

Add BlockState property value retrieval helpers


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

package org.apache.jmeter.resources;

import java.io.File;
import java.io.FileInputStream;
import java.util.Enumeration;
import java.util.Properties;

import org.apache.jmeter.junit.JMeterTestCaseJUnit3;
import org.apache.jmeter.util.JMeterUtils;

public class TestPropertiesFiles extends JMeterTestCaseJUnit3 {

    public void testUserProperties() throws Exception {
        Properties props = loadProps(new File(JMeterUtils.getJMeterBinDir(), "user.properties"));
        assertTrue("user.properties should not contain any enabled properties", props.isEmpty());
    }

    // The keys in jmeter.properties and reportgenerator.properties should be distinct
    public void testDefaultProperties() throws Exception {
        Properties jmeter = loadProps(new File(JMeterUtils.getJMeterBinDir(), "jmeter.properties"));
        Properties report = loadProps(new File(JMeterUtils.getJMeterBinDir(), "reportgenerator.properties"));
        {
            Enumeration<?> names = jmeter.propertyNames();
            while(names.hasMoreElements()) {
                final Object key = names.nextElement();
                assertFalse("reportgenerator should not contain the jmeter key " + key, report.containsKey(key));
            }
        }
        {
            Enumeration<?> names = report.propertyNames();
            while(names.hasMoreElements()) {
                final Object key = names.nextElement();
                assertFalse("jmeter should not contain the reportgenerator key " + key, jmeter.containsKey(key));
            }
        }
    }

    private static Properties loadProps(File file) throws Exception{
        Properties props = new Properties();
        try (FileInputStream inStream = new FileInputStream(file)){
            props.load(inStream);
        }
        return props;
    }
}

Add tests for properties files

Add tests for properties files

git-svn-id: https://svn.apache.org/repos/asf/jmeter/trunk@1742704 13f79535-47bb-0310-9956-ffa450edef68

Former-commit-id: 246862e7f64beade199629caba4eb1c116d56d4e


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

public class Solution {

    private int sum = 0;

    public TreeNode convertBST(TreeNode root) {

        if (root == null) {
            return null;
        }

        convertBST(root.right);

        root.val += sum;
        sum = root.val;

        convertBST(root.left);

        return root;

    }

}

Create : 538 Convert BST to Greater Tree


/*
 * Copyright 2002-2018 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.security.oauth2.client.web.reactive.function.client;

import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.function.Consumer;

/**
 * @author Rob Winch
 * @since 5.1
 */
public final class OAuth2ExchangeFilterFunctions {

	/**
	 * Configures the WebClient for OAuth2 support in a servlet environment.
	 * @param repository the repository to use
	 * @return the {@link Consumer} to configure the WebClient
	 */
	public static Consumer<WebClient.Builder> oauth2ServletConfig(OAuth2AuthorizedClientRepository repository) {
		return new ServletOAuth2AuthorizedClientExchangeFilterFunction(repository)
				.oauth2Configuration();
	}

	/**
	 * Configures the WebClient for OAuth2 support in a servlet environment.
	 * @return the {@link Consumer} to configure the WebClient
	 */
	public static Consumer<WebClient.Builder> oauth2ServletConfig() {
		return new ServletOAuth2AuthorizedClientExchangeFilterFunction()
				.oauth2Configuration();
	}

	private OAuth2ExchangeFilterFunctions() {}
}

Add static methods for ServletOAuth2AuthorizedClientExchangeFilterFunction

This will allow us to break up
ServletOAuth2AuthorizedClientExchangeFilterFunction into multiple
components if we decide to later.

Issue: gh-5545


package cs437.som.learningrate;

import cs437.som.LearningRateFunction;

/**
 * Learning rate strategy for self-organizing maps that decays the learning
 * rate exponentially as the iterations progress.
 *
 * <pre>
 * The exact behavior follows the formula:
 *      \alpha_0 * e^(-t / t_{max})
 *  where
 *      \alpha_0 is the initial learning rate
 *      e        is the base of the natural logarithm
 *      t        is the current iteration
 *      t_{max}  is the maximum expected iteration
 * </pre>
 */
public class ExponentialDecayLearningRateFunction implements LearningRateFunction {
    private final double initialLearningRate;
    private double expectedIterations = 0.0;

    /**
     * Create an exponentially decaying learning rate function.
     *
     * @param initialWidth The initial learning rate.
     */
    public ExponentialDecayLearningRateFunction(double initialWidth) {
        initialLearningRate = initialWidth;
    }

    public void setExpectedIterations(int expectedIterations) {
        this.expectedIterations = expectedIterations;
    }

    public double learningRate(int iteration) {
        return initialLearningRate * Math.exp(-iteration / expectedIterations);
    }

    @Override
    public String toString() {
        return "ExponentialDecayLearningRateFunction";
    }
}

Add exponential decay learning rate.

Add exponential decay learning rate.


/*
 * Electronic Logistics Management Information System (eLMIS) is a supply chain management system for health commodities in a developing country setting.
 *
 * Copyright (C) 2015  John Snow, Inc (JSI). This program was produced for the U.S. Agency for International Development (USAID). It was prepared under the USAID | DELIVER PROJECT, Task Order 4.
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.openlmis.vaccine.domain.inventory;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.openlmis.core.domain.BaseModel;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class AdjustmentReason extends BaseModel {
    private Long lotOnHandId;
    private String name;
    private Long quantity;
}

Add Adjustment Reason to save

Add Adjustment Reason to save