// Copyright (c) 2012 Microsoft Corporation.  All rights reserved.

package tlc2.tool.distributed.fp;

import java.util.Random;

import tlc2.tool.distributed.TLCWorker;

/**
 * This main class starts worker (compute) and fingerprints (storage) nodes and
 * crashes them randomly to simulate node failures.
 */
public class FailingTLCWorkerAndFPSet {

	@SuppressWarnings("deprecation")
	public static void main(final String[] args) throws InterruptedException {
		final Random rnd = new Random();

		Thread workers = null;
		Thread dfs = null;

		// Never end which is only acceptable in a test deployment where an
		// external instance kills this main thread.
		while (true) {

			// Start distributed FPSet first if null
			if (dfs == null) {
				dfs = new Thread(new Runnable() {
					/* (non-Javadoc)
					 * @see java.lang.Runnable#run()
					 */
					public void run() {
						DistributedFPSet.main(args);
					}
				}, DistributedFPSet.class.getName());
				dfs.start();
			}

			// Start worker afterwards as it requires FPSets to be available
			if (workers == null) {
				workers = new Thread(new Runnable() {
					/* (non-Javadoc)
					 * @see java.lang.Runnable#run()
					 */
					public void run() {
						TLCWorker.main(args);
					}
				}, TLCWorker.class.getName());
				workers.start();
			}

			// Calculate a random sleep time between 1 and 10 minutes
			int sleep = (rnd.nextInt(9) + 1) ;
			System.err.println("Sleeping for " + sleep + " minutes...");
			Thread.sleep(sleep * 1000 * 60);

			// Decide to either kill workers, dfs or both
			int action = rnd.nextInt(2);
			switch (action) {
				case 0:
					System.err.println("Doing nothing...");
					break;
				case 1:
					System.err.println("Killing fingerprint server...");
					dfs.stop();
					dfs = null;
					// Try to reclaim the heap used by dfs
					System.gc();
					break;
				// TODO support case 2,3,4 (2 & 3 fail due to TLC limitations of
				// only one run per JVM. Use OSGi based worker as a workaround)
				case 2:
					System.err.println("Killing workers...");
					workers.stop();
					workers = null;
					break;
				case 3:
					System.err.println("Killing workers and fingerprint server...");
					workers.stop();
					workers = null;
					dfs.stop();
					dfs = null;
					// Try to reclaim the heap used by dfs
					System.gc();
					break;
				case 4:
					System.exit(1);
					break;
			}

			// Give master a one minute grace period to clean up
			Thread.sleep(1000 * 60);
		}
	}
}

Add a failing TLCWorkerAndFPSet process that randomly crashes and restarts the FPSet server


/*******************************************************************************
 * Mission Control Technologies, Copyright (c) 2009-2012, United States Government
 * as represented by the Administrator of the National Aeronautics and Space
 * Administration. All rights reserved.
 *
 * The MCT platform is 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.
 *
 * MCT includes source code licensed under additional open source licenses. See
 * the MCT Open Source Licenses file included with this distribution or the About
 * MCT Licenses dialog available at runtime from the MCT Help menu for additional
 * information.
 *******************************************************************************/
package gov.nasa.arc.mct.scenario.component;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * Container for an Activity Type's model. (contains power, comms)
 */
@XmlRootElement()
@XmlAccessorType(XmlAccessType.FIELD)
public class ActivityTypeModel {
	private double power = 0;
	private double comms = 0;

	public double getPower() {
		return power;
	}
	public void setPower(double power) {
		this.power = power;
	}
	public double getComms() {
		return comms;
	}
	public void setComms(double comms) {
		this.comms = comms;
	}
}

Add model for power/comm costs


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

package com.google.bitcoin.utils;

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

/**
* A simple wrapper around a listener and an executor, with some utility methods.
*/
public class ListenerRegistration<T> {
    public T listener;
    public Executor executor;

    public ListenerRegistration(T listener, Executor executor) {
        this.listener = listener;
        this.executor = executor;
    }

    public static <T> boolean removeFromList(T listener, List<? extends ListenerRegistration<T>> list) {
        ListenerRegistration<T> item = null;
        for (ListenerRegistration<T> registration : list) {
            if (registration.listener == listener) {
                item = registration;
                break;
            }
        }
        if (item != null) {
            list.remove(item);
            return true;
        } else {
            return false;
        }
    }
}

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

package com.google.bitcoin.utils;

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

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

/**
* A simple wrapper around a listener and an executor, with some utility methods.
*/
public class ListenerRegistration<T> {
    public final T listener;
    public final Executor executor;

    public ListenerRegistration(T listener, Executor executor) {
        this.listener = checkNotNull(listener);
        this.executor = checkNotNull(executor);
    }

    public static <T> boolean removeFromList(T listener, List<? extends ListenerRegistration<T>> list) {
        checkNotNull(listener);

        ListenerRegistration<T> item = null;
        for (ListenerRegistration<T> registration : list) {
            if (registration.listener == listener) {
                item = registration;
                break;
            }
        }
        if (item != null) {
            list.remove(item);
            return true;
        } else {
            return false;
        }
    }
}

Check for and reject null event listeners.


package etomica.cavity;

import etomica.box.Box;
import etomica.data.DataProcessorForked;
import etomica.data.IData;
import etomica.data.IDataInfo;
import etomica.data.types.DataDouble;
import etomica.data.types.DataGroup;
import etomica.units.dimensions.Null;
import etomica.units.dimensions.Pressure;

/**
 * DataProcessor that determines g(sigma) from P (measured with the virial)
 */
public class DataProcessorPContactG extends DataProcessorForked {

    protected final DataGroup data = new DataGroup(new DataDouble[]{new DataDouble(), new DataDouble(), new DataDouble()});
    protected final Box box;

    public DataProcessorPContactG(Box box) {
        this.box = box;
        DataDouble.DataInfoDouble subDataInfo = new DataDouble.DataInfoDouble("stuff", Null.DIMENSION);
        dataInfo = new DataGroup.DataInfoGroup("pressure", Pressure.DIMENSION, new IDataInfo[]{subDataInfo, subDataInfo, subDataInfo});
        dataInfo.addTag(tag);
    }

    @Override
    protected IData processData(IData inputData) {
        double rho = box.getLeafList().size() / box.getBoundary().volume();
        double gsigma = inputData.getValue(0);
        // g(sigma) = (p/rho - 1) 1.5 / (pi rho)
        // p = rho + (2/3) pi rho^2 g(sigma)
        ((DataDouble) data.getData(0)).x = rho * (1 + 2.0 / 3.0 * Math.PI * rho * gsigma);
        gsigma = inputData.getValue(1);
        ((DataDouble) data.getData(1)).x = rho * (1 + 2.0 / 3.0 * Math.PI * rho * gsigma);
        double e = inputData.getValue(2);
        ((DataDouble) data.getData(2)).x = rho * 2.0 / 3.0 * Math.PI * rho * e;
        return data;
    }

    @Override
    protected IDataInfo processDataInfo(IDataInfo inputDataInfo) {
        return dataInfo;
    }
}

Add new data processor to compute P from g(sigma)


package com.kickstarter.viewmodels;

import android.content.Intent;

import com.kickstarter.KSRobolectricTestCase;
import com.kickstarter.factories.ProjectFactory;
import com.kickstarter.models.Project;
import com.kickstarter.ui.IntentKey;

import org.junit.Test;

import rx.observers.TestSubscriber;

public final class ThanksViewModelTest extends KSRobolectricTestCase {
  @Test
  public void testThanksViewModel_project() {
    final ThanksViewModel vm = new ThanksViewModel(environment());
    final Project project = ProjectFactory.project();

    final TestSubscriber<Project> projectTest = new TestSubscriber<>();
    vm.outputs.project().subscribe(projectTest);

    vm.intent(new Intent().putExtra(IntentKey.PROJECT, ProjectFactory.project()));
    projectTest.assertValues(project);
  }
}

Add test for emitting project


package edu.isi.karma.mapreduce.driver;

import static org.junit.Assert.assertEquals;

import java.io.File;
import java.net.URL;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.util.ToolRunner;
import org.junit.Test;

public class TestAvroGenerationLocal {

	@Test
	public void test() throws Exception {
		Configuration conf = new Configuration();

		String [] jobArgs = {"-files", new File(getTestResource("people-model.ttl").toURI()).getAbsolutePath().toString(), "-archives", new File( getTestResource("sample_karma_user_home.zip").toURI()).getAbsolutePath(), "-libjars", System.getProperty("user.home") + "/.m2/repository/edu/isi/karma-offline/0.0.1-SNAPSHOT/karma-offline-0.0.1-SNAPSHOT-shaded.jar", new File(getTestResource("JSONAvroProcessorLocal.properties").toURI()).getAbsolutePath().toString()};
		int res = ToolRunner.run(conf, new JSONAvroProcessor(), jobArgs);
		assertEquals(0, res);
	}

	protected URL getTestResource(String name)
	{
		return getClass().getClassLoader().getResource(name);
	}
}

