package org.apidesign.demo.rubyjs.fromjava;

import com.oracle.truffle.api.source.Source;
import com.oracle.truffle.api.vm.PolyglotEngine;
import java.io.File;
import java.net.URL;

public final class Main {
    private Main() {
    }

    public static void main(String[] args) throws Exception {
        System.err.println("Setting up PolyglotEngine");
        PolyglotEngine vm = PolyglotEngine.newBuilder().
            build();

        URL url = Main.class.getProtectionDomain().getCodeSource().getLocation();
        File local = new File(url.toURI());
        for (;;) {
            File sieveInRuby = new File(local, "sieve.rb");
            if (sieveInRuby.exists()) {
                break;
            }
            local = local.getParentFile();
        }

        Source ruby = Source.fromFileName(new File(local, "sieve.rb").getPath());
        Source js = Source.fromFileName(new File(local, "sieve.js").getPath());

        vm.eval(ruby);
        vm.eval(js);
    }
}

package org.apidesign.demo.rubyjs.fromjava;

import com.oracle.truffle.api.source.Source;
import com.oracle.truffle.api.vm.PolyglotEngine;
import java.io.File;
import java.net.URL;

public final class Main {
    private Main() {
    }

    public static void main(String[] args) throws Exception {
        System.err.println("Setting up PolyglotEngine");
        PolyglotEngine vm = PolyglotEngine.newBuilder().
            build();

        URL url = Main.class.getProtectionDomain().getCodeSource().getLocation();
        File local = new File(url.toURI());
        for (;;) {
            File sieveInRuby = new File(local, "sieve.rb");
            if (sieveInRuby.exists()) {
                break;
            }
            local = local.getParentFile();
        }

        Source ruby = Source.newBuilder(new File(local, "sieve.rb")).build();
        Source js = Source.newBuilder(new File(local, "sieve.js")).build();

        vm.eval(ruby);
        vm.eval(js);
    }
}

Use builder to construct the source


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

import java.util.Iterator;

import org.apache.commons.collections.PredicateUtils;

/**
 * A FilterIterator which only returns "unique" Objects.  Internally,
 * the Iterator maintains a Set of objects it has already encountered,
 * and duplicate Objects are skipped.
 *
 * @since Commons Collections 2.1
 * @version $Revision: 1.8 $ $Date: 2004/02/18 00:59:50 $
 *
 * @author Morgan Delagrange
 */
public class UniqueFilterIterator extends FilterIterator {

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

    /**
     *  Constructs a new UniqueFilterIterator.
     *
     *  @param iterator  the iterator to use
     */
    public UniqueFilterIterator( Iterator iterator ) {
        super(iterator, PredicateUtils.uniquePredicate());
    }

}

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

import java.util.Iterator;

import org.apache.commons.collections.functors.UniquePredicate;

/**
 * A FilterIterator which only returns "unique" Objects.  Internally,
 * the Iterator maintains a Set of objects it has already encountered,
 * and duplicate Objects are skipped.
 *
 * @since Commons Collections 2.1
 * @version $Revision: 1.9 $ $Date: 2004/05/07 23:29:02 $
 *
 * @author Morgan Delagrange
 */
public class UniqueFilterIterator extends FilterIterator {

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

    /**
     *  Constructs a new UniqueFilterIterator.
     *
     *  @param iterator  the iterator to use
     */
    public UniqueFilterIterator( Iterator iterator ) {
        super(iterator, UniquePredicate.getInstance());
    }

}

Change to UniquePredicate to avoid indirect references via PredicateUtils


package com.faforever.api.dto;

import com.faforever.api.elide.ElideEntity;
import com.github.jasminb.jsonapi.annotations.Id;
import com.github.jasminb.jsonapi.annotations.Relationship;
import com.github.jasminb.jsonapi.annotations.Type;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.jetbrains.annotations.Nullable;

import java.time.OffsetDateTime;

@Data
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Builder
@Type(GamePlayerStats.TYPE)
public class GamePlayerStats implements ElideEntity {
  public static final String TYPE = "game";

  @Id
  @EqualsAndHashCode.Include
  private String id;
  private boolean ai;
  private Faction faction;
  private byte color;
  private byte team;
  private byte startSpot;
  private Float beforeMean;
  private Float beforeDeviation;
  private Float afterMean;
  private Float afterDeviation;
  private byte score;
  @Nullable
  private OffsetDateTime scoreTime;

  @Relationship("game")
  private Game game;

  @Relationship("player")
  private Player player;
}

package com.faforever.api.dto;

import com.faforever.api.elide.ElideEntity;
import com.github.jasminb.jsonapi.annotations.Id;
import com.github.jasminb.jsonapi.annotations.Relationship;
import com.github.jasminb.jsonapi.annotations.Type;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.jetbrains.annotations.Nullable;

import java.time.OffsetDateTime;

@Data
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Builder
@Type(GamePlayerStats.TYPE)
public class GamePlayerStats implements ElideEntity {
  public static final String TYPE = "gamePlayerStats";

  @Id
  @EqualsAndHashCode.Include
  private String id;
  private boolean ai;
  private Faction faction;
  private byte color;
  private byte team;
  private byte startSpot;
  private Float beforeMean;
  private Float beforeDeviation;
  private Float afterMean;
  private Float afterDeviation;
  private byte score;
  @Nullable
  private OffsetDateTime scoreTime;

  @Relationship("game")
  private Game game;

  @Relationship("player")
  private Player player;
}

Fix wrong type mapping for game player stats


package com.codemonkeylabs.fpslibrary;

import android.app.Application;

/**
 * Created by brianplummer on 8/29/15.
 */
public class TinyDancer
{
    public static TinyDancerBuilder create(){
        return new TinyDancerBuilder();
    }

    public static void hide(Application context) {
        TinyDancerBuilder.hide(context);
    }

}

package com.codemonkeylabs.fpslibrary;

import android.app.Application;

/**
 * Created by brianplummer on 8/29/15.
 */
public class TinyDancer
{
    public static TinyDancerBuilder create(){
        return new TinyDancerBuilder();
    }

    public static void hide(Content context) {
        TinyDancerBuilder.hide(context.getApplicationContext());
    }

}

Change hide parameter to context


package it.axant.axemas;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.ViewGroup;
import java.lang.ref.WeakReference;

public class AXMSectionController {
    private WeakReference<SectionFragment> section;

    public AXMSectionController(SectionFragment section) {
        this.section = new WeakReference<SectionFragment>(section);
    }

    protected SectionFragment getSection() {
        return this.section.get();
    }

    public void sectionDidLoad() {
        // web page finished loading
    }

    public void sectionWillLoad() {
        // web page has not yet started to load
    }

    public void sectionOnViewCreate(ViewGroup view) {
        // axemas view/fragment got created
    }

    public boolean isInsideWebView(MotionEvent ev) {
        return true;
    }

    /*
    The following methods are specific to Android as they follow the android excluside lifecycle.
     */
    public void sectionFragmentWillPause() { }
    public void sectionFragmentWillResume() { }
    public void sectionFragmentOnSaveInstanceState(Bundle outState) { }
    public void sectionFragmentOnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { }
    public void sectionFragmentOnActivityResult(int requestCode, int resultCode, Intent data) { }
    public void actionbarRightButtonAction() {}
}

package it.axant.axemas;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.ViewGroup;
import java.lang.ref.WeakReference;

public class AXMSectionController {
    private WeakReference<SectionFragment> section;

    protected AXMSectionController() {
        throw new UnsupportedOperationException("Section Controllers should never be created without a section");
    }

    public AXMSectionController(SectionFragment section) {
        this.section = new WeakReference<SectionFragment>(section);
    }

    protected SectionFragment getSection() {
        return this.section.get();
    }

    public void sectionDidLoad() {
        // web page finished loading
    }

    public void sectionWillLoad() {
        // web page has not yet started to load
    }

    public void sectionOnViewCreate(ViewGroup view) {
        // axemas view/fragment got created
    }

    public boolean isInsideWebView(MotionEvent ev) {
        return true;
    }

    /*
    The following methods are specific to Android as they follow the android excluside lifecycle.
     */
    public void sectionFragmentWillPause() { }
    public void sectionFragmentWillResume() { }
    public void sectionFragmentOnSaveInstanceState(Bundle outState) { }
    public void sectionFragmentOnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { }
    public void sectionFragmentOnActivityResult(int requestCode, int resultCode, Intent data) { }
    public void actionbarRightButtonAction() {}
}

Add unusable default constructor to section controllers, for convenience when subclassing


package org.commcare.dalvik.application;

import org.commcare.android.database.HybridFileBackedSqlStorage;
import org.commcare.android.database.HybridFileBackedSqlStorageMock;
import org.javarosa.core.services.storage.Persistable;

/**
 * @author Phillip Mates (pmates@dimagi.com).
 */
public class CommCareTestApplication extends CommCareApplication {
    @Override
    public <T extends Persistable> HybridFileBackedSqlStorage<T> getFileBackedAppStorage(String name, Class<T> c) {
        return getCurrentApp().getFileBackedStorage(name, c);
    }

    @Override
    public <T extends Persistable> HybridFileBackedSqlStorage<T> getFileBackedUserStorage(String storage, Class<T> c) {
        return new HybridFileBackedSqlStorageMock<>(storage, c, buildUserDbHandle(), getUserKeyRecordId());
    }

    @Override
    public CommCareApp getCurrentApp() {
        return new CommCareTestApp(super.getCurrentApp());
    }
}

package org.commcare.dalvik.application;

import org.commcare.android.database.HybridFileBackedSqlStorage;
import org.commcare.android.database.HybridFileBackedSqlStorageMock;
import org.javarosa.core.services.storage.Persistable;
import org.junit.Assert;

/**
 * @author Phillip Mates (pmates@dimagi.com).
 */
public class CommCareTestApplication extends CommCareApplication {
    @Override
    public void onCreate() {
        super.onCreate();

        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable ex) {
                Assert.fail(ex.getMessage());
            }
        });
    }

    @Override
    public <T extends Persistable> HybridFileBackedSqlStorage<T> getFileBackedAppStorage(String name, Class<T> c) {
        return getCurrentApp().getFileBackedStorage(name, c);
    }

    @Override
    public <T extends Persistable> HybridFileBackedSqlStorage<T> getFileBackedUserStorage(String storage, Class<T> c) {
        return new HybridFileBackedSqlStorageMock<>(storage, c, buildUserDbHandle(), getUserKeyRecordId());
    }

    @Override
    public CommCareApp getCurrentApp() {
        return new CommCareTestApp(super.getCurrentApp());
    }
}

