package grails.plugin.multitenant.core.filter;

import grails.plugin.multitenant.core.CurrentTenant;
import grails.plugin.multitenant.core.resolve.TenantResolver;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class CurrentTenantFilter implements Filter {

    private CurrentTenant currentTenant;
    private TenantResolver tenantResolver;

    @Override
    public void init(FilterConfig fc) throws ServletException {
        ServletContext servletContext = fc.getServletContext();
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        currentTenant = (CurrentTenant) ctx.getBean("currentTenant");
        tenantResolver = (TenantResolver) ctx.getBean("tenantResolver");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain filterChain) throws IOException, ServletException {

        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            int currentTenantId = tenantResolver.resolve(httpRequest);
            currentTenant.set(currentTenantId);
        }

        filterChain.doFilter(request, response);
        currentTenant.set(-1);
    }

    @Override
    public void destroy() {
    }

}

package grails.plugin.multitenant.core.filter;

import grails.plugin.multitenant.core.CurrentTenant;
import grails.plugin.multitenant.core.resolve.TenantResolver;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 *
 * @author Kim A. Betti
 */
public class CurrentTenantFilter implements Filter {

    private CurrentTenant currentTenant; // thread local storage
    private TenantResolver tenantResolver; // provided by implementation

    @Override
    public void init(FilterConfig fc) throws ServletException {
        ServletContext servletContext = fc.getServletContext();
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        currentTenant = (CurrentTenant) ctx.getBean("currentTenant");
        tenantResolver = (TenantResolver) ctx.getBean("tenantResolver");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
    		FilterChain filterChain) throws IOException, ServletException {

    	try {
	        if (request instanceof HttpServletRequest) {
	            HttpServletRequest httpRequest = (HttpServletRequest) request;
	            int currentTenantId = tenantResolver.resolve(httpRequest);
	            currentTenant.set(currentTenantId);
	        }

	        filterChain.doFilter(request, response);
    	} finally {
    		currentTenant.set(-1);
    	}
    }

    @Override
    public void destroy() {
    }

}

Make sure that current-tenant thread local storage is reset in the event of an exception


package com.github.aureliano.achmed.helper;

import java.lang.reflect.Method;

import com.github.aureliano.achmed.exception.AchmedException;

public final class ReflectionHelper {

	private ReflectionHelper() {
		throw new InstantiationError(this.getClass().getName() + " cannot be instantiated.");
	}

    public static Object callMethod(Object object, String methodName, Class<?>[] parametersType, Object[] methodParameters) {
    	Class<?> clazz = object.getClass();
    	try {
    		Method method = clazz.getMethod(methodName, parametersType);
    		return method.invoke(object, methodParameters);
    	} catch (Exception ex) {
    		throw new AchmedException(ex);
    	}
    }

    public static String getSimpleAccessMethodName(Method method) {
    	String name = method.getName().replaceFirst("^(get|is|set|with)", "");
    	return Character.toLowerCase(name.charAt(0)) + name.substring(1);
    }
}

package com.github.aureliano.achmed.helper;

import java.lang.reflect.Method;

import com.github.aureliano.achmed.exception.AchmedException;

public final class ReflectionHelper {

	private ReflectionHelper() {
		throw new InstantiationError(this.getClass().getName() + " cannot be instantiated.");
	}

    public static Object newInstance(Class<?> clazz) {
    	try {
    		return clazz.newInstance();
    	} catch (Exception ex) {
    		throw new AchmedException(ex);
    	}
    }

    public static Object callMethod(Object object, String methodName, Class<?>[] parametersType, Object[] methodParameters) {
    	Class<?> clazz = object.getClass();
    	try {
    		Method method = clazz.getMethod(methodName, parametersType);
    		return method.invoke(object, methodParameters);
    	} catch (Exception ex) {
    		throw new AchmedException(ex);
    	}
    }

    public static String getSimpleAccessMethodName(Method method) {
    	String name = method.getName().replaceFirst("^(get|is|set|with)", "");
    	return Character.toLowerCase(name.charAt(0)) + name.substring(1);
    }
}

Add method to instantiate object by reflection.


package com.musicocracy.fpgk.ioc.activity;

import com.musicocracy.fpgk.domain.spotify.Browser;
import com.musicocracy.fpgk.mvp.model.SongSelectModel;
import com.musicocracy.fpgk.mvp.presenter.SongSelectPresenter;

import dagger.Module;
import dagger.Provides;

@Module
public class SongSelectModule {
    @Provides
    public SongSelectModel provideSongSelectModel(Browser browser) {
        return new SongSelectModel(browser, api);
    }

    @Provides
    public SongSelectPresenter provideSongSelectPresenter(SongSelectModel model) {
        return new SongSelectPresenter(model);
    }
}

package com.musicocracy.fpgk.ioc.activity;

import com.musicocracy.fpgk.domain.spotify.Browser;
import com.musicocracy.fpgk.mvp.model.SongSelectModel;
import com.musicocracy.fpgk.mvp.presenter.SongSelectPresenter;

import dagger.Module;
import dagger.Provides;
import kaaes.spotify.webapi.android.SpotifyApi;

@Module
public class SongSelectModule {
    @Provides
    public SongSelectModel provideSongSelectModel(Browser browser, SpotifyApi api) {
        return new SongSelectModel(browser, api);
    }

    @Provides
    public SongSelectPresenter provideSongSelectPresenter(SongSelectModel model) {
        return new SongSelectPresenter(model);
    }
}

Set up dependency injection for spotify module including Spotify Api, Spotify Service, and the Browser.


package com.obidea.semantika.cli2.command;

import java.io.PrintStream;
import java.util.Map;

import com.obidea.semantika.cli2.runtime.ConsoleSession;

public class ShowPrefixesCommand extends Command
{
   private ConsoleSession mSession;

   public ShowPrefixesCommand(String command, ConsoleSession session)
   {
      mSession = session;
   }

   @Override
   public Object execute() throws Exception
   {
      return mSession.getPrefixMapper();
   }

   @Override
   public void printOutput(PrintStream out, Object output)
   {
      if (output instanceof Map<?, ?>) {
         @SuppressWarnings("unchecked")
         Map<String, String> map = (Map<String, String>) output;
         for (String prefix : map.keySet()) {
            out.println(prefix + ": " + map.get(prefix));
         }
      }
      out.println();
   }
}

package com.obidea.semantika.cli2.command;

import java.io.PrintStream;
import java.util.Map;

import com.obidea.semantika.cli2.runtime.ConsoleSession;
import com.obidea.semantika.util.StringUtils;

public class ShowPrefixesCommand extends Command
{
   private ConsoleSession mSession;

   public ShowPrefixesCommand(String command, ConsoleSession session)
   {
      mSession = session;
   }

   @Override
   public Object execute() throws Exception
   {
      return mSession.getPrefixMapper();
   }

   @Override
   public void printOutput(PrintStream out, Object output)
   {
      if (output instanceof Map<?, ?>) {
         @SuppressWarnings("unchecked")
         Map<String, String> map = (Map<String, String>) output;
         for (String key : map.keySet()) {
            String prefix = key;
            if (StringUtils.isEmpty(prefix)) {
               prefix = "(default)"; //
            }
            out.println(prefix + " = " + map.get(key));
         }
      }
      out.println();
   }
}

Change the show prefixes commmand output.


package no.stelar7.api.r4j.basic.constants.types.val;

import no.stelar7.api.r4j.basic.constants.types.CodedEnum;

import java.util.Optional;
import java.util.stream.Stream;

public enum GameQueueType implements CodedEnum<GameQueueType>
{

    COMPETITIVE("competitive"),
    DEATHMATCH("deathmatch"),
    SPIKE_RUSH("spikerush"),
    UNRATED("unrated"),
    CUSTOM_GAME(""),
    ;

    private final String queue;

    /**
     * Constructor for MapType
     *
     * @param code the mapId
     */
    GameQueueType(final String code)
    {
        this.queue = code;
    }

    /**
     * Gets from code.
     *
     * @param mapId the map id
     * @return the from code
     */
    public Optional<GameQueueType> getFromCode(final String mapId)
    {
        return Stream.of(GameQueueType.values()).filter(t -> t.queue.equals(mapId)).findFirst();
    }

    @Override
    public String prettyName()
    {
        switch (this)
        {
            default:
                return "This enum does not have a pretty name";
        }
    }

    /**
     * Gets id.
     *
     * @return the id
     */
    public String getId()
    {
        return this.queue;
    }

    /**
     * Used internaly in the api...
     *
     * @return the value
     */
    public String getValue()
    {
        return getId();
    }

}

package no.stelar7.api.r4j.basic.constants.types.val;

import no.stelar7.api.r4j.basic.constants.types.CodedEnum;

import java.util.Optional;
import java.util.stream.Stream;

public enum GameQueueType implements CodedEnum<GameQueueType>
{

    COMPETITIVE("competitive"),
    DEATHMATCH("deathmatch"),
    SPIKE_RUSH("spikerush"),
    UNRATED("unrated"),
    CUSTOM_GAME(""),
    TOURNAMENT_MODE("tournamentmode"),
    ;

    private final String queue;

    /**
     * Constructor for MapType
     *
     * @param code the mapId
     */
    GameQueueType(final String code)
    {
        this.queue = code;
    }

    /**
     * Gets from code.
     *
     * @param mapId the map id
     * @return the from code
     */
    public Optional<GameQueueType> getFromCode(final String mapId)
    {
        return Stream.of(GameQueueType.values()).filter(t -> t.queue.equals(mapId)).findFirst();
    }

    @Override
    public String prettyName()
    {
        switch (this)
        {
            default:
                return "This enum does not have a pretty name";
        }
    }

    /**
     * Gets id.
     *
     * @return the id
     */
    public String getId()
    {
        return this.queue;
    }

    /**
     * Used internaly in the api...
     *
     * @return the value
     */
    public String getValue()
    {
        return getId();
    }

}

Add tournamentmode to valorant recent games


package pl.tomaszdziurko.jvm_bloggers;

public class TimeConstants {

    public static final String EVERY_TEN_MINUTES = "0 10,20,30,40,50 * * * *";

    public static final String EVERY_FRIDAY_AT_12_OCLOCK = "0 12 0 * * FRI";

}

package pl.tomaszdziurko.jvm_bloggers;

public class TimeConstants {