Test for generating JSON from Avro in local MR


package eu.redray.trevie;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

/**
 * Creates custom CursorAdapter to display records from favourites database
 */
public class FavouritesGridAdapter extends CursorAdapter {
    public FavouritesGridAdapter(Context context, Cursor c, int flags) {
        super(context, c, flags);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View view = LayoutInflater.from(context).inflate(R.layout.movie_grid_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        view.setTag(viewHolder);

        return view;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        ViewHolder viewHolder = (ViewHolder) view.getTag();

        // Read title from cursor
        String title = cursor.getString(MovieGridFragment.COL_MOVIE_TITLE);
        viewHolder.titleView.setText(title);
        viewHolder.titleView.setSelected(true);

        // Read release year from cursor
        String year = cursor.getString(MovieGridFragment.COL_MOVIE_RELEASE_DATE);
        viewHolder.yearView.setText(year.substring(0, 4));

        // Read poster path
        Picasso.with(context).load(cursor.getString(MovieGridFragment.COL_MOVIE_POSTER_PATH)).
                placeholder(R.drawable.temp).error(R.drawable.error).fit().into(viewHolder.posterView);
    }

    /**
     * Holds all the views used to display data in movie grid item.
     */
    private static class ViewHolder {
        ImageView posterView;
        ImageView favouriteIconView;
        TextView titleView;
        TextView yearView;

        public ViewHolder(View view) {
            posterView = (ImageView) view.findViewById(R.id.grid_movie_poster);
            favouriteIconView = (ImageView) view.findViewById(R.id.grid_movie_favourite);
            titleView = (TextView) view.findViewById(R.id.grid_movie_title);
            yearView = (TextView) view.findViewById(R.id.grid_movie_genre);
        }
    }
}

Add custom CursorAdapter to display records from favourites database


package com.boundary.sdk.event.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.camel.Converter;

/**
 * Uses Camel's conversion system to convert from a {@link InputStream} to {@link List}
 *
 * @author davidg
 *
 */
@Converter
public final class InputStreamConverter {

