package galileo.stat;

/**
 * Expanding on the {@link RunningStatistics} class, this class supports
 * two dimensions (x and y), along with some extra features (simple linear
 * regression and calculating correlation).
 *
 * @author malensek
 */
public class RunningStatistics2D {

    private RunningStatistics xs;
    private RunningStatistics ys;

    private double SSxy;

    public RunningStatistics2D() {
        xs = new RunningStatistics();
        ys = new RunningStatistics();
    }

    /**
     * Adds several new (x, y) sample pairs to the 2D running statistics.
     *
     * @param samples Array of two-element arrays (representing x and y)
     */
    public void put(double[]... samples) {
        for (double[] sample : samples) {
            if (sample.length != 2) {
                throw new IllegalArgumentException("Input arrays must contain "
                        + "a single sample pair (x, y)");
            }
            put(sample[0], sample[1]);
        }
    }

    /**
     * Adds a new sample to the 2D running statistics.
     */
    public void put(double x, double y) {
        double n = (double) xs.numSamples();

        double dx = x - xs.mean();
        double dy = y - ys.mean();
        SSxy += dx * dy * n / (n + 1);

        xs.put(x);
        ys.put(y);
    }

    /**
     * @return Sum of the cross products (xy)
     */
    public double SSxy() {
        return SSxy;
    }

    /**
     * @return Sum of squared deviations from the mean of x
     */
    public double SSxx() {
        return xs.var() * (xs.numSamples() - 1.0);
    }

    /**
     * @return Sum of squared deviations from the mean of y
     */
    public double SSyy() {
        return ys.var() * (xs.numSamples() - 1.0);
    }

    /**
     * Calculate the Pearson product-moment correlation coefficient.
     *
     * @return PPMCC (Pearson's r)
     */
    public double R() {
        return Math.sqrt(R2());
    }

    /**
     * Calculate the coefficient of determination (R squared).
     *
     * @return coefficient of determination
     */
    public double R2() {
        double SSE = (SSyy() - SSxy() * SSxy() / SSxx());
        return (SSyy() - SSE) / SSyy();
    }

    /**
     * @return the slope of the regression line (beta).
     */
    public double slope() {
        return SSxy() / SSxx();
    }

    /**
     * @return the y-intercept of the regression line (alpha).
     */
    public double intercept() {
        return ys.mean() - slope() * xs.mean();
    }

    /**
     * Given a value of x, estimate the outcome of y using simple linear
     * regression.
     *
     * @return estimated value of y
     */
    public double predict(double x) {
        return intercept() + slope() * x;
    }

    /**
     * @return a copy of the running statistics instance for x.
     */
    public RunningStatistics xStatistics() {
        return new RunningStatistics(xs);
    }

    /**
     * @return a copy of the running statistics instance for y.
     */
    public RunningStatistics yStatistics() {
        return new RunningStatistics(ys);
    }
}

Add 2D running stats class


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

package org.scijava.log;

/**
 * Interface for the objects which want to log their activities.
 *
 * @author Curtis Rueden
 */
public interface Logged {

	/** Gets the {@link LogService} to use when logging activities. */
	LogService log();
}

Add a common interface for objects that do logging


/*
 * Licensed to the University of California, Berkeley 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 tachyon.client.keyvalue;

import java.io.IOException;

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;

import tachyon.Constants;
import tachyon.LocalTachyonClusterResource;
import tachyon.TachyonURI;
import tachyon.client.file.TachyonFileSystem;
import tachyon.exception.TachyonException;
import tachyon.util.io.PathUtils;

/**
 * Integration tests for {@link KeyValueFileWriter}
 */
public final class KeyValueFileIntegrationTest {
  private static final int BLOCK_SIZE = 512 * Constants.MB;
  private static final byte[] KEY1 = "key1".getBytes();
  private static final byte[] KEY2 = "key2_foo".getBytes();
  private static final byte[] VALUE1 = "value1".getBytes();
  private static final byte[] VALUE2 = "value2_bar".getBytes();
  private static TachyonFileSystem sTfs;
  private KeyValueFileWriter mKeyValueFileWriter;
  private KeyValueFileReader mKeyValueFileReader;

  @ClassRule
  public static LocalTachyonClusterResource sLocalTachyonClusterResource =
      new LocalTachyonClusterResource(Constants.GB, Constants.KB, BLOCK_SIZE);

  @BeforeClass
  public static void beforeClass() throws Exception {
    sTfs = sLocalTachyonClusterResource.get().getClient();
  }

  @Test
  public void readerWriterTest() throws IOException, TachyonException {
    String uniqPath = PathUtils.uniqPath();
    TachyonURI uri = new TachyonURI(uniqPath);
    mKeyValueFileWriter = KeyValueFileWriter.Factory.create(uri);
    mKeyValueFileWriter.put(KEY1, VALUE1);
    mKeyValueFileWriter.put(KEY2, VALUE2);
    mKeyValueFileWriter.close();
    // Expect the key-value file exists
    Assert.assertNotNull(sTfs.openIfExists(uri));
    mKeyValueFileReader = KeyValueFileReader.Factory.create(uri);
    Assert.assertArrayEquals(VALUE1, mKeyValueFileReader.get(KEY1));
    Assert.assertArrayEquals(VALUE2, mKeyValueFileReader.get(KEY2));
    Assert.assertNull(mKeyValueFileReader.get("NoSuchKey".getBytes()));
  }
}

Add an integration tests for KeyValueFile Reader and Writer


package net.kencochrane.raven.sentrystub;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.ByteArrayInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@WebListener
public class SentryUdpContextListener implements ServletContextListener {
    private static final int DEFAULT_SENTRY_UDP_PORT = 9001;
    private static final String SENTRY_UDP_PORT_PARAMETER = "sentryUdpPort";
    private ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    private DatagramSocket udpSocket;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        String sentryUdpPortParameter = sce.getServletContext().getInitParameter(SENTRY_UDP_PORT_PARAMETER);
        int port = DEFAULT_SENTRY_UDP_PORT;
        if (sentryUdpPortParameter != null)
            port = Integer.parseInt(sentryUdpPortParameter);
        try {
            udpSocket = new DatagramSocket(port);
            new UdpListenerThread().start();
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        executorService.shutdownNow();
        udpSocket.close();
    }

    private static class UdpRequestHandler implements Runnable {
        private final DatagramPacket datagramPacket;

        private UdpRequestHandler(DatagramPacket datagramPacket) {
            this.datagramPacket = datagramPacket;
        }

