/*
 * Copyright 2014 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 net.kuujo.copycat.vertx;

import org.vertx.java.core.Vertx;

import java.util.concurrent.Executor;

/**
 * Vert.x execution context.
 *
 * @author Jordan Halterman
 */
public class VertxEventLoopExecutor implements Executor {
  private final Vertx vertx;

  public VertxEventLoopExecutor(Vertx vertx) {
    this.vertx = vertx;
  }

  @Override
  public void execute(Runnable command) {
    vertx.runOnContext(v -> command.run());
  }

}

/*
 * Copyright 2014 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 net.kuujo.copycat.vertx;

import org.vertx.java.core.Context;
import org.vertx.java.core.Vertx;

import java.util.concurrent.Executor;

/**
 * Vert.x execution context.
 *
 * @author Jordan Halterman
 */
public class VertxEventLoopExecutor implements Executor {
  private final Context context;

  public VertxEventLoopExecutor(Vertx vertx) {
    this.context = vertx.currentContext();
  }

  @Override
  public void execute(Runnable command) {
    context.runOnContext(v -> command.run());
  }

}

Refactor Vert.x 2 event loop context to store context upon construction in order to prevent issues with calling runOnContext from a non-context thread.


package io.keen.client.java;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * Tests AttemptCountingEventStore implementations.
 *
 * @author Simon Murtha Smith
 * @since 2.0.2
 */
public abstract class AttemptCountingEventStoreTestBase extends EventStoreTestBase {

    protected KeenAttemptCountingEventStore attemptCountingStore;

    @Before
    public void castStore() throws Exception {
        attemptCountingStore = (KeenAttemptCountingEventStore)store;
    }

    @Test
    public void storeAndGetEventAttempts() throws Exception {
        String attempts = "blargh";
        attemptCountingStore.setAttempts("project1", "collection1", attempts);
        assertEquals(attempts, attemptCountingStore.getAttempts("project1", "collection1"));
    }
}

package io.keen.client.java;

import org.junit.Before;
import org.junit.Test;

import java.util.List;
import java.util.Map;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

/**
 * Tests AttemptCountingEventStore implementations.
 *
 * @author Simon Murtha Smith
 * @since 2.0.2
 */
public abstract class AttemptCountingEventStoreTestBase extends EventStoreTestBase {

    protected KeenAttemptCountingEventStore attemptCountingStore;

    @Before
    public void castStore() throws Exception {
        attemptCountingStore = (KeenAttemptCountingEventStore)store;
    }

    @Test
    public void storeAndGetEventAttempts() throws Exception {
        String attempts = "blargh";
        attemptCountingStore.setAttempts("project1", "collection1", attempts);
        assertEquals(attempts, attemptCountingStore.getAttempts("project1", "collection1"));
    }

    @Test
    public void getHandlesWithAttempts() throws Exception {
        // Add a couple events to the store.
        attemptCountingStore.store("project1", "collection1", TEST_EVENT_1);
        attemptCountingStore.store("project1", "collection2", TEST_EVENT_2);

        // set some value for attempts.json. This is to ensure that setting attempts doesn't
        // interfere with getting handles
        attemptCountingStore.setAttempts("project1", "collection1", "{}");

        // Get the handle map.
        Map<String, List<Object>> handleMap = attemptCountingStore.getHandles("project1");
        assertNotNull(handleMap);
        assertEquals(2, handleMap.size());

        // Get the lists of handles.
        List<Object> handles1 = handleMap.get("collection1");
        assertNotNull(handles1);
        assertEquals(1, handles1.size());
        List<Object> handles2 = handleMap.get("collection2");
        assertNotNull(handles2);
        assertEquals(1, handles2.size());

        // Validate the actual events.
        assertEquals(TEST_EVENT_1, attemptCountingStore.get(handles1.get(0)));
        assertEquals(TEST_EVENT_2, attemptCountingStore.get(handles2.get(0)));
    }
}

Add test for attempt.json fix.


package org.springframework.security.crypto.codec;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.util.*;

/**
 * UTF-8 Charset encoder/decoder.
 * <p>
 * For internal use only.
 *
 * @author Luke Taylor
 */
public final class Utf8 {
    private static final Charset CHARSET = Charset.forName("UTF-8");

    /**
     * Get the bytes of the String in UTF-8 encoded form.
     */
    public static byte[] encode(CharSequence string) {
        try {
            ByteBuffer bytes = CHARSET.newEncoder().encode(CharBuffer.wrap(string));

            return Arrays.copyOfRange(bytes.array(), 0, bytes.limit());
        } catch (CharacterCodingException e) {
            throw new IllegalArgumentException("Encoding failed", e);
        }
    }

    /**
     * Decode the bytes in UTF-8 form into a String.
     */
    public static String decode(byte[] bytes) {
        try {
            return CHARSET.newDecoder().decode(ByteBuffer.wrap(bytes)).toString();
        } catch (CharacterCodingException e) {
            throw new IllegalArgumentException("Decoding failed", e);
        }
    }
}

package org.springframework.security.crypto.codec;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.util.*;

/**
 * UTF-8 Charset encoder/decoder.
 * <p>
 * For internal use only.
 *
 * @author Luke Taylor
 */
public final class Utf8 {
    private static final Charset CHARSET = Charset.forName("UTF-8");

    /**
     * Get the bytes of the String in UTF-8 encoded form.
     */
    public static byte[] encode(CharSequence string) {
        try {
            ByteBuffer bytes = CHARSET.newEncoder().encode(CharBuffer.wrap(string));
            byte[] bytesCopy = new byte[bytes.limit()];
            System.arraycopy(bytes.array(), 0, bytesCopy, 0, bytes.limit());

            return bytesCopy;
        } catch (CharacterCodingException e) {
            throw new IllegalArgumentException("Encoding failed", e);
        }
    }

    /**
     * Decode the bytes in UTF-8 form into a String.
     */
    public static String decode(byte[] bytes) {
        try {
            return CHARSET.newDecoder().decode(ByteBuffer.wrap(bytes)).toString();
        } catch (CharacterCodingException e) {
            throw new IllegalArgumentException("Decoding failed", e);
        }
    }
}

Remove use of Java 6 method Arrays.copyOfRange.


package alien4cloud.paas.plan;

import static alien4cloud.paas.plan.ToscaNodeLifecycleConstants.*;
import static alien4cloud.paas.plan.ToscaRelationshipLifecycleConstants.*;

import alien4cloud.paas.model.PaaSNodeTemplate;

/**
 * Generates the default tosca build plan.
 */
public class BuildPlanGenerator extends AbstractPlanGenerator {
    @Override
    protected void generateNodeWorkflow(PaaSNodeTemplate node) {
        state(node.getId(), INITIAL);

        call(node, STANDARD, CREATE);
        state(node.getId(), CREATED);

        waitTarget(node, DEPENDS_ON, STARTED);
        waitSource(node, DEPENDS_ON, CREATED);

        callRelations(node, ToscaRelationshipLifecycleConstants.CONFIGURE, PRE_CONFIGURE_SOURCE, PRE_CONFIGURE_TARGET);

        call(node, STANDARD, ToscaNodeLifecycleConstants.CONFIGURE);
        state(node.getId(), CONFIGURED);

        callRelations(node, ToscaRelationshipLifecycleConstants.CONFIGURE, POST_CONFIGURE_SOURCE, POST_CONFIGURE_TARGET);

        call(node, STANDARD, START);
        state(node.getId(), STARTED);

        waitTarget(node, DEPENDS_ON, AVAILABLE);

        // synchronous add source / target implementation.
        callRelations(node, ToscaRelationshipLifecycleConstants.CONFIGURE, ADD_SOURCE, ADD_TARGET);

        call(node, STANDARD, POST_START);
        state(node.getId(), AVAILABLE);

        // process child nodes.
        parallel(node.getChildren());
    }
}

package alien4cloud.paas.plan;

import static alien4cloud.paas.plan.ToscaNodeLifecycleConstants.*;
import static alien4cloud.paas.plan.ToscaRelationshipLifecycleConstants.*;
import alien4cloud.paas.model.PaaSNodeTemplate;

/**
 * Generates the default tosca build plan.
 */
public class BuildPlanGenerator extends AbstractPlanGenerator {
    @Override
    protected void generateNodeWorkflow(PaaSNodeTemplate node) {
        state(node.getId(), INITIAL);

        call(node, STANDARD, CREATE);
        state(node.getId(), CREATED);

        waitTarget(node, DEPENDS_ON, STARTED);
        waitSource(node, DEPENDS_ON, CREATED);

        callRelations(node, ToscaRelationshipLifecycleConstants.CONFIGURE, PRE_CONFIGURE_SOURCE, PRE_CONFIGURE_TARGET);

        call(node, STANDARD, ToscaNodeLifecycleConstants.CONFIGURE);
        state(node.getId(), CONFIGURED);

        callRelations(node, ToscaRelationshipLifecycleConstants.CONFIGURE, POST_CONFIGURE_SOURCE, POST_CONFIGURE_TARGET);

        call(node, STANDARD, START);
        state(node.getId(), STARTED);

        waitTarget(node, DEPENDS_ON, AVAILABLE);

        // synchronous add source / target implementation.
        callRelations(node, ToscaRelationshipLifecycleConstants.CONFIGURE, ADD_SOURCE, ADD_TARGET);

        state(node.getId(), AVAILABLE);

        // process child nodes.
        parallel(node.getChildren());
    }
}

Remove post start as TOSCA agreed to remove it.


package com.leakedbits.codelabs;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;

public class Main {
	public static void main(String[] args) {
		LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
		cfg.title = Codelabs.TITLE;
		cfg.useGL20 = false;
		cfg.width = 480;
		cfg.height = 320;

		new LwjglApplication(new Codelabs(), cfg);
	}
}

package com.leakedbits.codelabs;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;

public class Main {
	public static void main(String[] args) {
		LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
		cfg.title = Codelabs.TITLE;
		cfg.useGL20 = false;
		cfg.width = 800;
		cfg.height = 600;

		new LwjglApplication(new Codelabs(), cfg);
	}
}

Change desktop app resolution to 800x600


package com.novoda.downloadmanager;

import java.util.Map;

class DownloadManagerRequest {

    private final Map<String, String> headers;
    private final String url;
    private final Method method;

