package org.wikipedia.concurrency;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

public class CallbackTask<T> extends SaneAsyncTask<T> {
    public interface Callback<T> {
        void success(T row);
    }

    public interface Task<T> {
        T execute();
    }

    @NonNull private final Task<T> task;
    @Nullable private final Callback<T> callback;

    public static <T> void execute(@NonNull Task<T> task) {
        execute(task, null);
    }

    public static <T> void execute(@NonNull Task<T> task, @Nullable Callback<T> callback) {
        new CallbackTask<>(task, callback).execute();
    }

    CallbackTask(@NonNull Task<T> task, @Nullable Callback<T> callback) {
        this.task = task;
        this.callback = callback;
    }

    @Override public T performTask() throws Throwable {
        return task.execute();
    }

    @Override public void onFinish(T result) {
        super.onFinish(result);
        if (callback != null) {
            callback.success(result);
        }
    }
}

package org.wikipedia.concurrency;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

public class CallbackTask<T> extends SaneAsyncTask<T> {
    public interface Callback<T> {
        void success(T row);
    }

    public interface Task<T> {
        T execute();
    }

    @NonNull private final Task<T> task;
    @Nullable private Callback<T> callback;

    public static <T> void execute(@NonNull Task<T> task) {
        execute(task, null);
    }

    public static <T> void execute(@NonNull Task<T> task, @Nullable Callback<T> callback) {
        new CallbackTask<>(task, callback).execute();
    }

    CallbackTask(@NonNull Task<T> task, @Nullable Callback<T> callback) {
        this.task = task;
        this.callback = callback;
    }

    @Override public T performTask() throws Throwable {
        return task.execute();
    }

    @Override public void onFinish(T result) {
        super.onFinish(result);
        if (callback != null) {
            callback.success(result);
            callback = null;
        }
    }
}

Fix possible memory leak in feed.


package edu.virginia.psyc.pi.persistence;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import edu.virginia.psyc.pi.domain.DoNotDelete;
import edu.virginia.psyc.pi.domain.Exportable;
import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;

/**
 * Created by dan on 3/24/16.
 * Data about a Participant that can be exported.
 */
@Data
@Entity
@Table(name="participant")
@Exportable
@DoNotDelete
public class ParticipantExportDAO {

    @JsonProperty("participantId")
    @Id private long id;
    private String theme;
    private String study;
    private String cbmCondition;
    private String prime;
    private boolean admin;
    private boolean emailOptout;
    private boolean active;
    private boolean increase30;
    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="EEE, dd MMM yyyy HH:mm:ss Z", timezone="EST")
    private Date   lastLogin;
    private String currentSession;
}

package edu.virginia.psyc.pi.persistence;

import com.fasterxml.jackson.annotation.JsonFormat;
import edu.virginia.psyc.pi.domain.DoNotDelete;
import edu.virginia.psyc.pi.domain.Exportable;
import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;

/**
 * Created by dan on 3/24/16.
 * Data about a Participant that can be exported.
 */
@Data
@Entity
@Table(name="participant")
@Exportable
@DoNotDelete
public class ParticipantExportDAO {

    @Id private long id;
    private String theme;
    private String study;
    private String cbmCondition;
    private String prime;
    private boolean admin;
    private boolean emailOptout;
    private boolean active;
    private boolean increase30;
    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="EEE, dd MMM yyyy HH:mm:ss Z", timezone="EST")
    private Date   lastLogin;
    private String currentSession;
}

Change ParticipantDAO back to id


package ee.tuleva.onboarding.auth.session;

import java.io.Serial;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;

@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class GenericSessionStore implements Serializable {

  @Serial private static final long serialVersionUID = -648103071415508424L;

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

  public <T extends Serializable> void save(T sessionAttribute) {
    sessionAttributes.put(sessionAttribute.getClass().getName(), sessionAttribute);
  }

  public <T extends Serializable> Optional<T> get(Class clazz) {
    @SuppressWarnings("unchecked")
    T sessionAttribute = (T) sessionAttributes.get(clazz.getName());

    if (sessionAttribute == null) {
      return Optional.empty();
    }

    return Optional.of(sessionAttribute);
  }
}

package ee.tuleva.onboarding.auth.session;

import java.io.Serial;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.SessionScope;

@Component
@SessionScope
public class GenericSessionStore implements Serializable {

  @Serial private static final long serialVersionUID = -648103071415508424L;

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

  public <T extends Serializable> void save(T sessionAttribute) {
    sessionAttributes.put(sessionAttribute.getClass().getName(), sessionAttribute);
  }

  public <T extends Serializable> Optional<T> get(Class clazz) {
    @SuppressWarnings("unchecked")
    T sessionAttribute = (T) sessionAttributes.get(clazz.getName());

    if (sessionAttribute == null) {
      return Optional.empty();
    }

    return Optional.of(sessionAttribute);
  }
}

Use composed annotation for readability


/**
 * Twilio Video for React Native.
 *
 * Authors:
 *   Ralph Pina <ralph.pina@gmail.com>
 *   Jonathan Chang <slycoder@gmail.com>
 */

package com.twiliorn.library;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

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

public class TwilioPackage implements ReactPackage {
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }

    @Override
    public List<Class<? extends JavaScriptModule>> createJSModules() {
        return Collections.emptyList();
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Arrays.<ViewManager>asList(
            new CustomTwilioVideoViewManager(),
            new TwilioRemotePreviewManager(),
            new TwilioVideoPreviewManager()
        );
    }
}

/**
 * Twilio Video for React Native.
 *
 * Authors:
 *   Ralph Pina <ralph.pina@gmail.com>
 *   Jonathan Chang <slycoder@gmail.com>
 */

package com.twiliorn.library;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

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

public class TwilioPackage implements ReactPackage {
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }

    // Deprecated by RN 0.47
    public List<Class<? extends JavaScriptModule>> createJSModules() {
        return Collections.emptyList();
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Arrays.<ViewManager>asList(
            new CustomTwilioVideoViewManager(),
            new TwilioRemotePreviewManager(),
            new TwilioVideoPreviewManager()
        );
    }
}

Fix android build for RN 0.47


package com.cwainner.chris.recipecentral;

import android.os.Build;
import android.widget.TextView;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;

import static org.junit.Assert.*;

@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP)
@RunWith(RobolectricGradleTestRunner.class)

public class AboutActivityTest {
    private AboutActivity activity;

    @Before
    public void setup() {
        activity = Robolectric.setupActivity(AboutActivity.class);
    }

    @Test
    public void validateAboutHeader(){
        TextView aboutHeaderView = (TextView) activity.findViewById(R.id.aboutHeader);
        assertTrue("About".equals(aboutHeaderView.getText().toString()));
    }
}

package com.cwainner.chris.recipecentral;

import android.os.Build;
import android.widget.TextView;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;

import static org.junit.Assert.*;

@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP)
@RunWith(RobolectricGradleTestRunner.class)

public class AboutActivityTest {
    private AboutActivity activity;

    @Before
    public void setup() {
        activity = Robolectric.setupActivity(AboutActivity.class);
    }

    @Test
    public void validateAboutHeader(){
        TextView aboutHeaderView = (TextView) activity.findViewById(R.id.aboutHeader);
        assertTrue("About".equals(aboutHeaderView.getText().toString()));
    }

    @Test
    public void validateAboutText(){
        TextView aboutTextView = (TextView) activity.findViewById(R.id.aboutText);
        String aboutTextContent = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi egestas, ante sit amet facilisis auctor, risus arcu faucibus justo, at tempor odio est ut est. Sed sodales augue a egestas suscipit. Curabitur malesuada tellus dolor, quis laoreet ipsum suscipit tristique. Sed vel ex iaculis, sollicitudin ipsum ac, maximus augue. Phasellus ut dui sed sapien vulputate dapibus. Suspendisse sed neque nec dolor pulvinar iaculis. Suspendisse lorem nisi, tristique a sapien at, porta blandit eros. Nam ut tincidunt mauris, id sollicitudin nulla. Mauris sit amet tincidunt nulla. Etiam elit velit, rutrum sit amet velit in, placerat commodo augue. Curabitur vitae rhoncus velit. In porttitor dictum cursus. Mauris eu fermentum dolor. Phasellus laoreet, metus ut malesuada convallis, elit arcu porta urna, condimentum porttitor magna turpis eget dolor.";
        assertTrue(aboutTextContent.equals(aboutTextView.getText().toString()));
    }
}

Add additional test for About activity


package water;

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

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;

import static org.junit.Assert.*;

public class TCPReceiverThreadTest extends TestUtil {

  @BeforeClass()
  public static void setup() {
    stall_till_cloudsize(1);
  }

  @Test
  public void testDontShutdownOnGarbageRequests() throws Exception {
    NodeLocalEventCollectingListener ext = NodeLocalEventCollectingListener.getFreshInstance();

    // make a bogus request to our H2O PORT (NOT the API PORT!!!)
    // using HTTP is just a cheap trick to send some garbage data that H2O won't recognize
    URL apiURL = new URL("http:/" + H2O.SELF_ADDRESS + ":" + H2O.H2O_PORT + "/");
    try (InputStream is = apiURL.openStream()) {
      assertNull(is); // should never happen
    } catch (IOException e) {
      String m = e.getMessage();
      if (!m.equals("Connection reset") && !m.equals("Connection refused (Connection refused)")) {
        throw e;
      }
    }

    ArrayList<Object[]> protocolFailure = ext.getData("protocol-failure");
    assertEquals(1, protocolFailure.size());
    assertArrayEquals(new Object[]{"handshake"}, protocolFailure.get(0));
  }

}

