package co.smartreceipts.android.widget;

import android.content.Context;
import android.content.res.Configuration;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

public class ShowSoftKeyboardOnFocusChangeListener implements View.OnFocusChangeListener {

    /**
     * After we resume Smart Receipts after using the camera, the input manager isn't quite ready yet to actually
     * show the keyboard for some reason (as opposed to using a text receipt). I wasn't able to find any checks
     * for why this fails programtically, so I built in a hacky hardcoded delay to help resolve this
     */
    private static final int DELAY_TO_SHOW_KEYBOARD_MILLIS = 250;

    @Override
    public void onFocusChange(final View view, final boolean hasFocus) {
        if (hasFocus && view != null) {
            if (view.getResources().getConfiguration().hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
                final InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    // Try both immediately
                    imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
                    view.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            // And delayed
                            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
                        }
                    }, DELAY_TO_SHOW_KEYBOARD_MILLIS);
                }
            }
        }
    }
}

package co.smartreceipts.android.widget;

import android.content.Context;
import android.content.res.Configuration;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

public class ShowSoftKeyboardOnFocusChangeListener implements View.OnFocusChangeListener {

    /**
     * After we resume Smart Receipts after using the camera, the input manager isn't quite ready yet to actually
     * show the keyboard for some reason (as opposed to using a text receipt). I wasn't able to find any checks
     * for why this fails, so I built in a hacky hardcoded delay to help resolve this
     */
    private static final int DELAY_TO_SHOW_KEYBOARD_MILLIS = 400;

    @Override
    public void onFocusChange(final View view, final boolean hasFocus) {
        if (hasFocus && view != null) {
            if (view.getResources().getConfiguration().hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
                final InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    // Try both immediately
                    imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
                    view.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            // And delayed
                            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
                        }
                    }, DELAY_TO_SHOW_KEYBOARD_MILLIS);
                }
            }
        }
    }
}

Increase soft keyboard launch delay

Increase soft keyboard launch delay


package uk.ac.cam.gpe21.droidssl.analysis.util;

import soot.RefType;
import soot.Unit;
import soot.jimple.IntConstant;
import soot.jimple.ReturnStmt;
import soot.toolkits.exceptions.ThrowableSet;
import soot.toolkits.exceptions.UnitThrowAnalysis;
import soot.toolkits.graph.UnitGraph;

public final class FlowGraphUtils {
	public static boolean anyExitThrowsException(UnitGraph graph, RefType exceptionType) {
		for (Unit unit : graph.getTails()) {
			ThrowableSet set = UnitThrowAnalysis.v().mightThrow(unit);
			if (set.catchableAs(exceptionType)) {
				return true;
			}
		}

		return false;
	}

	public static boolean allExitsReturnTrue(UnitGraph graph) {
		for (Unit unit : graph.getTails()) {
			if (unit instanceof ReturnStmt) {
				ReturnStmt stmt = (ReturnStmt) unit;
				if (!stmt.getOp().equals(IntConstant.v(1))) {
					return true;
				}
			}
		}

		return true;
	}

	private FlowGraphUtils() {
		/* to prevent instantiation */
	}
}

package uk.ac.cam.gpe21.droidssl.analysis.util;

import soot.RefType;
import soot.Unit;
import soot.jimple.IntConstant;
import soot.jimple.ReturnStmt;
import soot.toolkits.exceptions.ThrowableSet;
import soot.toolkits.exceptions.UnitThrowAnalysis;
import soot.toolkits.graph.UnitGraph;

public final class FlowGraphUtils {
	public static boolean anyExitThrowsException(UnitGraph graph, RefType exceptionType) {
		for (Unit unit : graph.getTails()) {
			ThrowableSet set = UnitThrowAnalysis.v().mightThrow(unit);
			if (set.catchableAs(exceptionType)) {
				return true;
			}
		}

		return false;
	}

	public static boolean allExitsReturnTrue(UnitGraph graph) {
		for (Unit unit : graph.getTails()) {
			if (unit instanceof ReturnStmt) {
				ReturnStmt stmt = (ReturnStmt) unit;
				if (!stmt.getOp().equals(IntConstant.v(1))) {
					return false;
				}
			}
		}

		return true;
	}

	private FlowGraphUtils() {
		/* to prevent instantiation */
	}
}

Fix allExitsReturnTrue() always returning true itself.


package org.robolectric.util;

import android.content.ComponentName;
import android.content.ContentProvider;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import org.robolectric.RuntimeEnvironment;

public class ContentProviderController<T extends ContentProvider> {
  private T contentProvider;

  private ContentProviderController(T contentProvider) {
    this.contentProvider = contentProvider;
  }

  public static <T extends ContentProvider> ContentProviderController<T> of(T contentProvider) {
    return new ContentProviderController<>(contentProvider);
  }

  public ContentProviderController<T> create() {
    Context baseContext = RuntimeEnvironment.application.getBaseContext();
    ComponentName componentName = ComponentName.createRelative(baseContext, contentProvider.getClass().getName());

    ProviderInfo providerInfo;
    try {
      providerInfo = RuntimeEnvironment.getPackageManager().getProviderInfo(componentName, 0);
    } catch (PackageManager.NameNotFoundException e) {
      Logger.strict("Unable to find provider info for " + componentName, e);
      providerInfo = null;

    }
    contentProvider.attachInfo(baseContext, providerInfo);

    return this;
  }

  public T get() {
    return contentProvider;
  }

  public ContentProviderController<T> shutdown() {
    contentProvider.shutdown();
    return this;
  }
}

package org.robolectric.util;

import android.content.ComponentName;
import android.content.ContentProvider;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.text.TextUtils;
import org.robolectric.RuntimeEnvironment;

public class ContentProviderController<T extends ContentProvider> {
  private T contentProvider;

  private ContentProviderController(T contentProvider) {
    this.contentProvider = contentProvider;
  }

  public static <T extends ContentProvider> ContentProviderController<T> of(T contentProvider) {
    return new ContentProviderController<>(contentProvider);
  }

  public ContentProviderController<T> create() {
    Context baseContext = RuntimeEnvironment.application.getBaseContext();
    ComponentName componentName = createRelative(baseContext.getPackageName(), contentProvider.getClass().getName());

    ProviderInfo providerInfo;
    try {
      providerInfo = RuntimeEnvironment.getPackageManager().getProviderInfo(componentName, 0);
    } catch (PackageManager.NameNotFoundException e) {
      Logger.strict("Unable to find provider info for " + componentName, e);
      providerInfo = null;

    }
    contentProvider.attachInfo(baseContext, providerInfo);

    return this;
  }

  public T get() {
    return contentProvider;
  }

  public ContentProviderController<T> shutdown() {
    contentProvider.shutdown();
    return this;
  }

  private static ComponentName createRelative(String pkg, String cls) {
    final String fullName;
    if (cls.charAt(0) == '.') {
      // Relative to the package. Prepend the package name.
      fullName = pkg + cls;
    } else {
      // Fully qualified package name.
      fullName = cls;
    }
    return new ComponentName(pkg, fullName);
  }
}

Copy createRelative() from ComponentName since it is not available on older SDKs.


package edu.northwestern.bioinformatics.studycalendar.dao;

import edu.northwestern.bioinformatics.studycalendar.domain.StudySite;

/**
 * @author Padmaja Vedula
 */
public class StudySiteDao extends StudyCalendarMutableDomainObjectDao<StudySite> {
    @Override public Class<StudySite> domainClass() { return StudySite.class; }

    public void delete(StudySite studySite) {
        getHibernateTemplate().delete(studySite);
    }
}

package edu.northwestern.bioinformatics.studycalendar.dao;

import edu.northwestern.bioinformatics.studycalendar.domain.StudySite;

/**
 * @author Padmaja Vedula
 */
public class StudySiteDao extends StudyCalendarMutableDomainObjectDao<StudySite> {
    @Override public Class<StudySite> domainClass() { return StudySite.class; }

    /**
     * Deletes the study site relationship
     *
     * @param  studySite the study site relationship to delete
     */
    public void delete(StudySite studySite) {
        getHibernateTemplate().delete(studySite);
    }
}

Add javadoc to study segment dao.

Add javadoc to study segment dao.


package org.apache.xml.security.test.algorithms;

import java.security.KeyPairGenerator;
import java.security.PrivateKey;

import javax.xml.parsers.DocumentBuilderFactory;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import org.apache.xml.security.algorithms.SignatureAlgorithm;
import org.apache.xml.security.signature.XMLSignature;
import org.w3c.dom.Document;

public class SignatureAlgorithmTest extends TestCase {
	public void testSameKeySeveralAlgorithSigning() throws Exception {
		Document doc=DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
		SignatureAlgorithm signatureAlgorithm = new SignatureAlgorithm(doc,XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1);
		PrivateKey pk=KeyPairGenerator.getInstance("RSA").genKeyPair().getPrivate();
		signatureAlgorithm.initSign(pk);
		signatureAlgorithm.update((byte)2);
		signatureAlgorithm.sign();
		SignatureAlgorithm otherSignatureAlgorithm = new SignatureAlgorithm(doc,XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256);
		otherSignatureAlgorithm.initSign(pk);
		otherSignatureAlgorithm.update((byte)2);
		otherSignatureAlgorithm.sign();
	}
	public static Test suite() {
		return new TestSuite(SignatureAlgorithmTest.class);
	}
}