    DownloadManagerRequest(Map<String, String> headers, String url, Method method) {
        this.headers = headers;
        this.url = url;
        this.method = method;
    }

    Map<String, String> headers() {
        return headers;
    }

    String url() {
        return url;
    }

    Method method() {
        return method;
    }

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

        DownloadManagerRequest that = (DownloadManagerRequest) o;

        if (!headers.equals(that.headers)) {
            return false;
        }
        if (!url.equals(that.url)) {
            return false;
        }
        return method == that.method;
    }

    @Override
    public int hashCode() {
        int result = headers.hashCode();
        result = 31 * result + url.hashCode();
        result = 31 * result + method.hashCode();
        return result;
    }

    enum Method {
        GET("get"),
        HEAD("head");

        private final String rawMethod;

        Method(String rawMethod) {
            this.rawMethod = rawMethod;
        }

        public String rawMethod() {
            return rawMethod;
        }
    }

}

package com.novoda.downloadmanager;

import java.util.Map;

class DownloadManagerRequest {

    private final Map<String, String> headers;
    private final String url;
    private final Method method;

    DownloadManagerRequest(Map<String, String> headers, String url, Method method) {
        this.headers = headers;
        this.url = url;
        this.method = method;
    }

    Map<String, String> headers() {
        return headers;
    }

    String url() {
        return url;
    }

    Method method() {
        return method;
    }

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

        DownloadManagerRequest that = (DownloadManagerRequest) o;

        if (!headers.equals(that.headers)) {
            return false;
        }
        if (!url.equals(that.url)) {
            return false;
        }
        return method == that.method;
    }

    @Override
    public int hashCode() {
        int result = headers.hashCode();
        result = 31 * result + url.hashCode();
        result = 31 * result + method.hashCode();
        return result;
    }

    enum Method {
        GET("get"),
        HEAD("head");

        private final String rawMethod;

        Method(String rawMethod) {
            this.rawMethod = rawMethod;
        }

        String rawMethod() {
            return rawMethod;
        }
    }

}

Remove public modifier from Method getter.


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

package net.uncontended.precipice;

public interface BackPressure<Rejected extends Enum<Rejected>> {

    Rejected acquirePermit(long number, long nanoTime);

    void releasePermit(long number, long nanoTime);

    void releasePermit(long number, Failable result, long nanoTime);
}

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

package net.uncontended.precipice;

public interface BackPressure<Rejected extends Enum<Rejected>> {

    Rejected acquirePermit(long number, long nanoTime);

    void releasePermit(long number, long nanoTime);

    void releasePermit(long number, Failable result, long nanoTime);

    // <Result extends Enum<Result> & Failable> void registerGuardRail(GuardRail<Result, Rejected> guardRail);
}

Add GR register method commented out


/*
 * Copyright (C) 2009 XStream Committers.
 * All rights reserved.
 *
 * Created on 15. August 2009 by Joerg Schaible
 */
package com.thoughtworks.xstream.io.xml;

/**
 * A XmlFriendlyNameCoder to support backward compatibility with XStream 1.1.
 *
 * @author Jörg Schaible
 * @since upcoming
 */
public class XStream11NameCoder extends XmlFriendlyNameCoder {

    /**
     * {@inheritDoc} Noop implementation that does not decode. Used for XStream 1.1
     * compatibility.
     */
    public String decodeAttribute(String attributeName) {
        return attributeName;
    }

    /**
     * {@inheritDoc} Noop implementation that does not decode. Used for XStream 1.1
     * compatibility.
     */
    public String decodeNode(String elementName) {
        return elementName;
    }
}

/*
 * Copyright (C) 2009 XStream Committers.
 * All rights reserved.
 *
 * The software in this package is published under the terms of the BSD
 * style license a copy of which has been included with this distribution in
 * the LICENSE.txt file.
 *
 * Created on 15. August 2009 by Joerg Schaible
 */
package com.thoughtworks.xstream.io.xml;

/**
 * A XmlFriendlyNameCoder to support backward compatibility with XStream 1.1.
 *
 * @author Jörg Schaible
 * @since upcoming
 */
public class XStream11NameCoder extends XmlFriendlyNameCoder {

    /**
     * {@inheritDoc} Noop implementation that does not decode. Used for XStream 1.1
     * compatibility.
     */
    public String decodeAttribute(String attributeName) {
        return attributeName;
    }

    /**
     * {@inheritDoc} Noop implementation that does not decode. Used for XStream 1.1
     * compatibility.
     */
    public String decodeNode(String elementName) {
        return elementName;
    }
}

Fix file headers for missing BSD license.


package org.jboss.as.console.client.rbac;

import com.google.gwt.user.client.History;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.PopupView;
import com.gwtplatform.mvp.client.PresenterWidget;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import org.jboss.ballroom.client.layout.LHSHighlightEvent;
import org.jboss.ballroom.client.rbac.AuthorisationDecision;

import javax.inject.Inject;

/**
 * @author Heiko Braun
 * @date 7/24/13
 */
public class UnauthorisedPresenter extends PresenterWidget<UnauthorisedPresenter.MyView>
    implements AuthDecisionEvent.AuthDecisionHandler {

    /**
     * {@link UnauthorisedPresenter}'s view.
     */
    public interface MyView extends PopupView {
        void setPresenter(UnauthorisedPresenter unauthorisedPresenter);

        void setLastDecision(AuthorisationDecision decision);
    }

    @Inject
    public UnauthorisedPresenter(EventBus eventBus, MyView view) {
        super(eventBus, view);
        view.setPresenter(this);
        eventBus.addHandler(AuthDecisionEvent.TYPE, this);
    }

    public void onConfirmation() {
        History.back();
    }

    @Override
    public void onAuthDescision(AuthDecisionEvent event) {
        getView().setLastDecision(event.getDecision());
    }
}

package org.jboss.as.console.client.rbac;

import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.PopupView;
import com.gwtplatform.mvp.client.PresenterWidget;
import org.jboss.as.console.client.Console;
import org.jboss.ballroom.client.rbac.AuthorisationDecision;

import javax.inject.Inject;

/**
 * @author Heiko Braun
 * @date 7/24/13
 */
public class UnauthorisedPresenter extends PresenterWidget<UnauthorisedPresenter.MyView>
        implements AuthDecisionEvent.AuthDecisionHandler {

    /**
     * {@link UnauthorisedPresenter}'s view.
     */
    public interface MyView extends PopupView {
        void setPresenter(UnauthorisedPresenter unauthorisedPresenter);

        void setLastDecision(AuthorisationDecision decision);
    }

    @Inject
    public UnauthorisedPresenter(EventBus eventBus, MyView view) {
        super(eventBus, view);
        view.setPresenter(this);
        eventBus.addHandler(AuthDecisionEvent.TYPE, this);
    }

    public void onConfirmation() {
        Console.MODULES.getPlaceManager().revealDefaultPlace();
    }

    @Override
    public void onAuthDescision(AuthDecisionEvent event) {
        getView().setLastDecision(event.getDecision());
    }
}

Disable History.back() upon auth errors


package org.jboss.aerogear.unifiedpush.rest;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.datastax.driver.core.utils.UUIDs;
import com.qmino.miredot.annotations.ReturnType;

@Path("/hartbeat")
public class HartbeatEndpoint extends AbstractBaseEndpoint {
	/**
	 * Hartbeat Endpoint
	 *
	 * @return Hartbeat in form of time-based UUID.
	 * @statuscode 200 Successful response for your request
	 */
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	@ReturnType("java.lang.String")
	public Response hartbeat(@Context HttpServletRequest request) {
		return appendAllowOriginHeader(Response.ok().entity(quote(UUIDs.timeBased().toString())), request);
	}
}

package org.jboss.aerogear.unifiedpush.rest;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.datastax.driver.core.utils.UUIDs;
import com.qmino.miredot.annotations.ReturnType;

@Path("/hartbeat")
public class HartbeatEndpoint extends AbstractBaseEndpoint {

	@OPTIONS
	@ReturnType("java.lang.Void")
	public Response crossOriginForApplication(@Context HttpHeaders headers) {
		return appendPreflightResponseHeaders(headers, Response.ok()).build();
	}

	/**
	 * Hartbeat Endpoint
	 *
	 * @return Hartbeat in form of time-based UUID.
	 * @statuscode 200 Successful response for your request
	 */
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	@ReturnType("java.lang.String")
	public Response hartbeat(@Context HttpServletRequest request) {
		return appendAllowOriginHeader(Response.ok().entity(quote(UUIDs.timeBased().toString())), request);
	}
}

Add OPTIONS to hartbeat API


package com.hosseini.persian.dt.PersianDate.enumCollections;

/**
 * Month name and month number
 */
public enum Months {

    /*
    * dont worry we just use values */
    Farvardin("فروردین", 1),
    Ordibehesht("ارديبهشت", 2),
    Khordad("خرداد", 3),
    tir("تير", 4),
    Mordad("مرداد", 5),
    shahrivar("شهريور", 6),
    Mehr("مهر", 7),
    Aban("آبان", 8),
    Azar("آذر", 9),
    Dy("دي", 10),
    Bahman("بهمن", 11),
    Esfand("اسفند", 12);

    private String monthS;
    private int monthI;

    Months(String name, int index) {
        this.monthS = name;
        this.monthI = index;
    }

    /**
     * Getter for property 'monthAsString'.
     *
     * @return Value for property 'monthAsString'.
     */
    public String getMonthAsString() {
        return monthS;
    }

    /**
     * Getter for property 'monthAsInt'.
     *
     * @return Value for property 'monthAsInt'.
     */
    public int getMonthAsInt() {
        return monthI;
    }
}

package com.hosseini.persian.dt.PersianDate.enumCollections;

/**
 * Month name and month number
 */
public enum Months {

    /*
    * dont worry we just use values */
    Farvardin("فروردین", 1),
    Ordibehesht("اردیبهشت", 2),
    Khordad("خرداد", 3),
    tir("تیر", 4),
    Mordad("مرداد", 5),
    shahrivar("شهریور", 6),
    Mehr("مهر", 7),
    Aban("آبان", 8),
    Azar("آذر", 9),
    Dy("دی", 10),
    Bahman("بهمن", 11),
    Esfand("اسفند", 12);

    private String monthS;
    private int monthI;