package water;

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

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;

import static org.junit.Assert.*;

public class TCPReceiverThreadTest extends TestUtil {

  @BeforeClass()
  public static void setup() {
    stall_till_cloudsize(1);
  }

  @Test
  public void testDontShutdownOnGarbageRequests() throws Exception {
    NodeLocalEventCollectingListener ext = NodeLocalEventCollectingListener.getFreshInstance();

    // make a bogus request to our H2O PORT (NOT the API PORT!!!)
    // using HTTP is just a cheap trick to send some garbage data that H2O won't recognize
    URL apiURL = new URL("http:/" + H2O.SELF_ADDRESS + ":" + H2O.H2O_PORT + "/");
    try (InputStream is = apiURL.openStream()) {
      assertNull(is); // should never happen
    } catch (IOException e) {
      e.printStackTrace();
    }

    ArrayList<Object[]> protocolFailure = ext.getData("protocol-failure");
    assertEquals(1, protocolFailure.size());
    assertArrayEquals(new Object[]{"handshake"}, protocolFailure.get(0));
  }

}

Make a test more robust


package net.liftweb.actor;

import java.lang.annotation.*;

/**
 * The internal Java class where the annotations for
 * JavaActor are stored
 */
class JavaActorBase {
    /**
     * A method annotated with Receive will
     * receive a message of the type of its parameter.
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface Receive {
    }
}

package net.liftweb.actor;

import java.lang.annotation.*;

/**
 * The internal Java class where the annotations for
 * JavaActor are stored
 */
public class JavaActorBase {
    /**
     * A method annotated with Receive will
     * receive a message of the type of its parameter.
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface Receive {
    }
}

Adjust visibility for javadoc compliance


import java.util.Vector;

/**
 *
 */

/**
 * An interface for password store objects.
 *
 * @author Miltiadis Allamanis
 *
 */
public interface IPasswordStore {
	/**
	 * Return a list of all the stored passwords.
	 *
	 * @return a vector containing the ids of stored passwords
	 */
	public Vector<String> getAllStoredPasswordIds();

	public boolean removePassword(final String aId);

	/**
	 * Retrieve a unique password with the specified id.
	 *
	 * @param aId
	 *            the unique password id to look for
	 * @return a Password object or null if no password with an id is found
	 */
	public Password retrivePassword(final String aId);

	/**
	 * Store a password object to the store.
	 *
	 * @param aPassword
	 *            the password to store
	 * @return true if the password has been stored sucessfully
	 */
	public boolean storePassword(final Password aPassword);
}

import java.util.AbstractList;

/**
 *
 */

/**
 * An interface for password store objects.
 *
 * @author Miltiadis Allamanis
 *
 */
public interface IPasswordStore {
	/**
	 * Return a list of all the stored passwords.
	 *
	 * @return a vector containing the ids of stored passwords
	 */
	public AbstractList<String> getAllStoredPasswordIds();

	/**
	 * Remove password from store.
	 *
	 * @param aId
	 *            the id of the password
	 * @return true if the password has been sucessfuly removed
	 */
	public boolean removePassword(final String aId);

	/**
	 * Retrieve a unique password with the specified id.
	 *
	 * @param aId
	 *            the unique password id to look for
	 * @return a Password object or null if no password with an id is found
	 */
	public Password retrivePassword(final String aId);

	/**
	 * Store a password object to the store.
	 *
	 * @param aPassword
	 *            the password to store
	 * @return true if the password has been stored sucessfully
	 */
	public boolean storePassword(final Password aPassword);
}

Comment addition and interface change from Vector to AbstractList


package org.museautomation.selenium.steps;

import org.museautomation.core.*;
import org.museautomation.core.context.*;
import org.museautomation.core.resource.*;
import org.museautomation.core.step.*;
import org.museautomation.core.step.descriptor.*;
import org.museautomation.core.values.descriptor.*;

/**
 * @author Christopher L Merrill (see LICENSE.txt for license details)
 */
@MuseTypeId("close-window")
@MuseStepName("Close Window")
@MuseInlineEditString("Close current window")
@MuseStepIcon("glyph:FontAwesome:WINDOW_CLOSE")
@MuseStepTypeGroup("Selenium.Window")
@MuseStepShortDescription("Close the current browser tab and/or window")
@MuseStepLongDescription("Closes the current browser tab or window. If it is the last tab/window opened, it will shutdown the browser.")
public class CloseWindow extends BrowserStep
    {
    @SuppressWarnings("unused") // called via reflection
    public CloseWindow(StepConfiguration config, MuseProject project)
        {
        super(config);
        }

    @Override
    public StepExecutionResult executeImplementation(StepExecutionContext context) throws MuseExecutionError
        {
        getDriver(context).close();
        return new BasicStepExecutionResult(StepExecutionStatus.COMPLETE);
        }

    public final static String TYPE_ID = CloseWindow.class.getAnnotation(MuseTypeId.class).value();
    }

package org.museautomation.selenium.steps;

import org.museautomation.core.*;
import org.museautomation.core.context.*;
import org.museautomation.core.step.*;
import org.museautomation.core.step.descriptor.*;

/**
 * @author Christopher L Merrill (see LICENSE.txt for license details)
 */
@MuseTypeId("close-window")
@MuseStepName("Close Window")
@MuseInlineEditString("Close current window")
@MuseStepIcon("glyph:FontAwesome:WINDOW_CLOSE_ALT")
@MuseStepTypeGroup("Selenium.Window")
@MuseStepShortDescription("Close the current browser tab and/or window")
@MuseStepLongDescription("Closes the current browser tab or window. If it is the last tab/window opened, it will shutdown the browser.")
@SuppressWarnings("unused")  // discovered and instantiated via reflection
public class CloseWindow extends BrowserStep
    {
    @SuppressWarnings("unused") // called via reflection
    public CloseWindow(StepConfiguration config, MuseProject project)
        {
        super(config);
        }

    @Override
    public StepExecutionResult executeImplementation(StepExecutionContext context) throws MuseExecutionError
        {
        getDriver(context).close();
        return new BasicStepExecutionResult(StepExecutionStatus.COMPLETE);
        }

    public final static String TYPE_ID = CloseWindow.class.getAnnotation(MuseTypeId.class).value();
    }

ENHANCE - improve Close Window icon


package se.kth.csc.payload.message;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import se.kth.csc.model.QueuePosition;
import se.kth.csc.payload.api.QueuePositionInQueueSnapshot;
import se.kth.csc.payload.api.Snapshotters;

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
public class QueuePositionCreatedInQueue {
    private final QueuePositionInQueueSnapshot position;
    private final String queueName;

    public QueuePositionCreatedInQueue(QueuePosition queuePosition, String queueName) {
        this.queueName = queueName;
        this.position = Snapshotters.QueuePositionInQueueSnapshotter.INSTANCE.apply(queuePosition);
    }

    public QueuePositionInQueueSnapshot getQueuePosition() {
        return position;
    }
    public String getQueueName() {
        return queueName;
    }
}

package se.kth.csc.payload.message;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import se.kth.csc.model.QueuePosition;
import se.kth.csc.payload.api.QueuePositionInQueueSnapshot;
import se.kth.csc.payload.api.Snapshotters;

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
public class QueuePositionCreatedInQueue {
    private final QueuePositionInQueueSnapshot position;
    private final String queueName;

    public QueuePositionCreatedInQueue(QueuePosition queuePosition, String queueName) {
        this.position = Snapshotters.QueuePositionInQueueSnapshotter.INSTANCE.apply(queuePosition);
        this.queueName = queueName;
    }

    public QueuePositionInQueueSnapshot getQueuePosition() {
        return position;
    }
    public String getQueueName() {
        return queueName;
    }
}

Change order of "position" and "queueName" to correspond to QueuePositionCreatedInAccount.


package org.realityforge.arez;

/**
 * Interface that allows caller to release any resources associated with element.
 * It is safe to invoke {@link #dispose()} multiple times on a element. Dispose
 * is considered a state modifying action and must be called either within an
 * action where mutation is true or else it will start it's own transaction before
 * performing dispose. Once an element is disposed, no other methods should be invoked
 * on element.
 */
@FunctionalInterface
public interface Disposable
{
  /**
   * Dispose element.
   */
  void dispose();
}

package org.realityforge.arez;

/**
 * Interface that allows caller to release any resources associated with element.
 * It is safe to invoke {@link #dispose()} multiple times on a element. Dispose
 * is considered a state modifying action and must be called either within an
 * action where mutation is true or else it will start it's own transaction before
 * performing dispose. Once an element is disposed, no other methods should be invoked
 * on element.
 */
@FunctionalInterface
public interface Disposable
{
  /**
   * Dispose element. See {@link Disposable} for a description of the implications.
   */
  void dispose();
}

Update the description so docs can be inherited by implementers


package org.fedoraproject.javadeptools.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table
public class ManifestEntry {
    @Id
    @GeneratedValue(generator = "gen")
    @GenericGenerator(name = "gen", strategy = "increment")
    private Long id;

    @ManyToOne
    @JoinColumn(name = "fileArtifactId", nullable = false)
    private FileArtifact fileArtifact;

    public ManifestEntry() {
    }

    public ManifestEntry(String key, String value) {
        this.key = key;
        this.value = value;
    }

    public Long getId() {
        return id;
    }

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

    public FileArtifact getFileArtifact() {
        return fileArtifact;
    }