package org.apache.xml.security.test.algorithms;

import java.security.KeyPairGenerator;
import java.security.PrivateKey;

import javax.xml.parsers.DocumentBuilderFactory;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import org.apache.xml.security.algorithms.SignatureAlgorithm;
import org.apache.xml.security.signature.XMLSignature;
import org.w3c.dom.Document;

public class SignatureAlgorithmTest extends TestCase {

	static {
	    org.apache.xml.security.Init.init();
	}

	public void testSameKeySeveralAlgorithSigning() throws Exception {
		Document doc=DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
		SignatureAlgorithm signatureAlgorithm = new SignatureAlgorithm(doc,XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1);
		PrivateKey pk=KeyPairGenerator.getInstance("RSA").genKeyPair().getPrivate();
		signatureAlgorithm.initSign(pk);
		signatureAlgorithm.update((byte)2);
		signatureAlgorithm.sign();
		SignatureAlgorithm otherSignatureAlgorithm = new SignatureAlgorithm(doc,XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256);
		otherSignatureAlgorithm.initSign(pk);
		otherSignatureAlgorithm.update((byte)2);
		otherSignatureAlgorithm.sign();
	}
	public static Test suite() {
		return new TestSuite(SignatureAlgorithmTest.class);
	}
}

Fix test failure: call Init.init() in static block.

git-svn-id: c5bb8e2b15dc16fd1aec0e5653c08870c9ddec7d@557627 13f79535-47bb-0310-9956-ffa450edef68


package mrtim.sasscompiler.expr;

public class DivisionExpression extends AbstractExpressionValue {

    private final ExpressionValue numerator;
    private final ExpressionValue denominator;

    public DivisionExpression(ExpressionValue numerator, ExpressionValue denominator) {
        this.numerator = numerator;
        this.denominator = denominator;
    }

    public ExpressionValue evaluate() {
        return numerator.operate(Operator.DIVIDE, denominator);
    }

    @Override
    public ExpressionValue operate(Operator operator, ExpressionValue other) {
        return evaluate().operate(operator, other);
    }

    @Override
    public String stringValue() {
        return numerator.stringValue() + " / " + denominator.stringValue();
    }
}

package mrtim.sasscompiler.expr;

public class DivisionExpression extends AbstractExpressionValue {

    private final ExpressionValue numerator;
    private final ExpressionValue denominator;

    public DivisionExpression(ExpressionValue numerator, ExpressionValue denominator) {
        this.numerator = numerator;
        this.denominator = denominator;
    }

    public ExpressionValue evaluate() {
        return numerator.operate(Operator.DIVIDE, denominator);
    }

    @Override
    public ExpressionValue operate(Operator operator, ExpressionValue other) {
        return evaluate().operate(operator, other);
    }

    @Override
    public String stringValue() {
        return numerator.stringValue() + "/" + denominator.stringValue();
    }
}

Remove superfluous space in division expressions


package org.usfirst.frc4909.STEAMWORKS.commands;

import org.usfirst.frc4909.STEAMWORKS.Robot;

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

public class StopShooting extends Command {

    public StopShooting() {
    	requires(Robot.feeder);
    	requires(Robot.shooter);
    }

    protected void initialize() {
    	Robot.feeder.stopFeed();
    }

    protected void execute() {}

    protected boolean isFinished() {
        return true;
    }

    protected void end() {}

    protected void interrupted() {}
}

package org.usfirst.frc4909.STEAMWORKS.commands;

import org.usfirst.frc4909.STEAMWORKS.Robot;

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

public class StopShooting extends InstantCommand {

    public StopShooting() {
    	requires(Robot.feeder);
    	requires(Robot.shooter);
    }

    protected void initialize() {
    	Robot.feeder.stopFeed();
    }
}

Convert Stop Shooting to Instant Command


package com.ejpm.euler;

import com.ejpm.euler.problem.impl.Problem1;
import com.ejpm.euler.problem.impl.Problem2;
import com.ejpm.euler.problem.impl.Problem3;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class App {

    @SuppressWarnings("unused")
    private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

    public static void main(String[] args) {
        new App().proceed();
    }

    public void proceed() {
        System.out.println("Project Euler Solutions");
        //final Reflection

        new Problem1().execute();
        new Problem2().execute();
        new Problem3().execute();
    }
}

package com.ejpm.euler;