	@Converter
	public static List<String> toList(InputStream stream) {

		BufferedReader bufferedReader = null;

		bufferedReader = new BufferedReader(new InputStreamReader(stream));
		List<String> lines = new ArrayList<String>();

		String line = null;
		try {
			while ((line = bufferedReader.readLine()) != null) {
				System.out.println(line);
				lines.add(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return lines;
	}

}

Add converter from InputStream to List


/**
 * AddDeployment Implements Add Deployment Use Case
 *
 * @author Ushahidi Team <team@ushahidi.com>
 * @package com.ushahidi.android.core.usecase.deployment
 * @copyright 2014 Ushahidi
 * @license https://www.gnu.org/licenses/agpl-3.0.html GNU Affero General Public License Version 3 (AGPL3)
 */
package com.ushahidi.android.core.usecase.deployment;

import com.ushahidi.android.core.usecase.Interactor;

public interface AddDeployment extends Interactor {

}

Add use case for adding a deployment


/**
 * Copyright © 2011-2013 EMBL - European Bioinformatics Institute
 *
 * 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 uk.ac.ebi.phenotype.imaging.springrest.images.dao;

import java.util.List;

import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
/**
 * Interface for images data access from solr (probably not need an interface to this as it's solr specific...)
 * @author jwarren
 *
 */
public interface ImagesSolrDao {

	public abstract long getNumberFound();

	public abstract List<String> getIdsForKeywordsSearch(String query,
			int start, int length);

	public abstract QueryResponse getExperimentalFacetForGeneAccession(String geneId);

	public QueryResponse getExpressionFacetForGeneAccession(String geneId);
	public QueryResponse getDocsForGeneWithFacetField(String query, String facetName, String facetValue, String filterQuery, int start, int length);

	public QueryResponse getFilteredDocsForQuery(String query, List<String> filterField,String qf, String defType,
			int start, int length);

	public QueryResponse getDocsForMpTerm(String mpId, int start, int length);

}

Change copyright in Apache 2 license to 2013 documented documented Fixed solr gene details page images not limited to expression and gene id! image results works from mp, genedetails and search??? images links working on gene details and new server side icon on mp page hacks to show expression not filtered on geneid update all images to use SOLR only (no hibernate); reformat page to be the same as detail page layout; add MGI term search new backend images jsps for geneDetails and mp pages


/*
 * Copyright 2009-2011 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 info.joseluismartin.gui.bind;

import org.springframework.beans.PropertyAccessException;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DefaultBindingErrorProcessor;

/**
 * @author Jose Luis Martin - (jlm@joseluismartin.info)
 */
public class ControlBindingErrorProcessor extends DefaultBindingErrorProcessor {

	/**
	 * Add a ControlError instead FieldError to hold component that has failed.
	 * @param control
	 * @param ex
	 * @param bindingResult
	 */
	public void processPropertyAccessException(Object control, PropertyAccessException ex,
			BindingResult bindingResult ) {
		// Create field error with the exceptions's code, e.g. "typeMismatch".
		String field = ex.getPropertyName();
		String[] codes = bindingResult.resolveMessageCodes(ex.getErrorCode(), field);
		Object[] arguments = getArgumentsForBindError(bindingResult.getObjectName(), field);
		Object rejectedValue = ex.getValue();
		if (rejectedValue != null && rejectedValue.getClass().isArray()) {
			rejectedValue = StringUtils.arrayToCommaDelimitedString(ObjectUtils.toObjectArray(rejectedValue));
		}
		bindingResult.addError(new ControlError(control,
				bindingResult.getObjectName(), field, rejectedValue, true,
				codes, arguments, ex.getLocalizedMessage()));
	}
}

Add method to DefaultControlErrorProcessor for hold the swing control


/*
 * Copyright (c) 2013 Malhar Inc. ALL Rights Reserved.
 *
 * 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.datatorrent.lib.math;

import com.datatorrent.api.BaseOperator;
import com.datatorrent.api.DefaultOutputPort;
import com.datatorrent.api.annotation.OutputPortFieldAnnotation;

/**
 *  Abstract base operator defining optional double/float/long/integer output ports.

 *  Duplicate port declaration in operators.

 */
public abstract class AbstractOutports extends BaseOperator
{
	/**
	 * Double type output.
	 */
	@OutputPortFieldAnnotation(name = "doubleResult", optional = true)
	public final transient DefaultOutputPort<Double> doubleResult = new DefaultOutputPort<Double>();

	/**
	 * Float type output.
	 */
	@OutputPortFieldAnnotation(name = "floatResult", optional = true)
	public final transient DefaultOutputPort<Float> floatResult = new DefaultOutputPort<Float>();

	/**
	 * Long type output.
	 */
	@OutputPortFieldAnnotation(name = "longResult", optional = true)
	public final transient DefaultOutputPort<Long> longResult = new DefaultOutputPort<Long>();

	/**
	 * Integer type output.
	 */
	@OutputPortFieldAnnotation(name = "integerResult", optional = true)
	public final transient DefaultOutputPort<Integer> integerResult = new DefaultOutputPort<Integer>();
}

Change name to more logical name


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

package org.openmhealth.dsu.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * A set of exception handlers that are applied to all controllers, primarily to prevent information disclosure.
 *
 * @author Emerson Farrugia
 */
@ControllerAdvice
public class ExceptionHandlingControllerAdvice {

    private static final Logger log = LoggerFactory.getLogger(ExceptionHandlingControllerAdvice.class);

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public void handleException(Exception e) {

        log.error("The following API exception is being swallowed to prevent it from being passed to the browser.", e);
    }
}

Add an exception handling fallback for all controllers.


package org.apache.velocity.test.misc;

/*
 * Copyright 2006 The Apache Software Foundation.
 *
 * 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.
 */

public class UberspectorTestObject
{
    private String regular;
    private String premium;

    private boolean regularBool;
    private boolean premiumBool;

    private String ambigous;

    /**
     * @return the premium
     */
    public String getpremium()
    {
        return premium;
    }

    /**
     * @param premium the premium to set
     */
    public void setpremium(String premium)
    {
        this.premium = premium;
    }

    /**
     * @return the premiumBool
     */
    public boolean ispremiumBool()
    {
        return premiumBool;
    }

    /**
     * @param premiumBool the premiumBool to set
     */
    public void setpremiumBool(boolean premiumBool)
    {
        this.premiumBool = premiumBool;
    }

    /**
     * @return the regular
     */
    public String getRegular()
    {
        return regular;
    }

    /**
     * @param regular the regular to set
     */
    public void setRegular(String regular)
    {
        this.regular = regular;
    }

    /**
     * @return the regularBool
     */
    public boolean isRegularBool()
    {
        return regularBool;
    }

    /**
     * @param regularBool the regularBool to set
     */
    public void setRegularBool(boolean regularBool)
    {
        this.regularBool = regularBool;
    }

    /**
     * @return the ambigous
     */
    public String getAmbigous()
    {
        return ambigous;
    }

    /**
     * @param ambigous the ambigous to set
     */
    public void setAmbigous(String ambigous)
    {
        this.ambigous = ambigous;
    }

    /**
     * @param ambigous the ambigous to set
     */
    public void setAmbigous(StringBuffer ambigous)
    {
        this.ambigous = ambigous.toString();
    }
}

Test Object for the UberspectorTestCase


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

package org.jeeventstore.core.notifier;

import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
import javax.ejb.Lock;
import javax.ejb.LockType;
import org.jeeventstore.core.ChangeSet;

/**
 * A synchronous event store commit notifier.
 * Notifies interested listeners in the same thread that also commits
 * the changes to the event store. The notification order is currently
 * in the order of registration, but this is not a guarantee and might change
 * in the future.
 *
 * @author Alexander Langer
 */
@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
public class SyncEventStoreCommitNotifier
        extends AbstractEventStoreCommitNotifier
        implements EventStoreCommitNotifier {

    /**
     * @see EventStoreCommitNotifier#notifyListeners(org.jeeventstore.core.ChangeSet)
     */
    @Override
    @Lock(LockType.READ)
    public void notifyListeners(ChangeSet changeSet) {
        this.performNotification(changeSet);
    }

}

Add a synchronous commit notifier


package com.autonomy.abc.search;

import com.autonomy.abc.config.ABCTestBase;
import com.autonomy.abc.config.TestConfig;
import com.autonomy.abc.framework.KnownBug;
import com.autonomy.abc.framework.categories.CoreFeature;
import com.autonomy.abc.selenium.page.search.SearchPage;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import static com.autonomy.abc.framework.ABCAssert.assertThat;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.hamcrest.Matchers.not;

@Category(CoreFeature.class)
public class SearchCoreITCase extends ABCTestBase {
    private SearchPage searchPage;

    public SearchCoreITCase(TestConfig config) {
        super(config);
    }

    @Test
    @KnownBug("CSA-2058")
    public void testSearchResultsNotEmpty() {
        searchPage = getApplication().searchService().search("luke");
        for (String title : searchPage.getSearchResultTitles(SearchPage.RESULTS_PER_PAGE)) {
            assertThat(title, not(isEmptyOrNullString()));
        }
    }
}

Add core feature test for search


/*
 * #%L
 * SciJava mathematical expression parser.
 * %%
 * Copyright (C) 2015 Board of Regents of the University of
 * Wisconsin-Madison.
 * %%
 * 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.sjep;

import java.io.IOException;

import org.scijava.sjep.eval.EvaluatorConsole;

/**
 * Launches the console-driven expression evaluator.
 *
 * @author Curtis Rueden
 * @see EvaluatorConsole
 */
public final class Main {

	private Main() {
		// Prevent instantiation of utility class.
	}

	// -- Main method --

	public static void main(final String[] args) throws IOException {
		new EvaluatorConsole().showConsole();
	}

}

Add main class that launches the evaluator console


package org.zanata.common;

import javax.xml.bind.annotation.XmlType;

@XmlType(name = "userActionType")
public enum UserActionType
{
   LAST_TRANSLATED, UPLOAD_DOC, REVIEWED_TRANSLATION;
}

Create enum for user action type


package org.intermine.webservice.server.output;

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

import org.intermine.api.InterMineAPI;
import org.intermine.api.LinkRedirectManager;
import org.intermine.api.results.ResultElement;
import org.intermine.model.InterMineObject;
import org.intermine.web.logic.PortalHelper;
import org.json.JSONObject;

public class TableCellFormatter
{

    private static final String CELL_KEY_URL = "url";
    private static final String CELL_KEY_VALUE = "value";
    private static final String CELL_KEY_CLASS = "class";
    private static final String CELL_KEY_ID = "id";

    private final LinkRedirectManager redirector;
    private final InterMineAPI im;

    public TableCellFormatter(InterMineAPI im) {
        this.im = im;
        this.redirector = im.getLinkRedirector();
    }

    /**
     * Get the JSONObject that represents each cell in the results row
     * @param cell The result element with the data
     * @return A JSONObject
     */
    public JSONObject toJSON(ResultElement cell) {
        Map<String, Object> mapping = new HashMap<String, Object>();
        if (cell == null || cell.getId() == null) {
            mapping.put(CELL_KEY_URL, null);
            mapping.put(CELL_KEY_VALUE, null);
        } else {
            String link = null;
            if (redirector != null) {
                link = redirector.generateLink(im, (InterMineObject) cell.getObject());
            }
            if (link == null) {
                link = PortalHelper.generateReportPath(cell);
            }
            mapping.put(CELL_KEY_URL, link);
            mapping.put(CELL_KEY_CLASS, cell.getType());
            mapping.put(CELL_KEY_ID, cell.getId());
            mapping.put(CELL_KEY_VALUE, cell.getField());
        }
        JSONObject ret = new JSONObject(mapping);
        return ret;
    }
}

Refactor json cell formatting into own class


package org.jrebirth.af.core.wave;

/**
 * The class DefaultWaveListener is the default empty implementation.
 *
 * You can use it as base class to only override the method you need.
 *
 * @author Sébastien Bordes
 */
public class DefaultWaveListener implements WaveListener {

    /**
     * {@inheritDoc}
     */
    @Override
    public void waveCreated(Wave wave) {
        // Nothing to do yet
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void waveSent(Wave wave) {
        // Nothing to do yet
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void waveProcessed(Wave wave) {
        // Nothing to do yet
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void waveCancelled(Wave wave) {
        // Nothing to do yet
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void waveConsumed(Wave wave) {
        // Nothing to do yet
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void waveFailed(Wave wave) {
        // Nothing to do yet
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void waveDestroyed(Wave wave) {
        // Nothing to do yet
    }

}

Add default implementation of wave listener


/*
 * This file is released under terms of BSD license
 * See LICENSE file for more information
 */
package claw.tatsu.xcodeml.xnode.fortran;

import org.junit.Test;

import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertNotNull;
import static org.junit.Assert.assertNull;

/**
 * Test Xintrinsic class
 *
 * @author clementval
 */
public class XintrinsicTest {

  @Test
  public void xIntrinsicTest() {
    assertNull(Xintrinsic.fromString(null));
    assertNull(Xintrinsic.fromString("dummy"));
    assertNotNull(Xintrinsic.fromString("allocated"));
    assertEquals(Xintrinsic.ALLOCATED, Xintrinsic.fromString("allocated"));
  }
}

Add test class for Xintrinsic


/*
 * 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.qpid.proton4j.engine;

/**
 * Represents the state of an AMQP resource.
 */
public enum EndpointState {
    UNINITIALIZED,  // TODO - Better names ?
    ACTIVE,
    CLOSED,
}

Add an endpoint state enum for consideration


/*
 * Copyright 2016 Jaakko Hannikainen
 *
 * 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 fi.jgke.tagger.unit.repository;

import fi.jgke.tagger.domain.Source;
import fi.jgke.tagger.exception.SourceNotFoundException;
import fi.jgke.tagger.repository.SourceRepository;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.mockito.Mockito.when;

public class SourceRepositoryTest {
// Wake me up when Mockito 2 works with spring
    /*
    @Mock
    SourceRepository sourceRepository;

    @Before
    public void init() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void findOneWorks() throws Exception {
        Long id = 5L;
        Source source = new Source();
        when(sourceRepository.findOne(id)).thenReturn(source);
        when(sourceRepository.findOneOrThrow(id)).thenCallRealMethod();
        Source result = sourceRepository.findOneOrThrow(id);
        Assert.assertEquals(source, result);
    }

    @Test(expected = SourceNotFoundException.class)
    public void findOneThrows() throws Exception {
        Long id = 5L;
        when(sourceRepository.findOne(id)).thenReturn(null);
        when(sourceRepository.findOneOrThrow(id)).thenCallRealMethod();
        sourceRepository.findOneOrThrow(id);
    }
*/
}

Add a "test" for SourceRepository


package io.enmasse.systemtest.executor;

import java.io.*;
import java.util.ArrayList;
import java.util.concurrent.*;

/**
 * Class provide execution of external command
 */
public class Executor {
    private Process process;
    private String stdOut;
    private String stdErr;

    /**
     * Getter for stdOutput
     * @return string stdOut
     */
    public String getStdOut() {
        return stdOut;
    }

    /**
     * Getter for stdErrorOutput
     * @return string stdErr
     */
    public String getStdErr() {
        return stdErr;
    }

    /**
     * Method executes external command
     * @param commands arguments for command
     * @return returns true if command exit code is 0
     * @throws IOException
     * @throws InterruptedException
     * @throws ExecutionException
     */
    protected boolean execute(ArrayList<String> commands) throws IOException, InterruptedException, ExecutionException {
        return execute(commands, 0);
    }

    /**
     * Method executes external command
     * @param commands arguments for command
     * @param timeout timeout in ms for kill
     * @return returns true if command exit code is 0
     * @throws IOException
     * @throws InterruptedException
     * @throws ExecutionException
     */
    protected boolean execute(ArrayList<String> commands, int timeout) throws IOException, InterruptedException, ExecutionException{
        process = Runtime.getRuntime().exec((commands.toArray(new String[0])));

        Future<String> output = readStdOutput();
        Future<String> error = readStdError();

        int retCode = 1;
        if(timeout > 0){
            if (process.waitFor(5000, TimeUnit.MILLISECONDS)){
                retCode = process.exitValue();
            }
        }else{
            retCode = process.waitFor();
        }

        stdOut = output.get();
        stdErr = error.get();

        return retCode == 0;
    }

    /**
     * Get standard output of execution
     * @return future string output
     */
    private Future<String> readStdOutput() {
        StreamGobbler errorGobbler = new
                StreamGobbler(process.getInputStream());
        return errorGobbler.read();
    }

    /**
     * Get standard error output of execution
     * @return future string error output
     */
    private Future<String> readStdError(){
        StreamGobbler errorGobbler = new
                StreamGobbler(process.getErrorStream());
        return errorGobbler.read();
    }

    /**
     * Class represent async reader
     */
    class StreamGobbler {
        private final ExecutorService executorService = Executors.newSingleThreadExecutor();
        private InputStream is;

        /**
         * Constructor of StreamGobbler
         * @param is input stream for reading
         */
        StreamGobbler(InputStream is) {
            this.is = is;
        }

        /**
         * read method
         * @return return future string of output
         */
        public Future<String> read() {
            Future<String> future = executorService.submit(() -> {
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line;
                StringBuilder builder = new StringBuilder();
                while ( (line = br.readLine()) != null)
                    builder.append(line).append('\n');
                isr.close();
                br.close();
                return builder.toString();
            });

            return future;
        }
    }
}

Implement executor for external commands


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

package org.broadleafcommerce.common.util;

import org.broadleafcommerce.common.web.BroadleafRequestContext;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;

/**
 * Convenience class to faciliate getting internationalized messages.
 *
 * Note that this class is scanned as a bean to pick up the applicationContext, but the methods
 * this class provides should be invoked statically.
 *
 * @author Andre Azzolini (apazzolini)
 */
@Service("blBLCMessageUtils")
public class BLCMessageUtils implements ApplicationContextAware {

    protected static ApplicationContext applicationContext;

    /**
     * Returns the message requested by the code with no arguments and the currently set Java Locale on
     * the {@link BroadleafRequestContext} as returned by {@link BroadleafRequestContext#getJavaLocale()}
     *
     * @param code
     * @return the message
     */
    public static String getMessage(String code) {
        return getMessage(code, null);
    }

    /**
     * Returns the message requested by the code with the specified arguments and the currently set Java Locale on
     * the {@link BroadleafRequestContext} as returned by {@link BroadleafRequestContext#getJavaLocale()}
     *
     * @param code
     * @return the message
     */
    public static String getMessage(String code, Object[] args) {
        BroadleafRequestContext brc = BroadleafRequestContext.getBroadleafRequestContext();
        return getMessageSource().getMessage(code, args, brc.getJavaLocale());
    }

    /**
     * @return the "messageSource" bean from the application context
     */
    protected static MessageSource getMessageSource() {
        return (MessageSource) applicationContext.getBean("messageSource");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        BLCMessageUtils.applicationContext = applicationContext;
    }

}

Add a utility class for looking up internationalized messages


/*
 * Copyright 2015 Open Networking Laboratory
 *
 * 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.onosproject.vtnrsc.subnet;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable;

import org.junit.Test;
import org.onlab.packet.IpAddress;
import org.onosproject.vtnrsc.AllocationPool;
import org.onosproject.vtnrsc.DefaultAllocationPool;

import com.google.common.testing.EqualsTester;

/**
 * Unit tests for DefaultAllocationPool class.
 */
public class DefaultAllocationPoolTest {

    final IpAddress startIP1 = IpAddress.valueOf("192.168.1.1");
    final IpAddress startIP2 = IpAddress.valueOf("192.168.1.2");
    final IpAddress endIP1 = IpAddress.valueOf("192.168.1.1");
    final IpAddress endIP2 = IpAddress.valueOf("192.168.1.2");

    /**
     * Checks that the DefaultAllocationPool class is immutable.
     */
    @Test
    public void testImmutability() {
        assertThatClassIsImmutable(DefaultAllocationPool.class);
    }

    /**
     * Checks the operation of equals() methods.
     */
    @Test
    public void testEquals() {
        AllocationPool pool1 = new DefaultAllocationPool(startIP1, endIP1);
        AllocationPool pool2 = new DefaultAllocationPool(startIP1, endIP1);
        AllocationPool pool3 = new DefaultAllocationPool(startIP2, endIP2);
        new EqualsTester().addEqualityGroup(pool1, pool2)
                .addEqualityGroup(pool3).testEquals();
    }

    /**
     * Checks the construction of a DefaultAllocationPool object.
     */
    @Test
    public void testConstruction() {
        final AllocationPool apool = new DefaultAllocationPool(startIP1, endIP1);
        assertThat(startIP1, is(apool.startIp()));
        assertThat(endIP1, is(apool.endIp()));
    }
}

Add the junit test code of DefaultAllocationPool


/*
 * Copyright 2000-2009 JetBrains s.r.o.
 *
 * 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.
 */

/*
 * @author max
 */
package com.intellij.openapi.keymap.impl;

import java.util.Arrays;
import java.util.List;

public class DefaultBundledKeymaps implements BundledKeymapProvider {
  public List<String> getKeymapFileNames() {
    return Arrays.asList(
      "Keymap_Default.xml",
      "Keymap_Mac.xml",
      "Keymap_MacClassic.xml",
      "Keymap_Emacs.xml",
      "Keymap_VisualStudio.xml",
      "Keymap_GNOME.xml",
      "Keymap_XWin.xml",
      "Keymap_KDE.xml",
      "Keymap_Eclipse.xml",
      "Keymap_Netbeans.xml"
    );
  }
}

/*
 * Copyright 2000-2009 JetBrains s.r.o.
 *
 * 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.
 */

/*
 * @author max
 */
package com.intellij.openapi.keymap.impl;

import java.util.Arrays;
import java.util.List;

public class DefaultBundledKeymaps implements BundledKeymapProvider {
  public List<String> getKeymapFileNames() {
    return Arrays.asList(
      "Keymap_Default.xml",
      "Keymap_Mac.xml",
      "Keymap_MacClassic.xml",
      "Keymap_Emacs.xml",
      "Keymap_VisualStudio.xml",
      "Keymap_XWin.xml",
      "Keymap_GNOME.xml",
      "Keymap_KDE.xml",
      "Keymap_Eclipse.xml",
      "Keymap_Netbeans.xml"
    );
  }
}

Fix GNOME keymap missing shortcuts.


package net.kencochrane.raven.sentrystub;

import net.kencochrane.raven.sentrystub.auth.AuthValidator;
import net.kencochrane.raven.sentrystub.auth.InvalidAuthException;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@WebFilter(servletNames = "SentryHttpServlet")
public class SentryAuthenticationFilter implements Filter {
    private static final String SENTRY_AUTH = "X-Sentry-Auth";
    private AuthValidator authValidator;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        authValidator = new AuthValidator();
        //TODO: Load filter config to add users!
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //TODO: respond to everything that isn't "https://example.com/sentry/api/project-id/store/"
        String pathInfo = req.getPathInfo();

        if (!validateAuth(req, resp)) return;

        chain.doFilter(request, response);
    }

    private boolean validateAuth(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Map<String, String> sentryAuthDetails = extractSentryAuthDetails(req);
        String projectId = req.getPathInfo().substring(1, req.getPathInfo().indexOf('/', 1));

        try {
            authValidator.validateSentryAuth(sentryAuthDetails, projectId);
        } catch (InvalidAuthException iae) {
            resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
            PrintWriter writer = resp.getWriter();
            for (String message : iae.getDetailedMessages()) {
                writer.println(message);
            }
            return false;
        }
        return true;
    }

    private Map<String, String> extractSentryAuthDetails(HttpServletRequest request) {
        String sentryAuth = request.getHeader(SENTRY_AUTH);
        if (sentryAuth == null) {
            return Collections.emptyMap();
        }

        String[] authParameters = sentryAuth.split(",");
        Map<String, String> authDetails = new HashMap<String, String>(authParameters.length);
        for (String authParameter : authParameters) {
            String[] splitParameter = authParameter.split("=");
            authDetails.put(splitParameter[0], splitParameter[1]);
        }

        return authDetails;
    }

    @Override
    public void destroy() {
    }
}

Add a filter checking the Authorisation to access the API


package net.mostlyoriginal.api.component.graphics;

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

public class ColorTest {

	@Test
	public void should_convert_hex1_to_r()
	{
		Color color = new Color("FF000000");
		assertColor(color, 1f, 0f, 0f, 0f);
	}

	@Test
	public void should_convert_hex2_to_g()
	{
		Color color = new Color("00FF0000");
		assertColor(color, 0f, 1f, 0f, 0f);
	}

	@Test
	public void should_convert_hex3_to_b()
	{
		Color color = new Color("0000FF00");
		assertColor(color, 0f, 0f, 1f, 0f);
	}

	@Test
	public void should_convert_hex4_to_a()
	{
		Color color = new Color("000000FF");
		assertColor(color, 0f, 0f, 0f, 1f);
	}

	protected void assertColor(Color color, float r, float g, float b, float a) {
		Assert.assertEquals(r, color.r, 0.01f);
		Assert.assertEquals(g, color.g, 0.01f);
		Assert.assertEquals(b, color.b, 0.01f);
		Assert.assertEquals(a, color.a, 0.01f);
	}
}

Add test to color hex constructor.


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

import com.github.aureliano.achmed.resources.properties.FileProperties;

public class PosixFileProvider implements IFileProvider {

	private FileProperties properties;

	public PosixFileProvider() {
		super();
	}

	@Override
	public void setFileMode() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}

	@Override
	public void setFileOwner() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}

	@Override
	public void copyFile() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}

	@Override
	public void copyFolder() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}

	@Override
	public void setFileProperties(FileProperties properties) {
		this.properties = properties;
	}

	@Override
	public FileProperties getFileProperties() {
		return this.properties;
	}
}

Create file provider which implements POSIX pattern on file system commands.


package org.opennms.netmgt.dao.support;

import java.io.IOException;

import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.ValidationException;
import org.opennms.netmgt.dao.CastorDataAccessFailureException;
import org.springframework.dao.DataAccessException;

/**
 * This is modelled after the Spring SQLExceptionTrnaslator.
 *
 * @author DJ Gregor
 */
public class CastorExceptionTranslator {
    public DataAccessException translate(String task, IOException e) {
        return new CastorDataAccessFailureException("Failed to perform IO while " + task + ": " + e, e);
    }

    public DataAccessException translate(String task, ValidationException e) {
        return new CastorDataAccessFailureException("Failed to validate XML file while " + task + ": " + e, e);
    }

    public DataAccessException translate(String task, MarshalException e) {
        return new CastorDataAccessFailureException("Failed to marshal/unmarshal XML file while " + task + ": " + e, e);
    }
}

Add a translator for Castor exceptions (IOException, ValidationException, MarshalException) to Spring DataAccessException.


package se.michaelthelin.spotify.methods;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import se.michaelthelin.spotify.Api;
import se.michaelthelin.spotify.JsonUtilTest;
import se.michaelthelin.spotify.SpotifyProtos.Track;
import se.michaelthelin.spotify.SpotifyProtos.Album;
import se.michaelthelin.spotify.SpotifyProtos.Artist;

import java.util.List;

import static junit.framework.Assert.assertEquals;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class SearchRequestTest {

  @Test
  public void shouldGetArtistsResult() throws Exception {
    Api api = Api.DEFAULT_API;
    SearchRequest request = api.search().query("David Bowie").type("artist").build();

    // Mock response
    String responseFixture = JsonUtilTest.readTestData("artists.json");
    SearchRequest spy = spy(request);
    when(spy.getJson()).thenReturn(responseFixture);

    List<Artist> artists = spy.getArtists();
    assertEquals(2, artists.size());

    Artist firstArtist = artists.get(0);
    Artist secondArtist = artists.get(1);

    assertEquals("0oSGxfWSnnOXhD2fKuz2Gy", firstArtist.getId());
    assertEquals("3dBVyJ7JuOMt4GE9607Qin", secondArtist.getId());
  }

  @Test
  public void shouldGetTracksResult() throws Exception {
    Api api = Api.DEFAULT_API;
    SearchRequest request = api.search().query("Mr. Brightside").type("track").build();

    // Mock response
    String responseFixture = JsonUtilTest.readTestData("tracks.json");
    SearchRequest spy = spy(request);
    when(spy.getJson()).thenReturn(responseFixture);

    List<Track> tracks = spy.getTracks();

    assertEquals(2, tracks.size());

    Track firstTrack = tracks.get(0);
    assertEquals("0eGsygTp906u18L0Oimnem", firstTrack.getId());

    Track secondTrack = tracks.get(1);
    assertEquals("1lDWb6b6ieDQ2xT7ewTC3G", secondTrack.getId());
  }

  @Test
  public void shouldGetAlbumsResult() throws Exception {
    Api api = Api.DEFAULT_API;
    SearchRequest request = api.search().query("The Best Of Keane").type("album").build();

    // Mock response
    String responseFixture = JsonUtilTest.readTestData("albums.json");
    SearchRequest spy = spy(request);
    when(spy.getJson()).thenReturn(responseFixture);

    List<Album> albums = spy.getAlbums();

    assertEquals(2, albums.size());

    Album firstAlbum = albums.get(0);
    assertEquals("41MnTivkwTO3UUJ8DrqEJJ", firstAlbum.getId());

    Album secondAlbum = albums.get(1);
    assertEquals("6JWc4iAiJ9FjyK0B59ABb4", secondAlbum.getId());
  }

}

Add test for Search request


import stroom.search.elastic.search.SearchExpressionQueryBuilder;
import stroom.util.test.StroomJUnit4ClassRunner;

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

import java.util.List;

@RunWith(StroomJUnit4ClassRunner.class)
public class TestSearchExpressionQueryBuilder {
    SearchExpressionQueryBuilder builder;

    @Before
    public void init() {
        builder = new SearchExpressionQueryBuilder(
                null,
                null,
                null,
                System.currentTimeMillis()
        );
    }

    @Test
    public void testSimple() {
        Assert.assertEquals("Is true", 42, 42);
    }

    @Test
    public void testTokenizeExpression() {
        String expr = "123, 456,789";
        String[] expected = { "123", "456", "789" };
        String[] actual = builder.tokenizeExpression(expr);
        Assert.assertArrayEquals("Expression tokens were extracted", expected, actual);
    }
}

Add first ES unit test


package com.rainliu.emojipanel.span;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.text.style.DynamicDrawableSpan;

import java.lang.ref.WeakReference;

public class EmojiSpan extends DynamicDrawableSpan {

  private Context mContext;

  private int mIconId;

  private Drawable mDrawable;

  private int mSize = 50; // Should not be hard-coded

  public EmojiSpan(Context context, int resourceId, int size) {
    this.mContext = context;
    this.mIconId = resourceId;
    mSize = size;
  }

  @Override
  public Drawable getDrawable() {
    if (null == this.mDrawable) {
      this.mDrawable = this.mContext.getResources().getDrawable(this.mIconId);
      this.mDrawable.setBounds(0, 0, mSize, mSize);
    }

    return this.mDrawable;
  }

  @Override public int getSize(final Paint paint, final CharSequence text, final int start,
                               final int end, final Paint.FontMetricsInt fontMetrics) {
    if (fontMetrics != null) {
      final Paint.FontMetrics paintFontMetrics = paint.getFontMetrics();
      fontMetrics.top = (int) paintFontMetrics.top;
      fontMetrics.bottom = (int) paintFontMetrics.bottom;
    }

    return (int) mSize;
  }

  @Override public void draw(final Canvas canvas, final CharSequence text, final int start,
                             final int end, final float x, final int top, final int y,
                             final int bottom, final Paint paint) {
    final Drawable drawable = getDrawable();
    final Paint.FontMetrics paintFontMetrics = paint.getFontMetrics();
    final float fontHeight = paintFontMetrics.descent - paintFontMetrics.ascent;
    final float centerY = y + paintFontMetrics.descent - fontHeight / 2;
    final float transitionY = centerY - mSize / 2;

    canvas.save();
    canvas.translate(x, transitionY);
    drawable.draw(canvas);
    canvas.restore();
  }

  private Drawable getCachedDrawable() {
    WeakReference<Drawable> wr = mDrawableRef;
    Drawable d = null;

    if (wr != null)
        d = wr.get();

    if (d == null) {
        d = getDrawable();
        mDrawableRef = new WeakReference<Drawable>(d);
    }

    return d;
}

  private WeakReference<Drawable> mDrawableRef;
}

Move a copy to emojipicker library where there should be one


package com.github.aureliano.achmed.exception;

public class UnsupportedPackageManagerException extends RuntimeException {

	private static final long serialVersionUID = -4089891118124103597L;

	public UnsupportedPackageManagerException() {
		super();
	}

	public UnsupportedPackageManagerException(String message) {
		super(message);
	}

	public UnsupportedPackageManagerException(Throwable throwable) {
		super(throwable);
	}

	public UnsupportedPackageManagerException(String message, Throwable throwable) {
		super(message, throwable);
	}
}

Create unsupported package manager exception.


package com.averi.worldscribe.activities;

import android.support.v7.app.AppCompatActivity;

/**
 * Created by mark on 05/07/16.
 *
 * ArticleActivity is the superclass for each Activity that displays a certain Category of Articles.
 *
 * All subclasses must implement {@link #getLayoutResourceID} and call
 * {@link #setUpArticleCore} within onCreate.
 */
public abstract class ArticleActivity extends AppCompatActivity {

    /**
     * Load data pertaining to the selected Article, and use it in set-up processes that are common
     * to Article Activities of all Categories.
     */
    protected void setUpArticleCore() {

    }

    /**
     * @return The Android Resource ID of this Activity's layout resource file.
     */
    protected abstract int getLayoutResourceID();

}

Create a superclass for Article Activities


package org.ensembl.healthcheck.testcase.generic;

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

import java.sql.Connection;
import java.util.HashMap;
import java.util.Iterator;

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

/**
 * Check that there are no blank db_display_name fields in external_db.
 */

public class ExternalDBDisplayName extends SingleDatabaseTestCase {

	/**
   * Create a new PredictedXrefs testcase.
   */
	public ExternalDBDisplayName() {

		addToGroup("release");
		addToGroup("core_xrefs");
		setDescription("Check that there are no blank db_display_name fields in external_db");

	}

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

		boolean result = true;

		Connection con = dbre.getConnection();

		int rows = getRowCount(con, "SELECT COUNT(*) FROM external_db WHERE db_display_name IS NULL OR db_display_name LIKE ' %'");

		if (rows > 0) {

			ReportManager.problem(this, con, rows + " rows in external_db have null or blank db_display_name - this will mean their label is missing on the web page");
			result = false;

		} else {

			ReportManager.correct(this, con, "No blank db_display_name fields in external_db");

		}

		return result;

	} // run

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

} // ExternalDBDisplayName

Check that there are no blank or null db_display_name fields in external_db - would cause problems for web display.


package org.ovirt.engine.core.utils;

import static org.junit.Assert.assertEquals;
import static org.junit.runners.Parameterized.Parameters;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

@RunWith(Parameterized.class)
public class XmlUtilsTest {
    @Rule
    public RandomUtilsSeedingRule rusr = new RandomUtilsSeedingRule();

    private int level;
    private String value;

    public XmlUtilsTest(int level, String value) {
        this.level = level;
        this.value = value;
    }

    @Parameters
    public static List<Object[]> data() {
        List<Object[]> params = new ArrayList<>();
        // XmlUtils.getXYZValue support recursive searching from a depth of 2 and above, e.g.:
        // <tag><innerTag>value</innerTag><tag>
        for (int i = 2; i < 10; ++i) {
            params.add(new Object[]{i, String.valueOf(RandomUtils.instance().nextInt())});
        }
        return params;
    }

    @Test
    public void testGetIntValueNesting() throws Exception {
        int actual = XmlUtils.getIntValue(stringToElement(buildNestedXml(level, value)), "Level1");
        assertEquals(Integer.valueOf(value).intValue(), actual);
    }

    @Test
    public void testGetTextValue() throws Exception {
        String actual = XmlUtils.getTextValue(stringToElement(buildNestedXml(level, value)), "Level1");
        assertEquals(value, actual);
    }

    private static Element stringToElement(String s) throws ParserConfigurationException, IOException, SAXException {
        return DocumentBuilderFactory.newInstance()
                .newDocumentBuilder()
                .parse(new ByteArrayInputStream(s.getBytes("UTF-8")))
                .getDocumentElement();
    }

    private static String buildNestedXml (int count, String s) {
        if (count == 0) {
            return s;
        }
        return "<Level" + count + '>' + buildNestedXml(count - 1, s) + "</Level" + count + '>';
    }
}

Add minimal tests to XmlUtils


package org.jdesktop.swingx.painter;

import org.jdesktop.beans.AbstractBeanInfoTest;

public class AlphaPainterBeanInfoTest extends AbstractBeanInfoTest<AlphaPainter<Object>> {
    /**
     * {@inheritDoc}
     */
    @Override
    protected AlphaPainter<Object> createInstance() {
        return new AlphaPainter<Object>();
    }
}

Add bean test for AlphaPainter.


package org.ow2.proactive.workflow_catalog.rest.controller;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ow2.proactive.workflow_catalog.rest.Application;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;

import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;

/**
 * Created by paraita on 1/7/16.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class WorkflowControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setup() {
        //this.mockMvc = standaloneSetup(new WorkflowController()).build();
        this.mockMvc = webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void testList() throws Exception {
        this.mockMvc.perform(get("/buckets/1/workflows")).andExpect(status().isNotFound());
    }
}

Test the list method implementation of the workflows rest controller


package com.gmail.nossr50.events;

import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;

import com.gmail.nossr50.datatypes.SkillType;

/**
 * Called when a user levels up in a skill
 */
@SuppressWarnings("serial")
public class McMMOPlayerLevelUpEvent extends Event {
	private Player player;
	private SkillType skill;
	private int levelsGained;

	public McMMOPlayerLevelUpEvent(Player player, SkillType skill) {
		this.player = player;
		this.skill = skill;
		this.levelsGained = 1;	// Always 1 for now as we call in the loop where the levelups are calculated, could change later!
	}

	/**
	 * @return Player leveling up
	 */
	public Player getPlayer() {
		return player;
	}

	/**
	 * @return SkillType that is being leveled up
	 */
	public SkillType getSkill() {
		return skill;
	}

	/**
	 * @return The number of levels gained in this event
	 */
	public int getLevelsGained() {
		return levelsGained;
	}

	/** Rest of file is required boilerplate for custom events **/
	private static final HandlerList handers = new HandlerList();

	public HandlerList getHandlers() {
		return handers;
	}

	public static HandlerList getHandlerList() {
		return handers;
	}
}

package com.gmail.nossr50.events;

import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;

import com.gmail.nossr50.datatypes.SkillType;

/**
 * Called when a user levels up in a skill
 */
@SuppressWarnings("serial")
public class McMMOPlayerLevelUpEvent extends Event {
	private Player player;
	private SkillType skill;
	private int levelsGained;

	public McMMOPlayerLevelUpEvent(Player player, SkillType skill) {
		this.player = player;
		this.skill = skill;
		this.levelsGained = 1;	// Always 1 for now as we call in the loop where the levelups are calculated, could change later!
	}

	/**
	 * @return Player leveling up
	 */
	public Player getPlayer() {
		return player;
	}

	/**
	 * @return SkillType that is being leveled up
	 */
	public SkillType getSkill() {
		return skill;
	}

	/**
	 * @return The number of levels gained in this event
	 */
	public int getLevelsGained() {
		return levelsGained;
	}

	/** Rest of file is required boilerplate for custom events **/
	private static final HandlerList handlers = new HandlerList();

	public HandlerList getHandlers() {
		return handlers;
	}

	public static HandlerList getHandlerList() {
		return handlers;
	}
}

Fix typo Stop programming at late night


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

import java.text.SimpleDateFormat;
import java.util.TimeZone;
import java.util.Date;

import net.minidev.json.JSONObject;
import net.minidev.json.JSONValue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.pinterest.secor.common.SecorConfig;
import com.pinterest.secor.message.Message;
import com.pinterest.secor.message.ParsedMessage;

/**
 * PerfMetricsDateParser extracts timestamp field (specified by 'message.timestamp.name')
 * and creates custom output dirs based on a custom formatter, defined by defaultFormatter
 * the output dir will look like s3://<bucket>/<topic>/yyyy/MM/dd/HH/<file_name>
 *
 * @see http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
 *
 *
 *
 */
public class PerfMetricsDateParser extends MessageParser {
    private static final Logger LOG = LoggerFactory.getLogger(PerfMetricsDateParser.class);
    protected static final String defaultFormatter = "yyyy/MM/dd/HH";

    public PerfMetricsDateParser(SecorConfig config) {
        super(config);
    }

    @Override
    public String[] extractPartitions(Message message) {
        JSONObject jsonObject = (JSONObject) JSONValue.parse(message.getPayload());
        String result[]={};
        if (jsonObject != null) {
            Object fieldValue = jsonObject.get(mConfig.getMessageTimestampName());
            Object inputPattern = mConfig.getMessageTimestampInputPattern();
            if (fieldValue != null && inputPattern != null) {
                try {
                    SimpleDateFormat inputFormatter = new SimpleDateFormat(inputPattern.toString());
                    SimpleDateFormat outputFormatter = new SimpleDateFormat(defaultFormatter);
                    Date dateFormat = inputFormatter.parse(fieldValue.toString());
                    result[] = {outputFormatter.format(dateFormat)};
                    return result;
                } catch (Exception e) {
                    LOG.warn("Impossible to convert date = " + fieldValue.toString()
                            + " for the input pattern = " + inputPattern.toString());
                }
            }
        }

        return result;
    }
}

Add parser for parsing PerfMetrics msg date


package com.hewgill.android.nzsldict;

import android.content.Context;
import android.content.SharedPreferences;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class VocabSheetRepository {
    private final Context mContext;
    private final SharedPreferences mPrefsStore;
    private final String KEY = "NZSL_VOCAB_SHEET";
    private final String PREF_KEY = "VOCAB_SHEET_ITEMS";

    public VocabSheetRepository(Context ctx) {
        mContext = ctx;
        mPrefsStore = ctx.getSharedPreferences(KEY, Context.MODE_PRIVATE);
    }

    public List<DictItem> all() {
        List<DictItem> allItems = new ArrayList<>();
        Dictionary dict = new Dictionary(mContext);
        for (String key : allKeys()) {
            DictItem item = dict.getWord(key);
            if (item != null) { allItems.add(item); }
        }

        return allItems;
    }

    public void add(DictItem item) {
        SharedPreferences.Editor edit = mPrefsStore.edit();
        Set<String> newKeys = allKeys();
        newKeys.add(item.uniqueKey());
        edit.putStringSet(PREF_KEY, newKeys);
        edit.apply();
    }

    public void remove(DictItem item) {
        SharedPreferences.Editor edit = mPrefsStore.edit();
        Set<String> newKeys = allKeys();
        newKeys.remove(item.uniqueKey());
        (new DictItemOfflineAvailability(mContext, item)).unavailableOffline();
        edit.putStringSet(PREF_KEY, newKeys);
        edit.apply();
    }

    public boolean contains(DictItem item) {
        return allKeys().contains(item.uniqueKey());
    }

    private Set<String> allKeys() {
        Set<String> defaultValue = new TreeSet<>();
        return mPrefsStore.getStringSet(PREF_KEY, defaultValue);
    }
}

Add repository class for loading and saving vocab sheet items


package com.duastone.stalactite.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Version Controller.
 * Get project basic infomation.
 * Such as version
 * Created by Fernando on 9/24/16.
 */
@RestController
public class VersionController {

    @RequestMapping(value="/version", method= RequestMethod.GET)
    public JSONObject get() {
        JSONObject object = new JSONObject();
        object.put("name", "Stalactite");
        object.put("version", "v0.1.2");
        object.put("news", "Add version module and support subject total size.");
        return object;
    }
}

Add version support in stalactite


/*
 * #%L
 * TestNG System.out printer
 * %%
 * Copyright (C) 2014 Mats Henrikson
 * %%
 * 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.
 * #L%
 */
package com.little_fluffy_clouds.testng;

import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestNGMethod;
import org.testng.ITestResult;

/**
 * A very simple class that simply prints the class and method names of TestNG tests being run,
 * together with the elapsed time in milliseconds and the test outcome.
 */
public class SystemOutTestPrinter implements IInvokedMethodListener {

    @Override
    public void beforeInvocation(final IInvokedMethod method, final ITestResult testResult) { }

    @Override
    public void afterInvocation(final IInvokedMethod m, final ITestResult r) {
        if (!m.isTestMethod()) return;

        final ITestNGMethod method = m.getTestMethod();
        final String testName = method.getTestClass().getRealClass().getSimpleName();
        final ITestResult testResult = m.getTestResult();
        final long elapsed = testResult.getEndMillis() - testResult.getStartMillis();
        System.out.printf("%s.%s(): %s, %d millis\n",
                testName, method.getMethodName(), Status.forCode(testResult.getStatus()), elapsed);
    }

    /**
     * {@link org.testng.ITestResult}
     */
    @SuppressWarnings({"MagicNumber", "UnusedDeclaration"})
    private enum Status {
        OK(1),
        FAIL(2),
        SKIP(3),
        OK_PCT_FAIL(4),
        STARTED(16),
        UNKNOWN(-1);

        final int code;

        Status(final int code) { this.code = code; }

        static Status forCode(final int c) {
            for (final Status s : Status.values()) {
                if (s.code == c) return s;
            }
            return UNKNOWN;
        }
    }
}

Add the actual java class.


package redis.clients.jedis.tests.benchmark;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.tests.HostAndPortUtil;
import redis.clients.jedis.tests.HostAndPortUtil.HostAndPort;

public class HashingBenchmark {
    private static HostAndPort hnp1 = HostAndPortUtil.getRedisServers().get(0);
    private static HostAndPort hnp2 = HostAndPortUtil.getRedisServers().get(1);
    private static final int TOTAL_OPERATIONS = 100000;

    public static void main(String[] args) throws UnknownHostException,
            IOException {
        List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
        JedisShardInfo shard = new JedisShardInfo(hnp1.host, hnp1.port);
        shard.setPassword("foobared");
        shards.add(shard);
        shard = new JedisShardInfo(hnp2.host, hnp2.port);
        shard.setPassword("foobared");
        shards.add(shard);
        ShardedJedis jedis = new ShardedJedis(shards);
        Collection<Jedis> allShards = jedis.getAllShards();
        for (Jedis j : allShards) {
            j.flushAll();
        }

        long begin = Calendar.getInstance().getTimeInMillis();

        for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
            String key = "foo" + n;
            jedis.set(key, "bar" + n);
            jedis.get(key);
        }

        long elapsed = Calendar.getInstance().getTimeInMillis() - begin;

        jedis.disconnect();

        System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops");
    }
}

Add benchmark for hashing algos


package io.trigger.forge.android.modules.tabs;

import android.webkit.JavascriptInterface;

import io.trigger.forge.android.core.ForgeLog;

/**
 * Created by antoine on 16/03/18.
 */
public class DummyJSBridge {
    @JavascriptInterface
    public void callJavaFromJavaScript(final String callid, final String method, final String params) {
        ForgeLog.d("DummyJSBridge.callJavaFromJavaScript -> " + method + " -> " + params);
    }
}

Move vanilla code back into main source tree


/*
 * Copyright 2010, 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.zanata.rest.dto;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 * Status of a reindex operation.
 *
 * @author Carlos Munoz camunoz@redhat.com
 */
@XmlRootElement(name = "reindexStatus")
@XmlType(name = "reindexStatusType")
public class ReindexStatus
{
   private boolean startedReindex;