        @Override
        public void run() {
            try {
                ByteArrayInputStream bais = new ByteArrayInputStream(datagramPacket.getData(),
                        datagramPacket.getOffset(),
                        datagramPacket.getLength());
                //TODO extract the AUTH header validate it, send the rest to the JSon validator
            } catch (Exception e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
    }

    private class UdpListenerThread extends Thread {
        @Override
        public void run() {
            while (!udpSocket.isClosed()) {
                try {
                    // We'll assume that no-one sends a > 65KB datagram (max size allowed on IPV4).
                    byte[] buffer = new byte[1 << 16];
                    DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length);
                    udpSocket.receive(datagramPacket);
                } catch (Exception e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
        }
    }
}

Add a listener starting a UDP socket


package edu.uw.apl.tupelo.model;

import java.io.File;
import java.io.InputStream;

import org.apache.commons.io.input.CountingInputStream;

/**
 * Testing aspects of reading data from a PhysicalDisk. Warning, these
 * tests can read a LOT of data, 100GB+, so can take tens of minutes.
 * We really want a Maven profile (in additon to tester) that says
 * 'Yes I really want to run these lengthy (read slow!) tests
 */
public class ReadTest extends junit.framework.TestCase {

	public void testNull() {
	}

	/**
	   Testing that we really can read as many bytes as the disk's
	   advertised size. Note that 250GB took 40+ mins to read, on
	   rejewski.

	   Running edu.uw.apl.tupelo.model.ReadTest
	   Expected: 250000000000
	   Actual: 250000000000

	   [INFO] ---------------------------------------------------------
	   [INFO] BUILD SUCCESS
	   [INFO] ---------------------------------------------------------
	   [INFO] Total time: 41:16.609s
	   [INFO] Finished at: Thu Nov 13 12:54:53 PST 2014
	   [INFO] Final Memory: 14M/170M
	   [INFO] ---------------------------------------------------------
	*/
	public void _testAdvertisedSize() throws Exception {
		File f = new File( "/dev/sda" );
		if( !f.canRead() )
			return;
		PhysicalDisk pd = new PhysicalDisk( f );
		long expected = pd.size();
		System.out.println( "Expected: " + expected );
		byte[] ba = new byte[1024*1024];
		InputStream is = pd.getInputStream();
		CountingInputStream cis = new CountingInputStream( is );
		int nin = 0;
		while( (nin = cis.read( ba )) != -1 )
			;
		cis.close();
		long actual = cis.getByteCount();
		System.out.println( "Actual: " + actual );
		assertEquals( expected, actual );
	}
}

// eof

Verify physical disk read byte count matches advertised size


package no.ntnu.capgeminitest.binding.android;

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

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

import no.ntnu.capgeminitest.binding.android.propertyprovider.PropertyProviderFactory;
import no.ntnu.capgeminitest.data.Property;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;

import com.xtremelabs.robolectric.RobolectricTestRunner;

@RunWith(RobolectricTestRunner.class)
public class BindingFactoryTest {

    public class FakeViewFactory implements BindingFactory.ViewFactory {
        View view;

        public FakeViewFactory(View view) {
            this.view = view;
        }

        @Override
        public final View createView(String unusedName, String unusedPrefix,
                AttributeSet unusedAttr) {
            return view;
        }
    }

    public class TestBindingFactory extends BindingFactory {
        TestBindingFactory(PropertyProviderFactory propertyProviderFactory,
                ViewFactory viewFactory) {
            super(propertyProviderFactory, viewFactory);
        }

        @Override
        protected Map<String, String> getBindingAttrs(AttributeSet unused) {
            Map<String, String> bindingAttrs = new HashMap<String, String>();
            bindingAttrs.put("OnClickTo", "OnClickToTarget");
            return bindingAttrs;
        }
    }

    private View view;
    private FakeViewFactory viewFactory;
    private TestBindingFactory bindingFactory;

    @Before
    public void setUp() {
        view = new View(null);
        viewFactory = new FakeViewFactory(view);
        bindingFactory = new TestBindingFactory(PropertyProviderFactory.getDefaultFactory(),
                viewFactory);
    }

    @Test
    public void testOnClickProperty() {
        bindingFactory.onCreateView("View", null, null);
        Property<?> onClickProperty = bindingFactory.getBoundProperties()
                .get("OnClickToTarget");
        Object object1 = onClickProperty.get();
        view.performClick();
        assertThat(onClickProperty.get(), not(equalTo(object1)));
    }
}

Add unit test of BindingFactory.


/**
 * @file IdentifyMyParts.java
 * @author Valery Samovich
 * @version 1
 * @date 2015/01/14
 */

package com.samovich.java.basics.concepts.objects.exercises;

public class IdentifyMyParts {

    public static int x = 7;
    public int y = 3;

}

Add Class and Instance Variables.


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


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

package org.openmhealth.shimmer.common.domain;

import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriTemplate;

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

/**
 * A builder that constructs a {@link RequestEntity}.
 *
 * @author Emerson Farrugia
 * @author Chris Schaefbauer
 */
public class RequestEntityBuilder {

    private UriTemplate uriTemplate;
    private HttpMethod httpMethod = HttpMethod.GET;
    private MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    private MultiValueMap<String, String> queryParameters = new LinkedMultiValueMap<>();

    /**
     * @param uriTemplate the request entity URI as a template
     */
    public RequestEntityBuilder(UriTemplate uriTemplate) {

        checkNotNull(uriTemplate);

        this.uriTemplate = uriTemplate;
    }

    /**
     * @return the request entity URI as a template
     */
    public UriTemplate getUriTemplate() {
        return uriTemplate;
    }

    /**
     * @return the method to use to exchange the request entity
     */
    public HttpMethod getHttpMethod() {
        return httpMethod;
    }

    public void setHttpMethod(HttpMethod httpMethod) {

        checkNotNull(httpMethod);

        this.httpMethod = httpMethod;
    }

    /**
     * @param name the name of the header to add
     * @param value the value of the header
     */
    public void addHeader(String name, String value) {

        addToMultiValueMap(headers, name, value);
    }

    /**
     * @param name the name of the query parameter to add
     * @param value the value of the parameter
     */
    public void addQueryParameter(String name, String value) {

        addToMultiValueMap(queryParameters, name, value);
    }

    private void addToMultiValueMap(MultiValueMap<String, String> map, String key, String value) {

        checkNotNull(key);
        checkArgument(!key.isEmpty());
        checkNotNull(value);
        checkArgument(!value.isEmpty());

        map.add(key, value);
    }

    /**
     * @return the request entity
     */
    public RequestEntity<?> build() {

        // FIXME implement me
        return null;
    }
}

Add a skeletal request entity builder


package uk.ac.ebi.quickgo.ontology.model;

import javax.validation.Validator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;

/**
 * Check the operation of the java.validation.constraints for the GraphRepresentation class.
 * @author Tony Wardell
 * Date: 19/02/2018
 * Time: 11:10
 * Created with IntelliJ IDEA.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = GraphRequestValidationIT.GraphRequestValidationConfig.class)
public class GraphRequestValidationIT {

    static class GraphRequestValidationConfig {

        @Bean
        Validator validator() {
            return new LocalValidatorFactoryBean();
        }
    }

    @Autowired
    private Validator validator;

    private GraphRequest graphRequest;

    @Before
    public void setUp() {
        graphRequest = new GraphRequest();
    }

    @Test
    public void termBoxHeightMinimum1() {
        graphRequest.setTermBoxHeight(1);

        assertThat(validator.validate(graphRequest), hasSize(0));
    }

    @Test
    public void termBoxHeightCannotBeZero() {
        graphRequest.setTermBoxHeight(0);

        assertThat(validator.validate(graphRequest), hasSize(1));
    }

    @Test
    public void termBoxHeightCannotBeLessThan1() {
        graphRequest.setTermBoxHeight(-1);

        assertThat(validator.validate(graphRequest), hasSize(1));
    }

    @Test
    public void termBoxWidthMinimum1() {
        graphRequest.setTermBoxWidth(1);

        assertThat(validator.validate(graphRequest), hasSize(0));
    }

    @Test
    public void termBoxWidthCannotBeZero() {
        graphRequest.setTermBoxWidth(0);

        assertThat(validator.validate(graphRequest), hasSize(1));
    }

    @Test
    public void termBoxWidthCannotBeLessThan1() {
        graphRequest.setTermBoxWidth(-1);

        assertThat(validator.validate(graphRequest), hasSize(1));
    }
}


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

package io.michaelrocks.lightsaber.internal;

import io.michaelrocks.lightsaber.Injector;

import javax.inject.Provider;

public interface InjectingProvider<T> extends Provider<T> {
  T getWithInjector(Injector injector);
}

Create an interface for providers that support injection


// 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.cloudstack.acl.entity;

import java.util.List;

import org.apache.log4j.Logger;

import org.apache.cloudstack.acl.AclEntityType;
import org.apache.cloudstack.acl.QueryChecker;

import com.cloud.user.Account;
import com.cloud.utils.component.AdapterBase;

public class RoleBasedEntityQueryChecker extends AdapterBase implements QueryChecker {

    private static final Logger s_logger = Logger.getLogger(RoleBasedEntityQueryChecker.class.getName());

    @Override
    public List<Long> getAuthorizedDomains(Account caller, AclEntityType entityType) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<Long> getAuthorizedAccounts(Account caller, AclEntityType entityType) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<Long> getAuthorizedResources(Account caller, AclEntityType entityType) {
        // TODO Auto-generated method stub
        return null;
    }

}

Add QueryChecker adapter implementation skeleton.


package se.raddo.raddose3D;

import java.util.List;

public class CoefCalcFromSequenceSAXS extends CoefCalcCompute {
  /**
   * Right angle.
   */
  protected static final double RIGHT_ANGLE = 90;

  /**
   * Default unit cell dimension
   */
  private static final double   UNIT_CELL_LENGTH = 1000;

  /**
   * Average molecular mass of an amino acid (daltons = grams/mole)
   */
  private static final double   AVG_RESIDUE_MASS = 110;

  /**
   * Conversion factor to convert Angstroms^3 to litres
   */
  private static final double   ANGSTROM_TO_LITRE_VOLUME_CONVERSION = 1e-27;

  public CoefCalcFromSequenceSAXS(Double cellA, Double cellB, Double cellC,
      Double cellAlpha, Double cellBeta, Double cellGamma,
      List<String> heavyProteinAtomNames, List<Double> heavyProteinAtomNums,
      List<String> heavySolutionConcNames, List<Double> heavySolutionConcNums,
      Double solFrac, Double solventFraction, String sequenceFile) {

    /**
     * Create local variables for the unit cell parameters.
     * These don't have to be given in the input file for this module.
     * If these values are null then give suitable defaults.
     */
    Double a = cellA;
    Double b = cellB;
    Double c = cellC;
    Double alpha = cellAlpha;
    Double beta = cellBeta;
    Double gamma = cellGamma;

    if (alpha == null) {
      alpha = RIGHT_ANGLE;
    }
    if (beta == null) {
      beta = RIGHT_ANGLE;
    }
    if (gamma == null) {
      gamma = RIGHT_ANGLE;
    }
    if (a == null) {
      a = UNIT_CELL_LENGTH;
    }
    if (b == null) {
      b = UNIT_CELL_LENGTH;
    }
    if (c == null) {
      c = UNIT_CELL_LENGTH;
    }

    //Set local variable solvent fraction to minus 1
    Double sf = -1.0;

    //If actual solvent fraction is given then set the local variable
    //sf equal to the actual solvent fraction
    if (solventFraction != null) {
      sf = solventFraction;
    }

    //Calculate the Unit Cell Volume
    //This method exists in CoefCalcCompute Class
    double unitCellVolume = cellVolume(a, b, c, alpha, beta, gamma);

  }

}

Create a module to allow for sequence input with SAXS data. This module is unfinished


// Use XOR to encode and decode a message.
class Encode {
	public static void main(String args[]) {
		String msg = "This is a test";
		String encmsg = "";
		String decmsg = "";
		int key = 88;

		System.out.print("Original message: ");
		System.out.println(msg);

		// encode the message
		for(int i=0; i < msg.length(); i++)
			encmsg = encmsg + (char) (msg.charAt(i) ^ key);

		System.out.print("Encoded message: ");
		System.out.println(encmsg);

		// decode the message
		for(int i=0; i < msg.length(); i++)
			decmsg = decmsg + (char) (encmsg.charAt(i) ^ key);

		System.out.print("Decoded message: ");
		System.out.println(decmsg);
	}
}

Use XOR to encode and decode a message


package io.muoncore.protocol.reactivestream.server;

import io.muoncore.channel.ChannelConnection;

/*
 * workaround for inability to directly invoke lambdas from groovy without the dynamic coercion
 *
 * When performing spock argument capture, the actual lambda appears in a groovy context.
 *
 * Requiring this shim be used to convert and invoke in java.
 */
public class ChannelFunctionExecShimBecauseGroovyCantCallLambda {