import com.ejpm.euler.problem.Problem;
import java.util.logging.Level;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class App {

    @SuppressWarnings("unused")
    private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

    public static void main(String[] args) {
        System.out.println("Project Euler Solutions");
        new App().executeProblems();
        System.out.println("DONE");
    }

    public void executeProblems() {
        final String classPackage = "com.ejpm.euler.problem.impl";

        for (int i = 0; i < 900; i++) {
            final String className = classPackage.concat(".Problem") + i;
            try {
                final Class<?> c = Class.forName(className);
                final Problem problem = (Problem) c.newInstance();
                problem.execute();
            } catch (ClassNotFoundException ex) {
            } catch (InstantiationException | IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

Add reflection to problem execution

Add reflection to problem execution


// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.container.http;

import com.google.common.collect.Lists;
import com.yahoo.component.ComponentId;
import com.yahoo.component.ComponentSpecification;
import com.yahoo.vespa.model.container.ContainerCluster;
import com.yahoo.vespa.model.container.component.FileStatusHandlerComponent;
import com.yahoo.vespa.model.container.component.Handler;
import com.yahoo.vespa.model.container.http.Http.Binding;

import java.util.ArrayList;

/**
 * Helper class for http access control.
 *
 * @author gjoranv
 */
public final class AccessControl {

    public static final ComponentId ACCESS_CONTROL_CHAIN_ID = ComponentId.fromString("access-control-chain");

    public static final ArrayList<String> unprotectedHandlers = Lists.newArrayList(
            FileStatusHandlerComponent.CLASS,
            ContainerCluster.APPLICATION_STATUS_HANDLER_CLASS,
            ContainerCluster.BINDINGS_OVERVIEW_HANDLER_CLASS,
            ContainerCluster.STATE_HANDLER_CLASS,
            ContainerCluster.STATISTICS_HANDLER_CLASS
    );

    public static boolean shouldHandlerBeProtected(Handler<?> handler) {
        return ! unprotectedHandlers.contains(handler.getClassId().getName());
    }

    public static Binding accessControlBinding(String binding) {
        return new Binding(new ComponentSpecification(ACCESS_CONTROL_CHAIN_ID.stringValue()), binding);
    }

}

// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.container.http;

import com.google.common.collect.ImmutableList;
import com.yahoo.component.ComponentId;
import com.yahoo.component.ComponentSpecification;
import com.yahoo.vespa.model.container.ContainerCluster;
import com.yahoo.vespa.model.container.component.FileStatusHandlerComponent;
import com.yahoo.vespa.model.container.component.Handler;
import com.yahoo.vespa.model.container.http.Http.Binding;

import java.util.List;

/**
 * Helper class for http access control.
 *
 * @author gjoranv
 */
public final class AccessControl {

    public static final ComponentId ACCESS_CONTROL_CHAIN_ID = ComponentId.fromString("access-control-chain");

    private static final List<String> UNPROTECTED_HANDLERS = ImmutableList.of(
            FileStatusHandlerComponent.CLASS,
            ContainerCluster.APPLICATION_STATUS_HANDLER_CLASS,
            ContainerCluster.BINDINGS_OVERVIEW_HANDLER_CLASS,
            ContainerCluster.STATE_HANDLER_CLASS,
            ContainerCluster.STATISTICS_HANDLER_CLASS
    );

    public static boolean shouldHandlerBeProtected(Handler<?> handler) {
        return ! UNPROTECTED_HANDLERS.contains(handler.getClassId().getName());
    }

    public static Binding accessControlBinding(String binding) {
        return new Binding(new ComponentSpecification(ACCESS_CONTROL_CHAIN_ID.stringValue()), binding);
    }

}

Make constant list immutable and uppercase name.


/*
 * oxTrust is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
 *
 * Copyright (c) 2014, Gluu
 */

package org.gluu.oxauth.client.auth.user;

import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * User profile retrieved from oxAuth after successful authentication
 *
 * @author Yuriy Movchan 11/14/2014
 */
public class UserProfile implements Serializable {

	private static final long serialVersionUID = 4570636703916315314L;

	private String id;

	private final Map<String, Object> attributes = new HashMap<String, Object>();

	public String getId() {
		return id;
	}

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

	public Map<String, Object> getAttributes() {
		return Collections.unmodifiableMap(this.attributes);
	}

	public Object getAttribute(final String name) {
		return this.attributes.get(name);
	}

	public void addAttribute(final String key, final Object value) {
		if (value != null) {
			this.attributes.put(key, value);
		}
	}

}

/*
 * oxTrust is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
 *
 * Copyright (c) 2014, Gluu
 */

package org.gluu.oxauth.client.auth.user;

import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * User profile retrieved from oxAuth after successful authentication
 *
 * @author Yuriy Movchan 11/14/2014
 */
public class UserProfile implements Serializable {

	private static final long serialVersionUID = 4570636703916315314L;

	private String id;

	private final Map<String, Object> attributes = new HashMap<String, Object>();

	public String getId() {
		return id;
	}

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

	public Map<String, Object> getAttributes() {
		return Collections.unmodifiableMap(this.attributes);
	}

	public Object getAttribute(final String name) {
		return this.attributes.get(name);
	}

	public void addAttribute(final String key, final Object value) {
		if (value != null) {
			this.attributes.put(key, value);
		}
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("UserProfile [id=").append(id).append(", attributes=").append(attributes).append("]");
		return builder.toString();
	}

}

Add toString to dump profile attributes

Add toString to dump profile attributes


package com.ns.greg.library.fasthook.observer;

/**
 * @author Gregory
 * @since 2016/5/20
 */
public interface BaseSubject<T> {

  /**
   * Observe the task status
   *
   * @param observer observer
   */
  void addObserver(BaseObserver<T> observer);

  /**
   * Remove the observer
   *
   * @param observer observer
   */
  void removeObserver(BaseObserver<T> observer);

  /**
   * Clears all the observer
   */
  void clearAllObserver();

  /**
   * Notify the observer the task is completed
   *
   * @param data result data
   */
  void notifyObserversOnCompleted(T data);

  /**
   * Notify the observer the task is interrupted
   *
   * @param data result data
   */
  void notifyObserversOnError(T data);
}

package com.ns.greg.library.fasthook.observer;

/**
 * @author Gregory
 * @since 2016/5/20
 */
public interface BaseSubject<T> {

  /**
   * Observe the task status
   *
   * @param observer observer
   */
  void addObserver(BaseObserver<T> observer);

  /**
   * Remove the observer
   *
   * @param observer observer
   */
  void removeObserver(BaseObserver<T> observer);

  /**
   * Clears all the observer
   */
  void clearObservers();

  /**
   * Notify the observer the task is completed
   *
   * @param data result data
   */
  void notifyObserversOnCompleted(T data);

  /**
   * Notify the observer the task is interrupted
   *
   * @param data result data
   */
  void notifyObserversOnError(T data);
}

Change method name clearAllObserver() -> clearObservers()


package com.peterphi.std.guice.web.rest.templating.thymeleaf;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.name.Named;
import com.peterphi.std.annotation.Doc;
import com.peterphi.std.threading.Timeout;
import org.thymeleaf.templateresolver.ITemplateResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

import java.util.concurrent.TimeUnit;

public class TemplateResolverProvider implements Provider<ITemplateResolver>
{
	@Inject(optional = true)
	@Named("thymeleaf.cache-ttl")
	@Doc("The maximum Time-To-Live value on the thymeleaf in-memory template cache")
	Timeout cacheTTL = new Timeout(1, TimeUnit.HOURS);

	@Override
	public ITemplateResolver get()
	{
		ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();

		resolver.setTemplateMode("HTML5");

		// Load templates from WEB-INF/templates/{name}.html
		resolver.setPrefix("/WEB-INF/template/");
		resolver.setSuffix(".html");

		if (cacheTTL.getMilliseconds() > 0)
		{
			// cache templates for an hour
			resolver.setCacheTTLMs(cacheTTL.getMilliseconds());
			resolver.setCacheable(true);
		}
		else
		{
			// Don't cache
			resolver.setCacheable(false);
		}

		return resolver;
	}
}

package com.peterphi.std.guice.web.rest.templating.thymeleaf;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.name.Named;
import com.peterphi.std.annotation.Doc;
import com.peterphi.std.threading.Timeout;
import org.thymeleaf.templateresolver.ITemplateResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

import java.util.concurrent.TimeUnit;

public class TemplateResolverProvider implements Provider<ITemplateResolver>
{
	@Inject(optional = true)
	@Named("thymeleaf.cache-ttl")
	@Doc("The maximum Time-To-Live value on the thymeleaf in-memory template cache (default 1h)")
	Timeout cacheTTL = new Timeout(1, TimeUnit.HOURS);

	@Override
	public ITemplateResolver get()
	{
		ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();

		resolver.setTemplateMode("HTML5");

		// Load templates from WEB-INF/templates/{name}.html
		resolver.setPrefix("/WEB-INF/template/");
		resolver.setSuffix(".html");

		if (cacheTTL.getMilliseconds() > 0)
		{
			// cache templates for an hour
			resolver.setCacheTTLMs(cacheTTL.getMilliseconds());
			resolver.setCacheable(true);
		}
		else
		{
			// Don't cache
			resolver.setCacheable(false);
		}

		return resolver;
	}
}

Update thymeleaf.cache-ttl documentation to indicate the default value


package com.grayben.riskExtractor.htmlScorer.partScorers;

import org.jsoup.nodes.Attribute;
import org.jsoup.parser.Tag;

public class TagAndAttribute {
	private final Tag tag;
	private final Attribute attribute;

    public Tag getTag() {
        return tag;
    }

    public Attribute getAttribute() {
        return attribute;
    }

    public TagAndAttribute(Tag tag, Attribute attribute) {
		super();
        if (tag == null) {
            throw new NullPointerException(
                    "Attempted to pass in null tag:Tag"
            );
        }
        if (attribute == null) {
            throw new NullPointerException(
                    "Attempted to pass in null attribute:Attribute"
            );
        }

        this.tag = tag;
		this.attribute = attribute;
	}

    @Override
    public boolean equals(Object o) {
        assert getTag() != null;
        assert getAttribute() != null;

        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        TagAndAttribute that = (TagAndAttribute) o;

        if (!getTag().equals(that.getTag())) return false;
        return getAttribute().equals(that.getAttribute());

    }

    @Override
    public int hashCode() {
        assert getAttribute() != null;
        assert getTag() != null;
        int result = getTag().hashCode();
        result = 31 * result + getAttribute().hashCode();
        return result;
    }
}

package com.grayben.riskExtractor.htmlScorer.partScorers;

import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Tag;

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

public class TagAndAttribute {
	private final Tag tag;
	private final Attribute attribute;

    public Tag getTag() {
        return tag;
    }

    public Attribute getAttribute() {
        return attribute;
    }

    public static List<TagAndAttribute> fromElement(Element element){
        List<TagAndAttribute> list = new ArrayList<>();
        for (Attribute attribute :
                element.attributes()) {
            list.add(new TagAndAttribute(element.tag(), attribute));
        }
        return list;
    }

    public TagAndAttribute(Tag tag, Attribute attribute) {
		super();
        if (tag == null) {
            throw new NullPointerException(
                    "Attempted to pass in null tag:Tag"
            );
        }
        if (attribute == null) {
            throw new NullPointerException(
                    "Attempted to pass in null attribute:Attribute"
            );
        }

        this.tag = tag;
		this.attribute = attribute;
	}

    @Override
    public boolean equals(Object o) {
        assert getTag() != null;
        assert getAttribute() != null;

        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        TagAndAttribute that = (TagAndAttribute) o;

        if (!getTag().equals(that.getTag())) return false;
        return getAttribute().equals(that.getAttribute());

    }

    @Override
    public int hashCode() {
        assert getAttribute() != null;
        assert getTag() != null;
        int result = getTag().hashCode();
        result = 31 * result + getAttribute().hashCode();
        return result;
    }
}

Create static generator from Element

Create static generator from Element


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

import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.is;

import org.apache.camel.Endpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;

public class FluentdEndpointTest extends CamelTestSupport {

    @Test
    public void testDefaults() {
        Endpoint endpoint = context.getEndpoint("fluentd:hostname:port/tag");
        assertNotNull(endpoint);
    }

    // TODO
    @Test
    public void assertTodo() throws Exception {
        assertThat(true, is(true));
    }

}

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

import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.is;

import org.apache.camel.Endpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;

public class FluentdEndpointTest extends CamelTestSupport {

    @Test
    public void testDefaults() {
        Endpoint endpoint = context.getEndpoint("fluentd:hostname:port/tag");
        assertNotNull(endpoint);
    }

}

Delete an unnecessary test case

Delete an unnecessary test case


/*
 * JGrapes Event Driven Framework
 * Copyright (C) 2017-2018 Michael N. Lipp
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, see <http://www.gnu.org/licenses/>.
 */

package org.jgrapes.examples.core.helloworld;

import org.jgrapes.core.Component;
import org.jgrapes.core.Components;
import org.jgrapes.core.annotation.Handler;
import org.jgrapes.core.events.Start;

/**
 * A component that displays "Hello World" on start.
 */
public class Greeter extends Component {

    @Handler
    public void onStart(Start event) {
        System.out.println("Hello World!");
    }

    public static void main(String[] args)
            throws InterruptedException {
        Components.start(new Greeter());
        Components.awaitExhaustion();
        System.exit(0);
    }
}

/*
 * JGrapes Event Driven Framework
 * Copyright (C) 2017-2018 Michael N. Lipp
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, see <http://www.gnu.org/licenses/>.
 */

package org.jgrapes.examples.core.helloworld;

import org.jgrapes.core.Component;
import org.jgrapes.core.Components;
import org.jgrapes.core.annotation.Handler;
import org.jgrapes.core.events.Start;

/**
 * A component that displays "Hello World" on start.
 */
public class Greeter extends Component {

    @Handler
    public void onStart(Start event) {
        System.out.println("Hello World!");
    }

    public static void main(String[] args)
            throws InterruptedException {
        Components.start(new Greeter());
    }
}

Make use of new thread policy.

Make use of new thread policy.


package org.sagebionetworks.repo.manager.table;

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

import org.sagebionetworks.repo.model.EntityType;
import org.sagebionetworks.util.ValidateArgument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Simple mapping of entity types to transaction managers.
 *
 */
@Service
public class TableUpdateRequestManagerProviderImpl implements TableUpdateRequestManagerProvider {

	private Map<EntityType, TableUpdateRequestManager> managerMap;

	@Autowired
	public void configureMapping(TableEntityUpdateRequestManager tableEntityUpdateManager, TableViewUpdateRequestManager tableViewUpdateManager) {
		managerMap = new HashMap<>();
		managerMap.put(EntityType.table, tableEntityUpdateManager);
		managerMap.put(EntityType.entityview, tableViewUpdateManager);
		managerMap.put(EntityType.submissionview, tableViewUpdateManager);
		managerMap.put(EntityType.dataset, tableViewUpdateManager);
	}

	@Override
	public TableUpdateRequestManager getUpdateRequestManagerForType(EntityType type) {
		ValidateArgument.required(type, "type");
		TableUpdateRequestManager manager = managerMap.get(type);
		if (manager == null){
			throw new IllegalArgumentException("Unknown type: "+type);
		}
		return manager;
	}

}

package org.sagebionetworks.repo.manager.table;

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

import org.sagebionetworks.repo.model.EntityType;
import org.sagebionetworks.util.ValidateArgument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Simple mapping of entity types to transaction managers.
 *
 */
@Service
public class TableUpdateRequestManagerProviderImpl implements TableUpdateRequestManagerProvider {

	private Map<EntityType, TableUpdateRequestManager> managerMap;

	@Autowired
	public void configureMapping(TableEntityUpdateRequestManager tableEntityUpdateManager, TableViewUpdateRequestManager tableViewUpdateManager) {
		managerMap = new HashMap<>();
		managerMap.put(EntityType.table, tableEntityUpdateManager);
		managerMap.put(EntityType.entityview, tableViewUpdateManager);
		managerMap.put(EntityType.submissionview, tableViewUpdateManager);
		managerMap.put(EntityType.dataset, tableViewUpdateManager);
		managerMap.put(EntityType.datasetcollection, tableViewUpdateManager);
	}

	@Override
	public TableUpdateRequestManager getUpdateRequestManagerForType(EntityType type) {
		ValidateArgument.required(type, "type");
		TableUpdateRequestManager manager = managerMap.get(type);
		if (manager == null){
			throw new IllegalArgumentException("Unknown type: "+type);
		}
		return manager;
	}

}

PLFM-7403: Add missing mapping for datasetcollection updates


//tag::include[]
package org.hibernate.validator.referenceguide.chapter06.constraintvalidatorpayload;

//end::include[]

import javax.validation.ConstraintValidatorContext;
import javax.validation.ConstraintValidator;

import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;

//tag::include[]
public class ZipCodeValidator implements ConstraintValidator<ZipCode, String> {

	public String countryCode;

	@Override
	public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
		if ( object == null ) {
			return true;
		}

		boolean isValid = false;

		String countryCode = constraintContext.unwrap( HibernateConstraintValidatorContext.class )
				.getConstraintValidatorPayload( String.class );

		if ( "US".equals( countryCode ) ) {
			// checks specific to the United States
		}
		else if ( "FR".equals( countryCode ) ) {
			// checks specific to France
		}
		else {
			// ...
		}

		return isValid;
	}
}
//end::include[]

//tag::include[]
package org.hibernate.validator.referenceguide.chapter06.constraintvalidatorpayload;

//end::include[]

import javax.validation.ConstraintValidatorContext;
import javax.validation.ConstraintValidator;

import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;

//tag::include[]
public class ZipCodeValidator implements ConstraintValidator<ZipCode, String> {

	public String countryCode;

	@Override
	public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
		if ( object == null ) {
			return true;
		}

		boolean isValid = false;

		String countryCode = constraintContext
				.unwrap( HibernateConstraintValidatorContext.class )
				.getConstraintValidatorPayload( String.class );

		if ( "US".equals( countryCode ) ) {
			// checks specific to the United States
		}
		else if ( "FR".equals( countryCode ) ) {
			// checks specific to France
		}
		else {
			// ...
		}

		return isValid;
	}
}
//end::include[]

Improve line wrapping in the documentation


/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.xwiki.rendering.internal.macro.message;

import javax.inject.Named;
import javax.inject.Singleton;

import org.xwiki.component.annotation.Component;

/**
 * Displays an error message.
 *
 * @version $Id$
 * @since 2.0M3
 */
@Component
@Named("error")
@Singleton
public class ErrorMessageMacro extends AbstractMessageMacro
{
    /**
     * Create and initialize the descriptor of the macro.
     */
    public ErrorMessageMacro()
    {
        super("Error Message", "Displays an error message note.");
        setDefaultCategory(DEFAULT_CATEGORY_FORMATTING);
    }
}

[Misc] Add missing newline (new checkstyle rule)


/*
 * Copyright 2012-present Facebook, 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.facebook.buck.cli;

import com.facebook.buck.step.Verbosity;

import java.util.logging.Level;
import java.util.logging.Logger;

public class Logging {

  private Logging() {}

  public static void setLoggingLevelForVerbosity(Verbosity verbosity) {
    Level loggerLevel = verbosity == Verbosity.ALL
        ? Level.ALL
        : (verbosity.shouldPrintCommand()) ? Level.INFO : Level.OFF;
    // TODO(mbolin): Figure out why "com.facebook.buck" cannot be used instead of "".
    Logger.getLogger("").setLevel(loggerLevel);
  }

}

/*
 * Copyright 2012-present Facebook, 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.facebook.buck.cli;

import com.facebook.buck.step.Verbosity;

import java.util.logging.Level;
import java.util.logging.Logger;

public class Logging {

  private Logging() {}

  public static void setLoggingLevelForVerbosity(Verbosity verbosity) {
    Level loggerLevel = verbosity == Verbosity.ALL
        ? Level.ALL
        : (verbosity.shouldPrintOutput()) ? Level.INFO : Level.OFF;
    // TODO(mbolin): Figure out why "com.facebook.buck" cannot be used instead of "".
    Logger.getLogger("").setLevel(loggerLevel);
  }

}

Fix `buck build --verbose 2` so it prints only commands again.

Test Plan: Ran `buck build fb4a` and saw only Bash commands.


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

package io.spine.system.server;

import com.google.protobuf.Message;
import io.spine.annotation.Internal;

/**
 * A gateway for sending messages into a system bounded context.
 *
 * @author Dmytro Dashenkov
 */
@Internal
public interface SystemGateway {

    /**
     * Posts a system command.
     *
     * <p>In a multitenant environment, the command is posted for the current tenant.
     *
     * @param systemCommand command message
     */
    void postCommand(Message systemCommand);
}

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

package io.spine.system.server;

import com.google.protobuf.Message;
import io.spine.annotation.Internal;

/**
 * A gateway for sending messages into a system bounded context.
 *
 * @author Dmytro Dashenkov
 */
@Internal
public interface SystemGateway {

    /**
     * Posts a system command.
     *
     * <p>In a multitenant environment, the command is posted for
     * the {@linkplain io.spine.server.tenant.TenantAwareOperation current tenant}.
     *
     * @param systemCommand command message
     */
    void postCommand(Message systemCommand);
}

Add a link in doc.

Add a link in doc.


package nl.surfnet.mockoleth.controllers;

import java.io.UnsupportedEncodingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import nl.surfnet.mockoleth.model.Attribute;
import nl.surfnet.mockoleth.model.Configuration;

@Controller
public class RestApiController {

    private final static Logger LOGGER = LoggerFactory
            .getLogger(RestApiController.class);

    @Autowired
    Configuration configuration;

    @RequestMapping("/test")
    public String test() throws UnsupportedEncodingException {
        return "test-view";
    }

    @RequestMapping(value = {"/set-attribute"}, method = RequestMethod.POST)
    @ResponseBody
    public String setAttribute(@RequestBody Attribute attribute) throws UnsupportedEncodingException {
        LOGGER.info("Request to set attribute {} to {}", attribute.getValue(), attribute.getName());
        configuration.getAttributes().put(attribute.getValue(), attribute.getName());
        return "success";
    }

    @RequestMapping(value = {"/reset"}, method = RequestMethod.POST)
    @ResponseBody
    public String reset() throws UnsupportedEncodingException {
        LOGGER.info("Resetting to default configuration");
        return "success";
    }
}

package nl.surfnet.mockoleth.controllers;

import java.io.UnsupportedEncodingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import nl.surfnet.mockoleth.model.Attribute;
import nl.surfnet.mockoleth.model.Configuration;

@Controller
public class RestApiController {

    private final static Logger LOGGER = LoggerFactory
            .getLogger(RestApiController.class);

    @Autowired
    Configuration configuration;

    @RequestMapping("/test")
    public String test() throws UnsupportedEncodingException {
        return "test-view";
    }

    @RequestMapping(value = {"/set-attribute"}, method = RequestMethod.POST)
    @ResponseBody
    public String setAttribute(@RequestBody Attribute attribute) throws UnsupportedEncodingException {
        LOGGER.info("Request to set attribute {} to {}", attribute.getValue(), attribute.getName());
        configuration.getAttributes().put(attribute.getName(), attribute.getValue());
        return "success";
    }

    @RequestMapping(value = {"/reset"}, method = RequestMethod.POST)
    @ResponseBody
    public String reset() throws UnsupportedEncodingException {
        LOGGER.info("Resetting to default configuration");
        return "success";
    }
}

Fix bug in setting attributes

Fix bug in setting attributes


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

import java.awt.Color;
import java.util.ResourceBundle;

import javax.swing.UIManager;

public class ComponentDefaults {
    private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(UIDefaultsBundle.class.getName());

    public static Color getColor(String key) {
        Color color = UIManager.getColor(key);
        if (color == null) {
            color = (Color) BUNDLE.getObject(key);
        }
        return color;
    }
}

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

import java.awt.Color;
import java.util.ResourceBundle;

import javax.swing.UIManager;

public class ComponentDefaults {
    public static Color getColor(String key) {
        Color color = UIManager.getColor(key);
        if (color == null) {
            color = (Color) bundle().getObject(key);
        }
        return color;
    }

    private static ResourceBundle bundle() {
        return ResourceBundle.getBundle(UIDefaultsBundle.class.getName());
    }
}

Use ResourceBundle caching instead of static field


/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
package org.libreoffice.impressremote.activity;

import android.os.Bundle;

import com.actionbarsherlock.app.SherlockPreferenceActivity;
import com.actionbarsherlock.view.MenuItem;
import org.libreoffice.impressremote.R;

public class SettingsActivity extends SherlockPreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setUpHomeButton();
        setUpPreferences();
    }

    private void setUpHomeButton() {
        getSupportActionBar().setHomeButtonEnabled(true);
    }

    private void setUpPreferences() {
        // This action is deprecated
        // but we still need to target pre-Honeycomb devices

        addPreferencesFromResource(R.xml.preferences);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem aMenuItem) {
        switch (aMenuItem.getItemId()) {
            case android.R.id.home:
                navigateUp();
                return true;

            default:
                return super.onOptionsItemSelected(aMenuItem);
        }
    }

    private void navigateUp() {
        finish();
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */

/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
package org.libreoffice.impressremote.activity;

import android.os.Bundle;

import com.actionbarsherlock.app.SherlockPreferenceActivity;
import com.actionbarsherlock.view.MenuItem;
import org.libreoffice.impressremote.R;

public class SettingsActivity extends SherlockPreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setUpHomeButton();
        setUpPreferences();
    }

    private void setUpHomeButton() {
        getSupportActionBar().setHomeButtonEnabled(true);
    }

    @SuppressWarnings("deprecation")
    private void setUpPreferences() {
        // This action is deprecated
        // but we still need to target pre-Honeycomb devices.

        addPreferencesFromResource(R.xml.preferences);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem aMenuItem) {
        switch (aMenuItem.getItemId()) {
            case android.R.id.home:
                navigateUp();
                return true;

            default:
                return super.onOptionsItemSelected(aMenuItem);
        }
    }

    private void navigateUp() {
        finish();
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */

Add suppressing warnings for preferences activity.

Change-Id: I7808e8bbc080b65017dc273e423db51c9151d9f7


package com.nitorcreations.willow.servers;

import java.util.concurrent.TimeUnit;

import javax.inject.Singleton;

import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;

import com.nitorcreations.willow.ssh.RawSecureShellWS;

@Singleton
public class RawTerminalServlet extends WebSocketServlet {
  private static final long serialVersionUID = -7940037116569261919L;

  @Override
  public void configure(WebSocketServletFactory factory) {
    factory.getPolicy().setIdleTimeout(TimeUnit.MINUTES.toMillis(5));
    factory.getPolicy().setMaxBinaryMessageBufferSize(1024 * 1024);
    factory.getPolicy().setMaxBinaryMessageSize(1024 * 1024 * 5);
    factory.register(RawSecureShellWS.class);
  }
}

package com.nitorcreations.willow.servers;

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

import javax.inject.Singleton;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;

import com.nitorcreations.willow.ssh.RawSecureShellWS;

@Singleton
public class RawTerminalServlet extends WebSocketServlet {
  private static final long serialVersionUID = -7940037116569261919L;

  @Override
  protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (!SecurityUtils.getSubject().isPermitted("admin")) {
      resp.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
    super.service(req, resp);
  };
  @Override
  public void configure(WebSocketServletFactory factory) {
    factory.getPolicy().setIdleTimeout(TimeUnit.MINUTES.toMillis(5));
    factory.getPolicy().setMaxBinaryMessageBufferSize(1024 * 1024);
    factory.getPolicy().setMaxBinaryMessageSize(1024 * 1024 * 5);
    factory.register(RawSecureShellWS.class);
  }
}

Add permission check to terminal

Add permission check to terminal


// Copyright 2019 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.plugin.classanalysis;

import org.junit.Test;

import java.util.Set;

import static java.util.Collections.emptyMap;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

/**
 * @author gjoranv
 */
public class PackageTallyTest {

    @Test
    public void referenced_packages_missing_from_are_detected() {
        PackageTally tally = new PackageTally(emptyMap(), Set.of("p1", "java.util", "com.yahoo.api.annotations", "missing"));
        Set<String> missingPackages = tally.referencedPackagesMissingFrom(Set.of("p1"));
        assertThat(missingPackages, is(Set.of("missing")));
    }

}

Add copyright notice to new file

Add copyright notice to new file


package joshie.harvest.api.core;

import net.minecraft.item.ItemStack;

/** Items that implement this interface are associated with a certain
 *  ToolTier, this can affect various things **/
public interface ITiered {
    /** Returns the rating of this item. Values returned should
     *  between 1-100%
     *
     *  @param  stack   the item
     *  @return         the percentage complete **/
    double getLevel(ItemStack stack);

    /** Increases the tools level
     * @param stack the item **/
    void levelTool(ItemStack stack);

    /** Returns the tier of this item
     *
     *  @param  stack   the item
     *  @return         the tier **/
    ToolTier getTier(ItemStack stack);

    enum ToolTier {
        BASIC(0), COPPER(1), SILVER(2), GOLD(2), MYSTRIL(4), CURSED(5), BLESSED(5), MYTHIC(6);

        private final int level;

        ToolTier(int level) {
            this.level = level;
        }

        public int getToolLevel() {
            return level;
        }

        public boolean isGreaterThanOrEqualTo(ToolTier tier) {
            return this.ordinal() >= tier.ordinal() || ((tier == CURSED || tier == BLESSED) && (this == CURSED || this == BLESSED));
        }
    }
}

package joshie.harvest.api.core;

import net.minecraft.item.ItemStack;

/** Items that implement this interface are associated with a certain
 *  ToolTier, this can affect various things **/
public interface ITiered {
    /** Returns the rating of this item. Values returned should
     *  between 1-100%
     *
     *  @param  stack   the item
     *  @return         the percentage complete **/
    double getLevel(ItemStack stack);

    /** Increases the tools level
     * @param stack the item **/
    void levelTool(ItemStack stack);

    /** Returns the tier of this item
     *
     *  @param  stack   the item
     *  @return         the tier **/
    ToolTier getTier(ItemStack stack);

    enum ToolTier {
        BASIC(0), COPPER(1), SILVER(2), GOLD(3), MYSTRIL(4), CURSED(5), BLESSED(5), MYTHIC(6);

        private final int level;

        ToolTier(int level) {
            this.level = level;
        }

        public int getToolLevel() {
            return level;
        }

        public boolean isGreaterThanOrEqualTo(ToolTier tier) {
            return this.ordinal() >= tier.ordinal() || ((tier == CURSED || tier == BLESSED) && (this == CURSED || this == BLESSED));
        }
    }
}

Fix gold hoe charge level.

Fix gold hoe charge level.


package uk.ac.ebi.atlas.solr.query;

import org.apache.solr.client.solrj.SolrQuery;
import uk.ac.ebi.atlas.search.SemanticQueryTerm;
import uk.ac.ebi.atlas.species.Species;

import javax.inject.Inject;
import javax.inject.Named;
import java.util.List;
import java.util.stream.Collectors;

@Named
public class SolrBioentitiesSuggesterService {

    private final BioentitiesSolrClient solrClient;

    @Inject
    public SolrBioentitiesSuggesterService(BioentitiesSolrClient solrClient) {
        this.solrClient = solrClient;
    }

    public List<SemanticQueryTerm> fetchSuggestions(String query, Species species, int numberOfSuggestions) {
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.setRequestHandler("/suggest")
                 .setParam("suggest.dictionary", "propertySuggester")
                 .setParam("suggest.q", query)
                 .setParam("suggest.cfq", species.getEnsemblName().toLowerCase());

        return solrClient.query(solrQuery).getSuggesterResponse().getSuggestions().values().stream()
                .flatMap(List::stream)
                .distinct()
                .map(suggestion -> SemanticQueryTerm.create(suggestion.getTerm(), suggestion.getPayload()))
                .collect(Collectors.toList())
                .subList(0, numberOfSuggestions);
    }

}

package uk.ac.ebi.atlas.solr.query;

import org.apache.solr.client.solrj.SolrQuery;
import uk.ac.ebi.atlas.search.SemanticQueryTerm;
import uk.ac.ebi.atlas.species.Species;

import javax.inject.Inject;
import javax.inject.Named;
import java.util.List;
import java.util.stream.Collectors;

@Named
public class SolrBioentitiesSuggesterService {

    private final BioentitiesSolrClient solrClient;

    @Inject
    public SolrBioentitiesSuggesterService(BioentitiesSolrClient solrClient) {
        this.solrClient = solrClient;
    }

    public List<SemanticQueryTerm> fetchSuggestions(String query, Species species, int numberOfSuggestions) {
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.setRequestHandler("/suggest")
                 .setParam("suggest.dictionary", "propertySuggester")
                 .setParam("suggest.q", query)
                 .setParam("suggest.cfq", species.getEnsemblName().toLowerCase());

        return solrClient.query(solrQuery).getSuggesterResponse().getSuggestions().values().stream()
                .flatMap(List::stream)
                .distinct()
                .limit(numberOfSuggestions)
                .map(suggestion -> SemanticQueryTerm.create(suggestion.getTerm(), suggestion.getPayload()))
                .collect(Collectors.toList());
    }

}

Use Stream::limit instead of List::subList


package seedu.todo.commons.core;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import seedu.todo.commons.core.Config;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class ConfigTest {
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void toString_defaultObject_stringReturned() {
        String defaultConfigAsString = "App title : GetShitDone\n" +
                "Current log level : INFO\n" +
                "Local data file location : database.json";

        assertEquals(defaultConfigAsString, new Config().toString());
    }

    @Test
    public void equalsMethod(){
        Config defaultConfig = new Config();
        assertFalse(defaultConfig.equals(null));
        assertTrue(defaultConfig.equals(defaultConfig));
    }

}

package seedu.todo.commons.core;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import seedu.todo.commons.core.Config;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class ConfigTest {
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void toString_defaultObject_stringReturned() {
        String defaultConfigAsString = "App title : GetShitDone\n" +
                "Current log level : INFO\n" +
                "Local data file location : database.json";

        assertEquals(defaultConfigAsString, new Config().toString());
    }

    @Test
    public void equalsMethod(){
        Config defaultConfig = new Config();
        assertFalse(defaultConfig == null);
        assertTrue(defaultConfig.equals(defaultConfig));
    }

}

Use == instead of .equals

Use == instead of .equals


package tr.xip.wanikani.managers;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.preference.PreferenceManager;

/**
 * Created by xihsa_000 on 3/11/14.
 */
public class PrefManager {
    private static SharedPreferences prefs;
    private static SharedPreferences.Editor prefeditor;
    private static Context context;

    public PrefManager(Context mContext) {
        context = mContext;
        prefs = context.getSharedPreferences("prefs", 0);
        prefeditor = prefs.edit();
    }

    public String getApiKey() {
        return prefs.getString("api_key", "0");
    }

    public boolean isFirstLaunch() {
        return prefs.getBoolean("first_launch", true);
    }

    public void setFirstLaunch(boolean value) {
        prefeditor.putBoolean("first_launch", value).commit();
    }

    public void setApiKey(String key) {
        prefeditor.putString("api_key", key).commit();
    }

    public boolean isProfileFirstTime() {
        return prefs.getBoolean("first_time_profile", true);
    }

    public void setProfileFirstTime(boolean value) {
        prefeditor.putBoolean("first_time_profile", value).commit();
    }

    public void logout() {
        prefeditor.clear().commit();
    }

}

package tr.xip.wanikani.managers;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.preference.PreferenceManager;

/**
 * Created by xihsa_000 on 3/11/14.
 */
public class PrefManager {
    private static SharedPreferences prefs;
    private static SharedPreferences offlineData;
    private static SharedPreferences.Editor prefeditor;
    private static SharedPreferences.Editor offlineDataEditor;
    private static Context context;

    public PrefManager(Context mContext) {
        context = mContext;
        prefs = context.getSharedPreferences("prefs", 0);
        offlineData = context.getSharedPreferences("offline_data", 0);
        prefeditor = prefs.edit();
        offlineDataEditor = offlineData.edit();
    }

    public String getApiKey() {
        return prefs.getString("api_key", "0");
    }

    public boolean isFirstLaunch() {
        return prefs.getBoolean("first_launch", true);
    }

    public void setFirstLaunch(boolean value) {
        prefeditor.putBoolean("first_launch", value).commit();
    }

    public void setApiKey(String key) {
        prefeditor.putString("api_key", key).commit();
    }

    public boolean isProfileFirstTime() {
        return prefs.getBoolean("first_time_profile", true);
    }

    public void setProfileFirstTime(boolean value) {
        prefeditor.putBoolean("first_time_profile", value).commit();
    }

    public void logout() {
        prefeditor.clear().commit();
        offlineDataEditor.clear().commit();
    }

}

Clear offline data on logout

Clear offline data on logout


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

import io.prestosql.tests.tpch.TpchQueryRunnerBuilder;
import org.testng.annotations.Test;

import static io.prestosql.SystemSessionProperties.WORK_PROCESSOR_PIPELINES;

public class TestWorkProcessorPipelineQueries
        extends AbstractTestQueryFramework
{
    protected TestWorkProcessorPipelineQueries()
    {
        super(() -> TpchQueryRunnerBuilder
                .builder()
                .amendSession(builder -> builder.setSystemProperty(WORK_PROCESSOR_PIPELINES, "true"))
                .build());
    }

    @Test
    public void testTopN()
    {
        assertQuery("select * from orders order by totalprice limit 10");
    }
}

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

import io.prestosql.tests.tpch.TpchQueryRunnerBuilder;
import org.testng.annotations.Test;

import static io.prestosql.SystemSessionProperties.WORK_PROCESSOR_PIPELINES;

public class TestWorkProcessorPipelineQueries
        extends AbstractTestQueryFramework
{
    protected TestWorkProcessorPipelineQueries()
    {
        super(() -> TpchQueryRunnerBuilder
                .builder()
                .amendSession(builder -> builder.setSystemProperty(WORK_PROCESSOR_PIPELINES, "true"))
                .build());
    }

    @Test
    public void testTopN()
    {
        assertQuery("SELECT * FROM orders ORDER BY totalprice LIMIT 10");
    }
}

Use Upper case for SQL keywords

Use Upper case for SQL keywords


package sk.henrichg.phoneprofilesplus;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class ActivatorTargetHelpsActivity extends AppCompatActivity {

    public static ActivatorTargetHelpsActivity activity;
    //public static ActivateProfileActivity activatorActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        overridePendingTransition(0, 0);

        activity = this;
    }

    @Override
    protected void onResume()
    {
        super.onResume();

        if (ActivateProfileActivity.getInstance() == null) {
            finish();
            return;
        }

        ActivateProfileActivity.getInstance().showTargetHelps();
    }

    @Override
    public void finish()
    {
        super.finish();
        overridePendingTransition(0, 0);
    }

}

package sk.henrichg.phoneprofilesplus;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class ActivatorTargetHelpsActivity extends AppCompatActivity {

    public static ActivatorTargetHelpsActivity activity;
    //public static ActivateProfileActivity activatorActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        overridePendingTransition(0, 0);

        activity = this;
    }

    @Override
    protected void onResume()
    {
        super.onResume();

        if (ActivateProfileActivity.getInstance() == null) {
            finish();
            return;
        }

        GlobalGUIRoutines.setTheme(this, true, false, false);
        GlobalGUIRoutines.setLanguage(getBaseContext());

        ActivateProfileActivity.getInstance().showTargetHelps();
    }

    @Override
    public void finish()
    {
        super.finish();
        overridePendingTransition(0, 0);
    }

}