    public void setFileArtifact(FileArtifact fileArtifact) {
        this.fileArtifact = fileArtifact;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

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

    private String key;

    @Lob
    private String value;
}

package org.fedoraproject.javadeptools.model;

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

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table
public class ManifestEntry {
    @Id
    @GeneratedValue(generator = "gen")
    @GenericGenerator(name = "gen", strategy = "increment")
    private Long id;

    @ManyToOne
    @JoinColumn(name = "fileArtifactId", nullable = false)
    private FileArtifact fileArtifact;

    public ManifestEntry() {
    }

    public ManifestEntry(String key, String value) {
        this.key = key;
        this.value = value;
    }

    public Long getId() {
        return id;
    }

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

    public FileArtifact getFileArtifact() {
        return fileArtifact;
    }

    public void setFileArtifact(FileArtifact fileArtifact) {
        this.fileArtifact = fileArtifact;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

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

    private String key;

    @Column(columnDefinition = "VARCHAR")
    private String value;
}

Use VARCHAR instead of LOB


package arez.doc.examples.at_observe2;

import arez.Observer;
import arez.SafeProcedure;
import arez.annotations.Action;
import arez.annotations.ArezComponent;
import arez.annotations.CascadeDispose;
import arez.annotations.Observe;
import arez.annotations.ObserverRef;
import arez.annotations.OnDepsChange;
import elemental2.dom.DomGlobal;
import elemental2.dom.Element;
import javax.annotation.Nonnull;

@ArezComponent
public abstract class CurrencyView
{
  @CascadeDispose
  final Currency bitcoin = new Arez_Currency();

  @Observe
  void render()
  {
    final Element element = DomGlobal.document.getElementById( "currencyTracker" );
    element.innerHTML = "1 BTC = $" + bitcoin.getAmount() + "AUD";
  }

  @OnDepsChange
  void onRenderDepsChange()
  {
    debounce( this::scheduleRender, 2000 );
  }

  @ObserverRef
  abstract Observer getRenderObserver();

  @Action( verifyRequired = false )
  void scheduleRender()
  {
    // Actually schedule the re-render. Has to occur within
    // an action or inside a read-write transaction
    getRenderObserver().schedule();
  }

  private void debounce( @Nonnull final SafeProcedure action, final long timeInMillis )
  {
    // Execute this action at most one every timeInMillis
    //DOC ELIDE START
    //DOC ELIDE END
  }
}

package arez.doc.examples.at_observe2;

import arez.Observer;
import arez.SafeProcedure;
import arez.annotations.ArezComponent;
import arez.annotations.CascadeDispose;
import arez.annotations.Observe;
import elemental2.dom.DomGlobal;
import elemental2.dom.Element;
import javax.annotation.Nonnull;

@ArezComponent
public abstract class CurrencyView
{
  @CascadeDispose
  final Currency bitcoin = new Arez_Currency();

  @Observe
  void render()
  {
    final Element element = DomGlobal.document.getElementById( "currencyTracker" );
    element.innerHTML = "1 BTC = $" + bitcoin.getAmount() + "AUD";
  }

  void onRenderDepsChange( @Nonnull final Observer observer )
  {
    debounce( observer::schedule, 2000 );
  }

  private void debounce( @Nonnull final SafeProcedure action, final long timeInMillis )
  {
    // Execute this action at most one every timeInMillis
    //DOC ELIDE START
    //DOC ELIDE END
  }
}

Simplify code by passing an Observer


package cas.ypsiliform.mediator.negotiation;

import java.util.ArrayList;

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

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

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

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

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

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

package cas.ypsiliform.mediator.negotiation;

import java.util.ArrayList;

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

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

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

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

	public int getId() {
		// TODO implementation missing
		throw new UnsupportedOperationException();
	}

	public int getParentId() {
		// TODO implementation missing
		throw new UnsupportedOperationException();
	}

	public Iterable<Integer> getChildIds() {
		// TODO implementation missing
		throw new UnsupportedOperationException();
	}

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

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

Add agent methods to get supply chain structure


package com.macasaet.fernet;

/**
 * This exception indicates that a Fernet token could not be created because one or more of the parameters was invalid.
 *
 *
Copyright © 2017 Carlos Macasaet.

 *
 * @author Carlos Macasaet
 */
public class IllegalTokenException extends IllegalArgumentException {

    private static final long serialVersionUID = 8019898267609912205L;

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

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

}

package com.macasaet.fernet;

/**
 * This exception indicates that a Fernet token could not be created because one or more of the parameters was invalid.
 *
 *
Copyright © 2017 Carlos Macasaet.

 *
 * @author Carlos Macasaet
 */
public class IllegalTokenException extends IllegalArgumentException {

    private static final long serialVersionUID = -1794971941479648725L;

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

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

}

Update serialVersionUID for updated public API


package de.flux.playground.deckcompare.importer;

public class ImportException extends RuntimeException {

    public ImportException(String string, Throwable cause) {
        super(string, cause);
    }

    private static final long serialVersionUID = 1734612217426583223L;

}

package de.flux.playground.deckcompare.importer;

public class ImportException extends RuntimeException {

    private static final long serialVersionUID = 1734612217426583223L;

    public ImportException(String string, Throwable cause) {
        super(string, cause);
    }

}

Put field to top of class


package me.hfox.morphix.query;

import java.util.Iterator;
import java.util.List;

/**
 * Created by Harry on 28/11/2017.
 *
 * An iterable set of results returned by a query object
 */
public interface QueryResult<T> extends Iterator<T> {

    /**
     * Alias of
     * @see me.hfox.morphix.query.QueryResult#first();
     * @return The first result returned by the query
     */
    T get();

    /**
     * Get the first result from the query
     * @return The first result returned by the query
     */
    T first();

    /**
     * Get the last result from the query
     * @return The last result returned by the query
     */
    T last();

    /**
     * Get the results given by the query as a List
     * @return An unmodifiable list of results
     */
    List<T> asList();

}

package me.hfox.morphix.query;

import java.util.Iterator;
import java.util.List;

/**
 * Created by Harry on 28/11/2017.
 *
 * An iterable set of results returned by a query object
 */
public interface QueryResult<T> extends Iterator<T> {

    /**
     * Alias of
     * @see me.hfox.morphix.query.QueryResult#first();
     * @return The first result returned by the query
     */
    T one();

    /**
     * Get the first result from the query
     * @return The first result returned by the query
     */
    T first();

    /**
     * Get the last result from the query
     * @return The last result returned by the query
     */
    T last();

    /**
     * Get the results given by the query as a List
     * @return An unmodifiable list of results
     */
    List<T> all();

}

Rename get -> one and asList -> all


/*
 * Copyright DataStax, 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.datastax.oss.driver.internal.core.os;

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

import org.junit.Test;

public class NativeTest {

  /** Verifies that {@link Native#getCPU()} returns non-empty cpu architecture */
  @Test
  public void should_return_cpu_if_call_is_available() {
    if (Native.isPlatformAvailable()) {
      assertThat(Native.getCPU()).isNotEmpty();
    }
  }
}

/*
 * Copyright DataStax, 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.datastax.oss.driver.internal.core.os;

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

import org.junit.Test;

public class NativeTest {

  /** Verifies that {@link Native#getCPU()} returns non-empty cpu architecture */
  @Test
  public void should_return_cpu_if_call_is_available() {
    if (Native.isPlatformAvailable()) {
      assertThat(Native.getCPU()).isNotEmpty();
    }
  }
}

Remove references to deprecated Java6Assertions class


package org.apache.pig.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.pig.ExecType;
import org.apache.pig.backend.hadoop.executionengine.spark.SparkExecType;

public class SparkMiniCluster extends MiniGenericCluster {
    private static final File CONF_DIR = new File("build/classes");
    private static final File CONF_FILE = new File(CONF_DIR, "hadoop-site.xml");
    private ExecType spark = new SparkExecType();
    SparkMiniCluster() {

    }

    @Override
    public ExecType getExecType() {
        return spark;
    }

    @Override
    protected void setupMiniDfsAndMrClusters() {
        try {
            CONF_DIR.mkdirs();
            if (CONF_FILE.exists()) {
                CONF_FILE.delete();
            }
            m_conf = new Configuration();
            m_conf.set("io.sort.mb", "1");
            m_conf.writeXml(new FileOutputStream(CONF_FILE));
            int dataNodes = 4;
            m_dfs = new MiniDFSCluster(m_conf, dataNodes, true, null);
            m_fileSys = m_dfs.getFileSystem();
        } catch (IOException e) {
            throw new RuntimeException(e);

        }

    }

    @Override
    protected void shutdownMiniMrClusters() {
        if (CONF_FILE.exists()) {
            CONF_FILE.delete();
        }
    }

}

package org.apache.pig.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.pig.ExecType;
import org.apache.pig.backend.hadoop.executionengine.spark.SparkExecType;

public class SparkMiniCluster extends MiniGenericCluster {
    private static final File CONF_DIR = new File("build/classes");
    private static final File CONF_FILE = new File(CONF_DIR, "hadoop-site.xml");
    private ExecType spark = new SparkExecType();
    SparkMiniCluster() {

    }

    @Override
    public ExecType getExecType() {
        return spark;
    }

    @Override
    protected void setupMiniDfsAndMrClusters() {
        try {
            CONF_DIR.mkdirs();
            if (CONF_FILE.exists()) {
                CONF_FILE.delete();
            }
            m_conf = new Configuration();
            m_conf.set("io.sort.mb", "1");
            m_conf.writeXml(new FileOutputStream(CONF_FILE));
            int dataNodes = 4;
            m_dfs = new MiniDFSCluster(m_conf, dataNodes, true, null);
            m_fileSys = m_dfs.getFileSystem();
            m_fileSys.mkdirs(m_fileSys.getWorkingDirectory());
        } catch (IOException e) {
            throw new RuntimeException(e);

        }

    }