    private ChannelConnection.ChannelFunction function;

    public ChannelFunctionExecShimBecauseGroovyCantCallLambda(ChannelConnection.ChannelFunction func) {
        this.function = func;
    }

    public void call(Object arg) {
        function.apply(arg);
    }
}

Test helpder needs to behere too.


package com.github.vbauer.caesar.callback;

import com.github.vbauer.caesar.basic.BasicTest;
import org.junit.Assert;
import org.junit.Test;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author Vladislav Bauer
 */

public class FutureCallbackAdapterTest extends BasicTest {

    @Test
    public void testCallback() {
        final AtomicBoolean onSuccess = new AtomicBoolean(false);
        final AtomicBoolean onFailure = new AtomicBoolean(false);

        final FutureCallbackAdapter<Object> callback = new FutureCallbackAdapter<Object>() {
            @Override
            public void onSuccess(final Object result) {
                super.onSuccess(result);
                onSuccess.set(true);
            }

            @Override
            public void onFailure(final Throwable caught) {
                super.onFailure(caught);
                onFailure.set(true);
            }
        };

        callback.onSuccess(null);
        callback.onFailure(null);

        Assert.assertTrue(onSuccess.get());
        Assert.assertTrue(onFailure.get());
    }

}

Add unit tests for FutureCallbackAdapter


package org.bouncycastle.openpgp.test;

import org.bouncycastle.bcpg.ArmoredOutputStream;
import org.bouncycastle.util.test.SimpleTest;

import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;

public class ArmoredOutputStreamUTF8Test extends SimpleTest {

    private static final Charset utf8 = Charset.forName("UTF8");

    public static void main(String[] args) {
        runTest(new ArmoredOutputStreamUTF8Test());
    }

    @Override
    public String getName() {
        return ArmoredOutputStreamUTF8Test.class.getSimpleName();
    }

    @Override
    public void performTest() throws Exception {
        String utf8WithUmlauts = "ÄÖÜß&Umlauts";

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ArmoredOutputStream armorOut = new ArmoredOutputStream(out);
        armorOut.setHeader("Comment", utf8WithUmlauts);

        armorOut.write("Foo\nBar".getBytes(utf8));

        armorOut.close();

        String armoredOutput = out.toString();
        String[] lines = armoredOutput.split("\n");
        String comment = null;
        for (String line : lines) {
            if (line.startsWith("Comment: ")) {
                comment = line.substring("Comment: ".length());
                break;
            }
        }

        isTrue("We did not find the comment line. This MUST never happen.", comment != null);
        isEquals("Comment was not properly encoded. Expected: "  +utf8WithUmlauts + ", Actual: " + comment, comment, utf8WithUmlauts);
    }
}

Add test for UTF8 encoding issues in ASCII armor


/*
 * Copyright 2016 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.gradle.test.fixtures;

import org.gradle.internal.UncheckedException;
import org.gradle.internal.io.ClassLoaderObjectInputStream;
import org.gradle.internal.io.NullOutputStream;
import org.gradle.internal.io.StreamByteBuffer;

import java.io.ObjectOutputStream;

public class SerializationFixture {
    public static void assertSerializable(Object obj) {
        try {
            ObjectOutputStream out = new ObjectOutputStream(NullOutputStream.INSTANCE);
            out.writeObject(obj);
            out.close();
        } catch (Exception e) {
            throw UncheckedException.throwAsUncheckedException(e);
        }
    }

    public static <T> T serializationRoundtrip(T obj) {
        try {
            StreamByteBuffer buffer = new StreamByteBuffer();
            ObjectOutputStream out = new ObjectOutputStream(buffer.getOutputStream());
            out.writeObject(obj);
            out.close();
            ClassLoaderObjectInputStream input = new ClassLoaderObjectInputStream(buffer.getInputStream(), obj.getClass().getClassLoader());
            return (T) input.readObject();
        } catch (Exception e) {
            throw UncheckedException.throwAsUncheckedException(e);
        }
    }
}

Add test fixture for testing serialization


// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.http.ssl;

import org.eclipse.jetty.util.ssl.SslContextFactory;

/**
 * A dummy implementation of {@link SslContextFactoryProvider} to be injected into non-ssl connectors
 *
 * @author bjorncs
 */
public class ThrowingSslContextFactoryProvider implements SslContextFactoryProvider {
    @Override
    public SslContextFactory getInstance(String containerId, int port) {
        throw new UnsupportedOperationException();
    }
}

Add dummy implementation of SslContextFactoryProvider


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

package org.musicbrainz.search.solrwriter.moxy;

import org.musicbrainz.mmd2.Gender;

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

public class StringGenderAdapter extends XmlAdapter<String, Gender> {

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

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

}

Fix json artist gender output


package com.episode6.hackit.mockspresso.reflect;

import com.episode6.hackit.mockspresso.DefaultTestRunner;
import com.episode6.hackit.mockspresso.annotation.TestQualifierAnnotation;
import org.junit.Test;
import org.junit.runner.RunWith;

import javax.inject.Named;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

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

/**
 * Some basic tests for {@link AnnotationLiteral}
 * I'm not too worried about testing that code since we didn't write it, but
 * felt that some basic sanity checking was appropriate.
 */
@RunWith(DefaultTestRunner.class)
public class AnnotationLiteralTest {

  public static abstract class TestNamedAnnotationLiteral extends AnnotationLiteral<Named> implements Named {}
  public static class TestQualifierAnnotationLiteral extends AnnotationLiteral<TestQualifierAnnotation> implements TestQualifierAnnotation {}

  @Named("test1") String testProp1;
  @Named String testProp2;
  @TestQualifierAnnotation Integer testProp3;

  @Test
  public void testNamedAnnotationLiterals() {
    Annotation namedTest1Annot = annotationFromProp("testProp1");
    Annotation namedDefaultAnnot = annotationFromProp("testProp2");

    Annotation manualNamedTest1 = new NamedAnnotationLiteral("test1");
    Annotation manualNamedDefault = new NamedAnnotationLiteral();

    assertThat(namedTest1Annot)
        .isEqualTo(manualNamedTest1)
        .isNotEqualTo(manualNamedDefault);

    assertThat(namedDefaultAnnot)
        .isEqualTo(manualNamedDefault)
        .isNotEqualTo(manualNamedTest1);
  }

  @Test
  public void testOnTheFlyAnnotationLiterals() {
    Annotation namedTest1Annot = annotationFromProp("testProp1");
    Annotation namedDefaultAnnot = annotationFromProp("testProp2");
    Annotation testQualiAnnot = annotationFromProp("testProp3");

    Annotation manualNamedTest1 = new TestNamedAnnotationLiteral() {
      @Override
      public String value() {
        return "test1";
      }
    };
    Annotation manualNamedDefault = new TestNamedAnnotationLiteral() {
      @Override
      public String value() {
        return "";
      }
    };
    Annotation manualTestQuali = new TestQualifierAnnotationLiteral();

    assertThat(namedTest1Annot)
        .isEqualTo(manualNamedTest1)
        .isNotEqualTo(manualNamedDefault)
        .isNotEqualTo(manualTestQuali);

    assertThat(namedDefaultAnnot)
        .isEqualTo(manualNamedDefault)
        .isNotEqualTo(manualNamedTest1)
        .isNotEqualTo(manualTestQuali);

    assertThat(testQualiAnnot)
        .isEqualTo(manualTestQuali)
        .isNotEqualTo(manualNamedDefault)
        .isNotEqualTo(manualNamedTest1);
  }