Set theme for activator target help.

Set theme for activator target help.


package mb.nabl2.spoofax.analysis;

import java.util.List;
import java.util.Optional;

import mb.nabl2.constraints.IConstraint;
import mb.nabl2.solver.ISolution;
import mb.nabl2.terms.ITerm;

public interface IResult {

    boolean partial();

    List<IConstraint> constraints();

    ISolution solution();

    Optional<ITerm> customAnalysis();

    IResult withCustomAnalysis(ITerm term);

}

package mb.nabl2.spoofax.analysis;

import java.util.List;
import java.util.Optional;

import mb.nabl2.constraints.IConstraint;
import mb.nabl2.solver.ISolution;
import mb.nabl2.terms.ITerm;

public interface IResult {

    boolean partial();

    List<IConstraint> constraints();

    ISolution solution();

    IResult withSolution(ISolution solution);

    Optional<ITerm> customAnalysis();

    IResult withCustomAnalysis(ITerm term);

}

Add interface method to update solution.


package com.johnuckele.vivarium.visualization.animation;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.ImageObserver;

import javax.swing.ImageIcon;

import com.johnuckele.vivarium.core.Direction;
import com.johnuckele.vivarium.visualization.GraphicalSystem;

public class SwingGraphics extends GraphicalSystem
{
    private static ImageIcon IMAGE_ICON = new ImageIcon("src/main/resources/sprites.png");
    private static Image IMAGE = IMAGE_ICON.getImage();