    @Override
    protected void shutdownMiniMrClusters() {
        if (CONF_FILE.exists()) {
            CONF_FILE.delete();
        }
    }

}

Enable unit test "TestStreamingUDF" in spark (liyunzhang via praveen)


import codeu.chat.ServerMain;
import codeu.chat.common.User;
import models.DBUtility;
import models.Models;
import play.GlobalSettings;
import play.Application;

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

/**
 * Play's Global class, which runs custom code when the application starts / ends.
 */
public class Global extends GlobalSettings {

  /**
   * Setting up the application when it starts by adding default user and chatrooms to the database.
   * @param app this application.
   */
  public void onStart(Application app) {

    // run "sh run_server.sh" in background
    ExecutorService service = Executors.newFixedThreadPool(4);
    service.submit(new Runnable() {
      public void run() {
        ServerMain.runServer();
      }
    });

    // connect to the database
    try {
      String url = "jdbc:sqlite:chatapp.db";
      String driver = "org.sqlite.JDBC";
      Class.forName(driver);

      // set up initial database if it's empty
      boolean adminExists = DBUtility.checkDuplicateField(DriverManager.getConnection(url), "users", "name", "admin");
      if (!adminExists) {
        // create a default admin account
        User admin = Models.newUser("admin");
        DBUtility.addUser(DriverManager.getConnection(url), "admin", "123456", admin.id.toString());
      }

      // create a default public room
      DBUtility.addConversation(DriverManager.getConnection(url), "public", "admin");

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

import codeu.chat.ServerMain;
import codeu.chat.common.User;
import models.DBUtility;
import models.Models;
import play.GlobalSettings;
import play.Application;

import java.sql.DriverManager;

/**
 * Play's Global class, which runs custom code when the application starts / ends.
 */
public class Global extends GlobalSettings {

  /**
   * Setting up the application when it starts by adding default user and chatrooms to the database.
   * @param app this application.
   */
  public void onStart(Application app) {

    // connect to the database
    try {
      String url = "jdbc:sqlite:chatapp.db";
      String driver = "org.sqlite.JDBC";
      Class.forName(driver);

      // set up initial database if it's empty
      boolean adminExists = DBUtility.checkDuplicateField(DriverManager.getConnection(url), "users", "name", "admin");
      if (!adminExists) {
        // create a default admin account
        User admin = Models.newUser("admin");
        DBUtility.addUser(DriverManager.getConnection(url), "admin", "123456", admin.id.toString());
      }

      // create a default public room
      DBUtility.addConversation(DriverManager.getConnection(url), "public", "admin");
      DBUtility.makeRoomPublic(DriverManager.getConnection(url), "public");

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Remove code to run server (it should be run on a separate terminal tab).


package org.conjugates.analyzer.endpoints.info;

import org.conjugates.analyzer.services.properties.AnalyzerProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/v1/info")
@RestController
public class InfoController {

  private final AnalyzerProperties properties;

  @Autowired
  public InfoController(AnalyzerProperties properties) {
    this.properties = properties;
  }

  @RequestMapping("/")
  public String name() {
    return properties.getName();
  }

}

package org.conjugates.analyzer.endpoints.info;

import org.conjugates.analyzer.services.properties.AnalyzerProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/v1/info")
@RestController
public class InfoController {

  private static final Logger LOG = LoggerFactory.getLogger(InfoController.class);

  private final AnalyzerProperties properties;

  @Autowired
  public InfoController(AnalyzerProperties properties) {
    this.properties = properties;
  }

  @RequestMapping("/")
  public String name() {
    LOG.debug("Call to info made");
    return properties.getName();
  }

}

Validate logging works through slf4j


package com.google.samples.button;

import android.os.Build;

@SuppressWarnings("WeakerAccess")
public class BoardDefaults {
    private static final String DEVICE_EDISON = "edison";
    private static final String DEVICE_RPI3 = "rpi3";
    private static final String DEVICE_NXP = "nxp";

    /**
     * Return the GPIO pin that the LED is connected on.
     * For example, on Intel Edison Arduino breakout, pin "IO13" is connected to an onboard LED
     * that turns on when the GPIO pin is HIGH, and off when low.
     */
    public static String getGPIOForLED() {
        // TODO: confirm DEVICE and preferred port for RPI3 and NXP
        switch (Build.DEVICE) {
            case DEVICE_EDISON:
                return "IO13";
            case DEVICE_RPI3:
                return "BCM25";
            case DEVICE_NXP:
                return "??";
            default:
                throw new IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE);
        }
    }

    /**
     * Return the GPIO pin that the Button is connected on.
     */
    public static String getGPIOForButton() {
        // TODO: confirm DEVICE and preferred port for RPI3 and NXP
        switch (Build.DEVICE) {
            case DEVICE_EDISON:
                return "IO12";
            case DEVICE_RPI3:
                return "BCM22";
            case DEVICE_NXP:
                return "??";
            default:
                throw new IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE);
        }
    }
}

package com.google.samples.button;

import android.os.Build;

@SuppressWarnings("WeakerAccess")
public class BoardDefaults {
    private static final String DEVICE_EDISON = "edison";
    private static final String DEVICE_RPI3 = "rpi3";
    private static final String DEVICE_NXP = "imx6ul";

    /**
     * Return the GPIO pin that the LED is connected on.
     * For example, on Intel Edison Arduino breakout, pin "IO13" is connected to an onboard LED
     * that turns on when the GPIO pin is HIGH, and off when low.
     */
    public static String getGPIOForLED() {
        // TODO: confirm DEVICE and preferred port for RPI3 and NXP
        switch (Build.DEVICE) {
            case DEVICE_EDISON:
                return "IO13";
            case DEVICE_RPI3:
                return "BCM25";
            case DEVICE_NXP:
                return "??";
            default:
                throw new IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE);
        }
    }

    /**
     * Return the GPIO pin that the Button is connected on.
     */
    public static String getGPIOForButton() {
        // TODO: confirm DEVICE and preferred port for RPI3 and NXP
        switch (Build.DEVICE) {
            case DEVICE_EDISON:
                return "IO12";
            case DEVICE_RPI3:
                return "BCM22";
            case DEVICE_NXP:
                return "??";
            default:
                throw new IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE);
        }
    }
}

Fix references of nxp to imx6ul


/*
 * Copyright 2020, 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.code.gen.java;

import com.squareup.javapoet.TypeSpec;
import io.spine.code.java.PackageName;

import javax.lang.model.element.Modifier;

/**
 * A JavaPoet-based spec of a generated type.
 */
public interface GeneratedTypeSpec {

    /**
     * The package under which the type will be generated.
     */
    PackageName packageName();

    /**
     * A JavaPoet spec of the type.
     */
    // TODO:2019-12-20:dmytro.kuzmin:WIP: Consolidate singular/plural name usage after varargs.
    TypeSpec typeSpec(Modifier... modifiers);
}

/*
 * Copyright 2020, 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.code.gen.java;

import com.squareup.javapoet.TypeSpec;
import io.spine.code.java.PackageName;

import javax.lang.model.element.Modifier;

/**
 * A JavaPoet-based spec of a generated type.
 */
public interface GeneratedTypeSpec {

    /**
     * The package under which the type will be generated.
     */
    PackageName packageName();

    /**
     * A JavaPoet spec of the type.
     */
    TypeSpec typeSpec(Modifier... modifiers);
}

Remove a todo which is already resolved


package konstructs.api.messages;

/**
 * GlobalConfig is a message that informs the plugin of the current values of
 * the global server config. These values are used by the server to manage
 * overall behaviour of plugins and is informal.
 */
public class GlobalConfig {
    public final float DEFAULT_SIMULATION_SPEED = 1.0f;

    private final float simulationSpeed;

    /**
     * Construct an immutable GlobalConfig message
     * @param simulationSpeed The speed multiplier currently in use. 1.0 is normal speed.
     */
    public GlobalConfig(float simulationSpeed) {
        this.simulationSpeed = simulationSpeed;
    }

    /**
     * Get the simulation speed multiplier currently in use. 1.0 is normal speed.
     * @return The simulation speed multiplier
     */
    public float getSimulationSpeed() {
        return simulationSpeed;
    }

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

        GlobalConfig that = (GlobalConfig) o;

        return Float.compare(that.simulationSpeed, simulationSpeed) == 0;

    }

    @Override
    public int hashCode() {
        return (simulationSpeed != +0.0f ? Float.floatToIntBits(simulationSpeed) : 0);
    }

    @Override
    public String toString() {
        return "GlobalConfig(" +
                "simulationSpeed=" + simulationSpeed +
                ')';
    }
}

package konstructs.api.messages;

/**
 * GlobalConfig is a message that informs the plugin of the current values of
 * the global server config. These values are used by the server to manage
 * overall behaviour of plugins and is informal.
 */
public class GlobalConfig {
    public final static float DEFAULT_SIMULATION_SPEED = 1.0f;

    private final float simulationSpeed;

    /**
     * Construct an immutable GlobalConfig message
     * @param simulationSpeed The speed multiplier currently in use. 1.0 is normal speed.
     */
    public GlobalConfig(float simulationSpeed) {
        this.simulationSpeed = simulationSpeed;
    }

    /**
     * Get the simulation speed multiplier currently in use. 1.0 is normal speed.
     * @return The simulation speed multiplier
     */
    public float getSimulationSpeed() {
        return simulationSpeed;
    }

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