Add top-level exception handler that just fails test


package to.etc.testutil;

/**
 * @author Frits Jalvingh
 * Created on 15-04-22.
 */
final public class TestUtil {
	private TestUtil() {}

	public static void nonTestPrintln(String text) {
		if(! inTest())
			System.out.println(text);
	}

	static public boolean inTest() {
		return System.getProperty("surefire.real.class.path") != null || System.getProperty("surefire.test.class.path") != null;
	}

}

package to.etc.testutil;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @author Frits Jalvingh
 * Created on 15-04-22.
 */
final public class TestUtil {
	private TestUtil() {
	}

	public static void nonTestPrintln(String text) {
		if(!inTest())
			System.out.println(text);
	}

	static public boolean inTest() {
		return System.getProperty("surefire.real.class.path") != null || System.getProperty("surefire.test.class.path") != null;
	}

	static public String getGitBranch() {
		try {
			Process process = Runtime.getRuntime().exec("git rev-parse --abbrev-ref HEAD");
			process.waitFor();
			BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			return reader.readLine();
		} catch(Exception x) {
			return null;
		}
	}

	static public void main(String[] args) {
		System.out.println("branch: " + getGitBranch());
	}

}

Add code to detect a git branch


package br.com.bloder.better_migrations.migrations;

import br.com.bloder.migration.Migration;
import io.realm.DynamicRealm;

/**
 * Created by bloder on 25/09/16.
 */
public class VersionOne extends Migration {

  @Override
  public void up(DynamicRealm realm) {
    realm.getSchema().get("User").addField("age", Integer.class);
  }

  @Override
  public void down(DynamicRealm realm) {
    realm.getSchema().get("User").removeField("age");
  }
}

package br.com.bloder.better_migrations.migrations;

import br.com.bloder.migration.Migration;
import br.com.bloder.migration.schema.BetterSchema;
import io.realm.DynamicRealm;

/**
 * Created by bloder on 25/09/16.
 */
public class VersionOne extends Migration {

  @Override
  public void up(DynamicRealm realm) {
    BetterSchema betterSchema = new BetterSchema();
    betterSchema.setSchema(realm);
    betterSchema.addField("age", Integer.class).inClass("User");
  }

  @Override
  public void down(DynamicRealm realm) {
    BetterSchema betterSchema = new BetterSchema();
    betterSchema.setSchema(realm);
    betterSchema.removeField("age").inClass("User");
  }
}

Change better migration example actions


package com.github.vlsi.mat.optiq;

public class HeapFunctions {
    public static int get_id(Object r) {
        if (r == null || !(r instanceof HeapReference)) return -1;
        return ((HeapReference) r).getIObject().getObjectId();
    }

    public static String toString(Object r) {
        if (r == null) return null;
        return r.toString();
    }
}

package com.github.vlsi.mat.optiq;

import org.eclipse.mat.SnapshotException;
import org.eclipse.mat.snapshot.ISnapshot;
import org.eclipse.mat.snapshot.model.*;

public class HeapFunctions {
    public static int get_id(Object r) {
        HeapReference ref = ensureHeapReference(r);
        return ref == null ? -1 : ref.getIObject().getObjectId();
    }

    public static String toString(Object r) {
        if (r == null) return null;
        return r.toString();
    }

    public static Object get_by_key(Object r, String value) {
        HeapReference ref = ensureHeapReference(r);
        if (ref == null) {
            return null;
        }
        IObject iObject = ref.getIObject();
        ISnapshot snapshot = iObject.getSnapshot();
        String className = iObject.getClazz().getName();

        if (!"java.util.HashMap".equals(className))
        {
            throw new RuntimeException("Unsupported map type: "+className);
        }

        try
        {
            IObjectArray table = (IObjectArray)iObject.resolveValue("table");
            long[] referenceArray = table.getReferenceArray();
            for (long entryAddress : referenceArray)
            {
                if (entryAddress != 0)
                {
                    int entryId = snapshot.mapAddressToId(entryAddress);
                    IObject entry = snapshot.getObject(entryId);
                    while (entry != null)
                    {
                        IObject keyObject = (IObject) entry.resolveValue("key");
                        if (value.equals(toString(keyObject)))
                        {
                            IObject valueObject = (IObject) entry.resolveValue(("value"));
                            if (valueObject != null)
                            {
                                return new HeapReference(snapshot, valueObject);
                            }
                            else
                            {
                                return null;
                            }
                        }

                        entry = (IObject)entry.resolveValue("next");
                    }
                }
            }
        } catch (SnapshotException e)
        {
            throw new RuntimeException(e);
        }

        return null;
    }

    private static HeapReference ensureHeapReference(Object r) {
        return (r == null || !(r instanceof HeapReference)) ?
                null :
                (HeapReference) r;
    }

    private static String toString(IObject o) {
        String classSpecific = o.getClassSpecificName();
        if (classSpecific != null)
            return classSpecific;
        return o.getDisplayName();
    }
}

Add get_by_key function to extract value by key from HashMaps


/****************************************************************************
 * Copyright (C) 2017-2018 ecsec GmbH.
 * All rights reserved.
 * Contact: ecsec GmbH (info@ecsec.de)
 *
 * This file is part of the Open eCard App.
 *
 * GNU General Public License Usage
 * This file may be used under the terms of the GNU General Public
 * License version 3.0 as published by the Free Software Foundation
 * and appearing in the file LICENSE.GPL included in the packaging of
 * this file. Please review the following information to ensure the
 * GNU General Public License version 3.0 requirements will be met:
 * http://www.gnu.org/copyleft/gpl.html.
 *
 * Other Usage
 * Alternatively, this file may be used in accordance with the terms
 * and conditions contained in a signed written agreement between
 * you and ecsec GmbH.
 *
 ***************************************************************************/

package org.openecard.gui.android.eac.types;

/**
 *
 * @author Tobias Wich
 */
public enum PinStatus {

    RC3,
    RC2,
    CAN,
    BLOCKED,
    DEACTIVATED;

    public boolean isBlocked() {
	return BLOCKED == this;
    }

    public boolean isOperational() {
	return ! isBlocked();
    }

    public boolean needsCan() {
	return CAN == this;
    }

}

/****************************************************************************
 * Copyright (C) 2017-2018 ecsec GmbH.
 * All rights reserved.
 * Contact: ecsec GmbH (info@ecsec.de)
 *
 * This file is part of the Open eCard App.
 *
 * GNU General Public License Usage
 * This file may be used under the terms of the GNU General Public
 * License version 3.0 as published by the Free Software Foundation
 * and appearing in the file LICENSE.GPL included in the packaging of
 * this file. Please review the following information to ensure the
 * GNU General Public License version 3.0 requirements will be met:
 * http://www.gnu.org/copyleft/gpl.html.
 *
 * Other Usage
 * Alternatively, this file may be used in accordance with the terms
 * and conditions contained in a signed written agreement between
 * you and ecsec GmbH.
 *
 ***************************************************************************/

package org.openecard.gui.android.eac.types;

/**
 *
 * @author Tobias Wich
 */
public enum PinStatus {

    RC3,
    RC2,
    CAN,
    BLOCKED,
    DEACTIVATED;

    public boolean isBlocked() {
	return BLOCKED == this;
    }

    public boolean isOperational() {
	return ! isBlocked() && DEACTIVATED != this;
    }

    public boolean needsCan() {
	return CAN == this;
    }

}

Check PIN deactivated status when checking for card operationality


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

import org.gradle.api.Describable;
import org.gradle.api.Incubating;

/**
 * Captures user-provided information about a version control system.
 *
 * @since 4.4
 */
@Incubating
public interface VersionControlSpec extends Describable {
    /**
     * Returns a {@link String} identifier which will be unique to this version
     * control specification among other version control specifications.
     */
    String getUniqueId();

    /**
     * Returns the name of the repository.
     */
    String getRepoName();

    /**
     * Returns the relative path to the root of the build within the repository.
     */
    String getRootDir();

    /**
     * Sets the relative path to the root of the build within the repository.
     * <p>
     * Defaults to an empty relative path, meaning the root of the repository.
     */
    void setRootDir(String rootDir);
}

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

import org.gradle.api.Describable;
import org.gradle.api.Incubating;

/**
 * Captures user-provided information about a version control system.
 *
 * @since 4.4
 */
@Incubating
public interface VersionControlSpec extends Describable {
    /**
     * Returns a {@link String} identifier which will be unique to this version
     * control specification among other version control specifications.
     */
    String getUniqueId();

    /**
     * Returns the name of the repository.
     */
    String getRepoName();

    /**
     * Returns the relative path to the root of the build within the repository.
     *
     * @since 4.5
     */
    String getRootDir();

    /**
     * Sets the relative path to the root of the build within the repository.
     * <p>
     * Defaults to an empty relative path, meaning the root of the repository.
     *
     * @since 4.5
     */
    void setRootDir(String rootDir);
}

Annotate new methods with since 4.5


package cpw.mods.fml.common.network;

import net.minecraft.src.NetHandler;
import net.minecraft.src.NetworkManager;

public class ModMissingPacket extends FMLPacket
{

    public ModMissingPacket()
    {
        super(Type.MOD_MISSING);
    }