    private Graphics2D _graphics;
    private ImageObserver _observer;

    public SwingGraphics()
    {

    }

    public void setResources(Graphics2D graphics, ImageObserver observer)
    {
        _graphics = graphics;
        _observer = observer;
    }

    @Override
    public void drawImage(int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Direction heading)
    {
        _graphics.rotate(-Direction.getRadiansFromNorth(heading), (dx1 + dx2) / 2, (dy1 + dy2) / 2);
        _graphics.drawImage(IMAGE, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, _observer);
        _graphics.rotate(Direction.getRadiansFromNorth(heading), (dx1 + dx2) / 2, (dy1 + dy2) / 2);

    }

}

package com.johnuckele.vivarium.visualization.animation;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.ImageObserver;

import javax.swing.ImageIcon;

import com.johnuckele.vivarium.core.Direction;

public class SwingGraphics extends GraphicalSystem
{
    private static ImageIcon IMAGE_ICON = new ImageIcon("src/main/resources/sprites.png");
    private static Image IMAGE = IMAGE_ICON.getImage();

    private Graphics2D _graphics;
    private ImageObserver _observer;

    public SwingGraphics()
    {

    }

    public void setResources(Graphics2D graphics, ImageObserver observer)
    {
        _graphics = graphics;
        _observer = observer;
    }