    public static final String EVERY_TEN_MINUTES = "0 10,20,30,40,50 * * * *";

    public static final String EVERY_FRIDAY_AT_12_OCLOCK = "0 0 12 * * FRI";

}

Fix incorrect time to send mailing

Fix incorrect time to send mailing


package org.pikater.core.ontology.subtrees.metadata;

import java.util.List;

import jade.content.Concept;

public class Metadatas implements Concept {

	/**
	 *
	 */
	private static final long serialVersionUID = -7879865268316684239L;

	private List<Metadata> metadatas;

	public List<Metadata> getMetadatas() {
		return metadatas;
	}

	public void setMetadatas(List<Metadata> metadatas) {
		this.metadatas = metadatas;
	}

}

package org.pikater.core.ontology.subtrees.metadata;

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

import jade.content.Concept;

public class Metadatas implements Concept {

	/**
	 *
	 */
	private static final long serialVersionUID = -7879865268316684239L;

	private List<Metadata> metadatas;

	public Metadatas(){
		this.metadatas=new ArrayList<Metadata>();
	}

	public List<Metadata> getMetadatas() {
		return metadatas;
	}

	public void setMetadatas(List<Metadata> metadatas) {
		this.metadatas = metadatas;
	}

}

Fix NPE if no results are found

Fix NPE if no results are found


package am.app.mappingEngine.qualityEvaluation.metrics.ufl;

import java.util.List;

import am.app.mappingEngine.AbstractMatcher.alignType;
import am.app.mappingEngine.qualityEvaluation.AbstractQualityMetric;
import am.app.mappingEngine.similarityMatrix.SimilarityMatrix;
import static am.evaluation.disagreement.variance.VarianceComputation.computeVariance;

/**
 * Compute the disagreement between matching algorithms given their individual
 * similarity matrices. The constructor takes only one kind of matrix, either
 * the classes matrices or the properties matrices. You must instantiate a
 * separate object for each type of matrices.
 *
 * @author Cosmin Stroe
 *
 */
public class VarianceMatcherDisagreement extends AbstractQualityMetric {

	private SimilarityMatrix[] matrices;

	public VarianceMatcherDisagreement(List<SimilarityMatrix> matrices) {
		super();
		this.matrices = matrices.toArray(new SimilarityMatrix[0]);
	}

	/**
	 * @param type
	 *            This parameter is ignored.
	 */
	@Override
	public double getQuality(alignType type, int i, int j) {
		// create signature vector
		double[] signatureVector = new double[matrices.length];
		for(int k = 0; k < matrices.length; k++) {
			signatureVector[k] = matrices[k].getSimilarity(i, j);
		}

		// return the computed variance
		return computeVariance(signatureVector);
	}
}

package am.app.mappingEngine.qualityEvaluation.metrics.ufl;

import java.util.List;

import am.app.mappingEngine.AbstractMatcher.alignType;
import am.app.mappingEngine.qualityEvaluation.AbstractQualityMetric;
import am.app.mappingEngine.similarityMatrix.SimilarityMatrix;
import static am.evaluation.disagreement.variance.VarianceComputation.computeVariance;

/**
 * Compute the disagreement between matching algorithms given their individual
 * similarity matrices. The constructor takes only one kind of matrix, either
 * the classes matrices or the properties matrices. You must instantiate a
 * separate object for each type of matrices.
 *
 * @author Cosmin Stroe
 *
 */
public class VarianceMatcherDisagreement extends AbstractQualityMetric {

	private SimilarityMatrix[] matrices;

	public VarianceMatcherDisagreement(List<SimilarityMatrix> matrices) {
		super();
		this.matrices = matrices.toArray(new SimilarityMatrix[0]);
	}

	/**
	 * @param type
	 *            This parameter is ignored.
	 */
	@Override
	public double getQuality(alignType type, int i, int j) {
		// create signature vector
		double[] signatureVector = new double[matrices.length];
		for(int k = 0; k < matrices.length; k++) {
			signatureVector[k] = matrices[k].getSimilarity(i, j);
		}

		// return the computed variance
		// because variance of similarity values can be a maximum of 0.5, we
		// multiply by 2 to get a metric from 0 to 1.0
		return 2 * computeVariance(signatureVector);
	}
}

Normalize the variance to 1.0 (from 0.5)


package seedu.agendum.model.task;

import seedu.agendum.commons.exceptions.IllegalValueException;

/**
 * Represents a Task's name in the to do list.
 * Guarantees: immutable; is valid as declared in {@link #isValidName(String)}
 */
public class Name {

    public static final String MESSAGE_NAME_CONSTRAINTS = "Task names should only conyain spaces or alphanumeric characters";
    public static final String NAME_VALIDATION_REGEX = "[\\p{Alnum} ]+";

    public final String fullName;

    /**
     * Validates given name.
     *
     * @throws IllegalValueException if given name string is invalid.
     */
    public Name(String name) throws IllegalValueException {
        assert name != null;
        name = name.trim();
        if (!isValidName(name)) {
            throw new IllegalValueException(MESSAGE_NAME_CONSTRAINTS);
        }
        this.fullName = name;
    }

    /**
     * Returns true if a given string is a valid task name.
     */
    public static boolean isValidName(String test) {
        return test.matches(NAME_VALIDATION_REGEX);
    }

    @Override
    public String toString() {
        return fullName;
    }

    @Override
    public boolean equals(Object other) {
        return other == this // short circuit if same object
                || (other instanceof Name // instanceof handles nulls
                && this.fullName.equals(((Name) other).fullName)); // state check
    }

    @Override
    public int hashCode() {
        return fullName.hashCode();
    }

}

package seedu.agendum.model.task;

import seedu.agendum.commons.exceptions.IllegalValueException;

/**
 * Represents a Task's name in the to do list.
 * Guarantees: immutable; is valid as declared in {@link #isValidName(String)}
 */
public class Name {

    public static final String MESSAGE_NAME_CONSTRAINTS = "Task names should only contain spaces or alphanumeric characters";
    public static final String NAME_VALIDATION_REGEX = "[\\p{Alnum} ]+";

    public final String fullName;

    /**
     * Validates given name.
     *
     * @throws IllegalValueException if given name string is invalid.
     */
    public Name(String name) throws IllegalValueException {
        assert name != null;
        name = name.trim();
        if (!isValidName(name)) {
            throw new IllegalValueException(MESSAGE_NAME_CONSTRAINTS);
        }
        this.fullName = name;
    }

    /**
     * Returns true if a given string is a valid task name.
     */
    public static boolean isValidName(String test) {
        return test.matches(NAME_VALIDATION_REGEX);
    }

    @Override
    public String toString() {
        return fullName;
    }

    @Override
    public boolean equals(Object other) {
        return other == this // short circuit if same object
                || (other instanceof Name // instanceof handles nulls
                && this.fullName.equals(((Name) other).fullName)); // state check
    }

    @Override
    public int hashCode() {
        return fullName.hashCode();
    }

}

Fix typo in message name constraints

Fix typo in message name constraints


package tars.logic;

import org.junit.Test;

import tars.logic.commands.CdCommand;

/**
 * Logic command test for cd
 *
 * @@author A0124333U
 */
public class CdLogicCommandTest extends LogicCommandTest {
    @Test
    public void execute_cd_incorrectArgsFormatErrorMessageShown()
            throws Exception {
        assertCommandBehavior("cd ", CdCommand.MESSAGE_INVALID_FILEPATH);
    }

    @Test
    public void execute_cd_invalidFileTypeErrorMessageShown() throws Exception {
        assertCommandBehavior("cd invalidFileType",
                CdCommand.MESSAGE_INVALID_FILEPATH);
    }

    @Test
    public void execute_cd_success() throws Exception {
        String tempTestTarsFilePath =
                saveFolder.getRoot().getPath() + "TempTestTars.xml";
        assertCommandBehavior("cd " + tempTestTarsFilePath,
                String.format(CdCommand.MESSAGE_SUCCESS_NEW_FILE, tempTestTarsFilePath));
    }
}

package tars.logic;

import java.io.File;

import org.junit.Test;

import tars.commons.util.FileUtil;
import tars.logic.commands.CdCommand;
import tars.model.Tars;
import tars.storage.TarsStorage;
import tars.storage.XmlTarsStorage;

/**
 * Logic command test for cd
 *
 * @@author A0124333U
 */
public class CdLogicCommandTest extends LogicCommandTest {
  @Test
  public void execute_cd_incorrectArgsFormatErrorMessageShown() throws Exception {
    assertCommandBehavior("cd ", CdCommand.MESSAGE_INVALID_FILEPATH);
  }

  @Test
  public void execute_cd_invalidFileTypeErrorMessageShown() throws Exception {
    assertCommandBehavior("cd invalidFileType", CdCommand.MESSAGE_INVALID_FILEPATH);
  }

  @Test
  public void execute_cd_new_file_success() throws Exception {
    String tempTestTarsFilePath = saveFolder.getRoot().getPath() + "TempTestTars.xml";
    assertCommandBehavior("cd " + tempTestTarsFilePath,
        String.format(CdCommand.MESSAGE_SUCCESS_NEW_FILE, tempTestTarsFilePath));
  }

  @Test
  public void execute_cd_existing_file_failureToReadExistingFile() throws Exception {
    String existingFilePath = saveFolder.getRoot().getPath() + "TempTars.xml";
    File existingFile = new File(existingFilePath);
    FileUtil.createIfMissing(existingFile);
    assertCommandBehavior("cd " + existingFilePath, CdCommand.MESSAGE_FAILURE_READ_FILE);
  }

  @Test
  public void execute_cd_existing_file_success() throws Exception {
    String existingFilePath = saveFolder.getRoot().getPath() + "TempTars.xml";
    TarsStorage testStorage = new XmlTarsStorage(existingFilePath);
    testStorage.saveTars(Tars.getEmptyTars());
    assertCommandBehavior("cd " + existingFilePath,
        String.format(CdCommand.MESSAGE_SUCCESS_EXISTING_FILE, existingFilePath));
  }
}

Add logic tests for CdCommand

Add logic tests for CdCommand


package info.u_team.u_team_test.data.provider;

import info.u_team.u_team_core.data.*;
import info.u_team.u_team_test.init.*;

public class TestItemModelsProvider extends CommonItemModelsProvider {

	public TestItemModelsProvider(GenerationData data) {
		super(data);
	}