    @Override
    public byte[] generatePacket(Object... data)
    {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public FMLPacket consumePacket(byte[] data)
    {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void execute(NetworkManager network, FMLNetworkHandler handler, NetHandler netHandler, String userName)
    {
        // TODO Auto-generated method stub

    }

}

package cpw.mods.fml.common.network;

import java.util.List;

import net.minecraft.src.NetHandler;
import net.minecraft.src.NetworkManager;

public class ModMissingPacket extends FMLPacket
{

    public ModMissingPacket()
    {
        super(Type.MOD_MISSING);
    }

    @Override
    public byte[] generatePacket(Object... data)
    {
        // TODO
        List<String> missing = (List<String>) data[0];
        List<String> badVersion = (List<String>) data[1];

        return new byte[0];
    }

    @Override
    public FMLPacket consumePacket(byte[] data)
    {
        // TODO
        return this;
    }

    @Override
    public void execute(NetworkManager network, FMLNetworkHandler handler, NetHandler netHandler, String userName)
    {
        // TODO
    }

}

Fix NPE on missing mods - still need to actually handle missing mods properly on client


package forklift.integration;

import forklift.Forklift;
import forklift.connectors.ConnectorException;
import forklift.consumer.Consumer;
import forklift.exception.StartupException;
import forklift.producers.ForkliftProducerI;
import forklift.producers.ProducerException;
import org.junit.Test;

public class ConsumerActionTests extends BaseIntegrationTest {

    /**
     * Test subscribing to a topic, unsubscribing, then resubscribing to the topic.
     */
    @Test
    public void topicTurnoverTest() throws StartupException, ConnectorException, InterruptedException, ProducerException {
        Forklift forklift = serviceManager.newManagedForkliftInstance();
        ForkliftProducerI producer = forklift.getConnector().getQueueProducer("forklift-string-topic");
        sentMessageIds.add(producer.send("message1"));
        final Consumer c1 = new Consumer(StringConsumer.class, forklift);
        // Shutdown the consumer after all the messages have been processed.
        c1.setOutOfMessages((listener) -> {
            listener.shutdown();
        });
        // Start the consumer.
        c1.listen();
        Thread.sleep(3000);
        sentMessageIds.add(producer.send("message2"));
        final Consumer c2 = new Consumer(StringConsumer.class, forklift);
        // Shutdown the consumer after all the messages have been processed.
        c2.setOutOfMessages((listener) -> {
            listener.shutdown();
        });
        // Start the consumer.
        c2.listen();
        messageAsserts();
    }

}

package forklift.integration;

import forklift.Forklift;
import forklift.connectors.ConnectorException;
import forklift.consumer.Consumer;
import forklift.exception.StartupException;
import forklift.producers.ForkliftProducerI;
import forklift.producers.ProducerException;
import org.junit.Test;

public class ConsumerActionTests extends BaseIntegrationTest {

    /**
     * Test subscribing to a topic, unsubscribing, then resubscribing to the topic.
     */
    @Test
    public void topicTurnoverTest() throws StartupException, ConnectorException, InterruptedException, ProducerException {
        Forklift forklift = serviceManager.newManagedForkliftInstance();
        ForkliftProducerI producer = forklift.getConnector().getQueueProducer("forklift-string-topic");
        sentMessageIds.add(producer.send("message1"));
        final Consumer c1 = new Consumer(StringConsumer.class, forklift);

        // Shutdown the consumer after all the messages have been processed.
        c1.setOutOfMessages((listener) -> {
            timeouts++;

            if (sentMessageIds.equals(consumedMessageIds) || timeouts > maxTimeouts) {
                listener.shutdown();
            }
        });
        // Start the consumer.
        c1.listen();

        sentMessageIds.add(producer.send("message2"));
        final Consumer c2 = new Consumer(StringConsumer.class, forklift);

        // Shutdown the consumer after all the messages have been processed.
        timeouts = 0;
        c2.setOutOfMessages((listener) -> {
            timeouts++;

            if (sentMessageIds.equals(consumedMessageIds) || timeouts > maxTimeouts) {
                listener.shutdown();
            }
        });
        // Start the consumer.
        c2.listen();
        messageAsserts();
    }

}

Fix a test that should've been fixed long ago with the others


package com.varunvats.practice.sorting;

public class MergeTopDown extends MergeBase {

    public static <T extends Comparable<T>> void sort(T[] a) {
        final int N = a.length;
        aux = new Comparable[N];
        sort(a, 0, N - 1);
    }

    private static <T extends Comparable<T>> void sort(T[] a, int low, int high) {
        if (low >= high)
            return;
        final int mid = (low + high) / 2;
        sort(a, low, mid);
        sort(a, mid + 1, high);
        if (!less(a[mid], a[mid + 1]))
            merge(a, low, mid, high);
    }

}

package com.varunvats.practice.sorting;

public class MergeTopDown extends MergeBase {

    /**
     * Sorts an array in-place using the top-down merge-sort algorithm.
     *
     * @param a The array to be sorted.
     */
    public static <T extends Comparable<T>> void sort(T[] a) {
        final int N = a.length;
        aux = new Comparable[N];
        sort(a, 0, N - 1);
    }

    private static <T extends Comparable<T>> void sort(T[] a, int low, int high) {
        if (low >= high)
            return;
        final int mid = (low + high) / 2;
        sort(a, low, mid);
        sort(a, mid + 1, high);
        if (!less(a[mid], a[mid + 1]))
            merge(a, low, mid, high);
    }

}

Add doc comment for top-down Merge sort.


package org.basinmc.faucet.event;

import org.basinmc.faucet.internal.warn.Volatile;

/**
 * Marks the annotated type as an event which may be passed to the local event bus.
 *
 * @author Johannes Donath
 */
public interface Event<STATE extends Enum<STATE>> {

  /**
   * Retrieves the default state for this event's execution context.
   *
   * @return an arbitrary state.
   */
  @Volatile
  default STATE getDefaultState() {
    return null;
  }
}

package org.basinmc.faucet.event;

import javax.annotation.Nullable;

/**
 * Marks the annotated type as an event which may be passed to the local event bus.
 *
 * @author Johannes Donath
 */
public interface Event<STATE extends Enum<STATE>> {

  /**
   * Retrieves the default state for this event's execution context.
   *
   * @return an arbitrary state.
   */
  @Nullable
  default STATE getDefaultState() {
    return null;
  }
}

Mark the default state getter nullable in case no state is desired.


package me.devsaki.hentoid.collection.mikan;

import com.google.gson.annotations.Expose;

import me.devsaki.hentoid.database.domains.Attribute;
import me.devsaki.hentoid.enums.AttributeType;
import me.devsaki.hentoid.enums.Site;

public class MikanAttribute {
    // Published by both Collection and Attributes endpoints
    @Expose
    public String name;

    // Published by Collection (book search, recent) endpoints
    @Expose
    public String url;

    // Published by Attributes endpoints
    @Expose
    public int id;
    @Expose
    public int count;
    @Expose
    public String type;

    Attribute toAttribute() {
        AttributeType type;
        switch (this.type) {
            case "language":
                type = AttributeType.LANGUAGE;
                break;
            case "character":
                type = AttributeType.CHARACTER;
                break;
            case "artist":
                type = AttributeType.ARTIST;
                break;
            case "group":
                type = AttributeType.CIRCLE;
                break;
            default:
                type = AttributeType.TAG;
        }
        Attribute result = new Attribute(type, name, url, Site.HITOMI);
        result.setCount(count);
        result.setExternalId(id);

        return result;
    }
}

package me.devsaki.hentoid.collection.mikan;

import com.google.gson.annotations.Expose;

import me.devsaki.hentoid.database.domains.Attribute;
import me.devsaki.hentoid.enums.AttributeType;
import me.devsaki.hentoid.enums.Site;

public class MikanAttribute {
    // Published by both Collection and Attributes endpoints
    @Expose
    public String name;

    // Published by Collection (book search, recent) endpoints
    @Expose
    public String url;

    // Published by Attributes endpoints
    @Expose
    public int id;
    @Expose
    public int count;
    @Expose
    public String type;

    Attribute toAttribute() {
        AttributeType attrType;
        switch (type) {
            case "language":
                attrType = AttributeType.LANGUAGE;
                break;
            case "character":
                attrType = AttributeType.CHARACTER;
                break;
            case "artist":
                attrType = AttributeType.ARTIST;
                break;
            case "group":
                attrType = AttributeType.CIRCLE;
                break;
            default:
                attrType = AttributeType.TAG;
        }
        Attribute result = new Attribute(attrType, name, url, Site.HITOMI);
        result.setCount(count);
        result.setExternalId(id);

        return result;
    }
}

Fix issues reported by Sonar


package com.github.kratorius.cuckoohash;

public class ViewsTest {
}

package com.github.kratorius.cuckoohash;

import junit.framework.TestCase;

import java.util.AbstractMap;
import java.util.Map;
import java.util.Set;

/**
 * Tests for entrySet(), keySet() and values().
 */
public class ViewsTest extends TestCase {
  @SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
  public void testEmptyEntrySet() {
    CuckooHashMap<String, Integer> m = new CuckooHashMap<>();
    assertTrue(m.entrySet().isEmpty());
  }

  public void testSimpleEntrySet() {
    CuckooHashMap<String, Integer> m = new CuckooHashMap<>();

    m.put("key1", 1);
    assertEquals(1, m.entrySet().size());

    Map.Entry<String, Integer> item = m.entrySet().iterator().next();
    assertEquals(1, (int) item.getValue());
  }

  public void testLargeEntrySet() {
    final int size = 1024;
    CuckooHashMap<String, Integer> m = new CuckooHashMap<>();

    for (int i = 0; i < size; i++){
      m.put("key-" + i, 100);
    }

    Set<Map.Entry<String, Integer>> entrySet = m.entrySet();
    assertEquals(size, entrySet.size());
    assertEquals(size, m.size());

    for (int i = 0; i < size; i++) {
      assertTrue(entrySet.contains(new AbstractMap.SimpleEntry<>("key-" + i, 100)));
    }
  }

  // TODO keySet() and values()
}

Add thorough tests for entrySet()


package com.msgilligan.peerlist.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages="com.msgilligan.peerlist")
public class Application {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);
        app.setShowBanner(false);
        ApplicationContext ctx = app.run();
    }

    @Bean
    public ServerProperties myServerProperties() {
        ServerProperties p = new ServerProperties();
        String portStr = System.getProperty("app.port");  // CloudBees Environment Variable for local port
        int port = (portStr != null) ? Integer.parseInt(portStr) : 8080;
        p.setPort(port);
        return p;
    }
}

package com.msgilligan.peerlist.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages="com.msgilligan.peerlist")
public class Application {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);
        app.setShowBanner(false);
        ApplicationContext ctx = app.run();
    }
}

Remove CloudBees port setting method


package org.javarosa.core.services.storage;

public class StorageModifiedException extends RuntimeException {

}

package org.javarosa.core.services.storage;