    Months(String name, int index) {
        this.monthS = name;
        this.monthI = index;
    }

    /**
     * Getter for property 'monthAsString'.
     *
     * @return Value for property 'monthAsString'.
     */
    public String getMonthAsString() {
        return monthS;
    }

    /**
     * Getter for property 'monthAsInt'.
     *
     * @return Value for property 'monthAsInt'.
     */
    public int getMonthAsInt() {
        return monthI;
    }
}

Replace Arabic char with Persian one


package com.braintreepayments.api.test;

public class ExpirationDate {

    public static final String VALID_EXPIRATION = "12/19";
}

package com.braintreepayments.api.test;

public class ExpirationDate {

    public static final String VALID_EXPIRATION = "1219";
}

Fix failing tests caused by invalid expiration date


package totemic_commons.pokefenn.ceremony;

import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
import totemic_commons.pokefenn.api.ceremony.Ceremony;
import totemic_commons.pokefenn.api.music.MusicInstrument;
import totemic_commons.pokefenn.entity.boss.EntityBaykok;
import totemic_commons.pokefenn.util.EntityUtil;

public class CeremonyBaykok extends Ceremony
{
    public CeremonyBaykok(String name, int musicNeeded, int maxStartupTime, MusicInstrument... instruments)
    {
        super(name, musicNeeded, maxStartupTime, instruments);
    }

    @Override
    public void effect(World world, BlockPos pos, int time)
    {
        BlockPos spos = pos.offset(EnumFacing.getHorizontal(world.rand.nextInt(4)));
        EntityUtil.spawnEntity(world, spos.getX() + 0.5, spos.getY(), spos.getZ() + 0.5, new EntityBaykok(world));
    }

}

package totemic_commons.pokefenn.ceremony;

import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
import totemic_commons.pokefenn.api.ceremony.Ceremony;
import totemic_commons.pokefenn.api.music.MusicInstrument;
import totemic_commons.pokefenn.entity.boss.EntityBaykok;
import totemic_commons.pokefenn.util.EntityUtil;

public class CeremonyBaykok extends Ceremony
{
    public CeremonyBaykok(String name, int musicNeeded, int maxStartupTime, MusicInstrument... instruments)
    {
        super(name, musicNeeded, maxStartupTime, instruments);
    }

    @Override
    public void effect(World world, BlockPos pos, int time)
    {
        if(world.isRemote || time != getEffectTime() - 1)
            return;

        world.playBroadcastSound(1013, pos, 0); //Wither spawn sound
        BlockPos spos = pos.offset(EnumFacing.getHorizontal(world.rand.nextInt(4)));
        EntityUtil.spawnEntity(world, spos.getX() + 0.5, spos.getY(), spos.getZ() + 0.5, new EntityBaykok(world));
    }

    @Override
    public int getEffectTime()
    {
        return 3 * 20;
    }
}

Add delay to Baykok spawn and play sound


/*
 * Copyright 2011 Mikhail Lopatkin
 *
 * 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.bitbucket.mlopatkin.android.liblogcat;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class ProcessListParserTest {

    private static final String PS_LINE_1 = "root      1     0     244    228   fg  ffffffff 00000000 S /init";

    @Test
    public void testParseProcessListLine() {
        assertTrue(ProcessListParser.parseProcessListLine(PS_LINE_1).matches());
    }

}

/*
 * Copyright 2011 Mikhail Lopatkin
 *
 * 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.bitbucket.mlopatkin.android.liblogcat;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class ProcessListParserTest {

    private static final String PS_LINE_1 = "root      1     0     244    228   fg  ffffffff 00000000 S /init";
    private static final String PS_LINE_TWO_WORDS_PNAME = "root      279   2     0      0     fg  ffffffff 00000000 S Two words";

    @Test
    public void testParseProcessListLine() {
        assertTrue(ProcessListParser.parseProcessListLine(PS_LINE_1).matches());
    }

    @Test
    public void testParseProcessNameWithSpaces() {
        assertTrue(ProcessListParser.parseProcessListLine(PS_LINE_TWO_WORDS_PNAME).matches());
    }
}

Test for process name consisting of several words


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

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class URLStreams {
    private URLStreams() {

    }

    /**
     * Opens an {@link InputStream} reading from the given URL without
     * caching the stream. This prevents file descriptor leaks when reading
     * from file system URLs.
     *
     * @param url the URL to connect to
     * @return an input stream reading from the URL connection
     */
    public static InputStream openUncachedStream(URL url) throws IOException {
        URLConnection urlConnection = url.openConnection();
        urlConnection.setUseCaches(false);
        return urlConnection.getInputStream();
    }
}

Add the missing license header


package com.clipsub.rnbottomsheet;

import android.app.Activity;

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.ArrayList;
import java.util.Collections;
import java.util.List;

public class RNBottomSheetPackage implements ReactPackage {
    public RNBottomSheetPackage() {
        super();
    }

    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();
        modules.add(new RNBottomSheet(reactContext));

        return modules;
    }

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

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }
}

package com.clipsub.rnbottomsheet;

import android.app.Activity;

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.ArrayList;
import java.util.Collections;
import java.util.List;

public class RNBottomSheetPackage implements ReactPackage {
    public RNBottomSheetPackage() {
        super();
    }

    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();
        modules.add(new RNBottomSheet(reactContext));

        return modules;
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }
}

Fix Android compilation error with RN 0.47


package seedu.ezdo.model.task;

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

import org.junit.Test;

import seedu.ezdo.model.todo.StartDate;

public class StartDateTest {

    @Test
    public void isValidStartDate() {
        // invalid dates
        assertFalse(StartDate.isValidTaskDate(" ")); // spaces only
        assertFalse(StartDate.isValidTaskDate("next")); // non-numeric
        assertFalse(StartDate.isValidTaskDate("13 12 1999")); // spaces within
                                                              // digits
        assertFalse(StartDate.isValidTaskDate("05.10.1977")); // fullstops
                                                              // within digits
        assertFalse(StartDate.isValidTaskDate("22/11/q2r1")); // alphabets
                                                              // within digits

        // valid dates
        assertTrue(StartDate.isValidTaskDate("15/12/1992 10:12")); // month with
                                                                   // 31 days
        assertTrue(StartDate.isValidTaskDate("11/02/2014 07:21")); // month with
                                                                   // 30 days
        assertTrue(StartDate.isValidTaskDate("29/02/2003 20:21")); // leap year
    }

}

Remove trailing whitespace in line 31


package pl.edu.agh.amber.location;

import pl.edu.agh.amber.common.FutureObject;

public class LocationCurrent extends FutureObject {

	private double X;
	private double Y;
	private double angle;
	private double P;
	private double timeStamp;

	public LocationCurrent() {

	}

	public LocationCurrent(double x, double y, double angle, double p,
			double timeStamp) {
		this.X = x;
		this.Y = y;
		this.angle = angle;
		this.P = p;
		this.timeStamp = timeStamp;
	}

	public double getX() throws Exception {
		return X;
	}

	public void setX(double x) {
		this.X = x;
	}

	public double getY() throws Exception {
		return Y;
	}

	public void setY(double y) {
		this.Y = y;
	}

	public double getAngle() throws Exception {
		return angle;
	}

	public void setAngle(double angle) {
		this.angle = angle;
	}

	public double getP() throws Exception {
		return P;
	}

	public void setP(double p) {
		this.P = p;
	}

	public double getTimeStamp() throws Exception {
		return timeStamp;
	}

	public void setTimeStamp(double timeStamp) {
		this.timeStamp = timeStamp;
	}
}

Remove waitAvailable from location result, update handling location message


package br.com.bloder.blormlib.validation;

import br.com.bloder.blormlib.validation.validations.Checked;
import br.com.bloder.blormlib.validation.validations.Email;
import br.com.bloder.blormlib.validation.validations.Filled;
import br.com.bloder.blormlib.validation.validations.Number;

/**
 * Created by bloder on 05/06/16.
 */
public class Validations {

  public static Validation filled = new Filled();
  public static Validation checked = new Checked();
  public static Validation email = new Email();
  public static Number number = new Number();
}

package br.com.bloder.blormlib.validation;

import br.com.bloder.blormlib.validation.validations.Checked;
import br.com.bloder.blormlib.validation.validations.Email;
import br.com.bloder.blormlib.validation.validations.Filled;
import br.com.bloder.blormlib.validation.validations.Number;

/**
 * Created by bloder on 05/06/16.
 */
public class Validations {

  public static Filled filled = new Filled();
  public static Validation checked = new Checked();
  public static Validation email = new Email();
  public static Number number = new Number();
}

Change Validation type to Filled


package com.janosgyerik.utils.algorithm.unionfind;

import org.assertj.core.util.VisibleForTesting;

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

public class UnionFindImpl implements UnionFind {

    private final Map<Integer, Integer> ids = new HashMap<>();

    @Override
    public void union(int p, int q) {
        add(p);
        add(q);
        ids.put(root(p), root(q));
    }

    private void add(int p) {
        if (!ids.containsKey(p)) {
            ids.put(p, p);
        }
    }

    private int root(int p) {
        int root = p;
        while (root != ids.get(root)) {
            int parent = ids.get(ids.get(root));
            ids.put(root, parent);
            root = parent;
        }
        return root;
    }

    @Override
    public boolean connected(int p, int q) {
        return root(p) == root(q);
    }

    @Override
    public int find(int p) {
        return ids.get(p);
    }

    @VisibleForTesting
    Map<Integer, Integer> getIds() {
        return ids;
    }
}

package com.janosgyerik.utils.algorithm.unionfind;

import org.assertj.core.util.VisibleForTesting;

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

public class UnionFindImpl implements UnionFind {

    private final Map<Integer, Integer> ids = new HashMap<>();

    @Override
    public void union(int p, int q) {
        add(p);
        add(q);
        ids.put(root(p), root(q));
    }

    private void add(int p) {
        ids.putIfAbsent(p, p);
    }

    private int root(int p) {
        int root = p;
        while (root != ids.get(root)) {
            int parent = ids.get(ids.get(root));
            ids.put(root, parent);
            root = parent;
        }
        return root;
    }

    @Override
    public boolean connected(int p, int q) {
        return root(p) == root(q);
    }

    @Override
    public int find(int p) {
        return ids.get(p);
    }

    @VisibleForTesting
    Map<Integer, Integer> getIds() {
        return ids;
    }
}