   private long percentageComplete;

   private long indexedElements;

   private long totalElements;

   private String currentElementType;

   private long timeElapsed;

   private long timeRemaining;

   public boolean isStartedReindex()
   {
      return startedReindex;
   }

   public void setStartedReindex(boolean startedReindex)
   {
      this.startedReindex = startedReindex;
   }

   @XmlElement
   public long getPercentageComplete()
   {
      return this.indexedElements * 100 / this.totalElements;
   }

   @XmlElement
   public long getIndexedElements()
   {
      return indexedElements;
   }

   public void setIndexedElements(long indexedElements)
   {
      this.indexedElements = indexedElements;
   }

   @XmlElement
   public long getTotalElements()
   {
      return totalElements;
   }

   public void setTotalElements(long totalElements)
   {
      this.totalElements = totalElements;
   }

   @XmlElement
   public String getCurrentElementType()
   {
      return currentElementType;
   }

   public void setCurrentElementType(String currentElementType)
   {
      this.currentElementType = currentElementType;
   }

   @XmlElement
   public long getTimeElapsed()
   {
      return timeElapsed;
   }

   public void setTimeElapsed(long timeElapsed)
   {
      this.timeElapsed = timeElapsed;
   }

   @XmlElement
   public long getTimeRemaining()
   {
      return timeRemaining;
   }