        GlobalConfig that = (GlobalConfig) o;

        return Float.compare(that.simulationSpeed, simulationSpeed) == 0;

    }

    @Override
    public int hashCode() {
        return (simulationSpeed != +0.0f ? Float.floatToIntBits(simulationSpeed) : 0);
    }

    @Override
    public String toString() {
        return "GlobalConfig(" +
                "simulationSpeed=" + simulationSpeed +
                ')';
    }
}

Fix constant to be static


package roycurtis.signshopexport.json;

import org.bukkit.inventory.ItemStack;

/** Represents a JSON record for Gson serialization */
public class Record
{
    // Location
    public String locWorld;
    public int    locX;
    public int    locY;
    public int    locZ;

    // Owner
    public String ownerName;
    public String ownerUuid;

    // Sign data
    public String[] signText;
    public String   signType;
    public double   signPrice;

    // Inventory data
    public ItemStack[] invItems;
    public boolean     invInStock;
}

package roycurtis.signshopexport.json;

import org.bukkit.inventory.ItemStack;

/** Represents a JSON record for Gson serialization */
public class Record
{
    // Location
    public String locWorld;
    public int    locX;
    public int    locY;
    public int    locZ;

    // Owner
    public String ownerName;
    public String ownerUuid;

    // Sign data
    public String[] signText;
    public String   signType;
    public double   signPrice;

    // Inventory data
    public ItemStack[] invItems;
    public boolean     invInStock;

    @Override
    public String toString()
    {
        return String.format(
            "Record: %s sign at %d,%d,%d @ %s by %s (%s)",
            signType,
            locX, locY, locZ, locWorld,
            ownerName, ownerUuid
        );
    }
}

Add toString override for records


package spark.staticfiles;

import static spark.utils.StringUtils.removeLeadingAndTrailingSlashesFrom;

/**
 * Protecting against Directory traversal
 */
public class DirectoryTraversal {

    public static void protectAgainstInClassPath(String path) {
        if (!removeLeadingAndTrailingSlashesFrom(path).startsWith(StaticFilesFolder.local())) {
            throw new DirectoryTraversalDetection("classpath");
        }
    }

    public static void protectAgainstForExternal(String path) {
        if (!removeLeadingAndTrailingSlashesFrom(path).startsWith(StaticFilesFolder.external())) {
            throw new DirectoryTraversalDetection("external");
        }
    }

    public static final class DirectoryTraversalDetection extends RuntimeException {

        public DirectoryTraversalDetection(String msg) {
            super(msg);
        }

    }

}

package spark.staticfiles;

import static spark.utils.StringUtils.removeLeadingAndTrailingSlashesFrom;
import java.nio.file.Paths;

/**
 * Protecting against Directory traversal
 */
public class DirectoryTraversal {

    public static void protectAgainstInClassPath(String path) {
        if (!removeLeadingAndTrailingSlashesFrom(path).startsWith(StaticFilesFolder.local())) {
            throw new DirectoryTraversalDetection("classpath");
        }
    }

    public static void protectAgainstForExternal(String path) {
        String nixLikePath = Paths.get(path).toAbsolutePath().toString().replace("\\", "/");
        if (!removeLeadingAndTrailingSlashesFrom(nixLikePath).startsWith(StaticFilesFolder.external())) {
            throw new DirectoryTraversalDetection("external");
        }
    }

    public static final class DirectoryTraversalDetection extends RuntimeException {

        public DirectoryTraversalDetection(String msg) {
            super(msg);
        }

    }

}

Add Windows to *nix path conversion


package com.ezardlabs.lostsector.missions;

import com.ezardlabs.lostsector.objects.enemies.Enemy;

public abstract class Mission {
	protected int enemiesKilled = 0;
	private long missionStart = 0;
	private EnemyStatusListener enemyStatusListener;

	public void startMission() {
		missionStart = System.currentTimeMillis();
	}

	public long getMissionTime() {
		return System.currentTimeMillis() - missionStart;
	}

	public abstract void load();

	public final void notifyEnemySpawn(Enemy enemy) {
		if (enemyStatusListener != null) {
			enemyStatusListener.onEnemySpawned(enemy);
		}
	}

	public final void notifyEnemyDeath(Enemy enemy) {
		enemiesKilled++;
		if (enemyStatusListener != null) {
			enemyStatusListener.onEnemyKilled(enemy);
		}
	}

	void setEnemyStatusListener(EnemyStatusListener enemyStatusListener) {
		this.enemyStatusListener = enemyStatusListener;
	}

	protected interface EnemyStatusListener {
		void onEnemySpawned(Enemy enemy);

		void onEnemyKilled(Enemy enemy);
	}
}

package com.ezardlabs.lostsector.missions;

import com.ezardlabs.lostsector.objects.enemies.Enemy;

public abstract class Mission {
	protected int enemiesKilled = 0;
	private long missionStart = 0;
	private boolean completed = false;
	private EnemyStatusListener enemyStatusListener;
	private MissionStatusListener missionStatusListener;

	public void startMission() {
		missionStart = System.currentTimeMillis();
	}

	public long getMissionTime() {
		return System.currentTimeMillis() - missionStart;
	}

	public abstract void load();

	protected final void completedMission() {
		completed = true;
		if (missionStatusListener != null) {
			missionStatusListener.onMissionCompleted();
		}
	}

	public final void notifyEnemySpawn(Enemy enemy) {
		if (enemyStatusListener != null) {
			enemyStatusListener.onEnemySpawned(enemy);
		}
	}

	public final void notifyEnemyDeath(Enemy enemy) {
		enemiesKilled++;
		if (enemyStatusListener != null) {
			enemyStatusListener.onEnemyKilled(enemy);
		}
	}

	void setEnemyStatusListener(EnemyStatusListener enemyStatusListener) {
		this.enemyStatusListener = enemyStatusListener;
	}

	void setMissionStatusListener(MissionStatusListener listener) {
		this.missionStatusListener = listener;
	}

	protected interface EnemyStatusListener {
		void onEnemySpawned(Enemy enemy);

		void onEnemyKilled(Enemy enemy);
	}

	protected interface MissionStatusListener {
		void onMissionCompleted();
	}
}

Add listener for mission status


package com.sleekbyte.tailor.utils;

/**
 * TODO!!!
 */
public class CharFormatUtil {

    private static final String ALPHANUMERIC_REGEX = "^[a-zA-Z0-9]*$";

    public static boolean isUpperCamelCase(String word) {
        return !word.isEmpty() && word.matches(ALPHANUMERIC_REGEX) && Character.isUpperCase(word.charAt(0));
    }

    public static boolean isLowerCamelCase(String word) {
        return !word.isEmpty() && word.matches(ALPHANUMERIC_REGEX) && Character.isLowerCase(word.charAt(0));
    }

}

package com.sleekbyte.tailor.utils;

/**
 * Util class for character formatting
 */
public class CharFormatUtil {

    private static final String ALPHANUMERIC_REGEX = "^[a-zA-Z0-9]*$";

    public static boolean isUpperCamelCase(String word) {
        return !word.isEmpty() && word.matches(ALPHANUMERIC_REGEX) && Character.isUpperCase(word.charAt(0));
    }

    public static boolean isLowerCamelCase(String word) {
        return !word.isEmpty() && word.matches(ALPHANUMERIC_REGEX) && Character.isLowerCase(word.charAt(0));
    }

}

Add Javadoc for one more class


package org.jetbrains.kotlin.android.xmlconverter;

import org.junit.Rule;
import org.junit.rules.TestName;
import sun.plugin.dom.exception.InvalidStateException;
import java.io.File;

import static kotlin.collections.SetsKt.*;
import static kotlin.io.FilesKt.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class BaseXmlConverterTest {

    @Rule
    public TestName name = new TestName();

    protected void doLayoutTest() {
        File testDataDir = new File("xml-converter/testData");
        String testName = name.getMethodName();
        if (!testName.startsWith("test")) {
            throw new InvalidStateException("Test name must start with a 'test' preffix");
        }

        File testDir = new File(testDataDir, decapitalize(testName.substring("test".length())));
        File inputFile = new File(testDir, "layout.xml");
        File outputFile = new File(testDir, "layout.kt");

        assertTrue(inputFile + " does not exist", inputFile.exists());
        assertTrue(outputFile + " does not exist", outputFile.exists());

        String actual = XmlConverter.INSTANCE.convert(readText(inputFile, "UTF-8"), setOf("raw"));
        String expected = readText(outputFile, "UTF-8");

        assertEquals(expected, actual);
    }

    private String decapitalize(String original) {
        if (original.isEmpty()) return original;
        return Character.toLowerCase(original.charAt(0)) + original.substring(1);
    }

}

package org.jetbrains.kotlin.android.xmlconverter;

import kotlin.text.Charsets;
import org.junit.Rule;
import org.junit.rules.TestName;
import sun.plugin.dom.exception.InvalidStateException;
import java.io.File;

import static kotlin.collections.SetsKt.*;
import static kotlin.io.FilesKt.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class BaseXmlConverterTest {

    @Rule
    public TestName name = new TestName();

    protected void doLayoutTest() {
        File testDataDir = new File("xml-converter/testData");
        String testName = name.getMethodName();
        if (!testName.startsWith("test")) {
            throw new InvalidStateException("Test name must start with a 'test' preffix");
        }

        File testDir = new File(testDataDir, decapitalize(testName.substring("test".length())));
        File inputFile = new File(testDir, "layout.xml");
        File outputFile = new File(testDir, "layout.kt");

        assertTrue(inputFile + " does not exist", inputFile.exists());
        assertTrue(outputFile + " does not exist", outputFile.exists());

        String actual = XmlConverter.INSTANCE.convert(readText(inputFile, Charsets.UTF_8), setOf("raw"));
        String expected = readText(outputFile, Charsets.UTF_8);

        assertEquals(expected, actual);
    }

    private String decapitalize(String original) {
        if (original.isEmpty()) return original;
        return Character.toLowerCase(original.charAt(0)) + original.substring(1);
    }

}

Fix compilation error with Kotlin 1.0


package org.vaadin.spring.mvp.autowired;

import org.springframework.beans.factory.annotation.Autowired;
import org.vaadin.spring.UIScope;
import org.vaadin.spring.annotation.VaadinComponent;
import org.vaadin.spring.events.EventBus;
import org.vaadin.spring.events.annotation.EventBusListenerMethod;
import org.vaadin.spring.mvp.FooView;
import org.vaadin.spring.mvp.Presenter;

@UIScope
@VaadinComponent
public class AutowiredPresenter extends Presenter<FooView> {