Simplify using Java 8 putIfAbsent


// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.tenant;

import com.yahoo.path.Path;
import com.yahoo.vespa.config.server.TimeoutBudget;
import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.curator.recipes.CuratorLock;

import java.util.concurrent.TimeUnit;

/**
 * A lock to protect session activation.
 *
 * @author lulf
 * @since 5.1
 */
public class ActivateLock {

    private static final String ACTIVATE_LOCK_NAME = "activateLock";
    private final CuratorLock curatorLock;

    public ActivateLock(Curator curator, Path rootPath) {
        this.curatorLock = new CuratorLock(curator, rootPath.append(ACTIVATE_LOCK_NAME).getAbsolute());
    }

    public synchronized boolean acquire(TimeoutBudget timeoutBudget, boolean ignoreLockError) {
        try {
            return curatorLock.tryLock(timeoutBudget.timeLeft().toMillis(), TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            if (!ignoreLockError) {
                throw new RuntimeException(e);
            }
            return false;
        }
    }

    public synchronized void release() {
        if (curatorLock.hasLock()) {
            curatorLock.unlock();
        }
    }

    @Override
    public String toString() {
        return "ActivateLock (" + curatorLock + "), has lock: " + curatorLock.hasLock();
    }

}

// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.tenant;

import com.yahoo.path.Path;
import com.yahoo.vespa.config.server.TimeoutBudget;
import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.curator.recipes.CuratorLock;

import java.util.concurrent.TimeUnit;

/**
 * A lock to protect session activation.
 *
 * @author lulf
 * @since 5.1
 */
public class ActivateLock {

    private static final String ACTIVATE_LOCK_NAME = "activateLock";
    private final CuratorLock curatorLock;

    public ActivateLock(Curator curator, Path rootPath) {
        this.curatorLock = new CuratorLock(curator, rootPath.append(ACTIVATE_LOCK_NAME).getAbsolute());
    }

    public boolean acquire(TimeoutBudget timeoutBudget, boolean ignoreLockError) {
        try {
            return curatorLock.tryLock(timeoutBudget.timeLeft().toMillis(), TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            if (!ignoreLockError) {
                throw new RuntimeException(e);
            }
            return false;
        }
    }

    public void release() {
        if (curatorLock.hasLock()) {
            curatorLock.unlock();
        }
    }

    @Override
    public String toString() {
        return "ActivateLock (" + curatorLock + "), has lock: " + curatorLock.hasLock();
    }

}

Remove synchronization, it leads to deadlocks


package com.tasomaniac.muzei.earthview.data.analytics;

import timber.log.Timber;

public interface Analytics {

    void sendScreenView(String screenName);

    void sendEvent(String category, String action, String label);

    class DebugAnalytics implements Analytics {

        @Override
        public void sendScreenView(String screenName) {
            Timber.tag("Analytics").d("Screen: " + screenName);
        }

        @Override
        public void sendEvent(String category, String action, String label) {
            Timber.tag("Analytics").d("Event recorded:"
                                              + "\n\tCategory: " + category
                                              + "\n\tAction: " + action
                                              + "\n\tLabel: " + label);
        }
    }
}

package com.tasomaniac.muzei.earthview.data.analytics;

import timber.log.Timber;

public interface Analytics {

    void sendScreenView(String screenName);

    void sendEvent(String category, String action, String label);

    class DebugAnalytics implements Analytics {

        @Override
        public void sendScreenView(String screenName) {
            Timber.tag("Analytics").d("Screen: %s", screenName);
        }

        @Override
        public void sendEvent(String category, String action, String label) {
            Timber.tag("Analytics").d("Event recorded:\n\tCategory: %s\n\tAction: %s\n\tLabel: %s", category, action, label);
        }
    }
}

Use Timber's string format instead of concatenation


package hudson.plugins.copyProjectLink;

import hudson.Extension;
import hudson.model.TransientProjectActionFactory;
import hudson.model.AbstractProject;

import java.util.ArrayList;
import java.util.Collection;

@Extension
public class CopyProjectActionFactory extends TransientProjectActionFactory{

	/**
	 * {@inheritDoc}}
	 */
	@Override
	public Collection<CopyProjectAction> createFor(AbstractProject target){
		ArrayList<CopyProjectAction> ta = new ArrayList<CopyProjectAction>();
		ta.add(new CopyProjectAction(target));
		return ta;
	}

}

package hudson.plugins.copyProjectLink;

import hudson.Extension;
import hudson.model.TransientProjectActionFactory;
import hudson.model.AbstractProject;

import java.util.Collection;
import java.util.Collections;

@Extension
public class CopyProjectActionFactory extends TransientProjectActionFactory{

	/**
	 * {@inheritDoc}}
	 */
	@Override
	public Collection<CopyProjectAction> createFor(AbstractProject target){
    return Collections.singleton(new CopyProjectAction(target));
	}

}

Use Collections.singleton to create the Action


package org.subethamail.smtp.command;

import java.io.IOException;

import org.subethamail.smtp.server.BaseCommand;
import org.subethamail.smtp.server.ConnectionContext;

/**
 * @author Ian McFarland <ian@neo.com>
 * @author Jon Stevens
 */
public class QuitCommand extends BaseCommand
{
	public QuitCommand()
	{
		super("QUIT", "Exit the SMTP session.");
	}

	@Override
	public void execute(String commandString, ConnectionContext context) throws IOException
	{
		context.sendResponse("221 Bye");
		context.getSession().quit();
	}
}

package org.subethamail.smtp.command;

import java.io.IOException;

import org.subethamail.smtp.server.BaseCommand;
import org.subethamail.smtp.server.ConnectionContext;

/**
 * @author Ian McFarland <ian@neo.com>
 * @author Jon Stevens
 */
public class QuitCommand extends BaseCommand
{
	public QuitCommand()
	{
		super("QUIT", "Exit the SMTP session.");
	}

	@Override
	public void execute(String commandString, ConnectionContext context) throws IOException
	{
		context.getSession().quit();
		context.sendResponse("221 Bye");
	}
}

Fix to ensure session is closed on QUIT command response


/*
 * Copyright 2014 Avanza Bank AB
 *
 * 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.avanza.astrix.core;

/**
 *
 * @author Elias Lindholm (elilin)
 *
 */
public final class AstrixCallStackTrace extends RuntimeException {

	private static final long serialVersionUID = 1L;

	public AstrixCallStackTrace() {
		super("This stack contains the point where the astrix bean where invoked");
	}

}

/*
 * Copyright 2014 Avanza Bank AB
 *
 * 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.avanza.astrix.core;

/**
 *
 * @author Elias Lindholm (elilin)
 *
 */
public final class AstrixCallStackTrace extends RuntimeException {

	private static final long serialVersionUID = 1L;

	public AstrixCallStackTrace() {
		super("This stack contains the point where the astrix bean was invoked");
	}

}

Correct grammar of error message


package fr.masciulli.drinks.activity;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

import fr.masciulli.drinks.R;
import fr.masciulli.drinks.fragment.LiquorDetailFragment;

public class LiquorDetailActivity extends FragmentActivity {
    private LiquorDetailFragment mDetailFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_liquor_detail);

        if (savedInstanceState == null) {
            mDetailFragment = new LiquorDetailFragment();
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.liquor_detail_container, mDetailFragment)
                    .commit();
        } else {
            mDetailFragment = (LiquorDetailFragment) getSupportFragmentManager().findFragmentById(R.id.drink_detail_container);
        }

        getActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public void finish() {
        super.finish();

        // override transitions to skip the standard window animations
        overridePendingTransition(0, 0);
    }

    @Override
    public void onBackPressed() {
        mDetailFragment.onBackPressed();
    }
}

package fr.masciulli.drinks.activity;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

import fr.masciulli.drinks.R;
import fr.masciulli.drinks.fragment.LiquorDetailFragment;

public class LiquorDetailActivity extends FragmentActivity {
    private LiquorDetailFragment mDetailFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_liquor_detail);

        if (savedInstanceState == null) {
            mDetailFragment = new LiquorDetailFragment();
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.liquor_detail_container, mDetailFragment)
                    .commit();
        } else {
            mDetailFragment = (LiquorDetailFragment) getSupportFragmentManager().findFragmentById(R.id.liquor_detail_container);
        }

        getActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public void finish() {
        super.finish();

        // override transitions to skip the standard window animations
        overridePendingTransition(0, 0);
    }

    @Override
    public void onBackPressed() {
        mDetailFragment.onBackPressed();
    }
}

Fix crash on change orientation + back