  private static Annotation annotationFromProp(String name) {
    try {
      Field field = AnnotationLiteralTest.class.getDeclaredField(name);
      return field.getDeclaredAnnotations()[0];
    } catch (NoSuchFieldException e) {
      throw new RuntimeException(e);
    }
  }
}

Add some basic sanity checking for AnnotationLiteral


/*
* 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.jackrabbit.oak.plugins.document.util;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;

import java.nio.charset.StandardCharsets;

/**
 * Utility class related to encoding characters into (UTF-8) byte sequences.
 */
public class UTF8Encoder {

    private UTF8Encoder() {
    }

    /**
     * Get an encoder suitable for UTF-8, using the proper error handling flags.
     *
     * Note that the instance is kept in a thread local to avoid the cost of
     * constructing an encoder for every call. This actually mimics the
     * internals of {@link String#getBytes(String)}.
     */
    private static ThreadLocal<CharsetEncoder> CSE = new ThreadLocal<CharsetEncoder>() {
        @Override
        protected CharsetEncoder initialValue() {
            CharsetEncoder e = StandardCharsets.UTF_8.newEncoder();
            e.onUnmappableCharacter(CodingErrorAction.REPORT);
            e.onMalformedInput(CodingErrorAction.REPORT);
            return e;
        }
    };

    /**
     * Like {@link String#getBytes(java.nio.charset.Charset)} (with "UTF-8"),
     * except that invalid character sequences (such as unpaired surrogates) are
     * reported as exceptions (see {@link CodingErrorAction#REPORT}, instead of
     * being silently replaced by a replacement character as it would happen
     * otherwise.
     *
     * @param input
     *            String to encode
     * @return String encoded using {@link StandardCharsets#UTF_8}
     * @throws IOException
     *             on encoding error
     */
    public static byte[] encodeAsByteArray(String input) throws IOException {
        CharsetEncoder e = CSE.get();
        e.reset();
        return bytes(e.encode(CharBuffer.wrap(input.toCharArray())));
    }

    /**
     * @see {@link CharsetEncoder#canEncode(CharSequence)
     */
    public static boolean canEncode(CharSequence input) {
        CharsetEncoder e = CSE.get();
        e.reset();
        return e.canEncode(input);
    }

    private static byte[] bytes(ByteBuffer b) {
        byte[] a = new byte[b.remaining()];
        b.get(a);
        return a;
    }
}

Create charset encoding utility that detects malformed input


package org.monospark.spongematchers.parser.primitive;

import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.monospark.spongematchers.testutil.HamcrestSpongeMatchers.matches;

import java.util.Optional;

import org.junit.Test;
import org.monospark.spongematchers.matcher.SpongeMatcher;
import org.monospark.spongematchers.parser.SpongeMatcherParser;

public class BooleanMatcherTest {

    @Test
    public void parseMatcher_True_ReturnsCorrectMatcher() {
        Optional<SpongeMatcher<Boolean>> matcher = SpongeMatcherParser.BOOLEAN.parseMatcher("true");

        assertTrue(matcher.isPresent());
        assertThat(matcher.get(), matches(true));
        assertThat(matcher.get(), not(matches(false)));
    }

    @Test
    public void parseMatcher_False_ReturnsCorrectMatcher() {
        Optional<SpongeMatcher<Boolean>> matcher = SpongeMatcherParser.BOOLEAN.parseMatcher("false");

        assertTrue(matcher.isPresent());
        assertThat(matcher.get(), matches(false));
        assertThat(matcher.get(), not(matches(true)));
    }

    @Test
    public void parseMatcher_TrueAndFalse_ReturnsCorrectMatcher() {
        Optional<SpongeMatcher<Boolean>> matcher = SpongeMatcherParser.BOOLEAN.parseMatcher("true|false");

        assertTrue(matcher.isPresent());
        assertThat(matcher.get(), matches(true));
        assertThat(matcher.get(), matches(false));
    }

    @Test
    public void parseMatcher_FalseAndTrue_ReturnsCorrectMatcher() {
        Optional<SpongeMatcher<Boolean>> matcher = SpongeMatcherParser.BOOLEAN.parseMatcher("false|true");

        assertTrue(matcher.isPresent());
        assertThat(matcher.get(), matches(true));
        assertThat(matcher.get(), matches(false));
    }
}

Add unit tests for boolean matcher parsing


package com.gentest;
public abstract class AbstractJavaClass {
  public AbstractJavaClass(String a, String b) {
    System.out.println("Constructor: a, b");
  }
  public AbstractJavaClass(String a) {
    System.out.println("Constructor: a");
  }
  // The abstract method
  public abstract String getCurrentStatus();
  public string getSecret() {
    return "The Secret";
  }
}

Add sample abstract java class


/*
 * Copyright 2011 DTO Solutions, Inc. (http://dtosolutions.com)
 *
 *  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.
 */

/*
* NodeExecutorResultImpl.java
*
* User: Greg Schueler greg@dtosolutions.com
* Created: 3/31/11 6:54 PM
*
*/
package com.dtolabs.rundeck.core.execution.service;

/**
 * NodeExecutorResultImpl simple implementation of {@link NodeExecutorResult}
 *
 * @author Greg Schueler greg@dtosolutions.com
 */
public class NodeExecutorResultImpl implements NodeExecutorResult {
    private int resultCode;
    private boolean success;

    public NodeExecutorResultImpl(final int resultCode, final boolean success) {
        this.resultCode = resultCode;
        this.success = success;
    }

    public boolean isSuccess() {
        return success;
    }

    public int getResultCode() {
        return resultCode;
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        final NodeExecutorResultImpl that = (NodeExecutorResultImpl) o;

        if (resultCode != that.resultCode) {
            return false;
        }
        if (success != that.success) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int result = resultCode;
        result = 31 * result + (success ? 1 : 0);
        return result;
    }

    @Override
    public String toString() {
        return "NodeExecutorResultImpl{" +
               "resultCode=" + resultCode +
               ", success=" + success +
               '}';
    }
}

Add simple impl of NodeExecutorResult


/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License;
 * you may not use this file except in compliance with the Elastic License.
 */
package org.elasticsearch.smoketest;

import org.elasticsearch.test.ESIntegTestCase;

public class PreventFailingBuildIT extends ESIntegTestCase {

    public void testSoThatTestsDoNotFail() {
        // Noop

        // This is required because if tests are not enable no
        // tests will be run in the entire project and all tests will fail.
    }
}

Add noop test to prevent test failures


/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2015, Red Hat, Inc., and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.picketbox.plugins;

import org.jboss.security.AuthenticationManager;
import org.jboss.security.AuthorizationManager;
import org.jboss.security.ISecurityManagement;
import org.jboss.security.JSSESecurityDomain;
import org.jboss.security.audit.AuditManager;
import org.jboss.security.identitytrust.IdentityTrustManager;
import org.jboss.security.mapping.MappingManager;
import org.picketbox.factories.SecurityFactory;

/**
 * A {@link ISecurityManagement} implementation that delegates to the instance registered with the {@link SecurityFactory}.
 *
 * @author Darran Lofthouse
 */
public class SecurityFactorySecurityManagement implements ISecurityManagement {

    private static final long serialVersionUID = 4533649455497748886L;

    private transient ISecurityManagement delegate;

    private ISecurityManagement getDelegate() {
        return delegate != null ? delegate : (delegate = SecurityFactory.getSecurityManagement());
    }

    @Override
    public AuthenticationManager getAuthenticationManager(String securityDomain) {
        return getDelegate().getAuthenticationManager(securityDomain);
    }

    @Override
    public AuthorizationManager getAuthorizationManager(String securityDomain) {
        return getDelegate().getAuthorizationManager(securityDomain);
    }

    @Override
    public MappingManager getMappingManager(String securityDomain) {
        return getDelegate().getMappingManager(securityDomain);
    }

    @Override
    public AuditManager getAuditManager(String securityDomain) {
        return getDelegate().getAuditManager(securityDomain);
    }

    @Override
    public IdentityTrustManager getIdentityTrustManager(String securityDomain) {
        return getDelegate().getIdentityTrustManager(securityDomain);
    }