	@Override
	protected void registerModels() {
		// Items
		simpleGenerated(TestItems.BASIC.get());
		simpleGenerated(TestItems.BASIC_FOOD.get());
		simpleGenerated(TestItems.BETTER_ENDERPEARL.get());
		iterateItems(TestItems.BASIC_ARMOR, this::simpleGenerated);
		iterateItems(TestItems.BASIC_TOOL, this::simpleHandheld);
		// Blocks
		simpleBlock(TestBlocks.BASIC.get());
		simpleBlock(TestBlocks.BASIC_TILEENTITY.get());
		simpleBlock(TestBlocks.BASIC_ENERGY_CREATOR.get());
		simpleBlock(TestBlocks.BASIC_FLUID_INVENTORY.get());
	}

}

package info.u_team.u_team_test.data.provider;

import info.u_team.u_team_core.data.*;
import info.u_team.u_team_test.init.*;

public class TestItemModelsProvider extends CommonItemModelsProvider {

	public TestItemModelsProvider(GenerationData data) {
		super(data);
	}

	@Override
	protected void registerModels() {
		// Items
		simpleGenerated(TestItems.BASIC.get());
		simpleGenerated(TestItems.BASIC_FOOD.get());
		simpleGenerated(TestItems.BETTER_ENDERPEARL.get());
//		iterateItems(TestItems.BASIC_ARMOR, this::simpleGenerated); // TODO
//		iterateItems(TestItems.BASIC_TOOL, this::simpleHandheld); // TODO
		// Blocks
		simpleBlock(TestBlocks.BASIC.get());
		simpleBlock(TestBlocks.BASIC_TILEENTITY.get());
		simpleBlock(TestBlocks.BASIC_ENERGY_CREATOR.get());
		simpleBlock(TestBlocks.BASIC_FLUID_INVENTORY.get());
	}

}

Comment so it can compile for testing

Comment so it can compile for testing


package swift.crdt.interfaces;

import swift.clocks.CausalityClock;
import swift.exceptions.InvalidParameterException;

/**
 * Source for generating new timestamps.
 *
 * @author nmp
 */
public interface TimestampSource<T> {

    /**
     * Generates a new timestamp.
     *
     * @return
     */
    <V extends CausalityClock<V>> T generateNew();

}

package swift.crdt.interfaces;

/**
 * Source for generating new timestamps.
 *
 * @author nmp
 */
public interface TimestampSource<T> {

    /**
     * Generates a new timestamp.
     *
     * @return
     */
    T generateNew();

}

Remove unnecessary generic - does it help to compile?

git-svn-id: a3fb842d882947c797cf684233f17bdc7f2c8277@248 049c2a90-bdf1-4f83-8191-3719d539f8e0


package org.ensembl.healthcheck.testcase.eg_core;

import java.sql.Connection;

import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.Team;

/**
 * @author mnuhn
 *
 * <p>
 * 	Test for correctness of variation schemas, suggests a patch, if the schemas
 * differ.
 * </p>
 *
 */
public class EGCompareVariationSchema extends EGAbstractCompareSchema {

	public EGCompareVariationSchema() {
		setTeamResponsible(Team.ENSEMBL_GENOMES);
		addAppliesToType(DatabaseType.VARIATION);
	}

	@Override
	protected String getDefinitionFileKey() {
		return "variation_schema.file";
	}

	@Override
	protected String getMasterSchemaKey() {
		return "master.variation_schema";
	}

	@Override
	protected boolean assertSchemaCompatibility(
			Connection masterCon,
			Connection checkCon
	) {
		return
			assertSchemaTypesCompatible(masterCon, checkCon);
	}
}

package org.ensembl.healthcheck.testcase.eg_core;

import java.sql.Connection;

import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.Team;

/**
 * @author mnuhn
 *
 * <p>
 * 	Test for correctness of variation schemas, suggests a patch, if the schemas
 * differ.
 * </p>
 *
 */
public class EGCompareVariationSchema extends EGAbstractCompareSchema {

	public EGCompareVariationSchema() {
		setTeamResponsible(Team.ENSEMBL_GENOMES);
	}

	@Override
	public void types() {
		addAppliesToType(DatabaseType.VARIATION);
	}

	@Override
	protected String getDefinitionFileKey() {
		return "variation_schema.file";
	}

	@Override
	protected String getMasterSchemaKey() {
		return "master.variation_schema";
	}

	@Override
	protected boolean assertSchemaCompatibility(
			Connection masterCon,
			Connection checkCon
	) {
		return
			assertSchemaTypesCompatible(masterCon, checkCon);
	}
}

Make it apply only to variation databases


package org.col.dw.cors;

import org.hibernate.validator.constraints.NotEmpty;

public class CorsConfiguration {
  public static final String ANY_ORIGIN = "*";

  @NotEmpty
  public String origins = ANY_ORIGIN;

  @NotEmpty
  public String methods = "OPTIONS, GET, POST, PUT, DELETE";

  @NotEmpty
  public String headers = "Authorization";

  public boolean anyOrigin() {
    return ANY_ORIGIN.equals(origins);
  }

}

package org.col.dw.cors;

import org.hibernate.validator.constraints.NotEmpty;

public class CorsConfiguration {
  public static final String ANY_ORIGIN = "*";

  @NotEmpty
  public String origins = ANY_ORIGIN;

  @NotEmpty
  public String methods = "OPTIONS, HEAD, GET, POST, PUT, DELETE";

  @NotEmpty
  public String headers = "Authorization, Content-Type";

  public boolean anyOrigin() {
    return ANY_ORIGIN.equals(origins);
  }

}

Add Content-Type to allowed default headers


package com.lloydtorres.stately.dto;

/**
 * Created by Lloyd on 2016-07-24.
 * A holder for data in the main nation overview card.
 */
public class NationOverviewCardData {
    public String category;
    public String region;
    public String inflDesc;
    public int inflScore;
    public String population;
    public String motto;
    public String established;

    public String waState;
    public String endorsements;
    public String gaVote;
    public String scVote;

    public NationOverviewCardData() { super(); }
}

package com.lloydtorres.stately.dto;

/**
 * Created by Lloyd on 2016-07-24.
 * A holder for data in the main nation overview card.
 */
public class NationOverviewCardData {
    public String category;
    public String region;
    public String inflDesc;
    public int inflScore;
    public String population;
    public String motto;
    public String established;
    public String lastSeen;

    public String waState;
    public String endorsements;
    public String gaVote;
    public String scVote;

    public NationOverviewCardData() { super(); }
}

Add last seen parameter to nation overview card DTO


package jp.ac.nii.prl.mape.autoscaling.model;

import jp.ac.nii.prl.mape.autoscaling.model.dto.InstanceDTO;

public class InstanceFactory {

	public static Instance createInstance(InstanceDTO dto, Deployment deployment) {

		Instance instance = new Instance();

		instance.setInstID(dto.getInstID());
		instance.setDeployment(deployment);

		return instance;
	}

	public static Instance createInstance(InstanceDTO dto,
			Deployment deployment,
			InstanceType instanceType) {

		Instance instance = createInstance(dto, deployment);
		instance.setInstanceType(instanceType);

		return instance;
	}

	public static InstanceDTO createDTO(Instance instance) {

		InstanceDTO dto = new InstanceDTO();

		dto.setInstID(instance.getInstID());
		dto.setInstLoad(instance.getInstLoad());
		dto.setInstType(instance.getInstanceType().getTypeID());

		return dto;
	}

}

package jp.ac.nii.prl.mape.autoscaling.model;

import jp.ac.nii.prl.mape.autoscaling.model.dto.InstanceDTO;

public class InstanceFactory {

	public static Instance createInstance(InstanceDTO dto, Deployment deployment) {

		Instance instance = new Instance();

		instance.setInstID(dto.getInstID());
		instance.setDeployment(deployment);
		instance.setInstLoad(dto.getInstLoad());

		return instance;
	}

	public static Instance createInstance(InstanceDTO dto,
			Deployment deployment,
			InstanceType instanceType) {

		Instance instance = createInstance(dto, deployment);
		instance.setInstanceType(instanceType);

		return instance;
	}

	public static InstanceDTO createDTO(Instance instance) {

		InstanceDTO dto = new InstanceDTO();

		dto.setInstID(instance.getInstID());
		dto.setInstLoad(instance.getInstLoad());
		dto.setInstType(instance.getInstanceType().getTypeID());

		return dto;
	}

}

Set instance load in instance creation

Set instance load in instance creation


package com.yammer.dropwizard.json;

import ch.qos.logback.classic.Level;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.*;
import org.codehaus.jackson.map.annotate.JsonCachable;
import org.codehaus.jackson.type.JavaType;

import java.io.IOException;

class LogbackModule extends Module {
    @JsonCachable
    private static class LevelDeserializer extends JsonDeserializer<Level> {
        @Override
        public Level deserialize(JsonParser jp,
                                 DeserializationContext ctxt) throws IOException {

            final String text = jp.getText();

            if ("false".equalsIgnoreCase(text)) {
                return Level.OFF;
            }

            if ("true".equalsIgnoreCase(text)) {
                return Level.ALL;
            }

            return Level.toLevel(text, Level.INFO);
        }
    }

    private static class LogbackDeserializers extends Deserializers.Base {
        @Override
        public JsonDeserializer<?> findBeanDeserializer(JavaType type,
                                                        DeserializationConfig config,
                                                        DeserializerProvider provider,
                                                        BeanDescription beanDesc,
                                                        BeanProperty property) throws JsonMappingException {
            if (Level.class.isAssignableFrom(type.getRawClass())) {
                return new LevelDeserializer();
            }

            return super.findBeanDeserializer(type, config, provider, beanDesc, property);
        }
    }

    @Override
    public String getModuleName() {
        return "log4j";
    }

    @Override
    public Version version() {
        return Version.unknownVersion();
    }

    @Override
    public void setupModule(SetupContext context) {
        context.addDeserializers(new LogbackDeserializers());
    }
}

package com.yammer.dropwizard.json;

import ch.qos.logback.classic.Level;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.*;
import org.codehaus.jackson.map.annotate.JsonCachable;
import org.codehaus.jackson.type.JavaType;

import java.io.IOException;