public class StorageModifiedException extends RuntimeException {
	public StorageModifiedException() {
		super();
	}

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

Support Messages in storage modified exceptions


package seedu.address.logic.commands;

import seedu.address.commons.core.Messages;
import seedu.address.commons.core.UnmodifiableObservableList;
import seedu.address.model.person.ReadOnlyPerson;
import seedu.address.model.person.UniquePersonList.PersonNotFoundException;

/**
 * Deletes a person identified using it's last displayed index from the address book.
 */
public class DeleteCommand extends Command {

    public static final String COMMAND_WORD = "delete";

    public static final String MESSAGE_USAGE = COMMAND_WORD
            + ": Deletes the person identified by the index number used in the last person listing.\n"
            + "Parameters: INDEX (must be a positive integer)\n"
            + "Example: " + COMMAND_WORD + " 1";

    public static final String MESSAGE_DELETE_PERSON_SUCCESS = "Deleted Person: %1$s";

    public final int targetIndex;

    public DeleteCommand(int targetIndex) {
        this.targetIndex = targetIndex;
    }

    @Override
    public CommandResult execute() {

        UnmodifiableObservableList<ReadOnlyPerson> lastShownList = model.getFilteredPersonList();

        if (lastShownList.size() < targetIndex) {
            indicateAttemptToExecuteIncorrectCommand();
            return new CommandResult(Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX);
        }

        ReadOnlyPerson personToDelete = lastShownList.get(targetIndex - 1);

        try {
            model.deletePerson(personToDelete);
        } catch (PersonNotFoundException pnfe) {
            assert false : "The target person cannot be missing";
        }

        return new CommandResult(String.format(MESSAGE_DELETE_PERSON_SUCCESS, personToDelete));
    }

}

package seedu.address.logic.commands;

import seedu.address.commons.core.Messages;
import seedu.address.commons.core.UnmodifiableObservableList;
import seedu.address.model.person.ReadOnlyPerson;
import seedu.address.model.person.UniquePersonList.TaskNotFoundException;

/**
 * Deletes a task identified using it's last displayed index from the task manager.
 */
public class DeleteCommand extends Command {

    public static final String COMMAND_WORD = "delete";

    public static final String MESSAGE_USAGE = COMMAND_WORD
            + ": Deletes the task identified by the index number used in the last task listing.\n"
            + "Parameters: INDEX (must be a positive integer)\n"
            + "Example: " + COMMAND_WORD + " 1";

    public static final String MESSAGE_DELETE_TASK_SUCCESS = "Deleted Task: %1$s";

    public final int targetIndex;

    public DeleteCommand(int targetIndex) {
        this.targetIndex = targetIndex;
    }

    @Override
    public CommandResult execute() {

        UnmodifiableObservableList<ReadOnlyPerson> lastShownList = model.getFilteredPersonList();

        if (lastShownList.size() < targetIndex) {
            indicateAttemptToExecuteIncorrectCommand();
            return new CommandResult(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
        }

        ReadOnlyPerson taskToDelete = lastShownList.get(targetIndex - 1);

        try {
            model.deleteTask(taskToDelete);
        } catch (TaskNotFoundException pnfe) {
            assert false : "The target task cannot be missing";
        }

        return new CommandResult(String.format(MESSAGE_DELETE_TASK_SUCCESS, taskToDelete));
    }

}

Change occurrence of person to tasks in deleteCommand class


/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package info.zamojski.soft.towercollector.utils;

import android.Manifest;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;

public class NetworkUtils {
    public static String getNetworkType(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (manager == null)
            return "NO CONNECTIVITY";
        NetworkInfo netInfo = manager.getActiveNetworkInfo();
        if (netInfo == null)
            return "NO ACTIVE NETWORK";
        return netInfo.getTypeName().toUpperCase();
    }

    public static boolean isNetworkAvailable(Context context) {
        if (PermissionUtils.hasPermissions(context, Manifest.permission.ACCESS_NETWORK_STATE)) {
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo();
            return (activeNetworkInfo != null && activeNetworkInfo.isConnected());
        }
        return true; // assume there's one
    }

    public static boolean isInAirplaneMode(Context context) {
        return Settings.System.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
    }
}

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package info.zamojski.soft.towercollector.utils;

import android.Manifest;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;

public class NetworkUtils {
    public static String getNetworkType(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (manager == null)
            return "NO CONNECTIVITY";
        NetworkInfo netInfo = manager.getActiveNetworkInfo();
        if (netInfo == null)
            return "NO ACTIVE NETWORK";
        return netInfo.getTypeName().toUpperCase();
    }

    public static boolean isNetworkAvailable(Context context) {
        if (PermissionUtils.hasPermissions(context, Manifest.permission.ACCESS_NETWORK_STATE)) {
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo();
            return (activeNetworkInfo != null && activeNetworkInfo.isConnected());
        }
        return true; // assume there's one
    }

    public static boolean isInAirplaneMode(Context context) {
        return Settings.Global.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
    }
}

Use global settings instead of system settings.


package net.folab.fo.runtime._fo._lang;

import static net.folab.fo.runtime._fo._lang.Boolean.*;
import static net.folab.fo.runtime._fo._lang.Integer.*;

import net.folab.fo.runtime.Evaluable;
import net.folab.fo.runtime.Function;

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

public class BooleanTest {

    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void test() {

        Function<Evaluable<Boolean>, Function<Evaluable<Boolean>, Evaluable<Boolean>>> falseChoose = FALSE
                .choose();
        Function<Evaluable<Boolean>, Function<Evaluable<Boolean>, Evaluable<Boolean>>> trueChoose = TRUE
                .choose();

        System.out.println(falseChoose.apply(FALSE).apply(TRUE).evaluate()
                .getValue());
        System.out.println(trueChoose.apply(FALSE).apply(TRUE).evaluate()
                .getValue());

    }

    @Test
    public void testI() {

        Function<Evaluable<Integer>, Function<Evaluable<Integer>, Evaluable<Integer>>> falseChoose = FALSE
                .choose();
        Function<Evaluable<Integer>, Function<Evaluable<Integer>, Evaluable<Integer>>> trueChoose = TRUE
                .choose();

        System.out.println(falseChoose.apply(valueOf(1)).apply(valueOf(0))
                .evaluate().getValue());
        System.out.println(trueChoose.apply(valueOf(1)).apply(valueOf(0))
                .evaluate().getValue());

    }

}

package net.folab.fo.runtime._fo._lang;

import static net.folab.fo.runtime._fo._lang.Boolean.*;
import static net.folab.fo.runtime._fo._lang.Integer.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

import net.folab.fo.runtime._fo._lang._Boolean.choose;

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

public class BooleanTest {

    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void test_Boolean() {

        choose<Boolean> f = FALSE.choose();
        choose<Boolean> t = TRUE.choose();

        assertTrue(f.apply(FALSE).apply(TRUE).evaluate().getValue());
        assertFalse(t.apply(FALSE).apply(TRUE).evaluate().getValue());

    }

    @Test
    public void test_Integer() {

        choose<Integer> f = FALSE.choose();
        choose<Integer> t = TRUE.choose();

        Integer one = valueOf(1);
        Integer zero = valueOf(0);

        assertThat(f.apply(one).apply(zero).evaluate().getValue(), is(0));
        assertThat(t.apply(one).apply(zero).evaluate().getValue(), is(1));

    }

}

Clean up codes as test case


// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.impl.light;

import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiRecordComponent;
import org.jetbrains.annotations.NotNull;

public interface LightRecordMember extends PsiElement {
  @NotNull
  PsiRecordComponent getRecordComponent();
}

// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.impl.light;

import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiRecordComponent;
import com.intellij.psi.SyntheticElement;
import org.jetbrains.annotations.NotNull;

public interface LightRecordMember extends PsiElement, SyntheticElement {
  @NotNull
  PsiRecordComponent getRecordComponent();
}

Mark fields and fields generated by record components as SyntheticElement


package org.realityforge.arez.gwt.examples;

import elemental2.dom.DomGlobal;
import org.realityforge.arez.Arez;
import org.realityforge.arez.browser.extras.spy.ConsoleSpyEventProcessor;
import org.realityforge.arez.extras.WhyRun;

final class ExampleUtil
{
  private ExampleUtil()
  {
  }

  static void spyEvents()
  {
    Arez.context().getSpy().addSpyEventHandler( new ConsoleSpyEventProcessor() );
  }

  static void jsonLogSpyEvents()
  {
    Arez.context().getSpy().addSpyEventHandler( new JsonLogSpyEventProcessor() );
  }

  static void whyRun()
  {
    DomGlobal.console.log( new WhyRun( Arez.context() ).whyRun() );
  }

  static void logAllErrors()
  {
    Arez.context().addObserverErrorHandler( ( observer, error, throwable ) -> {
      DomGlobal.console.log( "Observer error: " + error + "\nobserver: " + observer );
      if ( null != throwable )
      {
        DomGlobal.console.log( throwable );
      }
    } );
  }
}

package org.realityforge.arez.gwt.examples;

import elemental2.dom.DomGlobal;
import org.realityforge.arez.Arez;
import org.realityforge.arez.extras.WhyRun;

final class ExampleUtil
{
  private ExampleUtil()
  {
  }

  static void jsonLogSpyEvents()
  {
    Arez.context().getSpy().addSpyEventHandler( new JsonLogSpyEventProcessor() );
  }

  static void whyRun()
  {
    DomGlobal.console.log( new WhyRun( Arez.context() ).whyRun() );
  }

  static void logAllErrors()
  {
    Arez.context().addObserverErrorHandler( ( observer, error, throwable ) -> {
      DomGlobal.console.log( "Observer error: " + error + "\nobserver: " + observer );
      if ( null != throwable )
      {
        DomGlobal.console.log( throwable );
      }
    } );
  }
}

Remove code no longer required


package org.neuralnetwork.neuron;

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

import org.neuralnetwork.synapse.AbstractSynapse;

public abstract class AbstractNeuron<ValueType, SynapseType extends AbstractSynapse<?, ?>> {
	private ValueType value;
	private Set<SynapseType> inputs = new HashSet<SynapseType>();

	public AbstractNeuron(ValueType initialValue) {
		value = initialValue;
	}

	public ValueType getValue() {
		return value;
	}