    @Override
    public void drawImage(int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Direction heading)
    {
        _graphics.rotate(-Direction.getRadiansFromNorth(heading), (dx1 + dx2) / 2.0, (dy1 + dy2) / 2.0);
        _graphics.drawImage(IMAGE, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, _observer);
        _graphics.rotate(Direction.getRadiansFromNorth(heading), (dx1 + dx2) / 2.0, (dy1 + dy2) / 2.0);

    }

}

Fix to division by int warning

Fix to division by int warning


/*
 * Copyright (c) 2015 IRCCloud, Ltd.
 *
 * 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.irccloud.android;

import java.util.ArrayList;

public class Ignore {
    private ArrayList<String> ignores = new ArrayList<String>();

    public synchronized void setIgnores(ArrayList<String> ignores) {
        this.ignores = new ArrayList<String>(ignores);
    }

    public synchronized void addMask(String usermask) {
        ignores.add(usermask);
    }

    public synchronized boolean match(String usermask) {
        if (ignores != null && ignores.size() > 0) {
            for (String ignore : ignores) {
                if (usermask.replace("!~", "!").toLowerCase().matches(ignore))
                    return true;
            }
        }
        return false;
    }
}

/*
 * Copyright (c) 2015 IRCCloud, Ltd.
 *
 * 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.irccloud.android;

import java.util.ArrayList;

public class Ignore {
    private ArrayList<String> ignores = new ArrayList<String>();

    public synchronized void setIgnores(ArrayList<String> ignores) {
        if(ignores != null)
            this.ignores = new ArrayList<>(ignores);
        else
            this.ignores = new ArrayList<>();
    }

    public synchronized void addMask(String usermask) {
        ignores.add(usermask);
    }

    public synchronized boolean match(String usermask) {
        if (ignores != null && ignores.size() > 0) {
            for (String ignore : ignores) {
                if (usermask.replace("!~", "!").toLowerCase().matches(ignore))
                    return true;
            }
        }
        return false;
    }
}

Fix empty messages listview on resume

Fix empty messages listview on resume


package org.apache.lucene;

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

import org.apache.lucene.util.LuceneTestCase;

public class TestAssertions extends LuceneTestCase {

  public void test() {
    try {
      assert Boolean.FALSE.booleanValue();
      fail("assertions are not enabled!");
    } catch (AssertionError e) {
    }
  }

}

package org.apache.lucene;

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

import org.apache.lucene.util.LuceneTestCase;

public class TestAssertions extends LuceneTestCase {

  public void test() {
    try {
      assert Boolean.FALSE.booleanValue();
      fail("assertions are not enabled!");
    } catch (AssertionError e) {
      assert Boolean.TRUE.booleanValue();
    }
  }

}

Add also the opposite assert statement

LUCENE-1769: Add also the opposite assert statement

git-svn-id: 4c5078813df38efa56971a28e09a55254294f104@891907 13f79535-47bb-0310-9956-ffa450edef68


/**
 * Copyright (c) 2016, German Neuroinformatics Node (G-Node)
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted under the terms of the BSD License. See
 * LICENSE file in the root of the Project.
 */