class LogbackModule extends Module {
    @JsonCachable
    private static class LevelDeserializer extends JsonDeserializer<Level> {
        @Override
        public Level deserialize(JsonParser jp,
                                 DeserializationContext ctxt) throws IOException {

            final String text = jp.getText();

            if ("false".equalsIgnoreCase(text)) {
                return Level.OFF;
            }

            if ("true".equalsIgnoreCase(text)) {
                return Level.ALL;
            }

            return Level.toLevel(text, Level.INFO);
        }
    }

    private static class LogbackDeserializers extends Deserializers.Base {
        @Override
        public JsonDeserializer<?> findBeanDeserializer(JavaType type,
                                                        DeserializationConfig config,
                                                        DeserializerProvider provider,
                                                        BeanDescription beanDesc,
                                                        BeanProperty property) throws JsonMappingException {
            if (Level.class.isAssignableFrom(type.getRawClass())) {
                return new LevelDeserializer();
            }

            return super.findBeanDeserializer(type, config, provider, beanDesc, property);
        }
    }

    @Override
    public String getModuleName() {
        return "LogbackModule";
    }

    @Override
    public Version version() {
        return Version.unknownVersion();
    }

    @Override
    public void setupModule(SetupContext context) {
        context.addDeserializers(new LogbackDeserializers());
    }
}

Replace log4j reference with Logback.

Replace log4j reference with Logback.


package io.bisq.gui.components;

import de.jensd.fx.fontawesome.AwesomeDude;
import de.jensd.fx.fontawesome.AwesomeIcon;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;

public class HyperlinkWithIcon extends Hyperlink {

    public HyperlinkWithIcon(String text) {
        this(text, AwesomeIcon.INFO_SIGN);
    }

    public HyperlinkWithIcon(String text, AwesomeIcon awesomeIcon) {

        super(text);

        Label icon = new Label();
        AwesomeDude.setIcon(icon, awesomeIcon);
        icon.setMinWidth(20);
        icon.setOpacity(0.7);
        icon.getStyleClass().add("hyperlink");

        setGraphic(icon);
        setContentDisplay(ContentDisplay.RIGHT);
    }
}

package io.bisq.gui.components;

import de.jensd.fx.fontawesome.AwesomeDude;
import de.jensd.fx.fontawesome.AwesomeIcon;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;

public class HyperlinkWithIcon extends Hyperlink {

    public HyperlinkWithIcon(String text) {
        this(text, AwesomeIcon.INFO_SIGN);
    }

    public HyperlinkWithIcon(String text, AwesomeIcon awesomeIcon) {

        super(text);

        Label icon = new Label();
        AwesomeDude.setIcon(icon, awesomeIcon);
        icon.setMinWidth(20);
        icon.setOpacity(0.7);
        icon.getStyleClass().add("hyperlink");

        setGraphic(icon);
        setContentDisplay(ContentDisplay.RIGHT);

        tooltipProperty().addListener((observable, oldValue, newValue) -> newValue.setStyle("-fx-text-fill: -bs-black"));
    }
}

Fix hierarchical/inherit issue with styles for Tooltip


/*
 * ReturnExporter.java
 *
 */

package de.uni_stuttgart.vis.vowl.owl2vowl.export.types;

/**
 * Simple exporter that saves the
 */
public class BackupExporter implements Exporter {
	@Override
	public void write(String text) throws Exception {
		// TODO
	}
}

/*
 * ReturnExporter.java
 *
 */

package de.uni_stuttgart.vis.vowl.owl2vowl.export.types;

/**
 * Simple exporter that saves the given text.
 */
public class BackupExporter implements Exporter {
	protected String convertedJson;

	public String getConvertedJson() {
		return convertedJson;
	}

	@Override
	public void write(String text) throws Exception {
		convertedJson = text;
	}
}

Add new exporter with method for direct integration in other projects.


package natlab;

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

import beaver.Parser;

import natlab.ast.Root;

public class Interpreter {
	private Interpreter() {}

	public static void main(String[] args) throws IOException {
		System.out.println("Welcome to the Natlab Interpreter!");
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		while(true) {
			System.out.print("> ");
			System.out.flush();

			String line = in.readLine();
			if(line == null) {
				break;
			}

			try {
				NatlabScanner scanner = new NatlabScanner(new StringReader(line));
				NatlabParser parser = new NatlabParser();
				Root original = (Root) parser.parse(scanner);

				if(parser.hasError()) {
					System.out.println("**ERROR**");
					for(String error : parser.getErrors()) {
						System.out.println(error);
					}
				} else {
					System.out.println(original.getStructureString());
				}
			} catch(Parser.Exception e) {
				System.out.println("**ERROR**");
				System.out.println(e.getMessage());
			}
		}
		System.out.println("Goodbye!");
	}
}

package natlab;

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

import natlab.ast.Root;
import beaver.Parser;

public class Interpreter {
	private Interpreter() {}

	public static void main(String[] args) throws IOException {
		System.out.println("Welcome to the Natlab Interpreter!");
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		while(true) {
			System.out.print("> ");
			System.out.flush();

			String line = in.readLine();
			if(line == null) {
				break;
			}

			NatlabParser parser = new NatlabParser();
			try {
				NatlabScanner scanner = new NatlabScanner(new StringReader(line));
				Root original = (Root) parser.parse(scanner);
				if(parser.hasError()) {
					System.out.println("**ERROR**");
					for(String error : parser.getErrors()) {
						System.out.println(error);
					}
				} else {
					System.out.println(original.getStructureString());
				}
			} catch(Parser.Exception e) {
				System.out.println("**ERROR**");
				System.out.println(e.getMessage());
				for(String error : parser.getErrors()) {
					System.out.println(error);
				}
			}
		}
		System.out.println("Goodbye!");
	}
}

Print error list in exception case.

Print error list in exception case.

git-svn-id: https://svn.sable.mcgill.ca/mclab/Project@70 89b902b4-d83f-0410-b942-89f7a419ffdb

Migrated from Sable/mclab@9a207c32906b6562aa0561a839effebf28d29b0b


package org.purl.wf4ever.robundle;

import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;

import org.purl.wf4ever.robundle.fs.BundleFileSystem;

public class Bundle implements AutoCloseable {

    private boolean deleteOnClose;
    private final Path root;

    public Bundle(Path root, boolean deleteOnClose) {
        this.root = root;
        this.setDeleteOnClose(deleteOnClose);
    }

    @Override
    public void close() throws IOException {
        close(isDeleteOnClose());
    }

    protected void close(boolean deleteOnClose) throws IOException {
        getFileSystem().close();
        if (deleteOnClose) {
            Files.deleteIfExists(getSource());
        }
    }

    public FileSystem getFileSystem() {
        return getRoot().getFileSystem();
    }

    public Path getRoot() {
        return root;
    }

    public Path getSource() {
        BundleFileSystem fs = (BundleFileSystem) getFileSystem();
        return fs.getSource();
    }

    public boolean isDeleteOnClose() {
        return deleteOnClose;
    }

    public void setDeleteOnClose(boolean deleteOnClose) {
        this.deleteOnClose = deleteOnClose;
    }

}

package org.purl.wf4ever.robundle;

import java.io.Closeable;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;

import org.purl.wf4ever.robundle.fs.BundleFileSystem;

public class Bundle implements Closeable {

    private boolean deleteOnClose;
    private final Path root;

    public Bundle(Path root, boolean deleteOnClose) {
        this.root = root;
        this.setDeleteOnClose(deleteOnClose);
    }

    @Override
    public void close() throws IOException {
        close(isDeleteOnClose());
    }

    protected void close(boolean deleteOnClose) throws IOException {
        if (! getFileSystem().isOpen()) {
            return;
        }
        getFileSystem().close();
        if (deleteOnClose) {
            Files.deleteIfExists(getSource());
        }
    }

    public FileSystem getFileSystem() {
        return getRoot().getFileSystem();
    }

    public Path getRoot() {
        return root;
    }

    public Path getSource() {
        BundleFileSystem fs = (BundleFileSystem) getFileSystem();
        return fs.getSource();
    }

    public boolean isDeleteOnClose() {
        return deleteOnClose;
    }

    public void setDeleteOnClose(boolean deleteOnClose) {
        this.deleteOnClose = deleteOnClose;
    }

}

Make close() idempotent and implement Closable rather than AutoClosable


package agoodfriendalwayspayshisdebts.web.actions.expense;

import agoodfriendalwayspayshisdebts.command.expense.DeleteExpenseCommand;
import com.vter.command.CommandBus;
import com.vter.infrastructure.bus.ExecutionResult;
import com.vter.web.actions.BaseAction;
import net.codestory.http.annotations.Delete;
import net.codestory.http.annotations.Resource;
import net.codestory.http.constants.HttpStatus;
import net.codestory.http.payload.Payload;

import javax.inject.Inject;
import java.util.UUID;

@Resource
public class DeleteExpense extends BaseAction {

  @Inject
  public DeleteExpense(CommandBus commandBus) {
    this.commandBus = commandBus;
  }

  @Delete("/events/:stringifiedEventUuid/expenses/:stringifiedExpenseUuid")
  public Payload delete(String stringifiedEventId, String stringifiedExpenseUuid) {
    final DeleteExpenseCommand command = new DeleteExpenseCommand();
    command.eventId = UUID.fromString(stringifiedEventId);
    command.expenseId = UUID.fromString(stringifiedExpenseUuid);
    final ExecutionResult<Void> result = commandBus.sendAndWaitResponse(command);
    return getDataAsPayloadOrFail(result, HttpStatus.NO_CONTENT);
  }

  private final CommandBus commandBus;
}

package agoodfriendalwayspayshisdebts.web.actions.expense;

import agoodfriendalwayspayshisdebts.command.expense.DeleteExpenseCommand;
import com.vter.command.CommandBus;
import com.vter.infrastructure.bus.ExecutionResult;
import com.vter.web.actions.BaseAction;
import net.codestory.http.annotations.Put;
import net.codestory.http.annotations.Resource;
import net.codestory.http.constants.HttpStatus;
import net.codestory.http.payload.Payload;

import javax.inject.Inject;
import java.util.UUID;

@Resource
public class DeleteExpense extends BaseAction {

  @Inject
  public DeleteExpense(CommandBus commandBus) {
    this.commandBus = commandBus;
  }