    @Override
    public JSSESecurityDomain getJSSE(String securityDomain) {
        return getDelegate().getJSSE(securityDomain);
    }

}

Add an implementation of ISecurityManagement that can use the SecurityFactory to find a globally registered implementation to delegate to.


package com.levelup.java.collections;

import static org.junit.Assert.assertTrue;

import java.util.Collection;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.junit.Before;
import org.junit.Test;

import com.google.common.base.Objects;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;

/**
 * This java example will demonstrate how to check if every
 * element in the collection satisfies a specified condition.
 *
 * @author Justin Musgrove
 * @see List contains all elements
 */
public class ListContainsAll {

	class Camera {

		String name;
		int focalLength;

		@Override
		public String toString() {
			return Objects.toStringHelper(this)
					.add("name", name)
					.add("focallength", focalLength)
					.toString();
		}

		public Camera(String name, int focalLength) {
			super();
			this.name = name;
			this.focalLength = focalLength;
		}
	}

	List<Camera> cameras;

	@Before
	public void setUp () {
		cameras = Lists.newArrayList();

		cameras.add(new Camera("Nikon", 80));
		cameras.add(new Camera("Cannon", 135));
		cameras.add(new Camera("Kodak", 300));
		cameras.add(new Camera("Olympus", 200));
		cameras.add(new Camera("Fujifilm", 600));
	}

	@Test
	public void list_contains_all_java () {

		boolean allCamerasOfMediumTelephoto = true;

		for (Camera camera : cameras) {
			if (camera.focalLength < 80) {
				allCamerasOfMediumTelephoto = false;
				break;
			}
		}

		assertTrue(allCamerasOfMediumTelephoto);
	}

	@Test
	public void list_contains_all_guava () {

		boolean allCamerasOfMediumTelephoto = Iterables.all(cameras, new Predicate<Camera>() {
			public boolean apply(Camera input) {
				return input.focalLength >= 80;
			}
		});

		assertTrue(allCamerasOfMediumTelephoto);
	}

	@Test
	public void list_contains_all_apache () {

		@SuppressWarnings("unchecked")
		Collection<Camera> mediumTelephotoCameras = CollectionUtils.select(cameras,
				new org.apache.commons.collections.Predicate() {
			public boolean evaluate(Object object) {
				Camera camera = (Camera) object;
				return camera.focalLength >= 80;
			}
		});

		assertTrue(mediumTelephotoCameras.size() == cameras.size());
	}

}

Add list contains all example


package wissolsoft.porada.webapp.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import wissolsoft.porada.webapp.model.Vote;

@Repository
public class VotesDao {

    @Autowired
    private SessionFactory sessionFactory;

    @Transactional
    public void insertVote(final Vote vote) {
        final Session session = sessionFactory.getCurrentSession();
        final Transaction transaction = session.beginTransaction();
        session.save(vote);
        transaction.commit();
    }

}

Add basic DAO for votes


/*
 * Copyright 2014 Codenvy, S.A.
 *
 * 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.codenvy.ide.ext.datasource.shared.exception;

/**
 * Exception for CSV export.
 *
 * @author "Mickaël Leduque"
 */
public class CSVExportException extends Exception {

    /** UID for serialization */
    private static final long serialVersionUID = 1L;

    public CSVExportException() {
    }

    public CSVExportException(final String message) {
        super(message);
    }

    public CSVExportException(final Throwable cause) {
        super(cause);
    }

    public CSVExportException(final String message, final Throwable cause) {
        super(message, cause);
    }

    public CSVExportException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
        // TODO Auto-generated constructor stub
    }

}

Add an exception for CSV export errors


package com.asascience.ncsos.util;

import java.io.PrintWriter;
import java.io.StringWriter;

public class LogUtils {

    public static String exceptionAsString(Exception exception) {
        /**
         * Gets the exception stack trace as a string.
         * @param exception
         * @return
         */
        {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            pw.print(" [ ");
            pw.print(exception.getClass().getName());
            pw.print(" ] ");
            pw.print(exception.getMessage());
            exception.printStackTrace(pw);
            return sw.toString();
        }
    }
}

Add a LogUtil to print consistent log message


/**
 * Created with IntelliJ IDEA.
 * User: jhasmanyquiroz
 * Date: 11/12/15
 * Time: 3:07 PM
 * To change this template use File | Settings | File Templates.
 */
package ui.pages;

import org.openqa.selenium.support.PageFactory;
import ui.BasePageObject;

public class CoursesPage extends BasePageObject {
    public CoursesPage() {
        PageFactory.initElements(driver, this);
        waitUntilPageObjectIsLoaded();
    }

    public void waitUntilPageObjectIsLoaded() {
    }
}

Implement the Page Factory Pattern and methods for search any course


package tests.net.sf.jabref.export.layout.format;

import net.sf.jabref.export.layout.format.AuthorLastFirstAbbreviator;
import junit.framework.Assert;
import junit.framework.TestCase;

/**
 * Test case  that verifies the functionalities of the
 * formater AuthorLastFirstAbbreviator.
 *
 * @author Carlos Silla
 */
public class AuthorLastFirstAbbreviatorTester extends TestCase {

	/**
	 * Verifies the Abbreviation of one single author with a simple name.
	 *
	 * Ex: Lastname, Name
	 */
	public void testOneAuthorSimpleName() {
		String name = new String("Lastname, Name");

		AuthorLastFirstAbbreviator ab = new AuthorLastFirstAbbreviator();

		String result = ab.format(name);

		//Expected Results:
		String expectedResult = new String ("Lastname, N.");

		//Verifies the functionality:
		Assert.assertEquals("Abbreviator Test", result, expectedResult);
	}

	/**
	 * Verifies the Abbreviation of one single author with a common name.
	 *
	 * Ex: Lastname, Name Middlename
	 */
	public void testOneAuthorCommonName() {
		String name = new String("Lastname, Name Middlename");

		AuthorLastFirstAbbreviator ab = new AuthorLastFirstAbbreviator();

		String result = ab.format(name);

		//Expected Results:
		String expectedResult = new String ("Lastname, N.M.");

		//Verifies the functionality:
		Assert.assertEquals("Abbreviator Test", result, expectedResult);
	}

	/**
	 * Verifies the Abbreviation of two single with a common name.
	 *
	 * Ex: Lastname, Name Middlename
	 */
	public void testTwoAuthorsCommonName() {
		String name = new String("Lastname, Name Middlename and Sobrenome, Nome Nomedomeio");

		AuthorLastFirstAbbreviator ab = new AuthorLastFirstAbbreviator();

		String result = ab.format(name);

		//Expected Results:
		String expectedResult = new String ("Lastname, N.M. and Sobrenome, N.N.");

		//Verifies the functionality:
		Assert.assertEquals("Abbreviator Test", result, expectedResult);
	}

	/**
	 * Verifies the Abbreviation of two authors in the incorrect format.
	 *
	 * Ex: Lastname, Name Middlename
	 */
	//TODO: Verify how to tell this test that it should pass if fail.
/*	public void testTwoAuthorsBadFormating() {
		String name = new String("Lastname, Name Middlename and Nome Nomedomeio Sobrenome");

		AuthorLastFirstAbbreviator ab = new AuthorLastFirstAbbreviator();

		String result = ab.format(name);
	}*/

}

Test dirs along with the first test case of jabref for the AuthorLastFirstAbbreviator formater.


package io.quarkus.smallrye.faulttolerance.runtime.graal;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.function.BooleanSupplier;

import org.graalvm.home.Version;

import com.oracle.svm.core.annotate.Substitute;
import com.oracle.svm.core.annotate.TargetClass;

public class FaultToleranceSubstitutions {
}

@TargetClass(className = "io.smallrye.faulttolerance.DefaultMethodFallbackProvider", onlyWith = GraalVM20OrEarlier.class)
final class Target_io_smallrye_faulttolerance_DefaultMethodFallbackProvider {

    @TargetClass(className = "io.smallrye.faulttolerance.ExecutionContextWithInvocationContext")
    static final class Target_io_smallrye_faulttolerance_ExecutionContextWithInvocationContext {

    }

    @Substitute
    static Object getFallback(Method fallbackMethod,
            Target_io_smallrye_faulttolerance_ExecutionContextWithInvocationContext ctx)
            throws IllegalAccessException, InstantiationException, IllegalArgumentException, InvocationTargetException,
            Throwable {
        throw new RuntimeException("Not supported in native image when using GraalVM releases prior to 21.0.0");
    }

}

class GraalVM20OrEarlier implements BooleanSupplier {

    @Override
    public boolean getAsBoolean() {
        return Version.getCurrent().compareTo(21) < 0;
    }
}

Substitute DefaultMethodFallbackProvider in GraalVM < 21.0


package net.kencochrane.raven.jul;

import net.kencochrane.raven.Raven;
import net.kencochrane.raven.event.EventBuilder;
import net.kencochrane.raven.event.LoggedEvent;
import net.kencochrane.raven.event.interfaces.ExceptionInterface;
import net.kencochrane.raven.event.interfaces.MessageInterface;
import net.kencochrane.raven.event.interfaces.StackTraceInterface;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;

public class SentryHandler extends Handler {
    private final Raven raven;