	public void addSynapse(SynapseType synapse) {
		inputs.add(synapse);
	}

	public void removeSynapse(SynapseType synapse) {
		inputs.remove(synapse);
	}

	abstract protected ValueType computeValueFromInputs(
			Set<SynapseType> inputs);

	public void computeValue() {
		value = computeValueFromInputs(inputs);
	}
}

package org.neuralnetwork.neuron;

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

import org.neuralnetwork.synapse.AbstractSynapse;

public abstract class AbstractNeuron<ValueType, SynapseType extends AbstractSynapse<?, ?>> {
	private ValueType value;
	private final Set<SynapseType> inputs = new HashSet<SynapseType>();

	public AbstractNeuron(ValueType initialValue) {
		value = initialValue;
	}

	public ValueType getValue() {
		return value;
	}

	public void addSynapse(SynapseType synapse) {
		inputs.add(synapse);
	}

	public void removeSynapse(SynapseType synapse) {
		inputs.remove(synapse);
	}

	abstract protected ValueType computeValueFromInputs(
			Set<SynapseType> inputs);

	public void computeValue() {
		value = computeValueFromInputs(inputs);
	}
}

Make the set of synapses final.


package edu.berkeley.eecs.emission.cordova.comm;

import org.apache.cordova.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import edu.berkeley.eecs.emission.cordova.comm.CommunicationHelper;
import edu.berkeley.eecs.emission.cordova.connectionsettings.ConnectionSettings;

public class CommunicationHelperPlugin extends CordovaPlugin {
    @Override
    public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {
        if (action.equals("pushGetJSON")) {
            try {
                Context ctxt = cordova.getActivity();
                String relativeURL = data.getString(0);
                JSONObject filledMessage = data.getJSONObject(1);

                String commuteTrackerHost = ConnectionSettings.getConnectURL(ctxt);
                String fullURL = commuteTrackerHost + relativeURL;

                String resultString = CommunicationHelper.pushGetJSON(ctxt, fullURL, filledMessage);
                callbackContext.success(new JSONObject(resultString));
            } catch (Exception e) {
                callbackContext.error("While pushing/getting from server "+e.getMessage());
            }
            return true;
        } else {
            return false;
        }
    }
}

package edu.berkeley.eecs.emission.cordova.comm;

import org.apache.cordova.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import edu.berkeley.eecs.emission.cordova.comm.CommunicationHelper;
import edu.berkeley.eecs.emission.cordova.connectionsettings.ConnectionSettings;

public class CommunicationHelperPlugin extends CordovaPlugin {
    @Override
    public boolean execute(String action, JSONArray data, final CallbackContext callbackContext) throws JSONException {
        if (action.equals("pushGetJSON")) {
            try {
                final Context ctxt = cordova.getActivity();
                String relativeURL = data.getString(0);
                final JSONObject filledMessage = data.getJSONObject(1);

                String commuteTrackerHost = ConnectionSettings.getConnectURL(ctxt);
                final String fullURL = commuteTrackerHost + relativeURL;

                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        try {
                String resultString = CommunicationHelper.pushGetJSON(ctxt, fullURL, filledMessage);
                callbackContext.success(new JSONObject(resultString));
            } catch (Exception e) {
                callbackContext.error("While pushing/getting from server "+e.getMessage());
            }
                    }
                });
            } catch (Exception e) {
                callbackContext.error("While pushing/getting from server "+e.getMessage());
            }
            return true;
        } else {
            return false;
        }
    }
}

Move the call to the server into a separate thread


/**
 * Copyright (C) 2014 Kasper Kronborg Isager and Sigrið Gyldenkærne Dalsgarð.
 */
package dk.itu.bookie.controller;

// General utilities
import java.util.ResourceBundle;

// Net utilities
import java.net.URL;

// FXML utilities
import javafx.fxml.Initializable;

/**
 * Application controller class.
 *
 * @version 1.0.0
 */
public final class ApplicationController implements Initializable {
  private static ApplicationController instance;

  public ApplicationController getInstance() {
    return ApplicationController.instance;
  }

  public void initialize(URL url, ResourceBundle resourceBundle) {
    ApplicationController.instance = this;
  }
}

/**
 * Copyright (C) 2014 Kasper Kronborg Isager and Sigrið Gyldenkærne Dalsgarð.
 */
package dk.itu.bookie.controller;

// General utilities
import java.util.ResourceBundle;

// Net utilities
import java.net.URL;

// SQL utilities
import java.sql.SQLException;

// JavaFX collections
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

// FXML utilities
import javafx.fxml.FXML;

// Donkey utilities
import dk.itu.donkey.Model;

// Models
import dk.itu.bookie.model.Showtime;
import dk.itu.bookie.model.Reservation;

/**
 * Application controller class.
 *
 * @version 1.0.0
 */
public final class ApplicationController {
  private static ApplicationController instance;

  private static ObservableList<Showtime> showtimes;

  private static ObservableList<Reservation> reservations;

  public ApplicationController getInstance() {
    return ApplicationController.instance;
  }

  public void initialize() {
    ApplicationController.instance = this;
  }

  public static ObservableList<Showtime> showtimes() throws SQLException {
    if (ApplicationController.showtimes == null) {
      ApplicationController.showtimes = FXCollections.observableArrayList(
        Model
          .find(Showtime.class)
          .where("playingat", ">", System.currentTimeMillis())
          .orderBy("movies.name")
          .orderBy("playingat")
          .get()
      );
    }

    return ApplicationController.showtimes;
  }

  public static ObservableList<Reservation> reservations() throws SQLException {
    if (ApplicationController.reservations == null) {
      ApplicationController.reservations = FXCollections.observableArrayList(
        Model
          .find(Reservation.class)
          .where("showtimes.playingat", ">", System.currentTimeMillis())
          .orderBy("showtimes.playingat")
          .get()
      );
    }

    return ApplicationController.reservations;
  }
}

Handle data querying in Application controller.


package liquibase.change.core;

import liquibase.change.AbstractSQLChange;
import liquibase.change.ChangeMetaData;

/**
 * Allows execution of arbitrary SQL.  This change can be used when existing changes are either don't exist,
 * are not flexible enough, or buggy.
 */
public class RawSQLChange extends AbstractSQLChange {

    private String comments;
    public RawSQLChange() {
        super("sql", "Custom SQL", ChangeMetaData.PRIORITY_DEFAULT);
    }

    public RawSQLChange(String sql) {
        this();
        setSql(sql);
    }

    public String getComments() {
        return comments;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }

    public String getConfirmationMessage() {
        return "Custom SQL executed";
    }
}

package liquibase.change.core;

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

import liquibase.change.AbstractSQLChange;
import liquibase.change.ChangeMetaData;
import liquibase.database.Database;
import liquibase.database.core.MSSQLDatabase;
import liquibase.exception.DatabaseException;
import liquibase.statement.SqlStatement;
import liquibase.statement.core.RawSqlStatement;
import liquibase.util.StringUtils;

/**
 * Allows execution of arbitrary SQL.  This change can be used when existing changes are either don't exist,
 * are not flexible enough, or buggy.
 */
public class RawSQLChange extends AbstractSQLChange {

    private String comments;
    public RawSQLChange() {
        super("sql", "Custom SQL", ChangeMetaData.PRIORITY_DEFAULT);
    }

    public RawSQLChange(String sql) {
        this();
        setSql(sql);
    }

    public String getComments() {
        return comments;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }

    public String getConfirmationMessage() {
        return "Custom SQL executed";
    }

	public SqlStatement[] generateStatements(Database database) {
		List<SqlStatement> returnStatements = new ArrayList<SqlStatement>();

		if (StringUtils.trimToNull(getSql()) == null) {
			return new SqlStatement[0];
		}

		String processedSQL = getSql().replaceAll("\r\n", "\n").replaceAll("\r", "\n");
		for (String statement : StringUtils.processMutliLineSQL(processedSQL, isStrippingComments(),
				isSplittingStatements(), getEndDelimiter())) {
			if (database instanceof MSSQLDatabase) {
				statement = statement.replaceAll("\n", "\r\n");
			}

			String escapedStatement;
			try {
				escapedStatement = database.getConnection().nativeSQL(statement);
			} catch (DatabaseException e) {
				escapedStatement = statement;
			}

			returnStatements.add(new RawSqlStatement(escapedStatement, getEndDelimiter()));
		}

		return returnStatements.toArray(new SqlStatement[returnStatements.size()]);
	}
}

Convert raw query to native representation


package hudson.plugins.analysis.util;

import org.apache.xerces.parsers.SAXParser;

/**
 * Registers the correct SAX driver if the environment variable is set.
 */
public class SaxSetup {
    /** Property of SAX parser factory. */
    private static final String SAX_DRIVER_PROPERTY = "org.xml.sax.driver";

    private String oldProperty;

    public SaxSetup() {
        oldProperty = System.getProperty(SAX_DRIVER_PROPERTY);
        if (oldProperty != null) {
            System.setProperty(SAX_DRIVER_PROPERTY, SAXParser.class.getName());
        }
    }

    public void cleanup() {
        if (oldProperty != null) {
            System.setProperty(SAX_DRIVER_PROPERTY, oldProperty);
        }
        else {
            System.clearProperty(SAX_DRIVER_PROPERTY);
        }
    }
}

package hudson.plugins.analysis.util;

import org.apache.xerces.parsers.SAXParser;

/**
 * Registers the correct SAX driver if the environment variable is set.
 */
public class SaxSetup {
    /** Property of SAX parser factory. */
    public static final String SAX_DRIVER_PROPERTY = "org.xml.sax.driver";

    private String oldProperty;

    public SaxSetup() {
        oldProperty = System.getProperty(SAX_DRIVER_PROPERTY);
        if (oldProperty != null) {
            System.setProperty(SAX_DRIVER_PROPERTY, SAXParser.class.getName());
        }
    }

    public void cleanup() {
        if (oldProperty != null) {
            System.setProperty(SAX_DRIVER_PROPERTY, oldProperty);
        }
        else {
            System.clearProperty(SAX_DRIVER_PROPERTY);
        }
    }
}

Clear SAX system property afterwards.


package org.ngrinder.infra.config;

import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletPath;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.support.HttpRequestHandlerServlet;
import org.springframework.web.servlet.DispatcherServlet;