  @Put("/events/:stringifiedEventUuid/expenses/:stringifiedExpenseUuid")
  public Payload delete(String stringifiedEventId, String stringifiedExpenseUuid) {
    final DeleteExpenseCommand command = new DeleteExpenseCommand();
    command.eventId = UUID.fromString(stringifiedEventId);
    command.expenseId = UUID.fromString(stringifiedExpenseUuid);
    final ExecutionResult<Void> result = commandBus.sendAndWaitResponse(command);
    return getDataAsPayloadOrFail(result, HttpStatus.NO_CONTENT);
  }

  private final CommandBus commandBus;
}

Set delete expense action as HTTP Put

Set delete expense action as HTTP Put


package org.apollo.net.codec.game;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.util.List;

import org.apollo.game.event.Event;
import org.apollo.net.release.EventDecoder;
import org.apollo.net.release.Release;

/**
 * A {@link OneToOneDecoder} that decodes {@link GamePacket}s into {@link Event}s.
 *
 * @author Graham
 */
public final class GameEventDecoder extends MessageToMessageDecoder<GamePacket> {

	/**
	 * The current release.
	 */
	private final Release release;

	/**
	 * Creates the game event decoder with the specified release.
	 *
	 * @param release The release.
	 */
	public GameEventDecoder(Release release) {
		this.release = release;
	}

	@Override
	protected void decode(ChannelHandlerContext ctx, GamePacket msg, List<Object> out) {
		GamePacket packet = (GamePacket) msg;
		EventDecoder<?> decoder = release.getEventDecoder(packet.getOpcode());
		if (decoder != null) {
			out.add(decoder.decode(packet));
		} else {
			System.out.println("Unidentified packet received - opcode: " + packet.getOpcode() + ".");
		}
	}

}

package org.apollo.net.codec.game;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.util.List;

import org.apollo.game.event.Event;
import org.apollo.net.release.EventDecoder;
import org.apollo.net.release.Release;

/**
 * A {@link OneToOneDecoder} that decodes {@link GamePacket}s into {@link Event}s.
 *
 * @author Graham
 */
public final class GameEventDecoder extends MessageToMessageDecoder<GamePacket> {

	/**
	 * The current release.
	 */
	private final Release release;

	/**
	 * Creates the game event decoder with the specified release.
	 *
	 * @param release The release.
	 */
	public GameEventDecoder(Release release) {
		this.release = release;
	}

	@Override
	protected void decode(ChannelHandlerContext ctx, GamePacket packet, List<Object> out) {
		EventDecoder<?> decoder = release.getEventDecoder(packet.getOpcode());
		if (decoder != null) {
			out.add(decoder.decode(packet));
		} else {
			System.out.println("Unidentified packet received - opcode: " + packet.getOpcode() + ".");
		}
	}

}

Remove unnecessary cast left over from netty 4 conversion.


package com.miguelgaeta.media_picker;

import android.os.Environment;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@SuppressWarnings("UnusedDeclaration")
public class MediaPickerFile {

    /**
     * Create a file in the devices external storage.
     *
     * @param directory Target directory.
     * @param name Target file name.
     * @param suffix Target file suffix.
     *
     * @return Created file.
     *
     * @throws IOException
     */
    public static File create(final String directory, final String name, final String suffix) throws IOException {

        final File dir = new File(Environment.getExternalStorageDirectory() + File.separator + directory);

        if (!dir.exists()) {

            boolean result = dir.mkdirs();

            if (!result) {

                throw new IOException("Unable to create directory.");
            }
        }

        return File.createTempFile(name, suffix, dir);
    }

    /**
     * @see #create(String, String, String)
     */
    public static File create(final String directory, final String name) throws IOException {

        return create(directory, name, null);
    }

    /**
     * @see #create(String, String)
     */
    public static File create(final String directory) throws IOException {

        return create(directory, UUID.randomUUID().toString());
    }

    /**
     * @see #create(String)
     */
    public static File create() throws IOException {

        return create("media_picker");
    }
}

package com.miguelgaeta.media_picker;

import android.os.Environment;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@SuppressWarnings("UnusedDeclaration")
public class MediaPickerFile {

    /**
     * Create a file in the devices external storage.
     *
     * @param directory Target directory.
     * @param name Target file name.
     * @param suffix Target file suffix.
     *
     * @return Created file.
     *
     * @throws IOException
     */
    public static File create(final String directory, final String name, final String suffix) throws IOException {

        final File dir = new File(Environment.getExternalStorageDirectory() + File.separator + directory);

        if (!dir.exists()) {

            boolean result = dir.mkdirs();

            if (!result) {

                throw new IOException("Unable to create directory.");
            }
        }

        final File file = File.createTempFile(name, suffix, dir);

        if (!file.exists()) {

            throw new IOException("Unable to create temporary file, does not exist.");
        }

        return File.createTempFile(name, suffix, dir);
    }

    /**
     * @see #create(String, String, String)
     */
    public static File create(final String directory, final String name) throws IOException {

        return create(directory, name, null);
    }

    /**
     * @see #create(String, String)
     */
    public static File create(final String directory) throws IOException {

        return create(directory, UUID.randomUUID().toString());
    }

    /**
     * @see #create(String)
     */
    public static File create() throws IOException {

        return create("media_picker");
    }
}

Check to make sure created file actually exists.


package peergos.server.net;

import com.sun.net.httpserver.*;

import java.io.*;

public class RedirectHandler implements HttpHandler
{
    private final String target;

    public RedirectHandler(String target) {
        this.target = target;
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        exchange.getResponseHeaders().add("Location", target);
        exchange.sendResponseHeaders(301, 0);
        exchange.close();
    }
}

package peergos.server.net;

import com.sun.net.httpserver.*;

import java.io.*;

public class RedirectHandler implements HttpHandler
{
    private final String target;

    public RedirectHandler(String target) {
        this.target = target;
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        exchange.getResponseHeaders().add("Location", target);
        exchange.sendResponseHeaders(302, 0);
        exchange.close();
    }
}

Make redirect to https do the same thing as google.com


/*
  Copyright 2016, 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.example.translate;

// [START translate_quickstart]
// Imports the Google Cloud client library
import com.google.cloud.translate.Translate;
import com.google.cloud.translate.Translate.TranslateOption;
import com.google.cloud.translate.TranslateOptions;
import com.google.cloud.translate.Translation;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    Translate translate = TranslateOptions.builder().apiKey("YOUR_API_KEY").build().service();

    // The text to translate
    String text = "Hello, world!";

    // Translates some text into Russian
    Translation translation = translate.translate(
      text,
      TranslateOption.sourceLanguage("en"),
      TranslateOption.targetLanguage("ru")
    );

    System.out.printf("Text: %s%n", text);
    System.out.printf("Translation: %s%n", translation.translatedText());
  }
}
// [END translate_quickstart]

/*
  Copyright 2016, 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.example.translate;

// [START translate_quickstart]
// Imports the Google Cloud client library
import com.google.cloud.translate.Translate;
import com.google.cloud.translate.Translate.TranslateOption;
import com.google.cloud.translate.TranslateOptions;
import com.google.cloud.translate.Translation;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    Translate translate = TranslateOptions.builder().apiKey("YOUR_API_KEY").build().service();

    // The text to translate
    String text = "Hello, world!";

    // Translates some text into Russian
    Translation translation =
        translate.translate(
            text,
            TranslateOption.sourceLanguage("en"),
            TranslateOption.targetLanguage("ru"));

    System.out.printf("Text: %s%n", text);
    System.out.printf("Translation: %s%n", translation.translatedText());
  }
}
// [END translate_quickstart]

Add quickstarts to root module.

samples: Add quickstarts to root module.

Fixes checkstyle errors in samples.


/*******************************************************************************
 * Copyright 2000-2014 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.
 *
 *******************************************************************************/
package org.jetbrains.kotlin.perspective;

import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;

public class KotlinPerspectiveFactory implements IPerspectiveFactory {

    @Override
    public void createInitialLayout(IPageLayout layout) {

    }

}

/*******************************************************************************
 * Copyright 2000-2014 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.
 *
 *******************************************************************************/
package org.jetbrains.kotlin.perspective;

import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;

public class KotlinPerspectiveFactory implements IPerspectiveFactory {

    @Override
    public void createInitialLayout(IPageLayout layout) {
        layout.addActionSet(IDebugUIConstants.LAUNCH_ACTION_SET);
        layout.addActionSet(JavaUI.ID_ACTION_SET);
    }
}

Set action set's for Kotlin perspective: open type, launch configurations


package com.github.tuxdude.yani.network;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.widget.Toast;

import com.github.tuxdude.yani.utils.Logger;

public class NetworkBroadcastListener extends BroadcastReceiver {

    private static NetworkBroadcastListener instance = null;

    @Override
    public void onReceive(Context context, Intent intent) {
        Logger.trace();
        if (intent.getAction().equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {
            Toast.makeText(context, "Airplane Mode Changed!", Toast.LENGTH_LONG).show();
            Logger.d("Airplane Mode Changed");
        }
        else if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
            Toast.makeText(context, "Wifi State Changed!", Toast.LENGTH_LONG).show();
            Logger.d("Wifi State Changed");
        }
        else if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
            Toast.makeText(context, "Network State Changed!", Toast.LENGTH_LONG).show();
            Logger.d("Network State Changed");
        }
        else {
            Logger.d("Unhandled intent: " + intent.getAction().toString());
        }
    }

    private NetworkBroadcastListener() {
        // Empty constructor
    }

    public static NetworkBroadcastListener getInstance() {
        if (instance == null) {
            instance = new NetworkBroadcastListener();
        }
        return instance;
    }
}

package com.github.tuxdude.yani.network;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.widget.Toast;

import com.github.tuxdude.yani.utils.Logger;

public class NetworkBroadcastListener extends BroadcastReceiver {

    private static NetworkBroadcastListener instance = null;

    @Override
    public void onReceive(Context context, Intent intent) {
        Logger.trace();
        if (intent.getAction().equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {
            //Toast.makeText(context, "Airplane Mode Changed!", Toast.LENGTH_LONG).show();
            Logger.d("Airplane Mode Changed");
        }
        else if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
            //Toast.makeText(context, "Wifi State Changed!", Toast.LENGTH_LONG).show();
            Logger.d("Wifi State Changed");
        }
        else if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
            //Toast.makeText(context, "Network State Changed!", Toast.LENGTH_LONG).show();
            Logger.d("Network State Changed");
        }
        else {
            Logger.d("Unhandled intent: " + intent.getAction().toString());
        }
    }

    private NetworkBroadcastListener() {
        // Empty constructor
    }

    public static NetworkBroadcastListener getInstance() {
        if (instance == null) {
            instance = new NetworkBroadcastListener();
        }
        return instance;
    }
}