package org.g_node.srv;

/**
 * Unit tests for the {@link ModelUtils} class. Output and Error streams are redirected
 * from the console to a different PrintStream and reset after tests are finished
 * to avoid mixing tool error messages with actual test error messages.
 *
 * @author Michael Sonntag (sonntag@bio.lmu.de)
 */
public class ModelUtilsTest {

}

/**
 * Copyright (c) 2016, German Neuroinformatics Node (G-Node)
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted under the terms of the BSD License. See
 * LICENSE file in the root of the Project.
 */

package org.g_node.srv;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import java.net.URL;
import java.nio.file.Paths;
import static org.assertj.core.api.Assertions.assertThat;
import org.g_node.micro.commons.RDFService;
import org.junit.Before;
import org.junit.Test;

/**
 * Unit tests for the {@link ModelUtils} class.
 *
 * @author Michael Sonntag (sonntag@bio.lmu.de)
 */
public class ModelUtilsTest {

    private Model baseModel;

    @Before
    public void setUp() {
        this.baseModel = ModelFactory.createDefaultModel();
    }

    @Test
    public void testRemoveAnonProperties() throws Exception {

        final URL testFileNameURL = this.getClass().getResource("/testFiles/RemoveAnonNodeTest.ttl");
        final String testFileName = Paths.get(testFileNameURL.toURI()).toFile().toString();

        this.baseModel = RDFService.openModelFromFile(testFileName);

        assertThat(this.baseModel.size()).isEqualTo(7);

        this.baseModel.listObjects().forEachRemaining(
                obj -> {
                    if (obj.isURIResource() && obj.asResource().listProperties().hasNext()) {
                       ModelUtils.removeAnonProperties(obj.asResource().listProperties());
                    }
                });

        assertThat(this.baseModel.size()).isEqualTo(5);
    }

    @Test
    public void testRemovePropertiesFromModel() throws Exception {
        System.out.println(
                String.join("", "[TEST DEBUG] Remove properties; Model size: ",
                        Long.toString(this.baseModel.size()))
        );
    }

}

Tests: Add remove anonymous node properties test


package org.jrebirth.af.core.command.basic.multi;

import org.jrebirth.af.core.command.basic.BasicCommandTest;

import org.junit.Test;

//@Ignore("JavaFX can't be run in headless mode yet")
public class MultiCommandTest extends BasicCommandTest {

    @Test
    public void sequentialTest1() {
        System.out.println("Sequential Test default");
        runCommand(DefaultSequentialCommand.class);
    }

    @Test
    public void sequentialTest2() {
        System.out.println("Sequential Test annotation");
        runCommand(AnnotatedSequentialCommand.class);
    }

    @Test
    public void sequentialTest3() {
        System.out.println("Sequential Test constructor");
        runCommand(ConstructorSequentialCommand.class);
    }

    @Test
    public void parallelTest1() {
        System.out.println("Parallel Test default");
        runCommand(DefaultParallelCommand.class);
    }

    @Test
    public void parallelTest2() {
        System.out.println("Parallel Test annotation");
        runCommand(AnnotatedParallelCommand.class);
    }

    @Test
    public void parallelTest3() {
        System.out.println("Parallel Test constructor");
        runCommand(ConstructorParallelCommand.class);
    }
}

package org.jrebirth.af.core.command.basic.multi;

import org.jrebirth.af.core.command.basic.BasicCommandTest;

import org.junit.Ignore;
import org.junit.Test;

@Ignore("JavaFX can't be run in headless mode yet")
public class MultiCommandTest extends BasicCommandTest {

    @Test
    public void sequentialTest1() {
        System.out.println("Sequential Test default");
        runCommand(DefaultSequentialCommand.class);
    }

    @Test
    public void sequentialTest2() {
        System.out.println("Sequential Test annotation");
        runCommand(AnnotatedSequentialCommand.class);
    }

    @Test
    public void sequentialTest3() {
        System.out.println("Sequential Test constructor");
        runCommand(ConstructorSequentialCommand.class);
    }

    @Test
    public void parallelTest1() {
        System.out.println("Parallel Test default");
        runCommand(DefaultParallelCommand.class);
    }

    @Test
    public void parallelTest2() {
        System.out.println("Parallel Test annotation");
        runCommand(AnnotatedParallelCommand.class);
    }

    @Test
    public void parallelTest3() {
        System.out.println("Parallel Test constructor");
        runCommand(ConstructorParallelCommand.class);
    }
}

Disable test untestable without x server


package se.vidstige.jadb;

/**
 * Created by vidstige on 2014-03-20
 */
public class RemoteFile {
    private final String path;

    public RemoteFile(String path) { this.path = path; }

    public String getName() { throw new UnsupportedOperationException(); }
    public int getSize() { throw new UnsupportedOperationException(); }
    public long getLastModified() { throw new UnsupportedOperationException(); }
    public boolean isDirectory() { throw new UnsupportedOperationException(); }

    public String getPath() { return path;}

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

        RemoteFile that = (RemoteFile) o;

        if (!path.equals(that.path)) return false;

        return true;
    }

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

package se.vidstige.jadb;

/**
 * Created by vidstige on 2014-03-20
 */
public class RemoteFile {
    private final String path;

    public RemoteFile(String path) { this.path = path; }