@Configuration
public class ServletConfig {
	@Bean
	@SuppressWarnings("unchecked")
	public ServletRegistrationBean appServletRegisterBean() {
		ServletRegistrationBean appServletRegistrationBean = new ServletRegistrationBean(dispatcherServlet(), dispatcherServletPath().getPath());
		appServletRegistrationBean.setLoadOnStartup(1);
		appServletRegistrationBean.setName("appServlet");
		return appServletRegistrationBean;
	}

	@Bean
	public DispatcherServlet dispatcherServlet() {
		return new DispatcherServlet();
	}

	@Bean
	@SuppressWarnings("unchecked")
	public ServletRegistrationBean svnDavServletRegisterBean() {
		ServletRegistrationBean SvnDavServletRegistrationBean = new ServletRegistrationBean(new HttpRequestHandlerServlet(), "/svn/*");
		SvnDavServletRegistrationBean.setLoadOnStartup(1);
		SvnDavServletRegistrationBean.setName("svnDavServlet");
		return SvnDavServletRegistrationBean;
	}

	@Bean
	public DispatcherServletPath dispatcherServletPath() {
		return () -> "/*";
	}
}

package org.ngrinder.infra.config;

import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletPath;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.support.HttpRequestHandlerServlet;
import org.springframework.web.servlet.DispatcherServlet;

@Configuration
public class ServletConfig {
	@Bean
	@SuppressWarnings("unchecked")
	public ServletRegistrationBean appServletRegisterBean() {
		ServletRegistrationBean appServletRegistrationBean = new ServletRegistrationBean(dispatcherServlet(), dispatcherServletPath().getPath());
		appServletRegistrationBean.setLoadOnStartup(1);
		appServletRegistrationBean.setName("appServlet");
		return appServletRegistrationBean;
	}

	@Bean
	public DispatcherServlet dispatcherServlet() {
		return new DispatcherServlet();
	}

	@Bean
	@SuppressWarnings("unchecked")
	public ServletRegistrationBean svnDavServletRegisterBean() {
		ServletRegistrationBean svnDavServletRegistrationBean = new ServletRegistrationBean(new HttpRequestHandlerServlet(), "/svn/*");
		svnDavServletRegistrationBean.setLoadOnStartup(1);
		svnDavServletRegistrationBean.setName("svnDavServlet");
		return svnDavServletRegistrationBean;
	}

	@Bean
	public DispatcherServletPath dispatcherServletPath() {
		return () -> "/*";
	}
}

Fix typo in variable name


package is.stanton.andy;

import com.google.inject.Guice;

import javax.naming.InitialContext;

public class EntryPoint {
    public static void main(String[] args) throws Exception {
        new InitialContext();
        Guice.createInjector();

        System.out.println("Running Camel + Guice example on http://127.0.0.1:8080/ping");
        System.out.println("Press Ctrl-C to quit");
    }
}

package is.stanton.andy;

import javax.naming.InitialContext;

public class EntryPoint {
    public static void main(String[] args) throws Exception {
        new InitialContext();

        System.out.println("Running Camel + Guice example on http://127.0.0.1:8080/ping");
        System.out.println("Press Ctrl-C to quit");
    }
}

Remove unnecessary Guice.createInjector() from main


package com.github.onsdigital.perkin.transform;

import org.junit.Test;

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

public class NumberServiceTest {

    private NumberService classUnderTest;

    @Test
    public void shouldStartAtCorrectNumber() {
        //Given
        classUnderTest = new NumberService("test", 5L, 10L);

        //When
        long start = classUnderTest.getNext();

        //Then
        assertThat(start, is(5L));
    }

    @Test
    public void shouldWrapAroundToStart() {
        //Given
        long start = 5L;
        classUnderTest = new NumberService("test", start, 10L);
        classUnderTest.reset();

        //When / Then
        for (int i = 0; i < 6; i++) {
            long sequence = classUnderTest.getNext();
            assertThat(sequence, is(start + i));
        }

        //Then
        long sequence = classUnderTest.getNext();
        assertThat(sequence, is(start));
    }
}

package com.github.onsdigital.perkin.transform;

import org.junit.Test;

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

public class NumberServiceTest {

    private NumberService classUnderTest;

    @Test
    public void shouldStartAtCorrectNumber() {
        //Given
        classUnderTest = new NumberService("test", 5L, 10L);

        //When
        long start = classUnderTest.getNext();

        //Then
        assertThat(start, is(5L));
    }

    @Test
    public void shouldWrapAroundToStart() {
        //Given
        long start = 5L;
        classUnderTest = new NumberService("test", start, 10L);
        classUnderTest.reset();

        //When / Then
        for (int i = 0; i < 6; i++) {
            long sequence = classUnderTest.getNext();
            assertThat(sequence, is(start + i));
        }

        //Then
        long sequence = classUnderTest.getNext();
        assertThat(sequence, is(start));
    }

    @Test
    public void shouldWrapAroundToStartWhenSaved() {
        //Given
        long start = 5L;
        classUnderTest = new NumberService("test", start, 10L);
        classUnderTest.reset();

        //When / Then
        for (int i = 0; i < 6; i++) {
            // Re-initialise (and re-load) on every increment:
            classUnderTest = new NumberService("test", start, 10L);
            long sequence = classUnderTest.getNext();
            assertThat(sequence, is(start + i));
        }

        //Then
        long sequence = new NumberService("test", start, 10L).getNext();
        assertThat(sequence, is(start));
    }
}

Test for looping a sequence when the value is saved on every increment.


package com.gitrekt.resort.controller;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.stage.Stage;
import javafx.scene.control.button

/**
 * FXML Controller class for the leave feedback screen.
 */
public class LeaveFeedbackScreenController implements Initializable {

    @FXML
    private Button submitButton;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }

    /**
     * Closes the window and saves the user's feedback to a database
     * @param event
     */
    @FXML
    private void onSubmitButtonClicked(ActionEvent event) {
        Stage stage = (Stage) submitButton.getScene().getWindow();
        //TODO Add feedback to database
        stage.close();
    }
}

Fix whitespace at end of file


package task.timer;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;

import javafx.stage.Stage;

public class Main extends Application{

	public void start(Stage primaryStage){

			ViewLoader<AnchorPane, Object> viewLoader =
					new ViewLoader<AnchorPane, Object>("view/EmployeeData.fxml");

			AnchorPane anchorPane = viewLoader.getLayout();

		Scene scene = new Scene(anchorPane);
		primaryStage.setScene(scene);

		primaryStage.show();

	}

	public static void main(String[] args) {
		launch(args);

	}

}

package task.timer;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;

import javafx.stage.Stage;

public class Main extends Application{

	public void start(Stage primaryStage){

			ViewLoader<AnchorPane, Object> viewLoader =
					//new ViewLoader<AnchorPane, Object>("view/EmployeeData.fxml");
					new ViewLoader<AnchorPane, Object>("view/MainManager.fxml");

			AnchorPane anchorPane = viewLoader.getLayout();

		Scene scene = new Scene(anchorPane);
		primaryStage.setScene(scene);

		primaryStage.show();

	}

	public static void main(String[] args) {
		launch(args);

	}

}

Change to show manager interface.


package at.ac.tuwien.inso.service;

import at.ac.tuwien.inso.entity.Course;
import at.ac.tuwien.inso.entity.Semester;
import at.ac.tuwien.inso.repository.CourseRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CoursesService {

    @Autowired
    private SemesterService semesterService;

    @Autowired
    private CourseRepository courseRepository;

    public List<Course> findForCurrentSemester() {
        Semester semester = semesterService.getCurrentSemester();
        return courseRepository.findAllBySemester(semester);
    }

}

package at.ac.tuwien.inso.service;

import at.ac.tuwien.inso.entity.Course;
import at.ac.tuwien.inso.entity.Semester;
import at.ac.tuwien.inso.repository.CourseRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import javax.validation.constraints.NotNull;

@Service
public class CoursesService {

    @Autowired
    private SemesterService semesterService;

    @Autowired
    private CourseRepository courseRepository;

    public List<Course> findCourseForCurrentSemesterWithName(@NotNull String name) {
        Semester semester = semesterService.getCurrentSemester();
        return courseRepository.findAllBySemesterAndSubjectNameLikeIgnoreCase(semester, "%" + name + "%");
    }

}

Add filter for name, combine with get all


package trantect.android_framework_demo.activity;

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

import trantect.android_framework_demo.R;

/**
 * Create by Trantect on 14-7-2.
 */
public class MainActivity extends Activity {

    private String getTag() {
        return getPackageName().toString() + getClass().toString();
    }

    @Override
    public void onCreate(Bundle savedInstance) {
        super.onCreate(savedInstance);
        Log.d(getTag(), "onCreate");
        setContentView(R.layout.welcome_main);
    }

    @Override
    public void onStart() {
        super.onStart();
    }
}

package trantect.android_framework_demo.activity;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import trantect.android_framework_demo.R;

/**
 * Create by Trantect on 14-7-2.
 */
public class MainActivity extends Activity {

    private Button bt_welcome;

    private TextView tv_welcome;

    @Override
    public void onCreate(Bundle savedInstance) {
        super.onCreate(savedInstance);
        Log.d(getTag(), "onCreate");
        setContentView(R.layout.welcome_main);
        initViews();
        onViewClick();
    }

    @Override
    public void onStart() {
        Log.d(getTag(), "onStart");
        super.onStart();
    }

    private String getTag() {
        return getPackageName().toString() + getClass().toString();
    }

    // init some views
    private void initViews(){
        bt_welcome = (Button)findViewById(R.id.bt_welcome);
        tv_welcome = (TextView)findViewById(R.id.tv_welcome);
        showBtView();
    }

    private void onViewClick(){
        MyListener myListener = new MyListener();
        bt_welcome.setOnClickListener(myListener);
        tv_welcome.setOnClickListener(myListener);
    }

    class MyListener implements View.OnClickListener{

        @Override
        public void onClick(View view) {
            int id = view.getId();
            switch (id){
                case R.id.bt_welcome:
                    showTvView();
                    break;
                case R.id.tv_welcome:
                    showBtView();
                    break;
            }
        }
    }