Disable toasts for network broadcast events.


package flickr.demo.qvdev.com.flickrdemo;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

import flickr.demo.qvdev.com.flickrdemo.dummy.DummyContent;

class FlickrItemRecyclerViewAdapter
        extends RecyclerView.Adapter<FlickrViewHolder> {

    private final List<DummyContent.DummyItem> mItems;

    FlickrItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
        mItems = items;
    }

    @Override
    public FlickrViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.flickritem_list_content, parent, false);
        return new FlickrViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final FlickrViewHolder holder, int position) {
        holder.mItem = mItems.get(position);
        holder.mIdView.setText(mItems.get(position).id);
        holder.mContentView.setText(mItems.get(position).content);
    }

    @Override
    public int getItemCount() {
        return mItems.size();
    }
}

package flickr.demo.qvdev.com.flickrdemo;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

import flickr.demo.qvdev.com.flickrdemo.dummy.DummyContent;

class FlickrItemRecyclerViewAdapter
        extends RecyclerView.Adapter<FlickrViewHolder> {

    private final List<DummyContent.DummyItem> mItems;

    FlickrItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
        mItems = items;
    }

    @Override
    public FlickrViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.flickritem_list_content, parent, false);
        return new FlickrViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final FlickrViewHolder holder, int position) {
        holder.mIdView.setText(mItems.get(position).id);
        holder.mContentView.setText(mItems.get(position).content);
    }

    @Override
    public int getItemCount() {
        return mItems.size();
    }
}

Remove holder item as not used anymore

Remove holder item as not used anymore


package org.intermine.webservice.server.lists;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.intermine.api.InterMineAPI;
import org.intermine.web.context.InterMineContext;

public class AvailableListsServlet extends HttpServlet
{
    /**
     * Serialisation constant.
     */
    private static final long serialVersionUID = 1L;

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        getAvailableLists(request, response);
    }

    private void getAvailableLists(HttpServletRequest request, HttpServletResponse response) {
        final InterMineAPI im = InterMineContext.getInterMineAPI();
        new AvailableListsService(im).service(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        saveUploadedList(request, response);
    }

    private void saveUploadedList(HttpServletRequest request, HttpServletResponse response) {
        final InterMineAPI im = InterMineContext.getInterMineAPI();
        new ListUploadService(im).service(request, response);
    }

    @Override
    public void doDelete(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        deleteList(request, response);
    }

    private void deleteList(HttpServletRequest request, HttpServletResponse response) {
        final InterMineAPI im = InterMineContext.getInterMineAPI();
        new ListDeletionService(im).service(request, response);
    }

}

package org.intermine.webservice.server.lists;

import org.intermine.webservice.server.WebService;
import org.intermine.webservice.server.core.NoServiceException;
import org.intermine.webservice.server.core.WebServiceServlet;

public class AvailableListsServlet extends WebServiceServlet
{
    private static final long serialVersionUID = 1L;

    @Override
    protected WebService getService(Method method) throws NoServiceException {
        switch (method) {
        case GET:
            return new AvailableListsService(api);
        case POST:
            return new ListUploadService(api);
        case DELETE:
            return new ListDeletionService(api);
        default:
            throw new NoServiceException();
        }
    }

}

Use the new WebServiceServlet framework

Use the new WebServiceServlet framework

Former-commit-id: 07bac49517b1151a281de191cd9e80c229196181


package org.spoofax.jsglr2.recovery;

import org.spoofax.jsglr2.parser.Position;

public class RecoveryJob {

    public Position position;
    public int iteration;
    public int quota;

    public RecoveryJob(Position position) {
        this.position = position;
        this.iteration = 0;
    }

    boolean hasNextIteration() {
        return iteration < 3;
    }

    int nextIteration() {
        quota = iteration++;

        return iteration;
    }

}

package org.spoofax.jsglr2.recovery;

import org.spoofax.jsglr2.parser.Position;

public class RecoveryJob {

    public Position position;
    public int iteration;
    public int quota;

    public RecoveryJob(Position position) {
        this.position = position;
        this.iteration = 0;
    }

    boolean hasNextIteration() {
        return iteration < 3;
    }

    int nextIteration() {
        quota = ++iteration;

        return iteration;
    }

}

Fix that first recovery iterations have quota


package orc.runtime.regions;

import orc.runtime.Token;

public class SemiRegion extends Region {

	Region parent;
	Token t;

	/* Create a new group region with the given parent and coupled group cell */
	public SemiRegion(Region parent, Token t) {
		this.parent = parent;
		this.t = t;
		this.parent.add(this);
	}

	protected void reallyClose(Token closer) {
		if (t != null) {
			t.getTracer().after(closer.getTracer().before());
			t.setPending();
			t.activate();
		}
		parent.remove(this, closer);
	}

	public Region getParent() {
		return parent;
	}

	public void cancel() {
		if (t != null) {
			t.die();
			t = null;
		}
	}
}

package orc.runtime.regions;

import orc.runtime.Token;

public class SemiRegion extends Region {

	Region parent;
	Token t;

	/* Create a new group region with the given parent and coupled group cell */
	public SemiRegion(Region parent, Token t) {
		this.parent = parent;
		this.t = t;
		this.parent.add(this);
	}

	protected void reallyClose(Token closer) {
		if (t != null) {
			t.getTracer().after(closer.getTracer().before());
			t.setPending();
			t.activate();
		}
		parent.remove(this, closer);
	}

	public Region getParent() {
		return parent;
	}

	public void cancel() {
		if (t != null) {
			// setPending so that the token can unsetPending when it
			// dies
			t.setPending();
			t.die();
			t = null;
		}
	}
}

Fix crash bug with new semicolon semantics.


package io.github.classgraph.issues;

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

import java.io.File;
import java.util.List;

import org.junit.Test;

import io.github.classgraph.ClassGraph;

public class TestGetUniqueClasspathElements {
    @Test
    public void testGetUniqueClasspathElements() {
        final List<File> classpathElements = new ClassGraph().whitelistPackages("com.xyz").getClasspathFiles();
        assertThat(classpathElements).isNotEmpty();
    }
}

package io.github.classgraph.issues;

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

import java.io.File;
import java.util.List;

import org.junit.Test;

import io.github.classgraph.ClassGraph;

public class TestGetUniqueClasspathElements {
    @Test
    public void testGetUniqueClasspathElements() {
        final List<File> classpathElements = new ClassGraph().verbose().whitelistPackages("com.xyz").getClasspathFiles();
        assertThat(classpathElements).isNotEmpty();
    }
}

Add .verbose() for Travis logging

Add .verbose() for Travis logging


// Copyright 2014 The Bazel Authors. 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.google.devtools.build.lib.actions;

import java.io.IOException;

/**
 * Used to indicate a filesystem inconsistency, e.g. file 'a/b' exists but directory 'a' doesn't
 * exist. This generally means the result of the build is undefined but we shouldn't crash hard.
 */
public class InconsistentFilesystemException extends IOException {
  public InconsistentFilesystemException(String inconsistencyMessage) {
    super(
        "Inconsistent filesystem operations. "
            + inconsistencyMessage
            + " The results of the "
            + "build are not guaranteed to be correct. You should probably run 'bazel clean' and "
            + "investigate the filesystem inconsistency (likely due to filesytem updates "
            + "concurrent with the build)");
  }
}

// Copyright 2014 The Bazel Authors. 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.google.devtools.build.lib.actions;

import java.io.IOException;

/**
 * Used to indicate a filesystem inconsistency, e.g. file 'a/b' exists but directory 'a' doesn't
 * exist. This generally means the result of the build is undefined but we shouldn't crash hard.
 */
public class InconsistentFilesystemException extends IOException {
  public InconsistentFilesystemException(String inconsistencyMessage) {
    super(
        "Inconsistent filesystem operations. "
            + inconsistencyMessage
            + " The results of the "
            + "build are not guaranteed to be correct. You should probably run 'bazel clean' and "
            + "investigate the filesystem inconsistency (likely due to filesystem updates "
            + "concurrent with the build)");
  }
}

Fix typo (filesytem --> filesystem).

Fix typo (filesytem --> filesystem).

RELNOTES: None.
PiperOrigin-RevId: 216337432


// fails
// TYPE_NOT_FOUND
// TYPE_NOT_FOUND
// TYPE_NOT_FOUND
// NAME_NOT_FOUND
// TYPE_MISMATCH

package java.util;

// import java.lang.*;
import java.io.File;
import java.io.JFile;  // fails

class A extends Object {
  String fname = "filename";
  File   file  = new java.io.File(fname);
  JFile  jfile  = new JFile(fname); /* fails four times:
                                       1- The first use of JFille
                                       2- The second use of JFille
                                       3- The missing constructor of JFille
                                       4- The unresolved types information
                                     */

  Object b1 = new Object();
  Object b2 = new Object();
  Object b3 = new Object();
  public String m(String a) {
    String s = "";
    Object b4 = new Object();
    Object b5 = new Object();
    return m(s);
  }
}

// fails
// TYPE_NOT_FOUND
// TYPE_NOT_FOUND
// TYPE_NOT_FOUND
// NAME_NOT_FOUND
// TYPE_MISMATCH

package java.util;

// import java.lang.*;
import java.io.File;
import java.io.JFile;  // fails

class A extends Object {
  String fname = "filename";
  File   file  = new java.io.File(fname);
  JFile  jfile  = new JFile(fname); /* fails four times:
                                       1- The first use of JFille
                                       2- The second use of JFille
                                       3- The missing constructor of JFille
                                       4- The unresolved types information
                                     */

  Object b1 = new Object();
  Object b2 = new Object();
  Object b3 = new Object();
  public String m(String a) {
    if("" instanceof String) {
      System.out.println("");
    }
    String s = "";
    Object b4 = new Object();
    Object b5 = new Object();
    return m(s);
  }
}

Add a test case for instanceof expressions


package org.vaadin.spring.mvp.explicit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.vaadin.spring.UIScope;
import org.vaadin.spring.annotation.EnableVaadin;
import org.vaadin.spring.events.EventBus;
import org.vaadin.spring.mvp.FooView;

@Configuration
@EnableVaadin
public class ExplicitConfig {