    @Autowired
    public AutowiredPresenter(FooView view, EventBus eventBus) {
        super(view, eventBus);
    }

    @EventBusListenerMethod
    public void onNewCaption(String caption) {
        getView().setCaption(caption);
    }
}

package org.vaadin.spring.mvp.autowired;

import org.springframework.beans.factory.annotation.Autowired;
import org.vaadin.spring.annotation.VaadinComponent;
import org.vaadin.spring.annotation.VaadinUIScope;
import org.vaadin.spring.events.EventBus;
import org.vaadin.spring.events.annotation.EventBusListenerMethod;
import org.vaadin.spring.mvp.FooView;
import org.vaadin.spring.mvp.Presenter;

@VaadinUIScope
@VaadinComponent
public class AutowiredPresenter extends Presenter<FooView> {

    @Autowired
    public AutowiredPresenter(FooView view, EventBus eventBus) {
        super(view, eventBus);
    }

    @EventBusListenerMethod
    public void onNewCaption(String caption) {
        getView().setCaption(caption);
    }
}

Test Class Update: Change UIScope => VaadinUIScope


package com.vryba.selenium.utilities;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;

import static org.testng.Assert.fail;

public class TestBase {

    private String baseUrl = Constant.URL;
    private StringBuffer verificationErrors = new StringBuffer();
    private Logger LOG = LogManager.getFormatterLogger();
    // annotated method will be run before the first test method in the current class is invoked
    @BeforeClass
    public void methodSetup() {
        BrowserFactory.startBrowser(BrowserFactory.BrowserType.FirefoxDriver, baseUrl);
        LOG.info("Starting Browser");
    }
    // annotated method will be run after each test method
    @AfterMethod
    public void testCleanUp() {
        new BrowserUtilities().executeJSCode(BrowserUtilities.CLEAR_LOCAL_STORAGE);
    }
    // annotated method will be run after all the test methods in the current class have been run
    @AfterClass(alwaysRun = true)
    public void tearDown() {
        BrowserFactory.closeSession();
        String verificationErrorString = verificationErrors.toString();
        if (!"".equals(verificationErrorString)) {
            fail(verificationErrorString);
        } else
            LOG.info("Browser Closed");
    }
}

package com.vryba.selenium.utilities;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import static org.testng.Assert.fail;

public class TestBase {

    private String baseUrl = Constant.BASE_URL;
    private StringBuffer verificationErrors = new StringBuffer();
    private Logger LOG = LogManager.getFormatterLogger();
    // annotated method will be run before the first test method in the current class is invoked
    @BeforeMethod
    public void methodSetup() {
        BrowserFactory.startBrowser(BrowserFactory.BrowserType.FirefoxDriver, baseUrl);
        LOG.info("Starting Browser");
    }
// annotated method will be run after each test method
    @AfterMethod
    public void testCleanUp() {
        new BrowserUtilities().executeJSCode(BrowserUtilities.CLEAR_LOCAL_STORAGE);
    }

    // annotated method will be run after all the test methods in the current class have been run
    @AfterClass(alwaysRun = true)
    public void tearDown() {
        BrowserFactory.closeSession();
        String verificationErrorString = verificationErrors.toString();
        if (!"".equals(verificationErrorString)) {
            fail(verificationErrorString);
        } else
            LOG.info("Browser Closed");
    }
}

Replace TestNG @BeforeClass with @BeforeMethod annotation


package uk.co.prenderj.trail.util;

import android.os.AsyncTask;

public abstract class CheckedAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {
    public abstract Result call(Params... params) throws Exception;

    public abstract void finish(Result result) throws Exception;

    @Override
    protected Result doInBackground(Params... params) {
        try {
            return call(params);
        } catch (Exception e) {
            onException(e);
            return null;
        }
    }

    @Override
    protected void onPostExecute(Result result) {
        try {
            finish(result);
        } catch (Exception e) {
            onException(e);
        }
    }

    public void onException(Exception thrown) {
        cancel(true);
    }
}

package uk.co.prenderj.trail.util;

import android.os.AsyncTask;

public abstract class CheckedAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {
    private Exception thrown;

    public abstract Result call(Params... params) throws Exception;

    public abstract void finish(Result result) throws Exception;

    @Override
    protected Result doInBackground(Params... params) {
        try {
            return call(params);
        } catch (Exception e) {
            thrown = e;
            return null;
        }
    }

    @Override
    protected void onPostExecute(Result result) {
        if (thrown != null) {
            onException(thrown);
        }
        try {
            finish(result);
        } catch (Exception e) {
            onException(e);
        }
    }

    public void onException(Exception thrown) {
        cancel(true);
    }
}

Revert "Handle exception straight away"


package pokefenn.totemic.item.music;

import net.minecraft.stats.Stats;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import pokefenn.totemic.api.TotemicAPI;
import pokefenn.totemic.init.ModContent;
import pokefenn.totemic.init.ModItems;

public class FluteItem extends Item {
    public FluteItem(Properties properties) {
        super(properties);
    }

    @SuppressWarnings("null")
    @Override
    public InteractionResultHolder<ItemStack> use(Level world, Player player, InteractionHand hand) {
        TotemicAPI.get().music().playMusic(player, ModContent.flute);

        player.getCooldowns().addCooldown(ModItems.flute.get(), 20);
        player.getCooldowns().addCooldown(ModItems.infused_flute.get(), 20);

        player.awardStat(Stats.ITEM_USED.get(this));
        return InteractionResultHolder.success(player.getItemInHand(hand));
    }
}

package pokefenn.totemic.item.music;

import net.minecraft.stats.Stats;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import pokefenn.totemic.api.TotemicAPI;
import pokefenn.totemic.init.ModContent;
import pokefenn.totemic.init.ModItems;

public class FluteItem extends Item {
    public FluteItem(Properties properties) {
        super(properties);
    }

    @Override
    public InteractionResultHolder<ItemStack> use(Level world, Player player, InteractionHand hand) {
        if(!world.isClientSide) {
            if(player.isShiftKeyDown())
                TotemicAPI.get().music().playSelector(player, ModContent.flute);
            else
                TotemicAPI.get().music().playMusic(player, ModContent.flute);
        }

        player.getCooldowns().addCooldown(ModItems.flute.get(), 20);
        player.getCooldowns().addCooldown(ModItems.infused_flute.get(), 20);

        player.awardStat(Stats.ITEM_USED.get(this));
        return InteractionResultHolder.success(player.getItemInHand(hand));
    }
}

Make flute item work properly


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

package org.elasticsearch.cloud.aws;

import com.amazonaws.auth.AWSCredentialsProvider;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ESTestCase;

public class EnvironmentCredentialsTests extends ESTestCase {

    public void test() {
        AWSCredentialsProvider provider =
            InternalAwsS3Service.buildCredentials(logger, deprecationLogger, Settings.EMPTY, Settings.EMPTY, "default");
        // NOTE: env vars are setup by the test runner in gradle
        assertEquals("env_access", provider.getCredentials().getAWSAccessKeyId());
        assertEquals("env_secret", provider.getCredentials().getAWSSecretKey());
        assertWarnings("Supplying S3 credentials through environment variables is deprecated");
    }
}

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

package org.elasticsearch.cloud.aws;

import com.amazonaws.auth.AWSCredentialsProvider;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ESTestCase;

public class EnvironmentCredentialsTests extends ESTestCase {