   public void setTimeRemaining(long timeRemaining)
   {
      this.timeRemaining = timeRemaining;
   }
}

Add DTO for indexing status.


/*
  Copyright (C) 2003 EBI, GRL

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

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

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

package org.ensembl.healthcheck.testcase;

import java.sql.*;

import org.ensembl.healthcheck.*;

import org.ensembl.healthcheck.util.*;

/**
 * An EnsEMBL Healthcheck test case that looks for broken foreign-key relationships.
 */

public class ComparaForeignKeyTestCaseHomologyId extends EnsTestCase {

  /**
   * Create an OrphanTestCase that applies to a specific set of databases.
   */
  public ComparaForeignKeyTestCaseHomologyId() {
      databaseRegexp = "^ensembl_compara_.*";
      addToGroup("compara_db_constraints");
      setDescription("Check for broken foreign-key relationships in ensembl_compara databases.");
  }

  public TestResult run() {

    boolean result = true;

    DatabaseConnectionIterator it = getDatabaseConnectionIterator();
    int orphans = 0;

    while (it.hasNext()) {

      Connection con = (Connection)it.next();
      // 1 test to check gene_relationship_id used as foreign key

      if( getRowCount( con, "select count(*) from homology" ) > 0 ) {
        orphans = countOrphans(con, "homology_member", "homology_id", "homology", "homology_id", false );
        if( orphans == 0 ) {
	    ReportManager.correct(this, con, "homology_member <-> homology relationships PASSED");
	} else if( orphans > 0 ) {
	    ReportManager.problem(this, con, "homology_member has unlinked entries in homology FAILED");
        } else {
	    ReportManager.problem(this, con, "homology_member <-> homology TEST NOT COMPLETED, look at the StackTrace if any");
        }
      } else {
	  ReportManager.correct(this, con, "NO ENTRIES in homology table, so nothing to test IGNORED");
      }

      result &= (orphans == 0);

    }

    return new TestResult(getShortTestName(), result);

  }

} // OrphanTestCase

Check homology_id when used as ForeignKey


package bluemix;

import java.io.File;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

import com.ibm.streamsx.topology.TStream;
import com.ibm.streamsx.topology.Topology;
import com.ibm.streamsx.topology.context.AnalyticsServiceProperties;
import com.ibm.streamsx.topology.context.JobProperties;
import com.ibm.streamsx.topology.context.StreamsContext;
import com.ibm.streamsx.topology.context.StreamsContext.Type;
import com.ibm.streamsx.topology.context.StreamsContextFactory;

/**
 * Sample demonstrating submission of a topology
 * to Streaming Analytic Service on Bluemix.
 *
 */
public class Submit2StreamingAnalyticService {

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