    @Autowired
    private EventBus eventBus;

    @Bean
    @UIScope
    public FooView fooView() {
        return new FooView();
    }

    @Bean
    @UIScope
    public ExplicitPresenter fooPresenter() {
        return new ExplicitPresenter(fooView(), eventBus);
    }
}

package org.vaadin.spring.mvp.explicit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.vaadin.spring.annotation.EnableVaadin;
import org.vaadin.spring.annotation.VaadinUIScope;
import org.vaadin.spring.events.EventBus;
import org.vaadin.spring.mvp.FooView;

@Configuration
@EnableVaadin
public class ExplicitConfig {

    @Autowired
    private EventBus eventBus;

    @Bean
    @VaadinUIScope
    public FooView fooView() {
        return new FooView();
    }

    @Bean
    @VaadinUIScope
    public ExplicitPresenter fooPresenter() {
        return new ExplicitPresenter(fooView(), eventBus);
    }
}

Test Class Update: Change UIScope => VaadinUIScope


package seedu.ezdo.model.todo;

/**
 * Represents the date associated with tasks.
 */
public abstract class TaskDate {

    public final String value;

    public static final String TASKDATE_VALIDATION_REGEX =
        "^$|([12][0-9]|3[01]|0?[1-9])/(0?[1-9]|1[012])/((?:19|20)\\d\\d)";;

    public TaskDate(String taskDate) {
        this.value = taskDate;
    }

    @Override
    public String toString() {
        return value;
    }

    @Override
    public boolean equals(Object other) {
        return other == this // short circuit if same object
                || (other instanceof TaskDate // instanceof handles nulls
                && this.value.equals(((TaskDate) other).value)); // state check
    }

    @Override
    public int hashCode() {
        return value.hashCode();
    }

    /**
     * Returns true if a given string is a valid task date.
     */
    public static boolean isValidTaskDate(String test) {
        return test.matches(TASKDATE_VALIDATION_REGEX);
    }
}

package seedu.ezdo.model.todo;

import com.joestelmach.natty.Parser;

/**
 * Represents the date associated with tasks.
 */
public abstract class TaskDate {

    public final String value;

    public static final String TASKDATE_VALIDATION_REGEX =
        "^$|([12][0-9]|3[01]|0?[1-9])/(0?[1-9]|1[012])/((?:19|20)\\d\\d)";;

    public TaskDate(String taskDate) {
    	Parser parser = new Parser();
        this.value = parser.parse(taskDate).get(0).getDates().get(0).toString();
    }

    @Override
    public String toString() {
        return value;
    }

    @Override
    public boolean equals(Object other) {
        return other == this // short circuit if same object
                || (other instanceof TaskDate // instanceof handles nulls
                && this.value.equals(((TaskDate) other).value)); // state check
    }

    @Override
    public int hashCode() {
        return value.hashCode();
    }

    /**
     * Returns true if a given string is a valid task date.
     */
    public static boolean isValidTaskDate(String test) {
        return test.matches(TASKDATE_VALIDATION_REGEX);
    }
}

Add the use of Natty in every date input


package com.splicemachine.test;

import com.splicemachine.concurrent.Threads;

import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.TimeUnit;

import static java.lang.String.format;

/**
 * Waits for connections on a given host+port to be available.
 */
public class SpliceTestPlatformWait {

    private static final long MAX_WAIT_SECS = TimeUnit.SECONDS.toSeconds(90);

    /**
     * argument 0 - hostname
     * argument 1 - port
     */
    public static void main(String[] arguments) throws IOException {

        String hostname = arguments[0];
        int port = Integer.valueOf(arguments[1]);

        long startTime = System.currentTimeMillis();
        long elapsedSecs = 0;
        while (elapsedSecs < MAX_WAIT_SECS) {
            try {
                new Socket(hostname, port);
                System.out.println("\nStarted\n");
                break;
            } catch (Exception e) {
                System.out.println(format("SpliceTestPlatformWait: Not started, still waiting for '%s:%s'. %s of %s seconds elapsed.",
                        hostname, port, elapsedSecs, MAX_WAIT_SECS));
                Threads.sleep(1, TimeUnit.SECONDS);
            }
            elapsedSecs = (long) ((System.currentTimeMillis() - startTime) / 1000d);
        }
        if (elapsedSecs >= MAX_WAIT_SECS) {
            System.out.println(format("Waited %s seconds without success", MAX_WAIT_SECS));
            System.exit(-1);
        }

    }

}

package com.splicemachine.test;

import com.splicemachine.concurrent.Threads;

import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.TimeUnit;

import static java.lang.String.format;

/**
 * Waits for connections on a given host+port to be available.
 */
public class SpliceTestPlatformWait {

    private static final long MAX_WAIT_SECS = TimeUnit.SECONDS.toSeconds(120);

    /**
     * argument 0 - hostname
     * argument 1 - port
     */
    public static void main(String[] arguments) throws IOException {

        String hostname = arguments[0];
        int port = Integer.valueOf(arguments[1]);

        long startTime = System.currentTimeMillis();
        long elapsedSecs = 0;
        while (elapsedSecs < MAX_WAIT_SECS) {
            try {
                new Socket(hostname, port);
                System.out.println("\nStarted\n");
                break;
            } catch (Exception e) {
                System.out.println(format("SpliceTestPlatformWait: Not started, still waiting for '%s:%s'. %s of %s seconds elapsed.",
                        hostname, port, elapsedSecs, MAX_WAIT_SECS));
                Threads.sleep(1, TimeUnit.SECONDS);
            }
            elapsedSecs = (long) ((System.currentTimeMillis() - startTime) / 1000d);
        }
        if (elapsedSecs >= MAX_WAIT_SECS) {
            System.out.println(format("Waited %s seconds without success", MAX_WAIT_SECS));
            System.exit(-1);
        }

    }

}

Increase waiting time for MapR standalone


package com.infinityraider.agricraft.plugins.minecraft;

import com.infinityraider.agricraft.api.v1.adapter.IAgriAdapter;
import com.infinityraider.agricraft.api.v1.crop.CropCapability;
import com.infinityraider.agricraft.api.v1.genetics.IAgriGenome;
import com.infinityraider.agricraft.api.v1.genetics.IAgriGenomeProvider;
import net.minecraftforge.common.capabilities.ICapabilityProvider;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Optional;

public class GenomeWrapper implements IAgriAdapter<IAgriGenome> {
    @Override
    public boolean accepts(@Nullable Object obj) {
        return obj instanceof IAgriGenomeProvider || obj instanceof ICapabilityProvider;
    }

    @Nonnull
    @Override
    public Optional<IAgriGenome> valueOf(@Nullable Object obj) {
        if(obj instanceof IAgriGenomeProvider) {
            return ((IAgriGenomeProvider) obj).getGenome();
        }
        if(obj instanceof ICapabilityProvider) {
            ICapabilityProvider capabilityProvider = (ICapabilityProvider) obj;
            return capabilityProvider.getCapability(CropCapability.getCapability())
                    .map(crop -> crop)
                    .flatMap(IAgriGenomeProvider::getGenome);
        }
        return Optional.empty();
    }
}

package com.infinityraider.agricraft.plugins.minecraft;

import com.infinityraider.agricraft.api.v1.adapter.IAgriAdapter;
import com.infinityraider.agricraft.api.v1.crop.CropCapability;
import com.infinityraider.agricraft.api.v1.genetics.IAgriGenome;
import com.infinityraider.agricraft.api.v1.genetics.IAgriGenomeProvider;
import net.minecraft.tileentity.TileEntity;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Optional;

public class GenomeWrapper implements IAgriAdapter<IAgriGenome> {
    @Override
    public boolean accepts(@Nullable Object obj) {
        return obj instanceof IAgriGenomeProvider || obj instanceof TileEntity;
    }

    @Nonnull
    @Override
    public Optional<IAgriGenome> valueOf(@Nullable Object obj) {
        if(obj instanceof IAgriGenomeProvider) {
            return ((IAgriGenomeProvider) obj).getGenome();
        }
        if(obj instanceof TileEntity) {
            TileEntity tile = (TileEntity) obj;
            return tile.getCapability(CropCapability.getCapability())
                    .map(crop -> crop)
                    .flatMap(IAgriGenomeProvider::getGenome);
        }
        return Optional.empty();
    }
}

Fix bug where it was impossible to plant seeds on crop sticks


/*
 *    Copyright 2010 Chris Sinjakli
 *
 * 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 Chris Sinjakli
 */

package uk.co.sinjakli.trivial;

import android.app.Activity;
import android.os.Bundle;

public class HomeActivity extends Activity {

	/** Called when the activity is first created. */
	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);

	}
}

/*
 *    Copyright 2010 Chris Sinjakli
 *
 * 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 Chris Sinjakli
 */

package uk.co.sinjakli.trivial;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class HomeActivity extends Activity {

	/** Called when the activity is first created. */
	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);

		final Button startQuiz = (Button) findViewById(R.id.btn_start_quiz);
		startQuiz.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				final Intent i = new Intent(HomeActivity.this, QuizActivity.class);
				startActivity(i);
			}

		});
	}
}

Implement onClick for Start Quiz button.

Change-Id: I7e65190731894b8069db68958b4663697e473190
Signed-off-by: Chris Sinjakli <711c73f64afdce07b7e38039a96d2224209e9a6c@sinjakli.co.uk>


package cas.ypsiliform.mediator.negotiation;

import java.util.ArrayList;

import cas.ypsiliform.mediator.async.Thenable;
import cas.ypsiliform.messages.AgentResponse;

public class AgentProxy {
	private ArrayList<AgentDeadListener> listeners = new ArrayList<AgentDeadListener>();

	public void addAgentDeadListener(AgentDeadListener listener) {
		listeners.add(listener);
	}

	public void removeAgentDeadListener(AgentDeadListener listener) {
		listeners.remove(listener);
	}

	public Thenable<AgentResponse> sendSolutionProposal(SolutionProposal solution) {
		// TODO implementation missing
		throw new UnsupportedOperationException();
	}
}

package cas.ypsiliform.mediator.negotiation;

import java.util.ArrayList;

import cas.ypsiliform.mediator.async.Thenable;
import cas.ypsiliform.messages.AgentResponse;

public class AgentProxy {
	private ArrayList<AgentDeadListener> listeners = new ArrayList<AgentDeadListener>();