    public SentryHandler() {
        this(new Raven());
    }

    public SentryHandler(Raven raven) {
        this.raven = raven;
    }

    private static LoggedEvent.Level getLevel(Level level) {
        if (level.intValue() >= Level.SEVERE.intValue())
            return LoggedEvent.Level.ERROR;
        else if (level.intValue() >= Level.WARNING.intValue())
            return LoggedEvent.Level.WARNING;
        else if (level.intValue() >= Level.INFO.intValue())
            return LoggedEvent.Level.INFO;
        else if (level.intValue() >= Level.ALL.intValue())
            return LoggedEvent.Level.DEBUG;
        else return null;
    }

    private static List<String> formatParameters(Object[] parameters) {
        List<String> formattedParameters = new ArrayList<String>(parameters.length);
        for (Object parameter : parameters)
            formattedParameters.add(parameter.toString());
        return formattedParameters;
    }

    @Override
    public void publish(LogRecord record) {
        if (!isLoggable(record)) {
            return;
        }

        EventBuilder eventBuilder = new EventBuilder()
                .setLevel(getLevel(record.getLevel()))
                .setTimestamp(new Date(record.getMillis()))
                .setLogger(record.getLoggerName())
                .setCulprit(record.getSourceClassName() + "." + record.getSourceMethodName() + "()");
        if (record.getThrown() != null) {
            eventBuilder.addSentryInterface(new ExceptionInterface(record.getThrown()))
                    .addSentryInterface(new StackTraceInterface(record.getThrown()));
        }

        if (record.getParameters() != null)
            eventBuilder.addSentryInterface(new MessageInterface(record.getMessage(), formatParameters(record.getParameters())));
        else
            eventBuilder.setMessage(record.getMessage());

        raven.sendEvent(eventBuilder);
    }

    @Override
    public void flush() {
    }

    @Override
    public void close() throws SecurityException {
    }
}

Create a JUL handler using Raven


package org.realityforge.replicant.client;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static org.realityforge.braincheck.Guards.*;

/**
 * A basic EntityLocator implementation that allows explicit per-type registration
 */
public class AggregateEntityLocator
  implements EntityLocator
{
  private final ArrayList<EntityLocator> _entityLocators = new ArrayList<>();

  protected final <T> void registerEntityLocator( @Nonnull final EntityLocator entityLocator )
  {
    apiInvariant( () -> !_entityLocators.contains( entityLocator ),
                  () -> "Attempting to register entityLocator " + entityLocator + " when already present." );
    _entityLocators.add( entityLocator );
  }

  /**
   * {@inheritDoc}
   */
  @Nullable
  @Override
  public final <T> T findByID( @Nonnull final Class<T> type, @Nonnull final Object id )
  {
    for ( final EntityLocator entityLocator : _entityLocators )
    {
      final T entity = entityLocator.findByID( type, id );
      if ( null != entity )
      {
        return entity;
      }
    }
    return null;
  }

  /**
   * {@inheritDoc}
   */
  @Nonnull
  @Override
  public <T> List<T> findAll( @Nonnull final Class<T> type )
  {
    final ArrayList<T> results = new ArrayList<>();
    for ( final EntityLocator entityLocator : _entityLocators )
    {
      results.addAll( entityLocator.findAll( type ) );
    }
    return results;
  }
}

Add locator that will delegate to list of locators


public class Solution {

    public int strStr(String haystack, String needle) {

        for (int i = 0; i <= haystack.length() - needle.length(); i++) {

            int j = 0;
            for ( ; j < needle.length(); j++) {

                if (haystack.charAt(i + j) != needle.charAt(j)) {
                    break;
                }

            }

            if (j == needle.length()) {
                return i;
            }

        }

        return -1;

    }

}

Create : 28 Implement strStr()


package tld.testmod;

/*
    Licenses for assets can be found in ASSETS_LICENSE.txt. All other files are licensed under the terms below:

    The MIT License (MIT)

    Test Mod 3 - Copyright (c) 2015-2017 Choonster

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.
 */
import net.minecraftforge.common.config.Config;
import net.minecraftforge.common.config.ConfigManager;
import net.minecraftforge.fml.client.event.ConfigChangedEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

@Config(modid = Main.MODID)
@Config.LangKey("testmod.config.title")
public class ModConfig {

    @Config.Comment("This is an example boolean property.")
    public static boolean fooBar = false;

    public static final Client client = new Client();

    public static class Client {

        @Config.Comment("This is an example int property.")
        public int baz = -100;

        public final HUDPos chunkEnergyHUDPos = new HUDPos(0, 0);

        public static class HUDPos {
            public HUDPos(final int x, final int y) {
                this.x = x;
                this.y = y;
            }

            @Config.Comment("The x coordinate")
            public int x;

            @Config.Comment("The y coordinate")
            public int y;
        }
    }

    @Mod.EventBusSubscriber
    private static class EventHandler {

        /**
         * Inject the new values and save to the config file when the config has been changed from the GUI.
         *
         * @param event The event
         */
        @SubscribeEvent
        public static void onConfigChanged(final ConfigChangedEvent.OnConfigChangedEvent event) {
            if (event.getModID().equals(Main.MODID)) {
                ConfigManager.sync(Main.MODID, Config.Type.INSTANCE);
            }
        }
    }
}

Add a test config for the heck of it. Thank you Choonster for your TestMod3.


package leetcode;

/**
 * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
 */
public class Problem122 {
    public int maxProfit(int[] prices) {
        return 0;
    }

    public static void main(String[] args) {
        Problem122 prob = new Problem122();
        System.out.println(prob.maxProfit(new int[]{1, 2, 4, 2, 1, 3}));
        System.out.println(prob.maxProfit(new int[]{3, 2, 6, 5, 0, 3}));
    }
}

Create skeleton for problem 122


package problems;

public class ReverseNodesInGroups {

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        if (k < 2)
            return head;
        ListNode newHead = new ListNode(-1), p = newHead;
        newHead.next = head;
        while (p != null && p.next != null) {
            ListNode[] t = reverse(p.next, k);
            p.next = t[0];
            p = t[1];
        }
        return newHead.next;
    }

    // return the head and tail of the reversed group
    ListNode[] reverse(ListNode head, int k) {
        ListNode p = head, q = p.next, r = null;
        ListNode[] out = { head, null };
        for (int i = 1; i < k; i++) {
            if (p.next == null)
                return out;
            p = p.next;
        }
        p = head;
        for (int i = 1; i < k; i++) {
            r = q.next;
            q.next = p;
            p = q;
            q = r;
        }
        head.next = q;
        out[0] = p;
        out[1] = head;
        return out;
    }

    public static void main(String[] args) {
        ReverseNodesInGroups rn = new ReverseNodesInGroups();

        int[] A = { 1, 2, 3, 4, 5 };
        ListNode head = null, p = null;
        for (int i = 0; i < A.length; i++) {
            ListNode t = rn.new ListNode(A[i]);
            if (head == null)
                head = p = t;
            else {
                p.next = t;
                p = t;
            }
        }

        ListNode l = rn.reverseKGroup(head, 5);
        while (l != null) {
            System.out.print(l.val + ", ");
            l = l.next;
        }
    }
}

Add Reverse Nodes In K Groups


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

import org.voltdb.SQLStmt;
import org.voltdb.VoltProcedure;

public class testCreateWriteProcFromClassProc extends VoltProcedure {
    public final SQLStmt write = new SQLStmt(
            "INSERT INTO T2 SELECT * FROM T2;"
    );

    public long run(long isbn, String title, String author)
    throws VoltAbortException {
        return 1;
    }
}

Add new class to support DIRECTED PROECEDURE FROM CLASS scenario added to FullDDL.


package org.openmhealth.shim.withings.domain;

/**
 * A body measure type included in responses from the Withings body measure endpoint, specifically in a 'meastype'
 * property.
 *
 * @author Chris Schaefbauer
 * @author Emerson Farrugia
 * @see {@link org.openmhealth.shim.withings.mapper.WithingsBodyMeasureDataPointMapper}
 * @see Body Measures API documentation
 */
public enum WithingsBodyMeasureType {

    BODY_WEIGHT(1),
    BODY_HEIGHT(4),
    // FAT_FREE_MASS(5), // TODO confirm what this means
    // FAT_RATIO(6), // TODO confirm what this means
    // FAT_MASS_WEIGHT(8), // TODO confirm what this means
    DIASTOLIC_BLOOD_PRESSURE(9),
    SYSTOLIC_BLOOD_PRESSURE(10),
    HEART_RATE(11),
    OXYGEN_SATURATION(54);

    private int magicNumber;

    WithingsBodyMeasureType(int magicNumber) {
        this.magicNumber = magicNumber;
    }

    /**
     * @return the magic number used to refer to this body measure type in responses
     */
    public int getMagicNumber() {
        return magicNumber;
    }
}