        String vcapFile = args[0];
        String serviceName = args[1];

        /*
         * Create a simple topology, focus of the
         * sample is the submission of the job
         * to the service.
         *
         * This topology is just like simple.HelloWorld
         * with different values printed to the console log.
         */
        Topology topology = new Topology("Submit2StreamingAnalyticService");
        topology.strings(
                "Hello", "Streaming Analytic Service",
                serviceName, "running on IBM Bluemix").print();

        // Require a configuration object.
        Map<String,Object> config = new HashMap<>();

        // Here the VCAP_SERVICES information is in a local file
        // (as serialized JSON)
        config.put(AnalyticsServiceProperties.VCAP_SERVICES, new File(vcapFile));

        // Explicitly state which service is the job will be submitted to
        // The service must be in the Streaming Analytic Service section
        // of the VCAP services.
        config.put(AnalyticsServiceProperties.SERVICE_NAME, serviceName);

        // Optionally we can specify a job name
        // (note job names must be unique within the instance).
        config.put(JobProperties.NAME, "BluemixSubmitSample");

        // Submit to the ANALYICS_SERVICE context
        @SuppressWarnings("unchecked")
        StreamsContext<BigInteger> context =
             (StreamsContext<BigInteger>) StreamsContextFactory.getStreamsContext(Type.ANALYTICS_SERVICE);