/*
 * Copyright 2015 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.googlejavaformat.java;

import com.google.common.base.MoreObjects;

public class GoogleJavaFormatVersion {
  public static final String VERSION =
      MoreObjects.firstNonNull(Main.class.getPackage().getImplementationVersion(), "dev");
}

/*
 * Copyright 2015 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.googlejavaformat.java;

public class GoogleJavaFormatVersion {
  public static final String VERSION = "1.0";
}

Add ij_product flag to Builder for google_java_format plugin.


package org.springframework.content.s3;

import java.io.Serializable;

public final class S3ContentId implements Serializable {
    private String bucket;
    private String objectId;

    public S3ContentId(String bucket, String objectId) {
        this.bucket = bucket;
        this.objectId = objectId;
    }

    public String getBucket() {
        return bucket;
    }

    public void setBucket(String bucket) {
        this.bucket = bucket;
    }

    public String getObjectId() {
        return objectId;
    }

    public void setObjectId(String objectId) {
        this.objectId = objectId;
    }

    @Override
    public String toString() {
        return "S3ContentId{" +
                "bucket='" + bucket + '\'' +
                ", objectId='" + objectId + '\'' +
                '}';
    }

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

        S3ContentId that = (S3ContentId) o;

        if (bucket != null ? !bucket.equals(that.bucket) : that.bucket != null) return false;
        return objectId != null ? objectId.equals(that.objectId) : that.objectId == null;
    }

    @Override
    public int hashCode() {
        int result = bucket != null ? bucket.hashCode() : 0;
        result = 31 * result + (objectId != null ? objectId.hashCode() : 0);
        return result;
    }
}

package org.springframework.content.s3;

import org.springframework.util.Assert;

import java.io.Serializable;

public final class S3ContentId implements Serializable {
    private String bucket;
    private String objectId;

    public S3ContentId(String bucket, String objectId) {
        Assert.hasText(bucket, "bucket must be specified");
        Assert.hasText(objectId, "objectId must be specified");
        this.bucket = bucket;
        this.objectId = objectId;
    }

    public String getBucket() {
        return bucket;
    }

    public void setBucket(String bucket) {
        this.bucket = bucket;
    }

    public String getObjectId() {
        return objectId;
    }

    public void setObjectId(String objectId) {
        this.objectId = objectId;
    }

    @Override
    public String toString() {
        return "S3ContentId{" +
                "bucket='" + bucket + '\'' +
                ", objectId='" + objectId + '\'' +
                '}';
    }

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

        S3ContentId that = (S3ContentId) o;

        if (bucket != null ? !bucket.equals(that.bucket) : that.bucket != null) return false;
        return objectId != null ? objectId.equals(that.objectId) : that.objectId == null;
    }

    @Override
    public int hashCode() {
        int result = bucket != null ? bucket.hashCode() : 0;
        result = 31 * result + (objectId != null ? objectId.hashCode() : 0);
        return result;
    }
}

Add assertions to ensure only valid s3content ids can be created


package android.content;

public class Intent {
	public Intent setComponent(ComponentName name) {
		return null;
	}
	public Intent putExtra(String name, String value) {
		return null;
	}
}

package android.content;

public class Intent {
	public Intent setComponent(ComponentName name) {
		return null;
	}
	public Intent putExtra(String name, String value) {
		return null;
	}
	public String getStringExtra(String name) {
		return null;
	}
}

Fix for missing test dependency


/*
 *
 *
 * Copyright (C) 2004 SIPfoundry Inc.
 * Licensed by SIPfoundry under the LGPL license.
 *
 * Copyright (C) 2004 Pingtel Corp.
 * Licensed to SIPfoundry under a Contributor Agreement.
 *
 * $
 */
package org.sipfoundry.sipxconfig.site.phone;

import org.apache.tapestry.BaseComponent;
import org.apache.tapestry.event.PageEvent;
import org.apache.tapestry.event.PageRenderListener;
import org.apache.tapestry.form.IPropertySelectionModel;
import org.sipfoundry.sipxconfig.components.MapSelectionModel;
import org.sipfoundry.sipxconfig.phone.PhoneContext;

/**
 * Editing a phone is reused for creating new phones and editing existing ones
 */
public abstract class EditPhoneForm extends BaseComponent implements PageRenderListener {

    /**
     * all the phoneModels available to the system ready for UI selection
     */
    public abstract void setPhoneSelectionModel(IPropertySelectionModel phoneModels);

    public abstract PhoneContext getPhoneContext();

    public void pageBeginRender(PageEvent event_) {
        PhoneContext phoneContext = getPhoneContext();
        setPhoneSelectionModel(new MapSelectionModel(phoneContext.getPhoneFactoryIds()));
    }
}

/*
 *
 *
 * Copyright (C) 2004 SIPfoundry Inc.
 * Licensed by SIPfoundry under the LGPL license.
 *
 * Copyright (C) 2004 Pingtel Corp.
 * Licensed to SIPfoundry under a Contributor Agreement.
 *
 * $
 */
package org.sipfoundry.sipxconfig.site.phone;

import org.apache.tapestry.BaseComponent;

public abstract class EditPhoneForm extends BaseComponent {

}

FIX BUILD: Resolve subversion evil twin issue, File was not shown as modified however it had been. This file should have been commited as part of r4886 merge


package app.intra;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.VpnService;
import android.util.Log;
import com.google.firebase.crash.FirebaseCrash;

/**
 * Broadcast receiver that runs on boot, and also when the app is restarted due to an update.
 */
public class AutoStarter extends BroadcastReceiver {

  private static String LOG_TAG = "AutoStarter";

  @Override
  public void onReceive(Context context, Intent intent) {
    FirebaseCrash.logcat(Log.DEBUG, LOG_TAG, "Boot event");
    if (DnsVpnServiceState.getInstance().isDnsVpnServiceStarting()) {
      // The service is already started or starting, so there's no work to do.
      FirebaseCrash.logcat(Log.DEBUG, LOG_TAG, "Already running");
      return;
    }
    if (Preferences.getVpnEnabled(context)) {
      FirebaseCrash.logcat(Log.DEBUG, LOG_TAG, "Autostart enabled");
      if (VpnService.prepare(context) != null) {
        // prepare() returns a non-null intent if VPN permission has not been granted.
        FirebaseCrash.logcat(Log.WARN, LOG_TAG, "VPN permission not granted");
        return;
      }
      Intent startServiceIntent = new Intent(context, DnsVpnService.class);
      context.startService(startServiceIntent);
      DnsVpnServiceState.getInstance().setDnsVpnServiceStarting();
    }
  }
}

package app.intra;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.VpnService;
import android.os.Build;
import android.util.Log;
import com.google.firebase.crash.FirebaseCrash;

/**
 * Broadcast receiver that runs on boot, and also when the app is restarted due to an update.
 */
public class AutoStarter extends BroadcastReceiver {

  private static String LOG_TAG = "AutoStarter";

  @Override
  public void onReceive(Context context, Intent intent) {
    FirebaseCrash.logcat(Log.DEBUG, LOG_TAG, "Boot event");
    if (DnsVpnServiceState.getInstance().isDnsVpnServiceStarting()) {
      // The service is already started or starting, so there's no work to do.
      FirebaseCrash.logcat(Log.DEBUG, LOG_TAG, "Already running");
      return;
    }
    if (Preferences.getVpnEnabled(context)) {
      FirebaseCrash.logcat(Log.DEBUG, LOG_TAG, "Autostart enabled");
      if (VpnService.prepare(context) != null) {
        // prepare() returns a non-null intent if VPN permission has not been granted.
        FirebaseCrash.logcat(Log.WARN, LOG_TAG, "VPN permission not granted");
        return;
      }
      Intent startServiceIntent = new Intent(context, DnsVpnService.class);
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context.startForegroundService(startServiceIntent);
      } else {
        context.startService(startServiceIntent);
      }
      DnsVpnServiceState.getInstance().setDnsVpnServiceStarting();
    }
  }
}

Fix autostart bug observed in recent Android OS


package org.genericsystem.mutability;

import java.io.Serializable;
import java.util.List;

import org.genericsystem.defaults.DefaultVertex;

public interface Generic extends DefaultVertex<Generic> {

	@Override
	default Engine getRoot() {
		throw new IllegalStateException();
	}

	@Override
	default Cache getCurrentCache() {
		return getRoot().getCurrentCache();
	}

	@Override
	default long getTs() {
		return getCurrentCache().unwrap(this).getBirthTs();
	}

	@Override
	default Generic getMeta() {
		return getCurrentCache().wrap(getCurrentCache().unwrap(this).getMeta());
	}

	@Override
	default List<Generic> getSupers() {
		return getCurrentCache().wrap(getCurrentCache().unwrap(this).getSupers());
	}

	@Override
	default List<Generic> getComponents() {
		return getCurrentCache().wrap(getCurrentCache().unwrap(this).getComponents());
	}

	@Override
	default Serializable getValue() {
		return getCurrentCache().unwrap(this).getValue();
	}

	@Override
	default long getBirthTs() {
		return getCurrentCache().unwrap(this).getBirthTs();
	}

	@Override
	default long[] getOtherTs() {
		return getCurrentCache().unwrap(this).getOtherTs();
	}
}

package org.genericsystem.mutability;

import java.io.Serializable;
import java.util.List;

import org.genericsystem.defaults.DefaultVertex;

public interface Generic extends DefaultVertex<Generic> {

	@Override
	default Engine getRoot() {
		throw new IllegalStateException();
	}

	@Override
	default Cache getCurrentCache() {
		return getRoot().getCurrentCache();
	}

	@Override
	default long getTs() {
		return getCurrentCache().unwrap(this).getBirthTs();
	}

	@Override
	default Generic getMeta() {
		return getCurrentCache().wrap(getCurrentCache().unwrap(this).getMeta());
	}

	@Override
	default List<Generic> getSupers() {
		return getCurrentCache().wrap(getCurrentCache().unwrap(this).getSupers());
	}

	@Override
	default List<Generic> getComponents() {
		return getCurrentCache().wrap(getCurrentCache().unwrap(this).getComponents());
	}

	@Override
	default Serializable getValue() {
		return getCurrentCache().unwrap(this).getValue();
	}

	@Override
	default long getBirthTs() {
		return getCurrentCache().unwrap(this).getBirthTs();
	}

}

Fix compilation error in mutability


package mn.devfest;

import android.app.Application;
import android.content.Context;

import net.danlew.android.joda.JodaTimeAndroid;

import timber.log.Timber;

/**
 * DevFest application class
 *
 * Performs application-wide configuration
 *
 * @author bherbst
 */
public class DevFestApplication extends Application {

    private DevFestGraph mGraph;

    @Override
    public void onCreate() {
        super.onCreate();

        init();
        buildComponent();
    }

    /**
     * Build the Dagger component
     */
    private void buildComponent() {
        mGraph = DevFestComponent.Initializer.init(this);
    }

    /**
     * Get the Dagger component
     */
    public DevFestGraph component() {
        return mGraph;
    }

    /**
     * Initialize app-wide configuration
     *
     * The default implementation sets up the app for release. Do not call through to super()
     * if you do not want the release configuration.
     */
    protected void init() {
        JodaTimeAndroid.init(this);
        Timber.plant(new ReleaseTree());
    }

    /**
     * Get a WvwApplication from a Context
     * @param context The Context in which to get the WvwApplication
     * @return The WvwApplication associated with the given Context
     */
    public static DevFestApplication get(Context context) {
        return (DevFestApplication) context.getApplicationContext();
    }
}

package mn.devfest;

import android.app.Application;
import android.content.Context;

import net.danlew.android.joda.JodaTimeAndroid;

import timber.log.Timber;

/**
 * DevFest application class
 *
 * Performs application-wide configuration
 *
 * @author bherbst
 */
public class DevFestApplication extends Application {

    private DevFestGraph mGraph;

    @Override
    public void onCreate() {
        super.onCreate();

        JodaTimeAndroid.init(this);

        init();
        buildComponent();
    }