    public void test() {
        AWSCredentialsProvider provider =
            InternalAwsS3Service.buildCredentials(logger, deprecationLogger, Settings.EMPTY, Settings.EMPTY, "default");
        // NOTE: env vars are setup by the test runner in gradle
        assertEquals("env_access", provider.getCredentials().getAWSAccessKeyId());
        assertEquals("env_secret", provider.getCredentials().getAWSSecretKey());
        assertWarnings("Supplying S3 credentials through environment variables is deprecated. "
                + "See the breaking changes lists in the documentation for details.");
    }
}

Fix warning assertion in credentials test


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

package com.google.enterprise.connector.pusher;

/**
 * Interface for a factory that creates {@link Pusher} instances for use by a
 * {@link com.google.enterprise.connector.traverser.Traverser Traverser}.
 */
public interface PusherFactory {
  /**
   * Create a new {@link Pusher} instance appropriate for the supplied
   * dataSource.
   *
   * @param dataSource a data source for a {@code Feed}, typically the name
   *        of a connector instance.
   * @return a {@link Pusher}
   * @throws {@link PushException} if no {@link Pusher} is assigned to the
   *         {@code dataSource}.
   */
  public Pusher newPusher(String dataSource) throws PushException;
}

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

package com.google.enterprise.connector.pusher;

/**
 * Interface for a factory that creates {@link Pusher} instances for use by a
 * {@link com.google.enterprise.connector.traversal.Traverser Traverser}.
 */
public interface PusherFactory {
  /**
   * Create a new {@link Pusher} instance appropriate for the supplied
   * dataSource.
   *
   * @param dataSource a data source for a {@code Feed}, typically the name
   *        of a connector instance.
   * @return a {@link Pusher}
   * @throws PushException if no {@link Pusher} is assigned to the
   *         {@code dataSource}.
   */
  public Pusher newPusher(String dataSource) throws PushException;
}

Resolve a couple of compiler warnings that crept into the code.


package com.msgilligan.bitcoinj.json.conversion;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.bitcoinj.core.Transaction;

import java.io.IOException;
import java.util.Formatter;

/**
 *
 */
public class TransactionHexSerializer extends JsonSerializer<Transaction> {
    @Override
    public void serialize(Transaction value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
        // From: http://bitcoin.stackexchange.com/questions/8475/how-to-get-hex-string-from-transaction-in-bitcoinj
        final StringBuilder sb = new StringBuilder();
        Formatter formatter = new Formatter(sb);
        byte[] bytes = value.bitcoinSerialize();
        for (byte b : bytes) {
            formatter.format("%02x", b);
        }
        formatter.close();
        gen.writeString(sb.toString());
    }
}

package com.msgilligan.bitcoinj.json.conversion;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.bitcoinj.core.Transaction;

import java.io.IOException;
import java.util.Formatter;

/**
 *
 */
public class TransactionHexSerializer extends JsonSerializer<Transaction> {
    @Override
    public void serialize(Transaction value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
        gen.writeString(bytesToHexString(value.bitcoinSerialize()));
    }

    // From: http://bitcoin.stackexchange.com/questions/8475/how-to-get-hex-string-from-transaction-in-bitcoinj
    public static String bytesToHexString(byte[] bytes) {
        final StringBuilder sb = new StringBuilder();
        Formatter formatter = new Formatter(sb);
        for (byte b : bytes) {
            formatter.format("%02x", b);
        }
        formatter.close();
        return sb.toString();
    }
}

Split out bytesToHexString as a static method.


package doubler.impl;

import doubler.Doubler;
import org.junit.Test;

public class DoublerImplTest {

    @Test
    public void testIt() {
        Doubler doubler = new DoublerImpl();
        assert doubler.doubleIt(2) == 4;
    }
}

package doubler.impl;

import doubler.Doubler;
import org.junit.Test;
import static org.junit.Assert.*;

public class DoublerImplTest {
    @Test
    public void testIt() {
        Doubler doubler = new DoublerImpl();
        assertEquals(4, doubler.doubleIt(2));
    }
}

Use JUnit assert method in test case


package amu.zhcet.email;

import amu.zhcet.common.utils.ConsoleHelper;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;

@Slf4j
@Configuration
public class EmailConfiguration {

    private static boolean EMAIL_ENABLED;

    @Autowired(required = false)
    public EmailConfiguration(JavaMailSender javaMailSender, EmailProperties emailProperties) {
        if (javaMailSender == null || Strings.isNullOrEmpty(emailProperties.getAddress())) {
            log.error(ConsoleHelper.red("CONFIG (Email): Email or Password not found {}"), emailProperties.getAddress());
            EMAIL_ENABLED = false;
        } else {
            EMAIL_ENABLED = true;
            log.info(ConsoleHelper.green("Email Initialized"));
        }
    }

    public static Boolean isEmailSet() {
        return EMAIL_ENABLED;
    }

}

package amu.zhcet.email;

import amu.zhcet.common.utils.ConsoleHelper;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;

@Slf4j
@Configuration
public class EmailConfiguration {

    private static boolean EMAIL_ENABLED;

    public EmailConfiguration(@Autowired(required = false) JavaMailSender javaMailSender,
                              EmailProperties emailProperties) {
        if (javaMailSender == null || Strings.isNullOrEmpty(emailProperties.getAddress())) {
            log.error(ConsoleHelper.red("CONFIG (Email): Email or Password not found {}"), emailProperties.getAddress());
            EMAIL_ENABLED = false;
        } else {
            EMAIL_ENABLED = true;
            log.info(ConsoleHelper.green("Email Initialized"));
        }
    }

    public static Boolean isEmailSet() {
        return EMAIL_ENABLED;
    }

}

Move optional autowired inside constructor


package mod.flatcoloredblocks.gui;

import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.fml.client.FMLConfigGuiFactory;

/**
 * Basic Config Factory.
 */
public class ConfigGuiFactory extends FMLConfigGuiFactory
{

	@Override
	public Class<? extends GuiScreen> mainConfigGuiClass()
	{
		return ConfigGui.class;
	}

}

package mod.flatcoloredblocks.gui;

import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.fml.client.FMLConfigGuiFactory;

/**
 * Basic Config Factory.
 */
public class ConfigGuiFactory extends FMLConfigGuiFactory
{

	@Override
	public GuiScreen createConfigGui(
			GuiScreen parentScreen )
	{
		return new ConfigGui( parentScreen );
	}

}

Use createConfigGui instead of mainConfigGuiClass


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

package org.slf4j.impl;

import org.slf4j.spi.LoggerFactoryBinder;
import org.slf4j.ILoggerFactory;

public final class StaticLoggerBinder implements LoggerFactoryBinder {

    public ILoggerFactory getLoggerFactory() {
        return new Slf4jLoggerFactory();
    }

    public String getLoggerFactoryClassStr() {
        return Slf4jLoggerFactory.class.getName();
    }
}

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

package org.slf4j.impl;

import org.slf4j.spi.LoggerFactoryBinder;
import org.slf4j.ILoggerFactory;

public final class StaticLoggerBinder implements LoggerFactoryBinder {

    public static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();

    public ILoggerFactory getLoggerFactory() {
        return new Slf4jLoggerFactory();
    }

    public String getLoggerFactoryClassStr() {
        return Slf4jLoggerFactory.class.getName();
    }
}

Add apparently important SINGLETON field


package com.nikita.recipiesapp.common;

import com.nikita.recipiesapp.common.models.Recipe;

import java.util.List;

public final class AppState {
  public final List<Recipe> recipes;

  private final String selectedRecipeId;
  private final String selectedStepId;

  public AppState(List<Recipe> recipes,
                  String selectedRecipeId,
                  String selectedStepId) {
    this.recipes = recipes;
    this.selectedRecipeId = selectedRecipeId;
    this.selectedStepId = selectedStepId;
  }
}

package com.nikita.recipiesapp.common;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.nikita.recipiesapp.common.models.Recipe;
import com.nikita.recipiesapp.common.models.Step;

import java.util.Collections;
import java.util.List;

public final class AppState {
  public final boolean isLoading;
  @Nullable
  public final String notification;
  @Nullable
  public final String error;

  @NonNull
  public final List<Recipe> recipes;

  @NonNull
  private final String selectedRecipeId;
  @NonNull
  private final String selectedStepId;

  public AppState(boolean isLoading,
                  String notification,
                  String error,
                  List<Recipe> recipes,
                  String selectedRecipeId,
                  String selectedStepId) {
    this.isLoading = isLoading;
    this.notification = notification;
    this.error = error;
    this.recipes = recipes;
    this.selectedRecipeId = selectedRecipeId;
    this.selectedStepId = selectedStepId;
  }

  public static AppState create(boolean isLoading,
                                String notification,
                                String error,
                                List<Recipe> recipes,
                                String selectedRecipeId,
                                String selectedStepId) {
    return new AppState(isLoading, notification, error, recipes, selectedRecipeId, selectedStepId);
  }

  public static AppState initial() {
    return create(true, null, null, Collections.emptyList(), "", "");
  }

  public AppState withLoading(boolean isLoading) {
    return create(isLoading, notification, error, recipes, selectedRecipeId, selectedStepId);
  }

  public AppState withNotification(@NonNull String notification) {
    return create(isLoading, notification, error, recipes, selectedRecipeId, selectedStepId);
  }

  public AppState withError(@NonNull String error) {
    return create(isLoading, notification, error, recipes, selectedRecipeId, selectedStepId);
  }

  public AppState withRecipes(@NonNull List<Recipe> recipes) {
    return create(isLoading, notification, error, recipes, selectedRecipeId, selectedStepId);
  }

  public AppState withSelectedRecipe(@NonNull Recipe recipe) {
    return create(isLoading, notification, error, recipes, recipe.id, selectedStepId);
  }

  public AppState withSelectedStep(@NonNull Step step) {
    return create(isLoading, notification, error, recipes, selectedRecipeId, step.id);
  }
}

Add app state mutation methods


package com.zaxxer.hikari.json.util;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

import com.zaxxer.hikari.json.JsonProperty;

public final class Clazz
{
   private final Class<?> actualClass;
   private final Map<Integer, Phield> fields;

   public Clazz(Class<?> clazz)
   {
      this.actualClass = clazz;
      this.fields = new HashMap<>();
   }

   void parseFields()
   {
      for (Field field : actualClass.getDeclaredFields()) {
         if (!Modifier.isStatic(field.getModifiers())) {
            JsonProperty jsonProperty = field.getAnnotation(JsonProperty.class);
            boolean excluded = (jsonProperty != null && jsonProperty.exclude());

            Phield phield = new Phield(field, excluded);
            if (jsonProperty != null) {
               fields.put(jsonProperty.name().hashCode(), phield);
            }
            else {
               fields.put(field.getName().hashCode(), phield);
               fields.put(field.getName().toLowerCase().hashCode(), phield);
            }
         }
      }
   }