        BigInteger jobId = context.submit(topology, config).get();

        System.out.println("Submitted job with jobId=" + jobId);

    }
}

Add sample for submission to bluemix


/*
 * #%L
 * SciJava Common shared library for SciJava software.
 * %%
 * Copyright (C) 2009 - 2017 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.script.process;

import org.scijava.log.LogService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.script.ScriptInfo;
import org.scijava.script.ScriptLanguage;
import org.scijava.script.ScriptService;

/**
 * A {@link ScriptProcessor} which looks for a {@code #!} at the beginning of a
 * script, and set the language accordingly.
 *
 * @author Curtis Rueden
 */
@Plugin(type = ScriptProcessor.class)
public class ShebangScriptProcessor implements ScriptProcessor {

	@Parameter
	private ScriptService scriptService;

	@Parameter
	private LogService log;

	private ScriptInfo info;
	private boolean first = true;

	// -- ScriptProcessor methods --

	@Override
	public void begin(final ScriptInfo scriptInfo) {
		info = scriptInfo;
	}

	@Override
	public void process(final String line) {
		if (!first) return;
		if (line.startsWith("#!")) {
			// shebang!
			final String langName = line.substring(2);
			final ScriptLanguage lang = scriptService.getLanguageByName(langName);
			if (lang != null) info.setLanguage(lang);
			else log.warn("Unknown script language: " + langName);
		}
		first = false;
	}
}

Add script processor for shebang syntax


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

import com.github.pedrovgs.app.binarytree.BinaryNode;
import java.util.List;

/**
 * Given a binary tree, can you write a method to get a List<BinaryNode> using a post order
 * traversal?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class BinaryTreePostOrder {

  public List<BinaryNode> get(BinaryNode<Integer> root) {
    return null;
  }
}

Add statement for problem 16


package com.drumonii.loltrollbuild.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.ShallowEtagHeaderFilter;

/**
 * Configuration for web mvc related beans.
 */
@Configuration
public class WebMvcConfig {