    /**
     * Build the Dagger component
     */
    private void buildComponent() {
        mGraph = DevFestComponent.Initializer.init(this);
    }

    /**
     * Get the Dagger component
     */
    public DevFestGraph component() {
        return mGraph;
    }

    /**
     * Initialize app-wide configuration
     *
     * The default implementation sets up the app for release. Do not call through to super()
     * if you do not want the release configuration.
     */
    protected void init() {
        Timber.plant(new ReleaseTree());
    }

    /**
     * Get a WvwApplication from a Context
     * @param context The Context in which to get the WvwApplication
     * @return The WvwApplication associated with the given Context
     */
    public static DevFestApplication get(Context context) {
        return (DevFestApplication) context.getApplicationContext();
    }
}

Fix for JodaTime not being initialized correctly in dev builds


package im.darkgeek.dicts;

/**
 * Created by justin on 15-8-28.
 */
public class DictItem {
    private String word;
    private String explanation;

    public String getWord() {
        return word;
    }

    public void setWord(String word) {
        this.word = handleUnsafeChars(word);
    }

    public String getExplanation() {
        return explanation;
    }

    public void setExplanation(String explanation) {
        this.explanation = handleUnsafeChars(explanation);
    }

    private String handleUnsafeChars(String raw) {
        return
                raw.replace("\n", "")
                   .replace("\r", "");
    }

    @Override
    public String toString() {
        return "DictItem{" +
                "word='" + word + '\'' +
                ", explanation='" + explanation + '\'' +
                '}';
    }
}

package im.darkgeek.dicts;

/**
 * Created by justin on 15-8-28.
 */
public class DictItem {
    private String word;
    private String explanation;

    public String getWord() {
        return word;
    }

    public void setWord(String word) {
        this.word = handleUnsafeChars(word);
    }

    public String getExplanation() {
        return explanation;
    }

    public void setExplanation(String explanation) {
        this.explanation = handleUnsafeChars(explanation);
    }

    private String handleUnsafeChars(String raw) {
        return
                raw.replace("\n", "")
                   .replace("\r", "");
    }

    @Override
    public String toString() {
        return "DictItem{" +
                "word='" + word + '\'' +
                ", explanation='" + explanation + '\'' +
                '}';
    }

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

        DictItem item = (DictItem) o;

        if (word != null ? !word.equals(item.word) : item.word != null) return false;
        return !(explanation != null ? !explanation.equals(item.explanation) : item.explanation != null);

    }

    @Override
    public int hashCode() {
        return 0;
    }
}

Add equals method for comparision purpose.


package tars.commons.core;

/**
 * Container for user visible messages.
 */
public class Messages {

    public static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command";
    public static final String MESSAGE_INVALID_COMMAND_FORMAT = "Invalid command format! \n%1$s";
    public static final String MESSAGE_INVALID_DATE = "Invalid date time entered!";
    public static final String MESSAGE_INVALID_TASK_DISPLAYED_INDEX = "The task index provided is invalid";
    public static final String MESSAGE_PERSONS_LISTED_OVERVIEW = "%1$d tasks listed!";
    public static final String MESSAGE_TASK_CANNOT_BE_FOUND = "Task cannot be found!";
}

package tars.commons.core;

/**
 * Container for user visible messages.
 */
public class Messages {

    public static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command";
    public static final String MESSAGE_INVALID_COMMAND_FORMAT = "Invalid command format! \n%1$s";
    public static final String MESSAGE_INVALID_DATE = "Invalid date time entered!";
    public static final String MESSAGE_INVALID_END_DATE = "End dateTime should be after start dateTime.";
    public static final String MESSAGE_INVALID_TASK_DISPLAYED_INDEX = "The task index provided is invalid";
    public static final String MESSAGE_PERSONS_LISTED_OVERVIEW = "%1$d tasks listed!";
    public static final String MESSAGE_TASK_CANNOT_BE_FOUND = "Task cannot be found!";
}

Add new messages for invalid end date


package net.zephyrizing.http_server;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServer {
    public static void main(String[] args) throws Exception {
        int portNumber = Integer.parseInt(args[0]);
        System.err.println("Starting server on port " + args[0]);

        try (ServerSocket listenSocket = new ServerSocket(portNumber)) {
            System.err.println("Listening for clients...");

            try (Socket socket = listenSocket.accept();
                 PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                 BufferedReader in = new BufferedReader(
                     new InputStreamReader(socket.getInputStream()));
                 BufferedReader stdIn = new BufferedReader(
                     new InputStreamReader(System.in))) {
                System.err.println("Connected to client. Proceeding to echo...");

                String clientInput;
                while ((clientInput = in.readLine()) != null) {
                    System.out.println("Got: "+clientInput);
                    out.println("Echo: "+clientInput);
                }
            }
        }
    }
}

package net.zephyrizing.http_server;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServer {
    public static void main(String[] args) throws Exception {
        int portNumber;
        if (args.length == 1) {
         portNumber = Integer.parseInt(args[0]);
        } else {
            portNumber = 80;
        }
        System.err.println("Starting server on port " + portNumber);

        try (ServerSocket listenSocket = new ServerSocket(portNumber)) {
            System.err.println("Listening for clients...");

            try (Socket socket = listenSocket.accept();
                 PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                 BufferedReader in = new BufferedReader(
                     new InputStreamReader(socket.getInputStream()));
                 BufferedReader stdIn = new BufferedReader(
                     new InputStreamReader(System.in))) {
                System.err.println("Connected to client.");

                String request = in.readLine();
                String[] params = request.split(" ");

                assert(params.length == 3);

                String method = params[0];
                String path = params[1];
                String protocolVersion = params[2];

                System.out.format("Client requested to %s file %s over %s.\n",
                                  method, path, protocolVersion);
                out.format("%s 200 OK\r\n", protocolVersion);
            }
        }
    }
}

Implement a very basic http server


package hu.bme.mit.spaceship;

import java.util.Random;

/**
* Class storing and managing the torpedoes of a ship
*/
public class TorpedoStore {

  private int torpedoCount = 0;
  private Random generator = new Random();

  public TorpedoStore(int numberOfTorpedos){
    this.torpedoCount = numberOfTorpedos;
  }

  public boolean fire(int numberOfTorpedos){
    if(numberOfTorpedos < 1 || numberOfTorpedos > this.torpedoCount){
      throw new IllegalArgumentException("numberOfTorpedos");
    }

    boolean success = false;

    //simulate random overheating of the launcher bay which prevents firing
    double r = generator.nextDouble();

    if (r > 0.01) {
      // successful firing
      this.torpedoCount -= numberOfTorpedos;
      success = true;
    } else {
      // failure
      success = false;
    }

    return success;
  }

  public boolean isEmpty(){
    return this.torpedoCount <= 0;
  }

  public int getTorpedoCount() {
    return this.torpedoCount;
  }
}

package hu.bme.mit.spaceship;

import java.util.Random;

/**
* Class storing and managing the torpedoes of a ship
*/
public class TorpedoStore {

  private double FAILURE_RATE = 0.0;

  private int torpedoCount = 0;
  private Random generator = new Random();

  public TorpedoStore(int numberOfTorpedos){
    this.torpedoCount = numberOfTorpedos;

    // update failure rate if it was specified in an environment variable
    String failureEnv = System.getenv("IVT_RATE");
    if (failureEnv != null){
      try {
        FAILURE_RATE = Double.parseDouble(failureEnv);
      } catch (NumberFormatException nfe) {
        FAILURE_RATE = 0.0;
      }
    }
  }

  public boolean fire(int numberOfTorpedos){
    if(numberOfTorpedos < 1 || numberOfTorpedos > this.torpedoCount){
      throw new IllegalArgumentException("numberOfTorpedos");
    }

    boolean success = false;

    // simulate random overheating of the launcher bay which prevents firing
    double r = generator.nextDouble();

    if (r >= FAILURE_RATE) {
      // successful firing
      this.torpedoCount -= numberOfTorpedos;
      success = true;
    } else {
      // simulated failure
      success = false;
    }

    return success;
  }

  public boolean isEmpty(){
    return this.torpedoCount <= 0;
  }

  public int getTorpedoCount() {
    return this.torpedoCount;
  }
}

Add torpedo failure rate as an environment variable


package com.cc4102.stringDict;

import java.util.ArrayList;

/**
 * @author Lucas Puebla Silva
 *
 */
public class PatriciaTree implements StringDictionary {

    private PatriciaNode root;

    public PatriciaTree() {
        this.root = new PatriciaNode("", true, null, new ArrayList<>());
    }

    @Override
    public int getLength() {
        return 0;
    }

    @Override
    public int getSize() {
        return 0;
    }

    @Override
    public Object getRoot() {
        return root;
    }

    @Override
    public ArrayList<Integer> search(String key) {
        return root.search(key);
    }

    @Override
    public void insert(String word, int pos) {
        root.insert(word, pos);
    }
}

package com.cc4102.stringDict;

import java.util.ArrayList;

/**
 * @author Lucas Puebla Silva
 *
 */
public class PatriciaTree implements StringDictionary {

    private PatriciaNode root;

    public PatriciaTree() {
        this.root = new PatriciaNode("", true, null, new ArrayList<>());
    }

    public int getLength() {
        return 0;
    }

    public int getSize() {
        return 0;
    }

    public Object getRoot() {
        return root;
    }

    public ArrayList<Integer> search(String key) {
        return root.search(key);
    }

    public void insert(String word, int pos) {
        root.insert(word, pos);
    }

    public String[] getKeys() {
        return new String[0];
    }

    public int count(String key) {
        return root.search(key).size();
    }
}

Add getKeys and count to Patricia Tree


package main.powercalc;

public class DataTuple {
	private double lat;
	private double lon;
	private double data;

	DataTuple() {
		this.lat = 0.0;
		this.lon = 0.0;
		this.data = 0.0;
	}

	DataTuple(double lat, double lon, double data) {
		this.lat = lat;
		this.lon = lon;
		this.data = data;
	}

	DataTuple(DataTuple dt) {
		this.lat = dt.getLat();
		this.lon = dt.getLon();
		this.data = dt.getData();
	}

	/**
	 * @return the lat
	 */
	public double getLat() {
		return lat;
	}

	/**
	 * @param lat the lat to set
	 */
	public void setLat(double lat) {
		this.lat = lat;
	}