    // show Button
    private void showBtView(){
        bt_welcome.setVisibility(View.VISIBLE);
        tv_welcome.setVisibility(View.GONE);
    }

    // show TextView
    private void showTvView(){
        tv_welcome.setVisibility(View.VISIBLE);
        bt_welcome.setVisibility(View.GONE);
    }
}

Add some logic on main activity


package org.pdxfinder.repositories;

import org.pdxfinder.dao.OntologyTerm;
import org.springframework.data.neo4j.annotation.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Collection;

/**
 * Created by csaba on 07/06/2017.
 */
@Repository
public interface OntologyTermRepository extends PagingAndSortingRepository<OntologyTerm, Long>
{

    OntologyTerm findById();

    @Query("MATCH (o:OntologyTerm) WHERE toLower(o.label) = toLower({label}) return o")
    OntologyTerm findByLabel(@Param("label") String label);

    OntologyTerm findByUrl(String url);

    @Query("match(o:OntologyTerm) return o limit 40")
    Collection<OntologyTerm>  findByOntologyTermLabel(@Param("label") String label);

    @Query("MATCH (oTerm:OntologyTerm)<-[SUBCLASS_OF]-(subNodes) where oTerm.label CONTAINS trim(toLower({searchParam})) WITH COLLECT(subNodes) AS subNodes " +
            "UNWIND subNodes AS subN " +
            "MATCH (oTerm:OntologyTerm)<-[SUBCLASS_OF]-(subNodes2) where oTerm.label=subN.label return subN,subNodes2 limit 8")
    Collection<OntologyTerm> findByDiseaseOntologyTerm(@Param("searchParam") String searchParam);

}

package org.pdxfinder.repositories;

import org.pdxfinder.dao.OntologyTerm;
import org.springframework.data.neo4j.annotation.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Collection;

/**
 * Created by csaba on 07/06/2017.
 */
@Repository
public interface OntologyTermRepository extends PagingAndSortingRepository<OntologyTerm, Long>
{

    OntologyTerm findById();

    @Query("MATCH (o:OntologyTerm) WHERE toLower(o.label) = toLower({label}) return o")
    OntologyTerm findByLabel(@Param("label") String label);

    OntologyTerm findByUrl(String url);

    @Query("match(o:OntologyTerm) return o limit 40")
    Collection<OntologyTerm>  findByOntologyTermLabel(@Param("label") String label);

    @Query("MATCH (oTerm:OntologyTerm)<-[SUBCLASS_OF]-(subNodes) where oTerm.label CONTAINS trim(toLower({searchParam})) WITH COLLECT(subNodes) AS subNodes " +
            "UNWIND subNodes AS subN " +
            "MATCH (oTerm:OntologyTerm)<-[SUBCLASS_OF]-(subNodes2) where oTerm.label=subN.label return subN,subNodes2 limit 15")
    Collection<OntologyTerm> findByDiseaseOntologyTerm(@Param("searchParam") String searchParam);

}

Adjust search to make use of Disease Ontology terms


package info.u_team.u_team_test.init;

import info.u_team.u_team_core.util.registry.RegistryWorker;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.screen.*;
import net.minecraft.client.gui.ScreenManager;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;

@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD, value = Dist.CLIENT)
public class TestScreens {

	@SubscribeEvent
	public static void register(FMLClientSetupEvent event) {
		RegistryWorker.runOnMainThread(() -> {
			ScreenManager.registerFactory(TestContainers.BASIC, BasicTileEntityScreen::new);
			ScreenManager.registerFactory(TestContainers.BASIC_ENERGY_CREATOR, BasicEnergyCreatorScreen::new);
			ScreenManager.registerFactory(TestContainers.BASIC_FLUID_INVENTORY, BasicFluidInventoryScreen::new);
		});
	}

}

package info.u_team.u_team_test.init;

import info.u_team.u_team_core.util.registry.SyncedWorker;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.screen.*;
import net.minecraft.client.gui.ScreenManager;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;

@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD, value = Dist.CLIENT)
public class TestScreens {

	@SubscribeEvent
	public static void register(FMLClientSetupEvent event) {
		SyncedWorker.runOnMainThread(() -> {
			ScreenManager.registerFactory(TestContainers.BASIC, BasicTileEntityScreen::new);
			ScreenManager.registerFactory(TestContainers.BASIC_ENERGY_CREATOR, BasicEnergyCreatorScreen::new);
			ScreenManager.registerFactory(TestContainers.BASIC_FLUID_INVENTORY, BasicFluidInventoryScreen::new);
		});
	}

}

Fix class rename in caller class


package org.javarosa.core.model.utils;

import org.javarosa.core.model.trace.EvaluationTrace;
import org.javarosa.core.model.trace.EvaluationTraceReporter;
import org.javarosa.core.model.trace.StringEvaluationTraceSerializer;

/**
 * Utility functions for instrumentation in the engine
 *
 * Created by ctsims on 7/6/2017.
 */

public class InstrumentationUtils {

    /**
     * Prints out traces (if any exist) from the provided reporter with a description into sysout
     */
    public static void printAndClearTraces(EvaluationTraceReporter reporter, String description) {
        if (reporter != null) {
            if (reporter.wereTracesReported()) {
                System.out.println(description);
            }

            StringEvaluationTraceSerializer serializer = new StringEvaluationTraceSerializer();

            for (EvaluationTrace trace : reporter.getCollectedTraces()) {
                System.out.println(trace.getExpression() + ": " + trace.getValue());
                System.out.print(serializer.serializeEvaluationLevels(trace));
            }

            reporter.reset();
        }
    }
}

package org.javarosa.core.model.utils;

import org.javarosa.core.model.trace.EvaluationTrace;
import org.javarosa.core.model.trace.EvaluationTraceReporter;
import org.javarosa.core.model.trace.StringEvaluationTraceSerializer;

/**
 * Utility functions for instrumentation in the engine
 *
 * Created by ctsims on 7/6/2017.
 */

public class InstrumentationUtils {

    /**
     * Prints out traces (if any exist) from the provided reporter with a description into sysout
     */
    public static void printAndClearTraces(EvaluationTraceReporter reporter, String description) {
        if (reporter != null) {
            if (reporter.wereTracesReported()) {
                System.out.println(description);
            }

            StringEvaluationTraceSerializer serializer = new StringEvaluationTraceSerializer();

            for (EvaluationTrace trace : reporter.getCollectedTraces()) {
                System.out.println(trace.getExpression() + ": " + trace.getValue());
                System.out.print(serializer.serializeEvaluationLevels(trace));
            }

            reporter.reset();
        }
    }

    /**
     * Prints out traces (if any exist) from the provided reporter with a description into sysout
     */
    public static String collectAndClearTraces(EvaluationTraceReporter reporter, String description) {
        String returnValue = "";
        if (reporter != null) {
            if (reporter.wereTracesReported()) {
                returnValue += description + "\n";
            }

            StringEvaluationTraceSerializer serializer = new StringEvaluationTraceSerializer();

            for (EvaluationTrace trace : reporter.getCollectedTraces()) {
                returnValue += trace.getExpression() + ": " + trace.getValue()  + "\n";
                returnValue += serializer.serializeEvaluationLevels(trace);
            }

            reporter.reset();
        }
        return returnValue;
    }

}

Add a way to evaluate traces into a single string output


package pl.touk.sputnik.processor.sonar;

import java.util.List;

import org.sonar.runner.api.EmbeddedRunner;

import pl.touk.sputnik.review.Review;
import pl.touk.sputnik.review.ReviewFile;

import com.google.common.collect.Lists;

class SonarRunnerBuilder {
    public SonarRunner prepareRunner(Review review) {
        List<String> files = Lists.newArrayList();
        for (ReviewFile file : review.getFiles()) {
            files.add(file.getReviewFilename());
        }
        SonarRunner sonarRunner = new SonarRunner(files, EmbeddedRunner.create());
        return sonarRunner;
    }
}

package pl.touk.sputnik.processor.sonar;

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

import org.sonar.runner.api.EmbeddedRunner;

import pl.touk.sputnik.review.Review;
import pl.touk.sputnik.review.ReviewFile;

import com.google.common.collect.Lists;

class SonarRunnerBuilder {
    public SonarRunner prepareRunner(Review review) {
        List<String> files = Lists.newArrayList();

        /*
         * Some sonar plugin do no include git path as the source file path (for
         * example, sonar-visual-studio plugin generates filenames that are relative
         * to the module csproj file).
         *
         * Using the file basename and a recursive match allows Sonar to match
         * modified files with their indexed names in Sonar.
         *
         * Although this can generate useless analysis (as some files that are not
         * included in a review may be analysed), this has a limited additional
         * cost considering that few files have the same basename inside a
         * repository.
         */
        for (ReviewFile file : review.getFiles()) {
            files.add("**/" + new File(file.getReviewFilename()).getName());
        }
        SonarRunner sonarRunner = new SonarRunner(files, EmbeddedRunner.create());
        return sonarRunner;
    }
}

Use file basename instead of fullname in sonar


package org.signaut.jetty.deploy.providers.couchdb;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.http.HttpServletRequest;

import org.eclipse.jetty.server.handler.ErrorHandler;
/**
 * Display the error as a json object
 *
 */
class JsonErrorHandler extends ErrorHandler {

    @Override
    protected void writeErrorPage(HttpServletRequest request, Writer writer, int code, String message,
            boolean showStacks) throws IOException {
        // TODO Auto-generated method stub
        final Throwable exception = (Throwable) request.getAttribute("javax.servlet.error.exception");
        if (exception == null) {
            message = String.format("{\"status\": %d, \"uri\":\"%s\"," + "\"message\": %s}", code,
                                    request.getRequestURI(), jsonStr(message));
        } else {
            message = String.format("{\"status\": %d, \"uri\":\"%s\"," + "\"message\": %s, " + "\"exception\": { "
                                            + "\"exception\": \"%s\", \"message\": %s} }", code,
                                    request.getRequestURI(), jsonStr(message),
                                    exception.getClass().getCanonicalName(), jsonStr(exception.getMessage()));
        }
        writer.write(message);
    }

    private final String jsonStr(String string) {
        return string == null ? null : "\"" + string + "\"";
    }
}

package org.signaut.jetty.deploy.providers.couchdb;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.http.HttpServletRequest;