Add class missed in last commit


/*
    JSPWiki - a JSP-based WikiWiki clone.

    Copyright (C) 2001-2002 Janne Jalkanen (Janne.Jalkanen@iki.fi)

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

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

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

package com.ecyrd.jspwiki.tags;

import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.Tag;

/**
 * ParamTag submits name-value pairs to the first enclosing
 * ParamHandler instance. Name and value are strings, and can
 * be given as tag attributes, or alternatively the value can be
 * given as the body contents of this tag.
 * <p>
 * The name-value pair is passed to the closest containing
 * ancestor tag that implements ParamHandler.
 */
public class ParamTag
    extends BodyTagSupport
{

    private String m_name;
    private String m_value;

    public void release()
    {
        m_name = m_value = null;
    }

    public void setName( String s )
    {
        m_name = s;
    }

    public void setValue( String s )
    {
        m_value = s;
    }

    public int doEndTag()
    {
        Tag t = null;
        while( (t = getParent()) != null && !(t instanceof ParamHandler) )
            ;
        if( t != null )
        {
            String val = m_value;
            if( val == null )
            {
                BodyContent bc = getBodyContent();
                if( bc != null )
                {
                    val = bc.getString();
                }
            }
            if( val != null )
            {
                ((ParamHandler)t).setContainedParameter( m_name, val );
            }
        }

        return EVAL_PAGE;
    }
}

Tag for providing name-value pairs to a parent tag


package info.u_team.u_team_core.item;

import java.util.function.Supplier;

import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.fluid.Fluid;
import net.minecraft.item.*;
import net.minecraft.util.*;
import net.minecraft.world.World;

public class NoPlaceUBucketItem extends UBucketItem {

	public NoPlaceUBucketItem(String name, ItemGroup group, Properties properties, Supplier<? extends Fluid> fluid) {
		super(name, group, properties, fluid);
	}

	public NoPlaceUBucketItem(String name, Properties properties, Supplier<? extends Fluid> fluid) {
		super(name, properties, fluid);
	}

	@Override
	public ActionResult<ItemStack> onItemRightClick(World world, PlayerEntity player, Hand hand) {
		return new ActionResult<ItemStack>(ActionResultType.PASS, player.getHeldItem(hand));
	}

}

Add no placement u bucket item


package gov.nih.nci.cananolab.service.admin;

import gov.nih.nci.cananolab.service.protocol.ProtocolService;
import gov.nih.nci.cananolab.service.publication.PublicationService;
import gov.nih.nci.cananolab.service.sample.SampleService;
import gov.nih.nci.cananolab.service.security.SecurityService;

import java.util.Set;

/**
 * Interface for transfer of ownership.
 */
public interface OwnershipTransferService {

	public void transferOwner(SampleService sampleService, SecurityService securityService, Set<String> sampleIds, String currentOwner,
			String newOwner) throws Exception ;

	public void transferOwner(PublicationService publicationService, SecurityService securityService, Set<String> publicationIds, String currentOwner,
			String newOwner) throws Exception ;

	public void transferOwner(ProtocolService protocolService, SecurityService securityService, Set<String> protocolIds, String currentOwner,
			String newOwner) throws Exception ;

	}

Refactor ownership transfer to service


package uk.ac.ox.oucs.oauth.admin;

import org.sakaiproject.authz.api.FunctionManager;
import org.sakaiproject.authz.api.SecurityService;
import org.sakaiproject.component.cover.ComponentManager;

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

/**
 * Filter users before displaying the oAuth administration page
 */
public class AdminFilter implements Filter {
    private static final String OAUTH_ADMIN_RIGHT = "oauth.admin";
    private SecurityService securityService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        FunctionManager functionManager = (FunctionManager) ComponentManager.get(FunctionManager.class);
        functionManager.registerFunction(OAUTH_ADMIN_RIGHT, false);
        securityService = (SecurityService) ComponentManager.get(SecurityService.class);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (securityService.unlock(OAUTH_ADMIN_RIGHT, "")) {
            chain.doFilter(request, response);
        } else {
            HttpServletResponse res = (HttpServletResponse) response;
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    }

    @Override
    public void destroy() {
    }
}

Create a filter to check if the user can access oAuth admin


package alien4cloud.ui;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class WizardController {

@RequestMapping({ "/wizard", "/wizard/#"})
   public String index() {
       return "forward:/wizard/index.html";
   }
}

Add spring controller for wizard


package org.hisp.dhis.android.testapp.datavalue;

import android.support.test.runner.AndroidJUnit4;

import org.hisp.dhis.android.core.datavalue.DataValue;
import org.hisp.dhis.android.testapp.arch.BasePublicAccessShould;
import org.junit.runner.RunWith;
import org.mockito.Mock;

@RunWith(AndroidJUnit4.class)
public class DataValuePublicAccessShould extends BasePublicAccessShould<DataValue> {

    @Mock
    private DataValue object;

    @Override
    public DataValue object() {
        return object;
    }

    @Override
    public void has_public_create_method() {
        DataValue.create(null);
    }

    @Override
    public void has_public_builder_method() {
        DataValue.builder();
    }

    @Override
    public void has_public_to_builder_method() {
        object().toBuilder();
    }
}

Add data value package tests


package com.phsshp.config;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

public class CommandLineParserTest {

    @Test
    public void parseFileNameFromCommandLine() throws Exception {
        CommandLineOptions options = parse("filepath");

        assertThat(options.getSourcePath(), equalTo("filepath"));
    }

    private CommandLineOptions parse(String ...arguments) {
        return new CommandLineParser().parse(arguments);
    }
}

Add test for parsing file path from command line


package cl.fatman.capital.fund;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

import java.time.LocalDate;

@Entity
@Table( name = "Rate" )
public class Rate {

	private int id;
	private double value;
	private LocalDate date;

	public Rate(double value, LocalDate date) {
		super();
		this.value = value;
		this.date = date;
	}

	public Rate() {
		super();
	}

	@Id
	@GeneratedValue(generator="increment")
	@GenericGenerator(name="increment", strategy = "increment")
	@Column(name="ID")
	public int getId() {
		return id;
	}

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

	@Column(name = "VALUE")
	public double getValue() {
		return value;
	}

	public void setValue(double value) {
		this.value = value;
	}

	@Column(name = "DATE", unique = true)
	public LocalDate getDate() {
		return date;
	}

	public void setDate(LocalDate date) {
		this.date = date;
	}
}

Create the class rate to registry the value of a fund.


package leetcode.compare_version_numbers;

public class Solution {
    public int compareVersion(String version1, String version2) {
    	version1 = version1.replaceAll("(\\.0+)+$", "");
    	version2 = version2.replaceAll("(\\.0+)+$", "");
        String[] sp1 = version1.split("\\.");
        String[] sp2 = version2.split("\\.");
        int l1 = sp1.length;
        int l2 = sp2.length;
        int l = Math.min(l1, l2);
        for(int i = 0; i < l; i++){
        	String n1 = sp1[i].replaceAll("^0+", "");
        	String n2 = sp2[i].replaceAll("^0+", "");
        	if(n1.length() > n2.length()){
        		return 1;
        	}else if(n1.length() < n2.length()){
        		return -1;
        	}else{
        		int cmp = n1.compareTo(n2);
        		if(cmp > 0) return 1;
        		if(cmp < 0) return -1;
        	}
        }
        if(l1 > l2) return 1;
        if(l1 < l2) return -1;
        return 0;
    }
}

Add java solution for 165. Compare Version Numbers


/*
 *                      Nividic development code
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  If you do not have a copy,
 * see:
 *
 *      http://www.gnu.org/copyleft/lesser.html
 *
 * Copyright for this code is held jointly by the microarray platform
 * of the cole Normale Suprieure and the individual authors.
 * These should be listed in @author doc comments.
 *
 * For more information on the Nividic project and its aims,
 * or to join the Nividic mailing list, visit the home page
 * at:
 *
 *      http://www.transcriptome.ens.fr/nividic
 *
 */

package fr.ens.transcriptome.nividic.om;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import fr.ens.transcriptome.nividic.om.io.GPRReader;
import fr.ens.transcriptome.nividic.om.io.NividicIOException;

import junit.framework.TestCase;

public class SerializationTest extends TestCase {

  public void testBioAssay1() throws FileNotFoundException, IOException,
      ClassNotFoundException {

    BioAssay b = BioAssayFactory.createBioAssay();

    File f = new File("/tmp/bioassaySerialized");

    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
    oos.writeObject(b);
    oos.close();

    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
    BioAssay copy = (BioAssay) ois.readObject();
    ois.close();

    assertEquals(b.getBiologicalId(), copy.getBiologicalId());

    f.delete();
  }