	/**
	 * @return the lon
	 */
	public double getLon() {
		return lon;
	}

	/**
	 * @param lon the lon to set
	 */
	public void setLon(double lon) {
		this.lon = lon;
	}

	/**
	 * @return the data
	 */
	public double getData() {
		return data;
	}

	/**
	 * @param data the data to set
	 */
	public void setData(double data) {
		this.data = data;
	}
}

Test change for retina branch


package co.omise.models;

import com.fasterxml.jackson.annotation.JsonProperty;

public enum SearchScope {
    @JsonProperty("dispute")Dispute,
    @JsonProperty("charge")Charge,
    @JsonProperty("customer")Customer,
    @JsonProperty("recipient")Recipient,
}

package co.omise.models;

import com.fasterxml.jackson.annotation.JsonProperty;

public enum SearchScope {
    @JsonProperty("dispute")Dispute,
    @JsonProperty("charge")Charge,
    @JsonProperty("customer")Customer,
    @JsonProperty("recipient")Recipient,
    @JsonProperty("refund")Refund,
    @JsonProperty("transfer")Transfer,
    @JsonProperty("link")Link,
}

Add new available search scopes.


package mnm.mods.achget;

import net.minecraft.entity.player.EntityPlayerMP;

public class StatHandler {

    private final StatAchievement achievement;

    public StatHandler(StatAchievement achievement) {
        this.achievement = achievement;
    }

    public int getStat(EntityPlayerMP player) {
        // this method `writeStat()` is wrongly named.
        return player.getStatFile().writeStat(achievement.getStat());
    }

    public boolean hasAchievement(EntityPlayerMP player) {
        return player.getStatFile().hasAchievementUnlocked(achievement);
    }

    public void giveAchievement(EntityPlayerMP player) {
        player.triggerAchievement(achievement);
    }

    public boolean shouldAward(EntityPlayerMP player) {
        return !hasAchievement(player) && getStat(player) > achievement.getCount();
    }
}

package mnm.mods.achget;

import net.minecraft.entity.player.EntityPlayerMP;

public class StatHandler {

    private final StatAchievement achievement;

    public StatHandler(StatAchievement achievement) {
        this.achievement = achievement;
    }

    public int getStat(EntityPlayerMP player) {
        // this method `writeStat()` is wrongly named.
        return player.getStatFile().writeStat(achievement.getStat());
    }

    public boolean hasAchievement(EntityPlayerMP player) {
        return player.getStatFile().hasAchievementUnlocked(achievement);
    }

    public void giveAchievement(EntityPlayerMP player) {
        player.triggerAchievement(achievement);
    }

    public boolean shouldAward(EntityPlayerMP player) {
        return !hasAchievement(player) && getStat(player) >= achievement.getCount();
    }
}

Fix stats triggering at count + 1


package pl.mkrystek.mkbot.task;

import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.mkrystek.mkbot.window.SkypeWindow;

public class TaskExecutionEngine {

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

    private final ScheduledExecutorService scheduler;
    private final SkypeWindow skypeWindow;
    private List<ReplyTask> replyTasks;
    private List<ScheduledTask> scheduledTasks;

    public TaskExecutionEngine(ScheduledExecutorService scheduler, SkypeWindow skypeWindow) {
        this.skypeWindow = skypeWindow;
        this.scheduler = scheduler;
    }

    public void init(List<ReplyTask> replyTasks, List<ScheduledTask> scheduledTasks) {
        this.replyTasks = replyTasks;
        this.scheduledTasks = scheduledTasks;
    }

    public void start() {
        scheduler.scheduleAtFixedRate(() -> skypeWindow.getNewMessages().forEach(skypeMessage -> replyTasks.forEach(replyTask -> {
            if (replyTask.checkIfApplies(skypeMessage)) {
                LOGGER.debug("Writing message on skype: {}", replyTask.performAction(skypeMessage));
            }
        })), 0, 1, TimeUnit.SECONDS);
    }

    public void shutdown() {
        scheduler.shutdownNow();
    }
}

package pl.mkrystek.mkbot.task;

import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.mkrystek.mkbot.window.SkypeWindow;

public class TaskExecutionEngine {

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

    private final ScheduledExecutorService scheduler;
    private final SkypeWindow skypeWindow;
    private List<ReplyTask> replyTasks;
    private List<ScheduledTask> scheduledTasks;

    public TaskExecutionEngine(ScheduledExecutorService scheduler, SkypeWindow skypeWindow) {
        this.skypeWindow = skypeWindow;
        this.scheduler = scheduler;
    }

    public void init(List<ReplyTask> replyTasks, List<ScheduledTask> scheduledTasks) {
        this.replyTasks = replyTasks;
        this.scheduledTasks = scheduledTasks;
    }

    public void start() {
        scheduler.scheduleAtFixedRate(() -> skypeWindow.getNewMessages().forEach(skypeMessage -> replyTasks.forEach(replyTask -> {
            if (replyTask.checkIfApplies(skypeMessage)) {
                String reply = replyTask.performAction(skypeMessage);
                LOGGER.debug("Writing message on skype: {}", reply);
                skypeWindow.writeMessage(reply);
            }
        })), 0, 100, TimeUnit.MILLISECONDS);
    }

    public void shutdown() {
        scheduler.shutdownNow();
    }
}

Write task output to skype window


package org.nguyenhuy.buffer.job;

import android.os.Handler;
import com.path.android.jobqueue.Params;
import com.squareup.otto.Bus;

import javax.inject.Inject;

/**
 * Created by nguyenthanhhuy on 1/14/14.
 */
public abstract class Job extends com.path.android.jobqueue.Job {
    @Inject
    transient Bus bus;
    @Inject
    transient Handler mainHandler;

    protected Job(Params params) {
        super(params);
    }
}

package org.nguyenhuy.buffer.job;

import android.os.Handler;
import com.path.android.jobqueue.Params;
import com.squareup.otto.Bus;

import javax.inject.Inject;

/**
 * Created by nguyenthanhhuy on 1/14/14.
 */
public abstract class Job extends com.path.android.jobqueue.Job {
    private static final int DEFAULT_RETRY_LIMIT =  3;

    @Inject
    transient Bus bus;
    @Inject
    transient Handler mainHandler;

    protected Job(Params params) {
        super(params);
    }

    @Override
    protected int getRetryLimit() {
        return DEFAULT_RETRY_LIMIT;
    }
}

Change retry limit from 20 down to 3, to fail fast.


package leetcode;

/**
 * https://leetcode.com/problems/count-primes/
 */
public class Problem204 {
    public int countPrimes(int n) {
        // TODO:
        return 0;
    }

    public static void main(String[] args) {
        Problem204 prob = new Problem204();
        System.out.println(prob.countPrimes(10));
    }
}

package leetcode;

import java.util.HashSet;
import java.util.Set;

/**
 * https://leetcode.com/problems/count-primes/
 */
public class Problem204 {
    public int countPrimes(int n) {
        // https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
        int prime = 0;
        Set<Integer> set = new HashSet<>();
        for (int i = 2; i <= n; i++) {
            set.add(i);
        }
        for (int i = 2; i <= n; i++) {
            if (!set.contains(i)) {
                continue;
            }
            for (int j = i; j <= n; j += i) {
                set.remove(j);
            }
            prime++;
        }
        return prime;
    }

    public static void main(String[] args) {
        Problem204 prob = new Problem204();
        System.out.println(prob.countPrimes(20));
        System.out.println(prob.countPrimes(999983));
    }
}

Update problem 204 (still too slow)


package com.frinder.frinder.model;

import org.parceler.Parcel;

import java.util.Date;

@Parcel(analyze={MessageThread.class})
public class MessageThread implements Comparable<MessageThread> {

    public String uid;
    public String userId;
    public String messageSnippet;
    public boolean unread;
    public Date lastTimestamp;

    @Override
    public int compareTo(MessageThread o) {
        return lastTimestamp.compareTo(o.lastTimestamp);
    }
}

package com.frinder.frinder.model;

import org.parceler.Parcel;

import java.util.Date;

@Parcel(analyze={MessageThread.class})
public class MessageThread implements Comparable<MessageThread> {

    public String uid;
    public String userId;
    public String messageSnippet;
    public boolean unread;
    public Date lastTimestamp;

    @Override
    public int compareTo(MessageThread o) {
        if (lastTimestamp == null || o.lastTimestamp == null) {
            return 0;
        }

        return lastTimestamp.compareTo(o.lastTimestamp);
    }
}

Fix timestamp crash in message list view


package net.md_5.bungee;

import java.net.InetAddress;
import java.net.UnknownHostException;
import org.junit.Assert;
import org.junit.Test;

public class ThrottleTest
{

    @Test
    public void testThrottle() throws InterruptedException, UnknownHostException
    {
        ConnectionThrottle throttle = new ConnectionThrottle( 5 );
        InetAddress address = InetAddress.getLocalHost();

        Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) );
        Assert.assertTrue( "Address should be throttled", throttle.throttle( address ) );

        throttle.unthrottle( address );
        Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) );

        Thread.sleep( 15 );
        Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) );
    }
}

package net.md_5.bungee;

import java.net.InetAddress;
import java.net.UnknownHostException;
import org.junit.Assert;
import org.junit.Test;

public class ThrottleTest
{

    @Test
    public void testThrottle() throws InterruptedException, UnknownHostException
    {
        ConnectionThrottle throttle = new ConnectionThrottle( 5 );
        InetAddress address;

        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException ex) {
            address = InetAddress.getByName( null );
        }

        Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) );
        Assert.assertTrue( "Address should be throttled", throttle.throttle( address ) );

        throttle.unthrottle( address );
        Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) );

        Thread.sleep( 15 );
        Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) );
    }
}

Fix compile error when compiling on OS X


/**
 * File: AbstractObjectFactory.java
 *
 * Author: David Hay (dhay@localmatters.com)
 * Creation Date: Apr 21, 2010
 * Creation Time: 10:46:54 AM
 *
 * Copyright 2010 Local Matters, Inc.
 * All Rights Reserved
 *
 * Last checkin:
 *  $Author$
 *  $Revision$
 *  $Date$
 */
package org.lesscss4j.factory;

import org.antlr.runtime.tree.Tree;
import org.lesscss4j.parser.LessCssParser;

import static org.lesscss4j.parser.LessCssLexer.*;