    public String getName() { throw new UnsupportedOperationException(); }
    public int getSize() { throw new UnsupportedOperationException(); }
    public long getLastModified() { throw new UnsupportedOperationException(); }
    public boolean isDirectory() { throw new UnsupportedOperationException(); }

    public String getPath() { return path;}

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

        RemoteFile that = (RemoteFile) o;
        return path.equals(that.path);
    }

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

Fix: Return of boolean expressions should not be wrapped into an "if-then-else" statement (squid:S1126)


package org.gitcontrib.client.perspectives;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;

import org.uberfire.client.annotations.Perspective;
import org.uberfire.client.annotations.WorkbenchPerspective;
import org.uberfire.mvp.impl.DefaultPlaceRequest;
import org.uberfire.workbench.model.PanelType;
import org.uberfire.workbench.model.PerspectiveDefinition;
import org.uberfire.workbench.model.impl.PartDefinitionImpl;
import org.uberfire.workbench.model.impl.PerspectiveDefinitionImpl;

/**
 * A Perspective to show File Explorer
 */
@ApplicationScoped
@WorkbenchPerspective(identifier = "MainPerspective", isDefault = true)
public class MainPerspective {

    private PerspectiveDefinition perspective;

    @PostConstruct
    public void init() {
        buildPerspective();
    }

    @Perspective
    public PerspectiveDefinition getPerspective() {
        return this.perspective;
    }

    public PerspectiveDefinition buildPerspective() {
        perspective = new PerspectiveDefinitionImpl( PanelType.ROOT_STATIC);
        perspective.setTransient(true);
        perspective.setName("MainPerspective");
        perspective.getRoot().addPart(new PartDefinitionImpl(new DefaultPlaceRequest("KIEDashboardScreen")));
        return perspective;
    }
}

package org.gitcontrib.client.perspectives;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;

import org.uberfire.client.annotations.Perspective;
import org.uberfire.client.annotations.WorkbenchPerspective;
import org.uberfire.mvp.impl.DefaultPlaceRequest;
import org.uberfire.workbench.model.PanelType;
import org.uberfire.workbench.model.PerspectiveDefinition;
import org.uberfire.workbench.model.impl.PartDefinitionImpl;
import org.uberfire.workbench.model.impl.PerspectiveDefinitionImpl;

/**
 * A Perspective to show File Explorer
 */
@ApplicationScoped
@WorkbenchPerspective(identifier = "MainPerspective", isDefault = true)
public class MainPerspective {

    @Perspective
    public PerspectiveDefinition buildPerspective() {
        PerspectiveDefinition perspective = new PerspectiveDefinitionImpl( PanelType.ROOT_STATIC);
        perspective.setTransient(true);
        perspective.setName("MainPerspective");
        perspective.getRoot().addPart(new PartDefinitionImpl(new DefaultPlaceRequest("KIEDashboardScreen")));
        return perspective;
    }
}

Fix perspective initialization issue when clicking on top menu navbar


package org.redline_rpm.header;

public enum Architecture {

	NOARCH,
	I386,
	ALPHA,
	SPARC,
	MIPS,
	PPC,
	M68K,
	IP,
	RS6000,
	IA64,
	SPARC64,
	MIPSEL,
	ARM,
	MK68KMINT,
	S390,
	S390X,
	PPC64,
	SH,
	XTENSA,
	X86_64
}

package org.redline_rpm.header;

public enum Architecture {

	NOARCH,
	I386,
	ALPHA,
	SPARC,
	MIPS,
	PPC,
	M68K,
	IP,
	RS6000,
	IA64,
	SPARC64,
	MIPSEL,
	ARM,
	MK68KMINT,
	S390,
	S390X,
	PPC64,
	PPC64LE,
	SH,
	XTENSA,
	X86_64
}

Add PPC64LE as an architecture to support OpenPower Platforms

- When trying to package rpms of Architecture type ppc64le (OpenPower) a
failure occurs stating it is not a supported architecture
- Added PPC64LE as an architecure type so downstream dependencies of
redline will be able to build rpm's for distro's running ppc64le --
specifically https://github.com/nebula-plugins/gradle-ospackage-plugin
needs this update to enable packaging with Gradle for OpenPower


package com.sandjelkovic.dispatch.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;

@SpringBootApplication
@EnableConfigServer
public class DispatchdConfigurationApplication {

	public static void main(String[] args) {
		SpringApplication.run(DispatchdConfigurationApplication.class, args);
	}
}

package com.sandjelkovic.dispatch.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
//@EnableConfigServer
public class DispatchdConfigurationApplication {

	public static void main(String[] args) {
		SpringApplication.run(DispatchdConfigurationApplication.class, args);
	}
}

Fix failing test by temporarily removing Config server activation


package com.phicdy.totoanticipation.model.storage;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.phicdy.totoanticipation.model.Game;
import com.phicdy.totoanticipation.model.Toto;

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

public class SettingStorageImpl implements SettingStorage {

    private SharedPreferences preferences;
    private static final String KEY_PREF = "keyPrefSetting";
    private static final String KEY_NOTIFY_DEADLINE = "keyNotifyDeadline";
    public SettingStorageImpl(@NonNull Context context) {
        preferences = context.getSharedPreferences(KEY_PREF, Context.MODE_PRIVATE);
    }

    @Override
    public boolean isDeadlineNotify() {
        return preferences.getBoolean(KEY_NOTIFY_DEADLINE, false);
    }

    @Override
    public void setDeadlineNotify(boolean isEnabled) {
        preferences.edit().putBoolean(KEY_NOTIFY_DEADLINE, isEnabled).apply();
    }
}

package com.phicdy.totoanticipation.model.storage;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.phicdy.totoanticipation.model.Game;
import com.phicdy.totoanticipation.model.Toto;

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

public class SettingStorageImpl implements SettingStorage {

    private SharedPreferences preferences;
    private static final String KEY_PREF = "keyPrefSetting";
    private static final String KEY_NOTIFY_DEADLINE = "keyNotifyDeadline";
    public SettingStorageImpl(@NonNull Context context) {
        preferences = context.getSharedPreferences(KEY_PREF, Context.MODE_PRIVATE);
    }

    @Override
    public boolean isDeadlineNotify() {
        return preferences.getBoolean(KEY_NOTIFY_DEADLINE, true);
    }

    @Override
    public void setDeadlineNotify(boolean isEnabled) {
        preferences.edit().putBoolean(KEY_NOTIFY_DEADLINE, isEnabled).apply();
    }
}

Change default deadline notify setting to true


package com.reidzeibel.animatedlistadapter.utils;

import android.content.Context;
import android.view.animation.AnimationUtils;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;

/**
 * Created by RidwanAditama on 16/01/2017.
 */

public class AnimUtils {

    private AnimUtils() { }

    private static Interpolator fastOutSlowIn;
    private static Interpolator fastOutLinearIn;
    private static Interpolator linearOutSlowIn;
    private static Interpolator linear;

    public static Interpolator getFastOutSlowInInterpolator(Context context) {
        if (fastOutSlowIn == null) {
            fastOutSlowIn = AnimationUtils.loadInterpolator(context,
                    android.R.interpolator.fast_out_slow_in);
        }
        return fastOutSlowIn;
    }

    public static Interpolator getFastOutLinearInInterpolator(Context context) {
        if (fastOutLinearIn == null) {
            fastOutLinearIn = AnimationUtils.loadInterpolator(context,
                    android.R.interpolator.fast_out_linear_in);
        }
        return fastOutLinearIn;
    }

    public static Interpolator getLinearOutSlowInInterpolator(Context context) {
        if (linearOutSlowIn == null) {
            linearOutSlowIn = AnimationUtils.loadInterpolator(context,
                    android.R.interpolator.linear_out_slow_in);
        }
        return linearOutSlowIn;
    }

    public static Interpolator getLinearInterpolator() {
        if (linear == null) {
            linear = new LinearInterpolator();
        }
        return linear;
    }
}

package com.reidzeibel.animatedlistadapter.utils;

import android.content.Context;
import android.support.v4.view.animation.FastOutLinearInInterpolator;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;

/**
 * Created by RidwanAditama on 16/01/2017.
 */

public class AnimUtils {

    private AnimUtils() { }

    private static Interpolator fastOutSlowIn;
    private static Interpolator fastOutLinearIn;
    private static Interpolator linearOutSlowIn;
    private static Interpolator linear;

    public static Interpolator getFastOutSlowInInterpolator(Context context) {
        if (fastOutSlowIn == null) {
            fastOutSlowIn = new FastOutSlowInInterpolator();
        }
        return fastOutSlowIn;
    }

    public static Interpolator getFastOutLinearInInterpolator(Context context) {
        if (fastOutLinearIn == null) {
            fastOutLinearIn = new FastOutLinearInInterpolator();
        }
        return fastOutLinearIn;
    }

    public static Interpolator getLinearOutSlowInInterpolator(Context context) {
        if (linearOutSlowIn == null) {
            linearOutSlowIn = new LinearOutSlowInInterpolator();
        }
        return linearOutSlowIn;
    }

    public static Interpolator getLinearInterpolator() {
        if (linear == null) {
            linear = new LinearInterpolator();
        }
        return linear;
    }
}

Fix compatibility with API v19

Fix compatibility with API v19

- use Interpolator from v7 support library instead of using the APIv21 version