  public void testBioAssay2() throws FileNotFoundException, IOException,
      ClassNotFoundException, NividicIOException {

    InputStream is = this.getClass().getResourceAsStream("/files/testGPR3.gpr");
    GPRReader gprr = new GPRReader(is);
    BioAssay b = gprr.read();

    File f = new File("/tmp/bioassaySerialized");

    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
    oos.writeObject(b);
    oos.close();

    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
    BioAssay copy = (BioAssay) ois.readObject();
    ois.close();

    assertEquals(b.getBiologicalId(), copy.getBiologicalId());

    f.delete();
  }

}

Add a class to test serialization of objects


/*
 * 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.logging.log4j.core.config.plugins.util;

/**
 * A type of Plugin builder that can be used to configure and create a plugin instance using a Java DSL instead of
 * through a configuration file. These builders are primarily useful for internal code and unit tests, but they can
 * technically be used as a verbose alternative to configuration files.
 *
 * <p>
 *     When creating plugin builders, it is customary to create the builder class as a public static inner class
 *     called {@code Builder}. For instance, the builder class for
 *     {@link org.apache.logging.log4j.core.layout.PatternLayout PatternLayout} would be
 *     {@code PatternLayout.Builder}.
 * </p>
 *
 * @param <T> the Plugin class this is a builder for.
 */
public interface ConfigurablePluginBuilder<T> {

    /**
     * Builds the plugin object after all configuration has been set. This will use default values for any
     * unspecified attributes for the plugin.
     *
     * @return the configured plugin instance.
     */
    T build();
}

Add interface for building plugins in Java instead of XML/JSON.


package org.openregistry.core.domain.jpa;

import static org.junit.Assert.*;

import org.junit.Test;
import org.openregistry.core.domain.Address;
import org.openregistry.core.domain.Country;
import org.openregistry.core.domain.Region;
import org.openregistry.core.domain.jpa.sor.JpaSorAddressImpl;
import org.springframework.test.context.ContextConfiguration;

@ContextConfiguration(locations = {"classpath:base-integration-tests.xml"})

public class JpaSorAddressImplTests {

	@Test
	public void testSetValidRegion () {
		Address sorAddress = new JpaSorAddressImpl();
		Region validRegion = new JpaRegionImpl();

		assertNull("Region must be null before setting", sorAddress.getRegion());
		sorAddress.setRegion(validRegion);
		assertNotNull("Region must not be null after setting", sorAddress.getRegion());
	}

	@Test
	public void testSetNullRegion () {
		Address sorAddress = new JpaSorAddressImpl();
		Region validRegion = new JpaRegionImpl();
		sorAddress.setRegion(validRegion);

		assertNotNull("Region must not be null before setting it to null", sorAddress.getRegion());
		sorAddress.setRegion(null);
		assertNull("Region must be null after setting it to null", sorAddress.getRegion());
	}

    @Test(expected = IllegalArgumentException.class)
    public void testSetIncorrectRegionType() {

		Address sorAddress = new JpaSorAddressImpl();

    	// This implements Region but is not instance of JpaRegionImpl
    	Region invalidRegion = new Region() {
			public String getName() {
				return null;
			}
			public String getCode() {
				return null;
			}
			public Country getCountry() {
				return null;
			}
    	};
    	sorAddress.setRegion(invalidRegion);
    }
}

Test for OR-346: setting valid, invalid and null region (initial version)


package com.example.playground.monadic.parser.combinators;

import org.junit.Test;

import java.util.Collections;
import java.util.List;
import java.util.stream.IntStream;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

public class ZeroParserTest {
    @Test
    public void shouldAlwaysReturnEmptyList() {
        final Parser<Integer, Integer, IntStream> parser = Parsers.<Integer, Integer, IntStream>zero();
        final String input = "word";
        final List<ParserResult<Integer, Integer, IntStream>> actualParserResults = parser.parse(input.chars());

        assertThat(actualParserResults, is(equalTo(Collections.emptyList())));
    }
}

Add simple test for zero parser


/**
 * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.engine.fudgemsg;

import java.util.List;

import org.testng.annotations.Test;

import com.google.common.collect.ImmutableList;
import com.opengamma.engine.function.config.FunctionConfigurationDefinition;
import com.opengamma.engine.function.config.ParameterizedFunctionConfiguration;
import com.opengamma.engine.function.config.StaticFunctionConfiguration;
import com.opengamma.util.test.AbstractFudgeBuilderTestCase;
import com.opengamma.util.test.TestGroup;

/**
 * Tests {@link FunctionConfigurationDefinitionFudgeBuilder}
 */
@Test(groups = TestGroup.UNIT)
public class FunctionConfigurationDefinitionBuilderTest extends AbstractFudgeBuilderTestCase {

  @Test
  public void functionConfigurationDefinition() {
    List<String> otherConfigs = ImmutableList.of("CF1", "CF2", "CF3");
    List<StaticFunctionConfiguration> staticFunctions = ImmutableList.of(new StaticFunctionConfiguration("SF1"),
        new StaticFunctionConfiguration("SF2"));
    List<ParameterizedFunctionConfiguration> parameterizedFunctions = ImmutableList.of(
        new ParameterizedFunctionConfiguration("PF1", ImmutableList.of("P11", "P12")),
        new ParameterizedFunctionConfiguration("PF2", ImmutableList.of("P21", "P22")));
    assertEncodeDecodeCycle(FunctionConfigurationDefinition.class, new FunctionConfigurationDefinition("FUNC_TEST", otherConfigs, staticFunctions, parameterizedFunctions));
  }

}

Add unit test for fudge builder


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

package org.spine3.server;

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

}

Create class for subscription service tests.


package net.tlahmann.gdg.creation.helper;

public class Tuple<X, Y> {
	public X x;
	public Y y;

	public Tuple(X x, Y y) {
		this.x = x;
		this.y = y;
	}
}

Add Tupel class to hold min and max value


/*
 * Copyright 2015 Ryan Gilera.
 *
 * 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.daytron.revworks.ui.dashboard;

import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.Reindeer;

/**
 * The screen when a user tried to navigate to a view that does not exist.
 *
 * @author Ryan Gilera
 */
public class ErrorView extends VerticalLayout implements View {

    private final Label errorLabel;

    public ErrorView() {
        setMargin(true);
        setSpacing(true);

        Label headerErrorLabel = new Label("The view could not be found!");
        headerErrorLabel.addStyleName(Reindeer.LABEL_H1);

        addComponent(headerErrorLabel);

        this.errorLabel = new Label();
        addComponent(this.errorLabel);
    }

    @Override
    public void enter(ViewChangeListener.ViewChangeEvent event) {
        String message = String.format(
                "You attempted to navigate to a view ('%s') "
                + "that does not exist.",
                event.getViewName());

        this.errorLabel.setValue(message);
    }

}

Add an errow view for navigator


/*
 * Copyright 2020 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
 *
 *      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 org.springframework.cloud.vault.config;

import org.junit.Test;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.Status;
import org.springframework.cloud.vault.util.IntegrationTestSupport;
import org.springframework.cloud.vault.util.Settings;
import org.springframework.cloud.vault.util.TestRestTemplateFactory;
import org.springframework.vault.client.ClientHttpConnectorFactory;
import org.springframework.vault.core.ReactiveVaultTemplate;
import org.springframework.vault.support.ClientOptions;

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

/**
 * Integration tests for {@link VaultReactiveHealthIndicator}.
 *
 * @author Mark Paluch
 */
public class VaultReactiveHealthIndicatorIntegrationTests extends IntegrationTestSupport {

	@Test
	public void shouldReturnHealthState() {

		ReactiveVaultTemplate vaultTemplate = new ReactiveVaultTemplate(
				TestRestTemplateFactory.TEST_VAULT_ENDPOINT, ClientHttpConnectorFactory
				.create(new ClientOptions(), Settings
						.createSslConfiguration()), () -> Mono.just(Settings.token()));

		VaultReactiveHealthIndicator healthIndicator = new VaultReactiveHealthIndicator(vaultTemplate);

		healthIndicator.doHealthCheck(Health.up()).as(StepVerifier::create)
				.consumeNextWith(actual -> {
					assertThat(actual.getStatus()).isEqualTo(Status.UP);
				}).verifyComplete();
	}
}

Add integration test for VaultReactiveHealthIndicator


/*
 * Transient.java June 2007
 *
 * Copyright (C) 2007, Niall Gallagher <niallg@users.sf.net>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 */

package simple.xml;

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

/**
 * The Transient annotation is an optional annotation
 * that can be used within an XML class schema to mark a method or
 * field as being transient, which indicates that it does not take
 * part in serialization or deserialization. This is used only as
 * a means to illustrate to the reader of your class that this has
 * not impact on the XML representation of the object. Fields or
 * methods annotated with this will be ignored, as will those that
 * contain no XML annotations.
 *
 * @author Niall Gallagher
 */
@Retention(RetentionPolicy.RUNTIME)
public @interface Transient {
}

Add the optional transient annotation