   public Class<?> getActualClass() {
      return actualClass;
   }

   public Phield getPhield(final int hashCode) {
      return fields.get(hashCode);
   }

   @Override
   public String toString()
   {
      return "Clazz [" + actualClass.getCanonicalName() + "]";
   }

   public Object newInstance() throws InstantiationException, IllegalAccessException
   {
      return actualClass.newInstance();
   }
}

package com.zaxxer.hikari.json.util;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

import com.zaxxer.hikari.json.JsonProperty;

public final class Clazz
{
   private final Class<?> actualClass;
   private final Map<Integer, Phield> fields;

   public Clazz(Class<?> clazz)
   {
      this.actualClass = clazz;
      this.fields = new HashMap<>((int)(actualClass.getDeclaredFields().length * 1.3));
   }

   void parseFields()
   {
      for (Field field : actualClass.getDeclaredFields()) {
         if (!Modifier.isStatic(field.getModifiers())) {
            JsonProperty jsonProperty = field.getAnnotation(JsonProperty.class);
            boolean excluded = (jsonProperty != null && jsonProperty.exclude());

            Phield phield = new Phield(field, excluded);
            if (jsonProperty != null) {
               fields.put(jsonProperty.name().hashCode(), phield);
            }
            else {
               fields.put(field.getName().hashCode(), phield);
               fields.put(field.getName().toLowerCase().hashCode(), phield);
            }
         }
      }
   }

   public Class<?> getActualClass() {
      return actualClass;
   }

   public Phield getPhield(final int hashCode) {
      return fields.get(hashCode);
   }

   @Override
   public String toString()
   {
      return "Clazz [" + actualClass.getCanonicalName() + "]";
   }

   public Object newInstance() throws InstantiationException, IllegalAccessException
   {
      return actualClass.newInstance();
   }
}

Set initial hash size (should be tuned more).


package net.glowstone.io.entity;

import net.glowstone.entity.passive.GlowWolf;
import net.glowstone.util.nbt.CompoundTag;
import org.bukkit.DyeColor;
import org.bukkit.entity.EntityType;

class WolfStore extends TameableStore<GlowWolf> {

    public WolfStore() {
        super(GlowWolf.class, EntityType.WOLF);
    }

    @Override
    public void load(GlowWolf entity, CompoundTag compound) {
        super.load(entity, compound);
        entity.setCollarColor(DyeColor.getByDyeData(compound.getByte("CollarColor")));
        entity.setAngry(compound.getBool("Angry"));
    }

    @Override
    public void save(GlowWolf entity, CompoundTag tag) {
        super.save(entity, tag);
        tag.putByte("CollarColor", entity.getCollarColor().getDyeData());
        tag.putBool("Angry", entity.isAngry());
    }

}

package net.glowstone.io.entity;

import net.glowstone.entity.passive.GlowWolf;
import net.glowstone.util.nbt.CompoundTag;
import org.bukkit.DyeColor;
import org.bukkit.entity.EntityType;

class WolfStore extends TameableStore<GlowWolf> {

    public WolfStore() {
        super(GlowWolf.class, EntityType.WOLF);
    }

    @Override
    public void load(GlowWolf entity, CompoundTag compound) {
        super.load(entity, compound);
        if (compound.isByte("CollarColor")) {
            entity.setCollarColor(DyeColor.getByDyeData(compound.getByte("CollarColor")));
        }
        if (compound.isByte("Angry")) {
            entity.setAngry(compound.getBool("Angry"));
        }
    }

    @Override
    public void save(GlowWolf entity, CompoundTag tag) {
        super.save(entity, tag);
        tag.putByte("CollarColor", entity.getCollarColor().getDyeData());
        tag.putBool("Angry", entity.isAngry());
    }

}

Fix exception when spawning Wolf from egg


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

package org.gradle.api.tasks;

import org.gradle.api.Action;
import org.gradle.api.Incubating;
import org.gradle.api.Task;
import org.gradle.api.provider.Provider;

/**
 * Providers a task of the given type.
 *
 * @param <T> Task type
 * @since 4.8
 */
@Incubating
public interface TaskProvider<T extends Task> extends Provider<T> {
    /**
     * Configures the task with the given action. Actions are run in the order added.
     *
     * @param action A {@link Action} that can configure the task when required.
     * @since 4.8
     */
    void configure(Action<? super T> action);

    /**
     * The task name referenced by this provider.
     * <p>
     * Must be constant for the life of the object.
     *
     * @return The task name. Never null.
     * @since 4.10
     */
    String getName();
}

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

package org.gradle.api.tasks;

import org.gradle.api.Action;
import org.gradle.api.Incubating;
import org.gradle.api.Task;
import org.gradle.api.provider.Provider;

/**
 * Providers a task of the given type.
 *
 * @param <T> Task type
 * @since 4.8
 */
@Incubating
public interface TaskProvider<T extends Task> extends Provider<T> {
    /**
     * Configures the task with the given action. Actions are run in the order added.
     *
     * @param action A {@link Action} that can configure the task when required.
     * @since 4.8
     */
    void configure(Action<? super T> action);

    /**
     * The task name referenced by this provider.
     * <p>
     * Must be constant for the life of the object.
     *
     * @return The task name. Never null.
     * @since 4.9
     */
    String getName();
}

Revert "Hackily unblock the build"


package at.lingu.sqlcompose;

import at.lingu.sqlcompose.projection.Projection;
import at.lingu.sqlcompose.source.Table;
import org.junit.Test;

/**
 * Tests for select statements.
 *
 * @author Florian Fankhauser <flo@lingu.at>
 */
public class SelectTests extends BaseSqlTests {

	private Table users = new Table("users");

	@Test
	public void testSelectAllFields() {

		Select select = new Select(users)
				.project(Projection.ALL);

		generateResult(select);

		assertSql("SELECT * FROM users");
		assertNoParams();
	}

	@Test
	public void testSelectFields() {
		Select select = new Select(users)
				.project(
						users.column("id"),
						users.column("last_name"),
						users.column("first_name"));

		generateResult(select);

		assertSql("SELECT id, last_name, first_name FROM users");
		assertNoParams();
	}

}

package at.lingu.sqlcompose;

import at.lingu.sqlcompose.projection.Projection;
import at.lingu.sqlcompose.source.Table;
import org.junit.Test;

/**
 * Tests for select statements.
 *
 * @author Florian Fankhauser <flo@lingu.at>
 */
public class SelectTests extends BaseSqlTests {

	private Table users = new Table("users");

	@Test
	public void testSelectAllFields() {

		Select select = new Select(users)
				.project(Projection.ALL);

		generateResult(select);

		assertSql("SELECT * FROM users");
		assertNoParams();
	}

	@Test
	public void testSelectFields() {
		Select select = new Select(users)
				.project(
						users.column("id"),
						users.column("last_name"),
						users.column("first_name"));

		generateResult(select);

		assertSql("SELECT id, last_name, first_name FROM users");
		assertNoParams();
	}

	@Test
	public void testSelectFieldsWithAlias() {
		Select select = new Select(users)
				.project(
						users.column("id").as("user_id"),
						users.column("last_name").as("l_name"),
						users.column("first_name").as("f_name"));

		generateResult(select);

		assertSql("SELECT id AS user_id, last_name AS l_name, "
				+ "first_name AS f_name FROM users");
		assertNoParams();
	}
}

Add test for projection alias


package com.thinkaurelius.titan.util.system;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;

public class NetworkUtil {
    public static String getLoopbackAddress() {
        return InetAddress.getLoopbackAddress().getHostAddress();
    }

    public static InetAddress getLocalHost() {
        try {
            return InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            throw new AssertionError(e);
        }
    }

    public static String getLocalAddress() {
        return getLocalHost().getHostAddress();
    }

    public static String getLocalHostName() {
        return getLocalHost().getHostName();
    }

    public static boolean hasLocalAddress(Collection<String> endpoints) {
        return endpoints.contains(getLoopbackAddress()) || endpoints.contains(getLocalAddress()) || endpoints.contains(getLocalHostName());
    }

    public static boolean isLocalConnection(String hostname) {
        InetAddress localhost = NetworkUtil.getLocalHost();
        return hostname.equalsIgnoreCase(NetworkUtil.getLoopbackAddress())
                || hostname.equals(localhost.getHostAddress())
                || hostname.equals(localhost.getHostName());
    }
}

package com.thinkaurelius.titan.util.system;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;

public class NetworkUtil {
    public static String getLoopbackAddress() {
        return InetAddress.getLoopbackAddress().getHostAddress();
    }

    public static InetAddress getLocalHost() {
        try {
            return InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            throw new AssertionError(e);
        }
    }

    public static String getLocalAddress() {
        return getLocalHost().getHostAddress();
    }

    public static String getLocalHostName() {
        return getLocalHost().getHostName();
    }

    public static boolean hasLocalAddress(Collection<String> endpoints) {
        return endpoints.contains(getLoopbackAddress()) || endpoints.contains(getLocalAddress()) || endpoints.contains(getLocalHostName());
    }

    public static boolean isLocalConnection(String hostname) {
        InetAddress localhost = NetworkUtil.getLocalHost();
        return hostname.equalsIgnoreCase(NetworkUtil.getLoopbackAddress())
                || hostname.equals(localhost.getHostAddress())
                || hostname.equals(localhost.getHostName())
                || hostname.equals(localhost.getCanonicalHostName());
    }
}

Make isLocalAddress(...) allow canonical addresses