    @Bean
    public ShallowEtagHeaderFilter shallowEtagHeaderFilter() {
        return new ShallowEtagHeaderFilter();
    }

}

Add ShallowEtagHeaderFilter to go with CacheControl headers


package org.frc4931.robot.command.autonomous;

import org.frc4931.robot.Subsystems;

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

public class FollowWall extends Command{
	private final static double TOLERANCE=0.01;
	private final double targetDistance;

	public FollowWall(double targetDistance) {
		this.targetDistance = targetDistance;
	}

	private double getTargetDistance(){
		//TODO Implement this method
		return targetDistance;
	}

	private double getCurrentDistance(){
		//TODO Implement this method
		return 0.0;
	}

	protected void end() {
		Subsystems.driveTrain.stop();
	}

	protected void execute() {
		Subsystems.driveTrain.setDriveSpeed(0.0);
		Subsystems.driveTrain.setTurnSpeed(0.0);

		if(getCurrentDistance()<getTargetDistance()-(getTargetDistance()*TOLERANCE)){
			Subsystems.driveTrain.setTurnSpeed(0.1);
		}else if(getCurrentDistance()>getTargetDistance()+(getTargetDistance()*TOLERANCE)){
			Subsystems.driveTrain.setTurnSpeed(-0.1);
		}else{
			Subsystems.driveTrain.setDriveSpeed(0.1);
		}
	}

	protected void initialize() {
	}

	protected void interrupted() {
		end();
	}

	protected boolean isFinished() {
		return false;
	}

}

Create the basic command to follow a wall


package in.twizmwaz.cardinal.module.modules.destroyable;

import in.twizmwaz.cardinal.module.GameObjective;
import in.twizmwaz.cardinal.teams.PgmTeam;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.block.BlockBreakEvent;

import java.util.List;

public class Destroyable implements GameObjective {

    private final PgmTeam team;
    private final String name;
    private final String id;

    private List<Block> blocks;
    private double complete;
    private double required;
    private boolean completed;

    protected Destroyable(final PgmTeam team, final String name, final String id, final List<Block> blocks, double required) {
        this.team = team;
        this.name = name;
        this.id = id;
        this.blocks = blocks;
        this.complete = 0;
        this.required = required;
        this.completed = false;
    }

    @Override
    public PgmTeam getTeam() {
        return this.team;
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public String getId() {
        return this.id;
    }

    @Override
    public boolean isTouched() {
        return this.complete > 0;
    }

    @Override
    public boolean isComplete() {
        return this.completed;
    }

    @Override
    public void unload() {
        HandlerList.unregisterAll(this);
    }

    @EventHandler
    public void onBlockBreak(BlockBreakEvent event) {
        if (this.blocks.contains(event.getBlock())) this.complete = this.complete + (1 / this.blocks.size());
        if (this.complete >= this.required) this.completed = true;
    }

}

Add destroyable module without parser


package edu.berkeley.eecs.cfc_tracker.wrapper;

/**
 * Created by shankari on 7/12/15.
 */
public class Transition {
    private String currState;
    private String transition;
    // Should we put newState in here as well?
    // If so, we will need to change the location of the save

    public Transition() {}
    public Transition(String currState, String transition) {
        this.currState = currState;
        this.transition = transition;
    }
}

Add a new BagOfProperties class for a transition


package com.github.jeffgbutler;

import static org.hamcrest.core.Is.*;
import static org.junit.Assert.assertThat;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import org.junit.Test;

/**
 * This is what's usually shown to illustrate map/filter/reduce.  It is useful to understand
 * the basic concepts, but no one has these problems in the real world.
 */
public class TypicalStreamExamplesTest {

    @Test
    public void testIntStreamMapReduce() {
        int answer = IntStream.rangeClosed(1, 10)
                .map(i -> i * 3)
                .filter(i -> i % 2 == 0)
                .reduce(0, (i1, i2) -> i1 + i2);

        assertThat(answer, is(90));
    }

    @Test
    public void testIntStreamBuiltIns() {
        int answer = IntStream.rangeClosed(1, 10)
                .map(i -> i * 3)
                .filter(i -> i % 2 == 0)
                .sum();

        assertThat(answer, is(90));
    }

    @Test
    public void testStrings() {
        String[] strings = {"fred", "pebbles", "wilma"};

        List<String> outlist = Arrays.stream(strings)
                .filter(s -> s.length() <= 5)
                .map(String::toUpperCase)
                .collect(Collectors.toList());

        assertThat(outlist.size(), is(2));
        assertThat(outlist.get(0), is("FRED"));
        assertThat(outlist.get(1), is("WILMA"));
    }
}

Add some typical stream examples


import java.sql.*;

public class DatabaseStreams {

    public static void method() {

        Connection connection = null;
        Statement statement = null;

        try {
            connection = DriverManager.getConnection("blah");
            statement = connection.createStatement();
            // do something with statement
        }
        catch (SQLException e) {
            System.err.println("Error: " + e);
        }
        finally {
            if (statement != null) {
                try {
                    statement.close();
                }
                catch (SQLException e) {
                    System.err.println("Error closing statement: " + e);
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                }
                catch (SQLException e) {
                    System.err.println("Error closing connection: " + e);
                }
            }
        }
    }
}

Check for closing database streams.