import org.eclipse.jetty.server.handler.ErrorHandler;
/**
 * Display the error as a json object
 *
 */
class JsonErrorHandler extends ErrorHandler {

    @Override
    protected void writeErrorPage(HttpServletRequest request, Writer writer, int code, String message,
            boolean showStacks) throws IOException {
        // TODO Auto-generated method stub
        final Throwable exception = (Throwable) request.getAttribute("javax.servlet.error.exception");
        final String user = request.getUserPrincipal()==null?null:request.getUserPrincipal().getName();
        if (exception == null) {
            message = String.format("{\"status\": %d, \"uri\":\"%s\", \"user\": %s, \"message\": %s}", code,
                                    request.getRequestURI(), jsonStr(user), jsonStr(message));
        } else {
            message = String.format("{\"status\": %d, \"uri\":\"%s\", \"user\": %s, \"message\": %s, \"exception\": { "
                                            + "\"exception\": \"%s\", \"message\": %s} }", code,
                                    request.getRequestURI(), jsonStr(user), jsonStr(message),
                                    exception.getClass().getCanonicalName(), jsonStr(exception.getMessage()));
        }
        writer.write(message);
    }

    private final String jsonStr(String string) {
        return string == null ? null : "\"" + string + "\"";
    }
}

Add user to error messages


package org.eclipse.scanning.points;

import java.util.Iterator;

import org.eclipse.scanning.api.points.AbstractGenerator;
import org.eclipse.scanning.api.points.GeneratorException;
import org.eclipse.scanning.api.points.IPosition;
import org.eclipse.scanning.api.points.models.ArrayModel;

public class ArrayGenerator extends AbstractGenerator<ArrayModel, IPosition> {

	ArrayGenerator() {
		setLabel("Position List Scan");
		setDescription("Creates a scan from a list of positions");
	}

	@Override
	public int size() throws GeneratorException {
		if (containers!=null) throw new GeneratorException("Cannot deal with regions in a position list scan!");
		if (model.getPositions() == null) {
			return 0;
		}
		return model.getPositions().length;
	}

	@Override
	public Iterator<IPosition> iterator() {
		return new ArrayIterator(this);
	}

}

package org.eclipse.scanning.points;

import java.util.Iterator;

import org.eclipse.scanning.api.points.AbstractGenerator;
import org.eclipse.scanning.api.points.GeneratorException;
import org.eclipse.scanning.api.points.IPosition;
import org.eclipse.scanning.api.points.models.ArrayModel;

public class ArrayGenerator extends AbstractGenerator<ArrayModel, IPosition> {

	ArrayGenerator() {
		setLabel("Array Scan");
		setDescription("Creates a scan from an array of positions");
	}

	@Override
	public int size() throws GeneratorException {
		if (containers!=null) throw new GeneratorException("Cannot deal with regions in an array scan!");
		if (model.getPositions() == null) {
			return 0;
		}
		return model.getPositions().length;
	}

	@Override
	public Iterator<IPosition> iterator() {
		return new ArrayIterator(this);
	}

}

Adjust name and description for consistency


package fape.core.planning.preprocessing;

import planstack.anml.model.abs.AbstractAction;

/**
 * An action an might support an open goal.
 *
 * The action might be given a decomposition to apply
 */
public class SupportingAction {
    public int decID;
    public final AbstractAction absAct;

    public SupportingAction(AbstractAction aa, int decID) {
        this.absAct = aa;
        this.decID = decID;
    }
    public SupportingAction(AbstractAction aa) {
        this.absAct = aa;
        this.decID = -1;
    }

    public boolean mustBeDecomposed() { return decID != -1; }
    public int getDecID() { return decID; }
}

package fape.core.planning.preprocessing;

import planstack.anml.model.abs.AbstractAction;

/**
 * An action an might support an open goal.
 *
 * The action might be given a decomposition to apply
 */
public class SupportingAction {
    public int decID;
    public final AbstractAction absAct;

    public SupportingAction(AbstractAction aa, int decID) {
        this.absAct = aa;
        this.decID = decID;
    }
    public SupportingAction(AbstractAction aa) {
        this.absAct = aa;
        this.decID = -1;
    }

    public boolean mustBeDecomposed() { return decID != -1; }
    public int getDecID() { return decID; }

    @Override
    public boolean equals(Object o) {
        if(o instanceof SupportingAction) {
            return ((SupportingAction) o).absAct.equals(this.absAct) && ((SupportingAction) o).decID == this.decID;
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return this.absAct.hashCode() + decID;
    }
}

Implement equals() and hashCode() for supporting actions.


package org.cyclops.cyclopscore.config.extendedconfig;

import org.cyclops.cyclopscore.config.ConfigurableType;
import org.cyclops.cyclopscore.config.configurable.ConfigurableVillager;
import org.cyclops.cyclopscore.init.ModBase;

/**
 * Config for villagers.
 * @author rubensworks
 * @see ExtendedConfig
 */
public abstract class VillagerConfig extends ExtendedConfig<VillagerConfig> {

    private final int id;

    /**
     * Make a new instance.
     * @param mod     The mod instance.
     * @param defaultId The default ID for the configurable.
     * @param namedId The unique name ID for the configurable.
     * @param comment The comment to add in the config file for this configurable.
     * @param element The class of this configurable.
     */
    public VillagerConfig(ModBase mod, int defaultId, String namedId,
            String comment, Class<? extends ConfigurableVillager> element) {
        super(mod, defaultId != 0, namedId, comment, element);
        this.id = defaultId;
    }

    public int getId() {
        return this.id;
    }

    @Override
	public String getUnlocalizedName() {
		return "entity.villager." + getNamedId();
	}

    @Override
	public ConfigurableType getHolderType() {
		return ConfigurableType.VILLAGER;
	}

}

package org.cyclops.cyclopscore.config.extendedconfig;

import org.cyclops.cyclopscore.config.ConfigurableType;
import org.cyclops.cyclopscore.config.configurable.ConfigurableVillager;
import org.cyclops.cyclopscore.init.ModBase;

/**
 * Config for villagers.
 * @author rubensworks
 * @see ExtendedConfig
 */
public abstract class VillagerConfig extends ExtendedConfig<VillagerConfig> {

    private int id;

    /**
     * Make a new instance.
     * @param mod     The mod instance.
     * @param defaultId The default ID for the configurable.
     * @param namedId The unique name ID for the configurable.
     * @param comment The comment to add in the config file for this configurable.
     * @param element The class of this configurable.
     */
    public VillagerConfig(ModBase mod, int defaultId, String namedId,
            String comment, Class<? extends ConfigurableVillager> element) {
        super(mod, defaultId != 0, namedId, comment, element);
        this.id = defaultId;
    }

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

    public int getId() {
        return this.id;
    }

    @Override
	public String getUnlocalizedName() {
		return "entity.villager." + getNamedId();
	}

    @Override
	public ConfigurableType getHolderType() {
		return ConfigurableType.VILLAGER;
	}

}

Allow changing of villager id


package com.example.jersey_sample.gitlab;

import javax.ws.rs.POST;
import javax.ws.rs.Path;

import static com.example.jersey_sample.Log.GITLAB_LOG;

/**
 * @author manhnt
 */
@SuppressWarnings("ALL")
public class WebHook {

	@POST
	@Path("/push")
	public void pushEventHook(String body) {
		GITLAB_LOG.trace("Body: " + body);
	}
}

package com.example.jersey_sample.gitlab;

import javax.ws.rs.POST;
import javax.ws.rs.Path;

import static com.example.jersey_sample.Log.GITLAB_LOG;

/**
 * @author manhnt
 */
public class WebHook {

	@POST
	@Path("/push")
	public void pushEventHook(String body) {
		GITLAB_LOG.warn("Body: " + body);
	}
}

Change log level of trace message


package com.puppycrawl.tools.checkstyle.checks.coding;
/* комментарий на русском */
public class InputReturnCount
{
    public boolean equals(Object obj) {
        int i = 1;
        switch (i) {
        case 1: return true;
        case 2: return true;
        case 3: return true;
        case 4: return true;
        case 5: return true;
        case 6: return true;
        }
        return false;
    }

    void foo(int i) {
        switch (i) {
        case 1: return;
        case 2: return;
        case 3: return;
        case 4: return;
        case 5: return;
        case 6: return;
        }
        return;
    }

    void foo1(int i) {
        if (i == 1) {
            return;
        }
        Object obj = new Object() {
                void method1(int i) {
                    switch (i) {
                    case 1: return;
                    case 2: return;
                    case 3: return;
                    case 4: return;
                    case 5: return;
                    }
                    return;
                }
            };
        return;
    }
}

class Test {

    public Test() {}
}

package com.puppycrawl.tools.checkstyle.coding;
/* комментарий на русском */
public class InputReturnCount
{
    public boolean equals(Object obj) {
        int i = 1;
        switch (i) {
        case 1: return true;
        case 2: return true;
        case 3: return true;
        case 4: return true;
        case 5: return true;
        case 6: return true;
        }
        return false;
    }

    void foo(int i) {
        switch (i) {
        case 1: return;
        case 2: return;
        case 3: return;
        case 4: return;
        case 5: return;
        case 6: return;
        }
        return;
    }

    void foo1(int i) {
        if (i == 1) {
            return;
        }
        Object obj = new Object() {
                void method1(int i) {
                    switch (i) {
                    case 1: return;
                    case 2: return;
                    case 3: return;
                    case 4: return;
                    case 5: return;
                    }
                    return;
                }
            };
        return;
    }
}

class Test {

    public Test() {}
}

Return Count Check compilable UT input


package com.intellij.plugins.haxe.lang.parser.statements;

import com.intellij.plugins.haxe.lang.parser.HaxeParsingTestBase;

public class StatementTestBase extends HaxeParsingTestBase {
  public StatementTestBase(String subFolder) {
    super("parsing", "haxe", "statements", subFolder);
  }
}

package com.intellij.plugins.haxe.lang.parser.statements;

import com.intellij.plugins.haxe.lang.parser.HaxeParsingTestBase;

abstract public class StatementTestBase extends HaxeParsingTestBase {
  public StatementTestBase(String subFolder) {
    super("parsing", "haxe", "statements", subFolder);
  }
}

Make abstract to avoid inspection.