public abstract class AbstractObjectFactory<T> implements ObjectFactory<T> {
    protected String formatNode(String prefix, Tree node) {
        return String.format("%s [%d=%s] %s",
                             prefix, node.getType(), LessCssParser.tokenNames[node.getType()], node.toString());
    }

    protected void handleUnexpectedChild(String prefix, Tree child) {
        int type = child.getType();
        if (type != WS && type != EOF) {
            throw new IllegalStateException(formatNode(prefix, child));
        }
    }
}

/**
 * File: AbstractObjectFactory.java
 *
 * Author: David Hay (dhay@localmatters.com)
 * Creation Date: Apr 21, 2010
 * Creation Time: 10:46:54 AM
 *
 * Copyright 2010 Local Matters, Inc.
 * All Rights Reserved
 *
 * Last checkin:
 *  $Author$
 *  $Revision$
 *  $Date$
 */
package org.lesscss4j.factory;

import org.antlr.runtime.tree.Tree;
import org.lesscss4j.parser.LessCssParser;

import static org.lesscss4j.parser.LessCssLexer.*;

public abstract class AbstractObjectFactory<T> implements ObjectFactory<T> {
    protected String formatNode(String prefix, Tree node) {
        return String.format("%s [%d=%s] %d:%d - %s",
                             prefix, node.getType(), LessCssParser.tokenNames[node.getType()],
                             node.getLine(), node.getCharPositionInLine(),
                             node.toString());
    }

    protected void handleUnexpectedChild(String prefix, Tree child) {
        int type = child.getType();
        if (type != WS && type != EOF) {
            throw new IllegalStateException(formatNode(prefix, child));
        }
    }
}

Include line number in unhandled token exception.


package backtype.storm.topology;

import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.tuple.Tuple;
import java.util.Map;
import org.apache.log4j.Logger;

public class BasicBoltExecutor implements IRichBolt {
    public static Logger LOG = Logger.getLogger(BasicBoltExecutor.class);

    private IBasicBolt _bolt;
    private transient BasicOutputCollector _collector;

    public BasicBoltExecutor(IBasicBolt bolt) {
        _bolt = bolt;
    }

    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        _bolt.declareOutputFields(declarer);
    }

    public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) {
        _bolt.prepare(stormConf, context);
        _collector = new BasicOutputCollector(collector);
    }

    public void execute(Tuple input) {
        _collector.setContext(input);
        try {
            _bolt.execute(input, _collector);
            _collector.getOutputter().ack(input);
        } catch(FailedException e) {
            if(e instanceof ReportedFailedException) {
                _collector.reportError(e);
            }
            _collector.getOutputter().fail(input);
        }
    }

    public void cleanup() {
        _bolt.cleanup();
    }

    public Map<String, Object> getComponentConfiguration() {
        return _bolt.getComponentConfiguration();
    }
}

package backtype.storm.topology;

import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.tuple.Tuple;
import java.util.Map;
import org.apache.log4j.Logger;

public class BasicBoltExecutor implements IRichBolt {
    public static Logger LOG = Logger.getLogger(BasicBoltExecutor.class);

    private IBasicBolt _bolt;
    private transient BasicOutputCollector _collector;

    public BasicBoltExecutor(IBasicBolt bolt) {
        _bolt = bolt;
    }

    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        _bolt.declareOutputFields(declarer);
    }

    public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) {
        _bolt.prepare(stormConf, context);
        _collector = new BasicOutputCollector(collector);
    }

    public void execute(Tuple input) {
        _collector.setContext(input);
        try {
            _bolt.execute(input, _collector);
            _collector.getOutputter().ack(input);
        } catch(FailedException e) {
            LOG.warn("Failed to process tuple", e);
            _collector.getOutputter().fail(input);
        }
    }

    public void cleanup() {
        _bolt.cleanup();
    }

    public Map<String, Object> getComponentConfiguration() {
        return _bolt.getComponentConfiguration();
    }
}

Revert "basic bolts check for reportedfailedexception"


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

package net.openhft.chronicle.wire;

/**
 * Created by peter on 16/03/16.
 */
public abstract class AbstractMarshallable implements Marshallable {
    @Override
    public boolean equals(Object o) {
        return Marshallable.$equals(this, o);
    }

    @Override
    public int hashCode() {
        return Marshallable.$hashCode(this);
    }

    @Override
    public String toString() {
        return Marshallable.$toString(this);
    }
}

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

package net.openhft.chronicle.wire;

/**
 * Created by peter on 16/03/16.
 */
public abstract class AbstractMarshallable implements Marshallable {
    @Override
    public boolean equals(Object o) {
        return Marshallable.$equals(this, o);
    }

    @Override
    public int hashCode() {
        assert false;
        return Marshallable.$hashCode(this);
    }

    @Override
    public String toString() {
        return Marshallable.$toString(this);
    }
}

Add a custom hashCode and equals for performance.


package com.alsash.reciper.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;

import com.alsash.reciper.R;

public class RecipeListActivity extends DrawerSpinnerActivity {

    private static final SpinnerArrayRes spinnerRes = new SpinnerArrayRes(
            R.array.spinner_recipe_group_names, null);

    @Override
    protected Fragment getSpinnerFragment(int position, @Nullable Intent activityIntent) {
        return RecipeListFragment.newInstance();
    }

    @Override
    protected SpinnerArrayRes getSpinnerArrayRes() {
        return spinnerRes;
    }

    @Override
    protected void setupFab(FloatingActionButton fab) {
        fab.hide();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
}

package com.alsash.reciper.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;

import com.alsash.reciper.R;

public class RecipeListActivity extends DrawerSpinnerActivity {

    private static final SpinnerArrayRes spinnerRes = new SpinnerArrayRes(
            R.array.spinner_recipe_group_names, R.array.spinner_recipe_group_icons);

    @Override
    protected Fragment getSpinnerFragment(int position, @Nullable Intent activityIntent) {
        return RecipeListFragment.newInstance();
    }

    @Override
    protected SpinnerArrayRes getSpinnerArrayRes() {
        return spinnerRes;
    }

    @Override
    protected void setupFab(FloatingActionButton fab) {
        fab.hide();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
}

Add spinner activity with navigation drawer


package sqlancer.dbms;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assumptions.assumeTrue;

import org.junit.jupiter.api.Test;

import sqlancer.Main;

public class TestMySQL {

    String mysqlAvailable = System.getenv("MYSQL_AVAILABLE");
    boolean mysqlIsAvailable = mysqlAvailable != null && mysqlAvailable.equalsIgnoreCase("true");

    @Test
    public void testMySQL() {
        assumeTrue(mysqlIsAvailable);
        assertEquals(0,
                Main.executeMain(new String[] { "--random-seed", "0", "--timeout-seconds", TestConfig.SECONDS,
                        "--max-expression-depth", "1", "--num-threads", "4", "--num-queries", TestConfig.NUM_QUERIES,
                        "mysql" }));
    }

    @Test
    public void testPQS() {
        assumeTrue(mysqlIsAvailable);
        assertEquals(0,
                Main.executeMain(new String[] { "--random-seed", "0", "--timeout-seconds", TestConfig.SECONDS,
                        "--num-threads", "4", "--random-string-generation", "ALPHANUMERIC", "--database-prefix",
                        "pqsdb" /* Workaround for connections not being closed */, "--num-queries", "100000", "mysql",
                        "--oracle", "PQS" }));
    }

}

package sqlancer.dbms;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assumptions.assumeTrue;

import org.junit.jupiter.api.Test;

import sqlancer.Main;

public class TestMySQL {

    String mysqlAvailable = System.getenv("MYSQL_AVAILABLE");
    boolean mysqlIsAvailable = mysqlAvailable != null && mysqlAvailable.equalsIgnoreCase("true");

    @Test
    public void testPQS() {
        assumeTrue(mysqlIsAvailable);
        assertEquals(0,
                Main.executeMain(new String[] { "--random-seed", "0", "--timeout-seconds", TestConfig.SECONDS,
                        "--num-threads", "4", "--random-string-generation", "ALPHANUMERIC", "--database-prefix",
                        "pqsdb" /* Workaround for connections not being closed */, "--num-queries",
                        TestConfig.NUM_QUERIES, "mysql", "--oracle", "PQS" }));
    }

    @Test
    public void testMySQL() {
        assumeTrue(mysqlIsAvailable);
        assertEquals(0,
                Main.executeMain(new String[] { "--random-seed", "0", "--timeout-seconds", TestConfig.SECONDS,
                        "--max-expression-depth", "1", "--num-threads", "4", "--num-queries", TestConfig.NUM_QUERIES,
                        "mysql" }));
    }

}

Use the default number of queries


package com.ibm.sk;

public class WorldConstans {

	public static final int X_BOUNDRY = 15;
	public static final int Y_BOUNDRY = 10;
	/**
	 * number of TURNS to evaluate game.
	 */
	public static final int TURNS = 50;
	/**
	 * the amount of ants in one anthill at the beginning of the world.
	 */
	public static final int INITIAL_ANT_COUNT = 5;
	/**
	 * frequency of food adding.
	 */
	public static final int FOOD_REFILL_FREQUENCY = 5;
	/**
	 * number of ants in the hill at the beginning of the game.
	 */
	public static final int ANTS_START_POPULATION = 5;
	public static final double POPULATION_WAR_FACTOR = 2.0 / 5.0;
	/**
	 * File where to serialize the world per step.
	 */
	public static final String FILE_NAME = "traciking.ser";
}

package com.ibm.sk;

public class WorldConstans {

	public static final int X_BOUNDRY = 15;
	public static final int Y_BOUNDRY = 10;
	/**
	 * number of TURNS to evaluate game.
	 */
	public static final int TURNS = 500;
	/**
	 * the amount of ants in one anthill at the beginning of the world.
	 */
	public static final int INITIAL_ANT_COUNT = 5;
	/**
	 * frequency of food adding.
	 */
	public static final int FOOD_REFILL_FREQUENCY = 5;
	/**
	 * number of ants in the hill at the beginning of the game.
	 */
	public static final int ANTS_START_POPULATION = 5;
	public static final double POPULATION_WAR_FACTOR = 2.0 / 5.0;
	/**
	 * File where to serialize the world per step.
	 */
	public static final String FILE_NAME = "traciking.ser";
}

Set more turns for testing.