	public void addAgentDeadListener(AgentDeadListener listener) {
		listeners.add(listener);
	}

	public void removeAgentDeadListener(AgentDeadListener listener) {
		listeners.remove(listener);
	}

	public Thenable<AgentResponse> sendSolutionProposal(SolutionProposal solution) {
		// TODO implementation missing
		throw new UnsupportedOperationException();
	}

	public Thenable<Void> endNegotiation(SolutionProposal solution) {
		// TODO implementation missing
		throw new UnsupportedOperationException();
	}
}

Add agent proxy operation to end the negotiation


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

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import net.simonvt.cathode.common.util.WakeLock;

public class NotificationReceiver extends BroadcastReceiver {

  @Override public void onReceive(Context context, Intent intent) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      PendingResult pendingResult = goAsync();
      NotificationHelper.displayNotifications(context);
      NotificationHelper.scheduleNextNotification(context);
      pendingResult.finish();
    } else {
      WakeLock.acquire(context, NotificationService.LOCK_TAG);
      NotificationService.start(context);
    }
  }
}

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

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import net.simonvt.cathode.common.util.WakeLock;
import net.simonvt.cathode.settings.Settings;

public class NotificationReceiver extends BroadcastReceiver {

  @Override public void onReceive(Context context, Intent intent) {
    if (Settings.get(context).getBoolean(Settings.NOTIFICACTIONS_ENABLED, false)) {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        PendingResult pendingResult = goAsync();
        NotificationHelper.displayNotifications(context);
        NotificationHelper.scheduleNextNotification(context);
        pendingResult.finish();
      } else {
        WakeLock.acquire(context, NotificationService.LOCK_TAG);
        NotificationService.start(context);
      }
    }
  }
}

Check notification setting before displaying notification.


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

package com.epam.ta.reportportal.ws.model.integration.auth;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * @author Ivan Budayeu
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ActiveDirectoryResource extends AbstractLdapResource {

	@JsonProperty(value = "domain")
	private String domain;

	public String getDomain() {
		return domain;
	}

	public void setDomain(String domain) {
		this.domain = domain;
	}

	@Override
	public String toString() {
		return "ActiveDirectoryResource{" + "domain='" + domain + '\'' + '}';
	}
}

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

package com.epam.ta.reportportal.ws.model.integration.auth;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * @author Ivan Budayeu
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ActiveDirectoryResource extends AbstractLdapResource {

	@JsonProperty(value = "domain")
	private String domain;

	@JsonProperty(value = "searchFilter")
	private String searchFilter;

	public String getDomain() {
		return domain;
	}

	public void setDomain(String domain) {
		this.domain = domain;
	}

	public String getSearchFilter() {
		return searchFilter;
	}

	public void setSearchFilter(String searchFilter) {
		this.searchFilter = searchFilter;
	}

	@Override
	public String toString() {
		return "ActiveDirectoryResource{" + "domain='" + domain + '\'' + ", searchFilter='" + searchFilter + '\'' + '}';
	}
}

Add a searchFilter field to ad resource

Add a searchFilter field to ad resource


package dk.statsbiblioteket.medieplatform.newspaper.editionRecords;

import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import dk.statsbiblioteket.medieplatform.autonomous.ConfigConstants;
import dk.statsbiblioteket.medieplatform.autonomous.DomsItemFactory;
import dk.statsbiblioteket.medieplatform.autonomous.Item;
import dk.statsbiblioteket.medieplatform.autonomous.SolrJConnector;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.Properties;

import static org.testng.Assert.*;

public class NewspaperIndexIT {

    private String summaLocation;

    @BeforeClass
    public void setUp() throws Exception {
        Properties props = new Properties();
        try {
            props.load(new FileReader(new File(System.getProperty("integration.test.newspaper.properties"))));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        summaLocation = props.getProperty(ConfigConstants.AUTONOMOUS_SBOI_URL);

    }

    @Test(groups = "externalTest")
    public void testGetNewspapers() throws Exception {
        NewspaperIndex newspaperIndex = new NewspaperIndex(new SolrJConnector(summaLocation).getSolrServer(), new DomsItemFactory());
        List<Item> newspapers = newspaperIndex.getNewspapers("berlingsketidende", "1970-01-01");
        assertTrue(newspapers.size() == 1);
    }
}

package dk.statsbiblioteket.medieplatform.newspaper.editionRecords;

import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import dk.statsbiblioteket.medieplatform.autonomous.ConfigConstants;
import dk.statsbiblioteket.medieplatform.autonomous.DomsItemFactory;
import dk.statsbiblioteket.medieplatform.autonomous.Item;
import dk.statsbiblioteket.medieplatform.autonomous.SolrJConnector;

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

import static org.testng.Assert.*;

public class NewspaperIndexIT {

    private String summaLocation;

    @BeforeClass(alwaysRun = true)
    public void setUp() throws Exception {
        String pathToProperties = System.getProperty("integration.test.newspaper.properties");
        Properties props = new Properties();

        props.load(new FileInputStream(pathToProperties));
        summaLocation = props.getProperty(ConfigConstants.AUTONOMOUS_SBOI_URL);

    }

    @Test(groups = "externalTest")
    public void testGetNewspapers() throws Exception {
        NewspaperIndex newspaperIndex = new NewspaperIndex(new SolrJConnector(summaLocation).getSolrServer(), new DomsItemFactory());
        List<Item> newspapers = newspaperIndex.getNewspapers("berlingsketidende", "1970-01-01");
        assertTrue(newspapers.size() == 1);
    }
}

Fix integration test to run the BeforeClass method for all groups


package io.github.droidkaigi.confsched.util;

import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;

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

import java.util.Arrays;
import java.util.Locale;

import io.github.droidkaigi.confsched.prefs.DefaultPrefsSchema;

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

@RunWith(AndroidJUnit4.class)
public class LocaleUtilsTest {

    @Test
    public void testCurrentLanguageId() throws Exception {
        Context context = InstrumentationRegistry.getContext();
        // is not null value.
        assertThat(LocaleUtil.getCurrentLanguageId(context)).isNotNull();

        DefaultPrefsSchema.get(context).putLanguageId("ja");
        // eq to languageID is put in SharedPreferences.
        assertThat(LocaleUtil.getCurrentLanguageId(context)).isEqualTo("ja");

        DefaultPrefsSchema.get(context).removeLanguageId();
        String defaultLanguage = Locale.getDefault().getLanguage().toLowerCase();
        if (Arrays.asList(LocaleUtil.SUPPORT_LANG).contains(defaultLanguage)) {
            // eq to Locale.getDefault().getLanguage() when it is supported
            assertThat(LocaleUtil.getCurrentLanguageId(context)).isEqualTo(defaultLanguage);
        } else {
            // eq to "en" when Locale.getDefault().getLanguage() is not supported
            assertThat(LocaleUtil.getCurrentLanguageId(context)).isEqualTo("en");
        }
    }

}

package io.github.droidkaigi.confsched.util;

import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;

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

import java.util.Arrays;
import java.util.Locale;

import io.github.droidkaigi.confsched.prefs.DefaultPrefs;

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

@RunWith(AndroidJUnit4.class)
public class LocaleUtilsTest {

    @Test
    public void testCurrentLanguageId() throws Exception {
        Context context = InstrumentationRegistry.getContext();
        // is not null value.
        assertThat(LocaleUtil.getCurrentLanguageId(context)).isNotNull();

        DefaultPrefs.get(context).putLanguageId("ja");
        // eq to languageID is put in SharedPreferences.
        assertThat(LocaleUtil.getCurrentLanguageId(context)).isEqualTo("ja");

        DefaultPrefs.get(context).removeLanguageId();
        String defaultLanguage = Locale.getDefault().getLanguage().toLowerCase();
        if (Arrays.asList(LocaleUtil.SUPPORT_LANG).contains(defaultLanguage)) {
            // eq to Locale.getDefault().getLanguage() when it is supported
            assertThat(LocaleUtil.getCurrentLanguageId(context)).isEqualTo(defaultLanguage);
        } else {
            // eq to "en" when Locale.getDefault().getLanguage() is not supported
            assertThat(LocaleUtil.getCurrentLanguageId(context)).isEqualTo("en");
        }
    }

}

Rename old class name of kvs-schema

Rename old class name of kvs-schema


package com.amebame.triton.server;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.amebame.triton.config.TritonServerConfiguration;
import com.amebame.triton.util.NamedThreadFactory;

@Singleton
public class TritonServerContext {

	private TritonServerMethodMap methodMap;

	private ExecutorService executor;

	@Inject
	public TritonServerContext(TritonServerConfiguration config) {
		methodMap = new TritonServerMethodMap();
		executor = new ThreadPoolExecutor(
				1,
				config.getNetty().getWorker(),
				60L,
				TimeUnit.SECONDS,
				new LinkedBlockingQueue<Runnable>(),
				new NamedThreadFactory("triton-worker-")
		);
	}

	/**
	 * Add server methods from the target object
	 * @param target
	 */
	public void addServerMethod(Object target) {
		methodMap.register(target);
	}

	/**
	 * Get server method by name
	 * @param name
	 * @return
	 */
	public TritonServerMethod getServerMethod(String name) {
		return methodMap.getMethod(name);
	}

	/**
	 * Get worker executor
	 * @return
	 */
	public ExecutorService getWorkerExecutor() {
		return executor;
	}
}

package com.amebame.triton.server;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.amebame.triton.config.TritonServerConfiguration;
import com.amebame.triton.util.NamedThreadFactory;

@Singleton
public class TritonServerContext {

	private TritonServerMethodMap methodMap;

	private ExecutorService executor;

	@Inject
	public TritonServerContext(TritonServerConfiguration config) {
		methodMap = new TritonServerMethodMap();
		executor = Executors.newFixedThreadPool(
				config.getNetty().getWorker(),
				new NamedThreadFactory("triton-worker-"));
	}

	/**
	 * Add server methods from the target object
	 * @param target
	 */
	public void addServerMethod(Object target) {
		methodMap.register(target);
	}

	/**
	 * Get server method by name
	 * @param name
	 * @return
	 */
	public TritonServerMethod getServerMethod(String name) {
		return methodMap.getMethod(name);
	}

	/**
	 * Get worker executor
	 * @return
	 */
	public ExecutorService getWorkerExecutor() {
		return executor;
	}
}

Make worker executor to FixedThreadPoolExecutor.