package com.josenaves.plugin;

import android.util.Log;
import android.location.LocationManager;
import android.content.Context;

import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;

public class CheckGps {

	private static final String TAG = CheckGps.class.getSimpleName();

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if ("isGpsEnabled".equals(action)) {

        	if (isGpsEnabled()) {
        		callbackContext.success("GPS is enabled");
        	} else  {
        		callbackContext.error("GPS is not enabled");
        	}

            return true;
        }
        return false;  // Returning false results in a "MethodNotFound" error.
    }

	private boolean isGpsEnabled() {
		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		boolean enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
		Log.d(TAG, String.format("CheckGps.isGpsEnabled() = %s", enabled) );
		return enabled;
	}
}

package com.josenaves.plugin;

import android.util.Log;
import android.location.LocationManager;
import android.content.Context;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;

public class CheckGps extends CordovaPlugin {

	private static final String TAG = CheckGps.class.getSimpleName();

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if ("isGpsEnabled".equals(action)) {

        	if (isGpsEnabled()) {
        		callbackContext.success("GPS is enabled");
        	} else  {
        		callbackContext.error("GPS is not enabled");
        	}

            return true;
        }
        return false;  // Returning false results in a "MethodNotFound" error.
    }

	private boolean isGpsEnabled() {
		LocationManager locationManager = (LocationManager) Context.getSystemService(Context.LOCATION_SERVICE);
		boolean enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
		Log.d(TAG, String.format("CheckGps.isGpsEnabled() = %s", enabled) );
		return enabled;
	}
}

Fix missing imports and extends

Fix missing imports and extends


package squeek.veganoption.asm;

import java.util.Map;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin;

@IFMLLoadingPlugin.MCVersion("1.7.10")
public class ASMPlugin implements IFMLLoadingPlugin
{

	@Override
	public String[] getASMTransformerClass()
	{
		return new String[]{ClassTransformer.class.getName()};
	}

	@Override
	public String getModContainerClass()
	{
		return null;
	}

	@Override
	public String getSetupClass()
	{
		return null;
	}

	@Override
	public void injectData(Map<String, Object> data)
	{
	}

	@Override
	public String getAccessTransformerClass()
	{
		return null;
	}

}

package squeek.veganoption.asm;

import java.util.Map;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin;

@IFMLLoadingPlugin.MCVersion("1.7.10")
@IFMLLoadingPlugin.TransformerExclusions("squeek.veganoption.asm")
public class ASMPlugin implements IFMLLoadingPlugin
{

	@Override
	public String[] getASMTransformerClass()
	{
		return new String[]{ClassTransformer.class.getName()};
	}

	@Override
	public String getModContainerClass()
	{
		return null;
	}

	@Override
	public String getSetupClass()
	{
		return null;
	}

	@Override
	public void injectData(Map<String, Object> data)
	{
	}

	@Override
	public String getAccessTransformerClass()
	{
		return null;
	}

}

Exclude asm package from being transformed


package mn.devfest.api.adapter;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

import org.joda.time.DateTime;

import java.lang.reflect.Type;

/**
 * Adapts API dates to JodaTime DateTimes
 *
 * @author bherbst
 */
public class DateTimeTypeAdapter implements JsonDeserializer<DateTime> {
    @Override
    public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        return new DateTime(json.getAsString());
    }
}

package mn.devfest.api.adapter;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import org.joda.time.DateTime;

import java.lang.reflect.Type;

/**
 * Adapts API dates to JodaTime DateTimes
 *
 * @author bherbst
 */
public class DateTimeTypeAdapter implements JsonDeserializer<DateTime>, JsonSerializer<DateTime> {
    @Override
    public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        return new DateTime(json.getAsString());
    }

    @Override
    public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) {
        String jsonString = src == null ? "" : src.toString();
        return new JsonPrimitive(jsonString);
    }
}

Add serialization to the date time adapter


package hackerrank;

import java.util.Scanner;

/**
 * https://www.hackerrank.com/challenges/the-love-letter-mystery
 */
public class TheLoveLetterMystery {
    private static int loveLetterMystery(String str) {
        // TODO:
        return 0;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int testCases = in.nextInt();
        for (int t = 0; t < testCases; t++) {
            String str = in.next();
            System.out.println(loveLetterMystery(str));
        }
    }
}

package hackerrank;

import java.util.Scanner;

/**
 * https://www.hackerrank.com/challenges/the-love-letter-mystery
 */
public class TheLoveLetterMystery {
    private static int loveLetterMystery(String str) {
        int count = 0;
        char[] chars = str.toCharArray();
        for (int i = 0, j = chars.length - 1; i < j; i++, j--) {
            char left = chars[i];
            char right = chars[j];
            if (left != right) {
                if (left < right) {
                    while (left < right) {
                        right--;
                        count++;
                    }
                } else if (left > right) {
                    while (left > right) {
                        left--;
                        count++;
                    }
                }
            }
        }
        return count;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int testCases = in.nextInt();
        for (int t = 0; t < testCases; t++) {
            String str = in.next();
            System.out.println(loveLetterMystery(str));
        }
    }
}

Solve The Love Letter Mystery

Solve The Love Letter Mystery


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

import org.apache.camel.Endpoint;
import org.apache.camel.impl.UriEndpointComponent;

import java.util.Map;

// [WIP]
public class FluentdComponent extends UriEndpointComponent {
    public FluentdComponent() {
        super(FluentdEndpoint.class);
    }

    @Override
    protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
        Endpoint endpoint = new FluentdEndpoint(uri, this);
        return endpoint;
    }
}

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

import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.impl.UriEndpointComponent;

import java.util.Map;

// [WIP]
public class FluentdComponent extends UriEndpointComponent {
    public FluentdComponent() {
        super(FluentdEndpoint.class);
    }

    public FluentdComponent(CamelContext context) {
        super(context, FluentdEndpoint.class);
    }

    @Override
    protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
        Endpoint endpoint = new FluentdEndpoint(uri, this);
        return endpoint;
    }
}

Add a constructor of component

Add a constructor of component


// Copyright 2004-present Facebook. All Rights Reserved.

package com.facebook.react.cxxbridge;

import java.util.Map;

import com.facebook.jni.HybridData;
import com.facebook.proguard.annotations.DoNotStrip;
import com.facebook.react.bridge.NativeModule;
import com.facebook.soloader.SoLoader;

/**
 * A Java Object which represents a cross-platform C++ module
 *
 * This module implements the NativeModule interface but will never be invoked from Java,
 * instead the underlying Cxx module will be extracted by the bridge and called directly.
 */
@DoNotStrip
public class CxxModuleWrapperBase implements NativeModule
{
  static {
    SoLoader.loadLibrary(CatalystInstanceImpl.REACT_NATIVE_LIB);
  }

  @DoNotStrip
  private HybridData mHybridData;

  @Override
  public native String getName();

  @Override
  public void initialize() {
    // do nothing
  }

  @Override
  public boolean canOverrideExistingModule() {
    return false;
  }

  @Override
  public boolean supportsWebWorkers() {
    return false;
  }

  @Override
  public void onCatalystInstanceDestroy() {
    mHybridData.resetNative();
  }

  // For creating a wrapper from C++, or from a derived class.
  protected CxxModuleWrapperBase(HybridData hd) {
    mHybridData = hd;
  }
}

// Copyright 2004-present Facebook. All Rights Reserved.

package com.facebook.react.cxxbridge;

import com.facebook.jni.HybridData;
import com.facebook.proguard.annotations.DoNotStrip;
import com.facebook.react.bridge.NativeModule;
import com.facebook.soloader.SoLoader;

/**
 * A Java Object which represents a cross-platform C++ module
 *
 * This module implements the NativeModule interface but will never be invoked from Java,
 * instead the underlying Cxx module will be extracted by the bridge and called directly.
 */
@DoNotStrip
public class CxxModuleWrapperBase implements NativeModule
{
  static {
    SoLoader.loadLibrary(CatalystInstanceImpl.REACT_NATIVE_LIB);
  }

  @DoNotStrip
  private HybridData mHybridData;

  @Override
  public native String getName();

  @Override
  public void initialize() {
    // do nothing
  }

  @Override
  public boolean canOverrideExistingModule() {
    return false;
  }

  @Override
  public boolean supportsWebWorkers() {
    return false;
  }

  @Override
  public void onCatalystInstanceDestroy() {
    mHybridData.resetNative();
  }

  // For creating a wrapper from C++, or from a derived class.
  protected CxxModuleWrapperBase(HybridData hd) {
    mHybridData = hd;
  }

  // Replace the current native module held by this wrapper by a new instance
  protected void resetModule(HybridData hd) {
    if (hd != mHybridData) {
      mHybridData.resetNative();
      mHybridData = hd;
    }
  }
}

Add API to reset CxxModuleWrapper's module pointer

Reviewed By: mhorowitz

Differential Revision: D4914335

fbshipit-source-id: f28f57c2e74d590dacfb85d8027747837f768fdc


package com.crawljax.core.configuration;

import static com.crawljax.core.configuration.CrawlElementMatcher.withXpath;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;

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

import com.crawljax.core.state.Eventable.EventType;

public class XPathEscapeApostropheTest {

	private CrawlActionsBuilder actions;
	private CrawlElement element;

	@Before
	public void setup() {
		element = new CrawlElement(EventType.click, "button");
	}

	@Test
	public void testStringNoApostrophes() {
		String test = "Test String";
		test = element.escapeApostrophes(test);
		assertEquals("'Test String'", test);
	}

	@Test
	public void testStringConcat() {
		String test = "I'm Feeling Lucky";
		test = element.escapeApostrophes(test);
		assertEquals("concat('I',\"'\",'m Feeling Lucky')", test);
	}

}

package com.crawljax.core.configuration;

import static org.junit.Assert.assertEquals;

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

import com.crawljax.core.state.Eventable.EventType;

public class XPathEscapeApostropheTest {

	private CrawlElement element;

	@Before
	public void setup() {
		element = new CrawlElement(EventType.click, "button");
	}

	@Test
	public void testStringNoApostrophes() {
		String test = "Test String";
		test = element.escapeApostrophes(test);
		assertEquals("'Test String'", test);
	}

	@Test
	public void testStringConcat() {
		String test = "I'm Feeling Lucky";
		test = element.escapeApostrophes(test);
		assertEquals("concat('I',\"'\",'m Feeling Lucky')", test);
	}

}

Remove unused code from test case

Remove unused code from test case


package com.fatico.winthing;

import com.fatico.winthing.gui.WindowGui;
import com.fatico.winthing.messaging.Engine;

import com.google.inject.Guice;
import com.google.inject.Injector;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Application {
    private boolean debug = false;
    private static Application app = new Application();
    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    private void parseArgs(String[] args) {
        for (String arg : args) {
            if (arg.equals("-debug")) {
                debug = true;
            }
        }
    }

    public static boolean debug() {
        return app.debug;
    }

    public static void quit() {
        logger.info("Application terminated.");
        System.exit(0);
    }

    public static void main(final String[] args) {
        try {
            app.parseArgs(args);
            WindowGui gui = WindowGui.getInstance();
            gui.tray();

            final Injector injector = Guice.createInjector(new ApplicationModule());
            final Engine engine = injector.getInstance(Engine.class);
            engine.run();

        } catch (final Throwable throwable) {
            logger.error("Critical error.", throwable);
            System.exit(1);
        }
    }
}

package com.fatico.winthing;

import com.fatico.winthing.gui.WindowGui;
import com.fatico.winthing.messaging.Engine;

import com.google.inject.Guice;
import com.google.inject.Injector;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Application {
    private static final Application app = new Application();

    private boolean debug = false;
    private WindowGui gui;
    private Logger logger;

    private void parseArgs(String[] args) {
        for (String arg : args) {
            if (arg.equals("-debug")) {
                debug = true;
            }
        }
    }

    public static boolean debug() {
        return app.debug;
    }

    public static WindowGui getApp() {
        return app.gui;
    }

    public static void quit() {
        app.logger.info("Application terminated.");
        System.exit(0);
    }

    public static void main(final String[] args) {
        try {
            app.parseArgs(args);

            app.logger = LoggerFactory.getLogger(Application.class);

            app.gui = new WindowGui();
            app.gui.initialize();

            final Injector injector = Guice.createInjector(new ApplicationModule());
            final Engine engine = injector.getInstance(Engine.class);
            engine.run();

        } catch (final Throwable throwable) {
            app.logger.error("Critical error.", throwable);
            System.exit(1);
        }
    }
}

Change how GUI and logger is created. Initialize logger after we get console parameters and only then initialize logger.


package de.prob2.ui.consoles.b;

import java.io.File;
import java.util.ResourceBundle;

import com.google.inject.Inject;
import com.google.inject.Singleton;

import de.prob2.ui.consoles.Console;
import de.prob2.ui.prob2fx.CurrentTrace;

@Singleton
public final class BConsole extends Console {
	@Inject
	private BConsole(BInterpreter bInterpreter, ResourceBundle bundle, CurrentTrace currentTrace) {
		super(bundle, bundle.getString("consoles.b.header"), bundle.getString("consoles.b.prompt.classicalB"), bInterpreter);

		currentTrace.addListener((o, from, to) -> {
			final String message;
			if (to == null) {
				message = bundle.getString("consoles.b.message.modelUnloaded");
			} else {
				final File modelFile = to.getStateSpace().getModel().getModelFile();
				final String name = modelFile == null ? to.getStateSpace().getMainComponent().toString() : modelFile.getName();
				message = String.format(bundle.getString("consoles.b.message.modelLoaded"), name);
			}
			this.insertText(this.getLineNumber(), 0, message + '\n');
			this.requestFollowCaret();
		});
	}
}

package de.prob2.ui.consoles.b;

import java.io.File;
import java.util.ResourceBundle;

import com.google.inject.Inject;
import com.google.inject.Singleton;

import de.prob2.ui.consoles.Console;
import de.prob2.ui.prob2fx.CurrentTrace;

@Singleton
public final class BConsole extends Console {
	@Inject
	private BConsole(BInterpreter bInterpreter, ResourceBundle bundle, CurrentTrace currentTrace) {
		super(bundle, bundle.getString("consoles.b.header"), bundle.getString("consoles.b.prompt.classicalB"), bInterpreter);

		currentTrace.stateSpaceProperty().addListener((o, from, to) -> {
			final String message;
			if (to == null) {
				message = bundle.getString("consoles.b.message.modelUnloaded");
			} else {
				final File modelFile = to.getModel().getModelFile();
				final String name = modelFile == null ? to.getMainComponent().toString() : modelFile.getName();
				message = String.format(bundle.getString("consoles.b.message.modelLoaded"), name);
			}
			this.insertText(this.getLineNumber(), 0, message + '\n');
			this.requestFollowCaret();
		});
	}
}

Fix "Model loaded" messages appearing when animating


package com.komanov.stringformat;

import org.slf4j.helpers.MessageFormatter;

import java.text.MessageFormat;
import java.util.Locale;

public class JavaFormats {
    private static final MessageFormat messageFormatInstance = new MessageFormat("{0}a{1}b{2}{3}");

    public static String concat(int value1, String value2, Object nullObject) {
        return value1 + "a" + value2 + "b" + value2 + nullObject;
    }

    public static String stringFormat(int value1, String value2, Object nullObject) {
        return String.format(Locale.ENGLISH, "%da%sb%s%s", value1, value2, value2, nullObject);
    }

    public static String messageFormat(int value1, String value2, Object nullObject) {
        return MessageFormat.format("{0}a{1}b{2}{3}", value1, value2, value2, nullObject);
    }

    public static String messageFormatCached(int value1, String value2, Object nullObject) {
        return messageFormatInstance.format(new Object[]{value1, value2, value2, nullObject});
    }

    public static String slf4j(int value1, String value2, Object nullObject) {
        return MessageFormatter
                .arrayFormat("{}a{}b{}{}", new Object[]{value1, value2, value2, nullObject})
                .getMessage();
    }
}

package com.komanov.stringformat;

import org.slf4j.helpers.MessageFormatter;

import java.text.MessageFormat;
import java.util.Locale;

public class JavaFormats {
    private static final MessageFormat messageFormatInstance = new MessageFormat("{0,number,#}a{1}b{2}{3}");

    public static String concat(int value1, String value2, Object nullObject) {
        return value1 + "a" + value2 + "b" + value2 + nullObject;
    }

    public static String stringFormat(int value1, String value2, Object nullObject) {
        return String.format(Locale.ENGLISH, "%da%sb%s%s", value1, value2, value2, nullObject);
    }

    public static String messageFormat(int value1, String value2, Object nullObject) {
        return MessageFormat.format("{0,number,#}a{1}b{2}{3}", value1, value2, value2, nullObject);
    }

    public static String messageFormatCached(int value1, String value2, Object nullObject) {
        return messageFormatInstance.format(new Object[]{value1, value2, value2, nullObject});
    }

    public static String slf4j(int value1, String value2, Object nullObject) {
        return MessageFormatter
                .arrayFormat("{}a{}b{}{}", new Object[]{value1, value2, value2, nullObject})
                .getMessage();
    }
}

Fix format string for MessageFormat

Fix format string for MessageFormat


package de.markusfisch.android.shadereditor.opengl;

public class InfoLog
{
	private static String message;
	private static int errorLine;

	public static String getMessage()
	{
		return message;
	}

	public static int getErrorLine()
	{
		return errorLine;
	}

	public static void parse( String infoLog )
	{
		message = null;
		errorLine = 0;

		if( infoLog == null )
			return;

		int from;

		if( (from = infoLog.indexOf( "ERROR: 0:" )) > -1 )
			from += 9;
		else if( (from = infoLog.indexOf( "0:" )) > -1 )
			from += 2;

		if( from > -1 )
		{
			int to;

			if( (to = infoLog.indexOf( ":", from )) > -1 )
			{
				try
				{
					errorLine = Integer.valueOf(
						infoLog.substring( from, to ).trim() );
				}
				catch( NumberFormatException e )
				{
					// can't do anything about it
				}
				catch( NullPointerException e )
				{
					// can't do anything about it
				}

				from = ++to;
			}

			if( (to = infoLog.indexOf( "\n", from )) < 0 )
				to = infoLog.length();

			infoLog = infoLog.substring( from, to ).trim();
		}

		message = infoLog;
	}
}

package de.markusfisch.android.shadereditor.opengl;

public class InfoLog
{
	private static String message;
	private static int errorLine;

	public static String getMessage()
	{
		return message;
	}

	public static int getErrorLine()
	{
		return errorLine;
	}

	public static void parse( String infoLog )
	{
		message = null;
		errorLine = 0;

		if( infoLog == null )
			return;

		int from;

		if( (from = infoLog.indexOf( "ERROR: 0:" )) > -1 )
			from += 9;
		else if( (from = infoLog.indexOf( "0:" )) > -1 )
			from += 2;

		if( from > -1 )
		{
			int to;

			if( (to = infoLog.indexOf( ":", from )) > -1 )
			{
				try
				{
					errorLine = Integer.parseInt(
						infoLog.substring( from, to ).trim() );
				}
				catch( NumberFormatException e )
				{
					// can't do anything about it
				}
				catch( NullPointerException e )
				{
					// can't do anything about it
				}

				from = ++to;
			}

			if( (to = infoLog.indexOf( "\n", from )) < 0 )
				to = infoLog.length();

			infoLog = infoLog.substring( from, to ).trim();
		}

		message = infoLog;
	}
}

Use parseInt() instead of valueOf()

Use parseInt() instead of valueOf()

It's more efficient to just use parseInt() instead of
box then unbox the value.


package com.autonomy.abc.selenium.menu;

import com.hp.autonomy.frontend.selenium.util.AppElement;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.util.List;

public class SideNavBar extends AppElement {

    public SideNavBar(WebDriver driver){
        super(driver.findElement(By.cssSelector(".navbar-static-side")), driver);
    }

    public Tab getTab(NavBarTabId id){
        return null;
    }

    public Tab getSelectedTab(){
        final List<WebElement> activeTabs = $el().findElements(By.cssSelector("li.active"));

        if (activeTabs.size() != 1) {
            throw new IllegalStateException("Number of active tabs != 1");
        }

        return new SideNavBarTab(activeTabs.get(0), getDriver());
    }

    public String getPageName() {
        return getSelectedTab().getName();
    }

    public String getPageId() {
        return getSelectedTab().getId();
    }

    public void switchPage(final NavBarTabId tab) {
        new WebDriverWait(getDriver(),30).until(
                ExpectedConditions.visibilityOfElementLocated(By.xpath("//ul//li//*[text()=' " + tab.toString() + "']/.."))).click();
    }
}

package com.autonomy.abc.selenium.menu;

import com.hp.autonomy.frontend.selenium.util.AppElement;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.util.List;

public class SideNavBar extends AppElement {

    public SideNavBar(WebDriver driver){
        super(driver.findElement(By.cssSelector(".navbar-static-side")), driver);
    }

    public Tab getTab(NavBarTabId id){
        return null;
    }

    public Tab getSelectedTab(){
        final List<WebElement> activeTabs = $el().findElements(By.cssSelector("li.active"));

        if (activeTabs.size() != 1) {
            throw new IllegalStateException("Number of active tabs != 1");
        }

        return new SideNavBarTab(activeTabs.get(0), getDriver());
    }

    public String getPageName() {
        return getSelectedTab().getName();
    }

    public String getPageId() {
        return getSelectedTab().getId();
    }

    public void switchPage(final NavBarTabId tab) {
        tryClickThenTryParentClick(new WebDriverWait(getDriver(),30).until(
                ExpectedConditions.visibilityOfElementLocated(By.xpath("//ul//li//*[text()=' " + tab.toString() + "']"))));
    }
}

Fix side nav bar - click was failing due to span inside link on some pages


package com.stripe.model;

public class Money {
	Integer amount;
	String currency;

	public Integer getAmount() {
		return amount;
	}

	public String getCurrency() {
		return currency;
	}
}

package com.stripe.model;

public class Money {
	Long amount;
	String currency;

	public Long getAmount() {
		return amount;
	}

	public String getCurrency() {
		return currency;
	}
}

Change the type to a long because the API is returning a number larger than an Integer


package net.ontopia.presto.jaxb;

import javax.xml.bind.annotation.XmlRootElement;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

@XmlRootElement
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown=true)
public class TopicMessage {

    private String type;
    private String title;
    private String message;

    public TopicMessage() {
    }

    public TopicMessage(String type, String title, String message) {
        this.type = type;
        this.title = title;
        this.message = message;
    }

    public String getType() {
        return type;
    }

    public String getFormat() {
        return "message";
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

package net.ontopia.presto.jaxb;

import java.util.Map;

import javax.xml.bind.annotation.XmlRootElement;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

@XmlRootElement
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown=true)
public class TopicMessage {

    private String type;
    private String title;
    private String message;
    private Map<String, Object> params;

    public TopicMessage() {
    }

    public TopicMessage(String type, String title, String message) {
        this.type = type;
        this.title = title;
        this.message = message;
    }

    public String getType() {
        return type;
    }

    public String getFormat() {
        return "message";
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Map<String, Object> getParams() {
        return params;
    }

    public void setParams(Map<String, Object> params) {
        this.params = params;
    }

}

Add params to topic message

Add params to topic message


package info.u_team.u_team_test;

import org.apache.logging.log4j.*;

import info.u_team.u_team_core.util.annotation.AnnotationManager;
import info.u_team.u_team_core.util.verify.JarSignVerifier;
import net.minecraftforge.fml.common.Mod;

@Mod(TestMod.MODID)
public class TestMod {

	public static final String MODID = "uteamtest";
	public static final Logger LOGGER = LogManager.getLogger("UTeamTest");

	public TestMod() {
		JarSignVerifier.checkSigned(MODID);

		LOGGER.info("--------------------------------------- LOADING TEST MOD ---------------------------------------");

		// TestCommonBusRegister.register();
		// DistExecutor.safeRunWhenOn(Dist.CLIENT, () -> TestClientBusRegister::register);

		AnnotationManager.callAnnotations(MODID);
	}
}

package info.u_team.u_team_test;

import org.apache.logging.log4j.*;

import info.u_team.u_team_core.util.annotation.AnnotationManager;
import info.u_team.u_team_core.util.verify.JarSignVerifier;
import net.minecraftforge.fml.common.Mod;

@Mod(TestMod.MODID)
public class TestMod {

	public static final String MODID = "uteamtest";
	public static final Logger LOGGER = LogManager.getLogger("UTeamTest");

	public TestMod() {
		JarSignVerifier.checkSigned(MODID);

		LOGGER.info("--------------------------------------- LOADING TEST MOD ---------------------------------------");

		AnnotationManager.callAnnotations(MODID);
	}
}

Remove old calls that are no longer nessessary


/*++

NASM Assembly Language Plugin
Copyright (c) 2017-2018 Aidan Khoury. All rights reserved.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

--*/

package com.nasmlanguage;

import com.intellij.lang.Language;
import org.jetbrains.annotations.NotNull;

public class NASMLanguage extends Language {
    public static final NASMLanguage INSTANCE = new NASMLanguage();

    private NASMLanguage() {
        super("NASM");
    }

    @NotNull
    @Override
    public String getDisplayName() {
        return "NASM Assembly Language";
    }
}

/*++

NASM Assembly Language Plugin
Copyright (c) 2017-2018 Aidan Khoury

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

--*/

package com.nasmlanguage;

import com.intellij.lang.Language;
import org.jetbrains.annotations.NotNull;

public class NASMLanguage extends Language {
    public static final NASMLanguage INSTANCE = new NASMLanguage();

    private NASMLanguage() {
        super("NASM");
    }

    @NotNull
    @Override
    public String getDisplayName() {
        return "NASM Assembly Language";
    }
}

Update copyright notice with MIT license


package com.nigorojr.typebest;

import java.sql.SQLException;

public class Records extends Database {

    public Records() throws SQLException {
        super("RECORDS");
    }
    }
}

package com.nigorojr.typebest;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;

public class Records extends Database {

    public Records() throws SQLException {
        super("RECORDS");
    }

    /**
     * Executes a INSERT query for the given pair of column names and values.
     */
    @Override
    public void insert(HashMap<String, String> pair) {
        String query = String.format("INSERT INTO %s %s",
                super.getTableName(), super.formatInsertQuery(pair));
        try {
            statement.execute(query);
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    ResultSet select(String condition) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    void update(HashMap<String, String> pair) {
        // TODO Auto-generated method stub
    }

    @Override
    void delete(String condition) {
        // TODO Auto-generated method stub
    }
}

Add the four abstract methods inherited from Database

This commit implements the methods from the Database class. Only the insert
method is implemented. However, it might be a better choice to move these four
methods to the parent class because it seems that there is nothing
particularly different between the Records and Preferences
class, which are the only classes that the four methods are currently planned
on being implemented.


package org.rhq.metrics.restServlet;

import java.util.Collections;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;

import org.rhq.metrics.core.MetricsService;

/**
 * @author John Sanda
 */
@ApplicationScoped
public class MetricsServiceProducer {

    @Inject
    private javax.servlet.ServletContext context;

    private MetricsService metricsService;

    @Produces
    public MetricsService getMetricsService() {
        if (metricsService == null) {
            try {
                String className = context.getInitParameter("rhq-metrics.backend");
                Class clazz = Class.forName(className);
                metricsService = (MetricsService) clazz.newInstance();
                // TODO passs servlet params
                metricsService.startUp(Collections.<String, String>emptyMap());

                ServiceKeeper.getInstance().service = metricsService;

                return metricsService;
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                throw new RuntimeException("Cannot create MetricsService class", e);
            }
        }
        return metricsService;
    }

}

package org.rhq.metrics.restServlet;

import java.util.Collections;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;

import org.rhq.metrics.core.MetricsService;

/**
 * @author John Sanda
 */
@SuppressWarnings("unused")
@ApplicationScoped
public class MetricsServiceProducer {

    @Inject
    private javax.servlet.ServletContext context;

    private MetricsService metricsService;

    @Produces
    public MetricsService getMetricsService() {
        if (metricsService == null) {
            try {
                String className = null;
                String backend = System.getProperty("rhq-metrics.backend");
                if (backend!=null) {
                    switch (backend) {
                    case "mem":
                        className="org.rhq.metrics.impl.memory.MemoryMetricsService";
                        break;
                    case "cass":
                        className="org.rhq.metrics.impl.cassandra.MetricsServiceCassandra";
                        break;
                    }
                }

                if (className==null) {
                    className = context.getInitParameter("rhq-metrics.backend");
                }
                Class clazz = Class.forName(className);
                metricsService = (MetricsService) clazz.newInstance();
                // TODO passs servlet params
                metricsService.startUp(Collections.<String, String>emptyMap());

                ServiceKeeper.getInstance().service = metricsService;

                return metricsService;
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                throw new RuntimeException("Cannot create MetricsService class", e);
            }
        }
        return metricsService;
    }

}

Allow to specify the backend as vm property rhq-metrics.backend. Choices are 'mem' and 'cass'.


package org.firebears.sensors;
// made by Jacob Wiggins

import edu.wpi.first.wpilibj.AnalogInput;

/*
 * Range Sensor
 */
public class sharpIRRange extends AnalogInput {

	public sharpIRRange(int channel) {
		super(channel);
	}
	//distance will be close to the distance that the robot is
	//assuming that it is between 10cm and 80cm.
	//volt represents the voltage that the sensor outputs
	//when taking the range between the robot and something
	//we got the constants by plotting points, making a function that fits the data
	//and using trial and error to make it more accurate
	//return value in inches

	public double getRangefinderDistance() {
		double volt = this.getAverageVoltage(); // value from sensor * (5/1024)
		//System.out.println(volt);
		double distance = (26.86 * Math.pow(volt, -1.15))/2.54;
		return distance;

	}

//	@Override
//	public void updateTable() {
//		ITable m_table = super.getTable();
//		if (m_table != null) {
//			m_table.putNumber("Distance", getRangefinderDistance());
//		}
//	}

}

package org.firebears.sensors;
// made by Jacob Wiggins

import edu.wpi.first.wpilibj.AnalogInput;

/*
 * Range Sensor
 */
public class sharpIRRange extends AnalogInput {

	public sharpIRRange(int channel) {
		super(channel);
	}
	//distance will be close to the distance that the robot is
	//assuming that it is between 10cm and 80cm.
	//volt represents the voltage that the sensor outputs
	//when taking the range between the robot and something
	//we got the constants by plotting points, making a function that fits the data
	//and using trial and error to make it more accurate
	//return value in inches  8" approx 20 cm.

	public double getRangefinderDistance() {
		double volt = this.getAverageVoltage(); // value from sensor * (5/1024)
		//System.out.println(volt);
		double distance = (26.86 * Math.pow(volt, -1.15))/2.54;
		return distance;

	}

//	@Override
//	public void updateTable() {
//		ITable m_table = super.getTable();
//		if (m_table != null) {
//			m_table.putNumber("Distance", getRangefinderDistance());
//		}
//	}

}

Update range comments inches and centimeters


package com.tasomaniac.seriesguide.plex;

import android.app.SearchManager;
import android.content.ComponentName;
import android.content.Intent;

import com.battlelancer.seriesguide.api.Action;
import com.battlelancer.seriesguide.api.Episode;
import com.battlelancer.seriesguide.api.SeriesGuideExtension;
import com.tasomaniac.seriesguide.plex.data.Injector;

import javax.inject.Inject;

public class PlexExtension extends SeriesGuideExtension {

    @Inject Analytics analytics;

    public PlexExtension() {
        super("PlexExtension");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Injector.obtain(getApplicationContext()).inject(this);
    }

    @Override
    protected void onRequest(int episodeIdentifier, Episode episode) {

        Intent plexSearchIntent = new Intent(Intent.ACTION_SEARCH)
                .setComponent(new ComponentName("com.plexapp.android", "com.plexapp.plex.activities.SearchActivity"))
                .putExtra(SearchManager.QUERY, episode.getTitle());

        analytics.sendScreenView("Extension");
        analytics.sendEvent("Extension", "Search Plex", episode.getTitle());

        publishAction(new Action.Builder(getString(R.string.action_extension), episodeIdentifier)
                .viewIntent(plexSearchIntent)
                .build());
    }
}

package com.tasomaniac.seriesguide.plex;

import android.app.SearchManager;
import android.content.ComponentName;
import android.content.Intent;

import com.battlelancer.seriesguide.api.Action;
import com.battlelancer.seriesguide.api.Episode;
import com.battlelancer.seriesguide.api.Movie;
import com.battlelancer.seriesguide.api.SeriesGuideExtension;
import com.tasomaniac.seriesguide.plex.data.Injector;

import javax.inject.Inject;

public class PlexExtension extends SeriesGuideExtension {

    @Inject Analytics analytics;

    public PlexExtension() {
        super("PlexExtension");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Injector.obtain(getApplicationContext()).inject(this);
    }

    @Override
    protected void onRequest(int episodeIdentifier, Episode episode) {
        publishActionWithTitleSearch(episodeIdentifier, episode.getTitle());
    }

    @Override
    protected void onRequest(int movieIdentifier, Movie movie) {
        publishActionWithTitleSearch(movieIdentifier, movie.getTitle());
    }

    private void publishActionWithTitleSearch(int identifier, String title) {
        Intent plexSearchIntent = new Intent(Intent.ACTION_SEARCH)
                .setComponent(new ComponentName("com.plexapp.android", "com.plexapp.plex.activities.SearchActivity"))
                .putExtra(SearchManager.QUERY, title);

        analytics.sendScreenView("Extension");
        analytics.sendEvent("Extension", "Search Plex", title);

        publishAction(new Action.Builder(getString(R.string.action_extension), identifier)
                .viewIntent(plexSearchIntent)
                .build());
    }
}

Add movie support to plex

Add movie support to plex


package de.craften.plugins.educraft.luaapi.functions;

import de.craften.plugins.educraft.luaapi.EduCraftApiFunction;
import org.bukkit.Location;
import org.bukkit.block.BlockFace;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;

/**
 * Lua API function to move one block forward.
 */
public class MoveForwardFunction extends EduCraftApiFunction {
    @Override
    public Varargs execute(Varargs varargs) {
        Location targetLocation = getApi().getStationaryBehavior().getLocation().clone().add(getApi().getDirection());

        if (!targetLocation.getBlock().getType().isSolid()
                && !targetLocation.getBlock().getRelative(BlockFace.UP).getType().isSolid()) {
            getApi().getStationaryBehavior().setLocation(targetLocation);
        }

        return LuaValue.NIL;
    }
}

package de.craften.plugins.educraft.luaapi.functions;

import de.craften.plugins.educraft.luaapi.EduCraftApiFunction;
import org.bukkit.Location;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Entity;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;

import java.util.Collection;

/**
 * Lua API function to move one block forward.
 */
public class MoveForwardFunction extends EduCraftApiFunction {
    @Override
    public Varargs execute(Varargs varargs) {
        Location targetLocation = getApi().getStationaryBehavior().getLocation().clone().add(getApi().getDirection());
        Collection<Entity> entities = targetLocation.getWorld().getNearbyEntities(targetLocation.getBlock().getLocation().add(0.5, 0.5, 0.5), 0.5, 0.5, 0.5);

        if (!targetLocation.getBlock().getType().isSolid()
                && !targetLocation.getBlock().getRelative(BlockFace.UP).getType().isSolid()
                && entities.isEmpty()) {
            getApi().getStationaryBehavior().setLocation(targetLocation);
        }

        return LuaValue.NIL;
    }
}

Check for entities ahead before moving forward.


/**
 * Copyright 2011-2012 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.informantproject.core;

import java.util.Collection;

import org.informantproject.core.util.Threads;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * @author Trask Stalnaker
 * @since 0.5
 */
public class MainEntryPointTest {

    private Collection<Thread> preExistingThreads;

    @Before
    public void before() {
        preExistingThreads = Threads.currentThreads();
        MainEntryPoint.start();
    }

    @After
    public void after() throws Exception {
        Threads.preShutdownCheck(preExistingThreads);
        MainEntryPoint.shutdown();
        Threads.postShutdownCheck(preExistingThreads);
    }

    @Test
    public void testNoGuiceBindingErrorsEtc() {
        // all the work is done in before() and after()
    }
}

/**
 * Copyright 2011-2012 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.informantproject.core;

import java.util.Collection;

import org.informantproject.core.util.Threads;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * @author Trask Stalnaker
 * @since 0.5
 */
public class MainEntryPointTest {

    private Collection<Thread> preExistingThreads;

    @Before
    public void before() {
        preExistingThreads = Threads.currentThreads();
        MainEntryPoint.start("ui.port:0");
    }

    @After
    public void after() throws Exception {
        Threads.preShutdownCheck(preExistingThreads);
        MainEntryPoint.shutdown();
        Threads.postShutdownCheck(preExistingThreads);
    }

    @Test
    public void testNoGuiceBindingErrorsEtc() {
        // all the work is done in before() and after()
    }
}

Use dynamically allocated ports in unit tests

Use dynamically allocated ports in unit tests so they won't unexpectedly
fail if a port happens to be in use.


package info.izumin.android.sunazuri.infrastructure;

import com.facebook.stetho.okhttp3.StethoInterceptor;
import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

import javax.inject.Singleton;

/**
 * Created by izumin on 6/7/2016 AD.
 */
@Module
public class HttpClientModule {
    public static final String TAG = HttpClientModule.class.getSimpleName();

    @Provides
    @Singleton
    OkHttpClient httpClient(HttpLoggingInterceptor loggingInterceptor) {
        return new OkHttpClient.Builder()
                .addInterceptor(new StethoInterceptor())
                .addInterceptor(loggingInterceptor)
                .build();
    }

    @Provides
    @Singleton
    HttpLoggingInterceptor loggingInterceptor() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        return interceptor;
    }
}

package info.izumin.android.sunazuri.infrastructure;

import com.facebook.stetho.okhttp3.StethoInterceptor;
import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

import javax.inject.Singleton;

/**
 * Created by izumin on 6/7/2016 AD.
 */
@Module
public class HttpClientModule {
    public static final String TAG = HttpClientModule.class.getSimpleName();

    @Provides
    @Singleton
    OkHttpClient httpClient(HttpLoggingInterceptor loggingInterceptor) {
        return new OkHttpClient.Builder()
                .addNetworkInterceptor(new StethoInterceptor())
                .addInterceptor(loggingInterceptor)
                .build();
    }

    @Provides
    @Singleton
    HttpLoggingInterceptor loggingInterceptor() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        return interceptor;
    }
}

Add StethoInterceptor as a network interceptor


package Database;

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

import static org.junit.Assert.*;

public class DatabaseConnectorTest {

    @Before
    public void setUp() throws Exception {

    }

    @After
    public void tearDown() throws Exception {

    }

    @Test
    public void testConnect() throws Exception {

    }

    @Test
    public void testDisconnect() throws Exception {

    }
}

package Database;

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

import java.sql.Connection;

import static org.junit.Assert.*;

public class DatabaseConnectorTest {

    DatabaseConnector databaseConnector;

    @Before
    public void setUp() throws Exception {
        databaseConnector = new DatabaseConnector(Config.URL.toString(), Config.USERNAME.toString(), Config.PASSWORD.toString(), Config.DATABASE.toString());
    }

    @After
    public void tearDown() throws Exception {

    }

    @Test
    public void testConnect() throws Exception {
        Connection connection = null;
        try {
            connection = databaseConnector.connect();
            assertNotNull(connection);
        } catch (Exception e) {
            assertTrue(e.toString().contains("SQLException"));
            assertNull(connection);
        }
    }

    @Test
    public void testDisconnect() throws Exception {
        Connection connection = null;
        try {
            databaseConnector.connect();
            assertTrue(databaseConnector.isActive());
            databaseConnector.disconnect();
            assertFalse(databaseConnector.isActive());
        } catch (Exception e) {
            assertTrue(e.toString().contains("SQLException"));
            assertNull(connection);
        }
    }
}

Add Tests to DatabaseConnectionTest class


package com.alexrnl.jbetaseries.request.parameters;

/**
 * Parameter which allow to set the note of a show or an episode.

 * @author Alex
 */
public class Note extends Parameter<Integer> {
	/** Name of the note parameter */
	public static final String	PARAMETER_NOTE	= "note";

	/**
	 * Constructor #1.

	 * @param note
	 *        the note to set.
	 * @throws IllegalArgumentException
	 *         if the not is outside the range [1;5].
	 */
	public Note (final Integer note) throws IllegalArgumentException {
		super(PARAMETER_NOTE, note);
		if (note < 1 || 5 < note) {
			throw new IllegalArgumentException("The note must be comprise between 1 and 5.");
		}
	}

}

package com.alexrnl.jbetaseries.request.parameters;

/**
 * Parameter which allow to set the note of a show or an episode.

 * @author Alex
 */
public class Note extends Parameter<Integer> {
	/** Name of the note parameter */
	public static final String	PARAMETER_NOTE	= "note";
	/** The minimum note allowed by the API */
	public static final int		NOTE_MIN		= 1;
	/** The maximum note allowed by the API */
	public static final int		NOTE_MAX		= 5;

	/**
	 * Constructor #1.

	 * @param note
	 *        the note to set.
	 * @throws IllegalArgumentException
	 *         if the not is outside the range [1;5].
	 */
	public Note (final Integer note) throws IllegalArgumentException {
		super(PARAMETER_NOTE, note);
		if (note < NOTE_MIN || note > NOTE_MAX) {
			throw new IllegalArgumentException("The note must be comprise between 1 and 5.");
		}
	}

}

Fix Sonar violation: create constants for note min/max


package com.github.aureliano.achmed.os.fs;

import com.github.aureliano.achmed.resources.properties.FileProperties;

public interface IFileProvider {

	public abstract void setFileMode();

	public abstract void setFileOwner();

	public abstract void createFile();

	public abstract void copyFile();

	public abstract void copyFolder();

	public abstract void setFileProperties(FileProperties properties);

	public abstract FileProperties getFileProperties();
}

package com.github.aureliano.achmed.os.fs;

import com.github.aureliano.achmed.resources.properties.FileProperties;

public interface IFileProvider {

	public abstract void setFileMode();

	public abstract void setFileOwner();

	public abstract void createFile();

	public abstract void deleteFile();

	public abstract void copyFile();

	public abstract void copyFolder();

	public abstract void setFileProperties(FileProperties properties);

	public abstract FileProperties getFileProperties();
}

Add method to delete file.

Add method to delete file.


/*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2005, PostgreSQL Global Development Group
*
* IDENTIFICATION
*   $PostgreSQL: pgjdbc/org/postgresql/jdbc3g/Jdbc3gCallableStatement.java,v 1.3 2004/11/09 08:51:22 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.jdbc3g;

import java.sql.*;
import java.util.Map;

class Jdbc3gCallableStatement extends Jdbc3gPreparedStatement implements CallableStatement
{
    Jdbc3gCallableStatement(Jdbc3gConnection connection, String sql, int rsType, int rsConcurrency, int rsHoldability) throws SQLException
    {
        super(connection, sql, true, rsType, rsConcurrency, rsHoldability);
    }

    public Object getObject(int i, Map < String, Class < ? >> map) throws SQLException
    {
        return getObjectImpl(i, map);
    }

    public Object getObject(String s, Map < String, Class < ? >> map) throws SQLException
    {
        return getObjectImpl(s, map);
    }

}

/*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2005, PostgreSQL Global Development Group
*
* IDENTIFICATION
*   $PostgreSQL: pgjdbc/org/postgresql/jdbc3g/Jdbc3gCallableStatement.java,v 1.4 2005/01/11 08:25:47 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.jdbc3g;

import java.sql.*;
import java.util.Map;

class Jdbc3gCallableStatement extends Jdbc3gPreparedStatement implements CallableStatement
{
    Jdbc3gCallableStatement(Jdbc3gConnection connection, String sql, int rsType, int rsConcurrency, int rsHoldability) throws SQLException
    {
        super(connection, sql, true, rsType, rsConcurrency, rsHoldability);
        if ( !connection.haveMinimumServerVersion("8.1") || connection.getProtocolVersion() == 2)
        {
            adjustIndex = true;
        }
    }

    public Object getObject(int i, Map < String, Class < ? >> map) throws SQLException
    {
        return getObjectImpl(i, map);
    }

    public Object getObject(String s, Map < String, Class < ? >> map) throws SQLException
    {
        return getObjectImpl(s, map);
    }

}

Make callable statements work again for JDK 1.5 builds. Any code int the jdbc3/Jdbc3 classes also needs to get into the corresponding jdbc3g/Jdbc3g class.


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

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MultivaluedMap;

public class CORSFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext req, ContainerResponseContext res) throws IOException {
        MultivaluedMap<String, String> headers = req.getHeaders();
        headers.add("Access-Control-Allow-Origin", "*");
        headers.add("Access-Control-Allow-Methods", "GET, POST");
        headers.add("Access-Control-Max-Age", "86400");
        headers.add("Access-Control-Allow-Credentials", "true");
        headers.add("Access-Control-Allow-Headers", "Content-Type");
    }

}

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

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;

@Provider
public class CORSFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext req, ContainerResponseContext res) throws IOException {
        MultivaluedMap<String, Object> headers = res.getHeaders();
        headers.add("Access-Control-Allow-Origin", "*");
        headers.add("Access-Control-Allow-Methods", "GET, POST");
        headers.add("Access-Control-Max-Age", "86400");
        headers.add("Access-Control-Allow-Credentials", "true");
        headers.add("Access-Control-Allow-Headers", "Content-Type");
    }

}

Update to use response object for setting headers Signed off by : Adam Pilkington apilkington@uk.ibm.com


package com.insa.rocketlyonandroid.utils;

import android.app.Activity;
import android.support.v4.app.Fragment;

import butterknife.ButterKnife;
import trikita.log.Log;

/* With this Base Class, we can access to parent activity of fragment very easily */
public abstract class BaseFragment extends Fragment {
    protected Activity mActivity;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = activity;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(mActivity.getClass().toString());
        //VolleySingleton.getInstance().getRequestQueue().cancelAll(getClass().toString());
    }
}

package com.insa.rocketlyonandroid.utils;

import android.app.Activity;
import android.support.v4.app.Fragment;

import butterknife.ButterKnife;
import trikita.log.Log;

/* With this Base Class, we can access to parent activity of fragment very easily */
public abstract class BaseFragment extends Fragment {
    protected Activity mActivity;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = activity;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(mActivity.getClass().toString());
    }
}

Remove operation specific to Volley

Remove operation specific to Volley


package org.apache.mesos.logstash.common;

public interface LogstashConstants {
    String FRAMEWORK_NAME = "logstash";
    int FAILOVER_TIMEOUT = 300000;
    String EXECUTOR_IMAGE_NAME = "mesos/logstash-executor";
    String NODE_NAME = "logstash.node";
    String TASK_NAME = "logstash.task";
    String TASK_DATE_FORMAT = "yyyyMMdd'T'HHmmss.SSS'Z'";
}

package org.apache.mesos.logstash.common;

public interface LogstashConstants {
    String FRAMEWORK_NAME = "logstash";
    int FAILOVER_TIMEOUT = 300000;
    String EXECUTOR_IMAGE_NAME = "mesos/logstash-executor:0.0.2";
    String NODE_NAME = "logstash.node";
    String TASK_NAME = "logstash.task";
    String TASK_DATE_FORMAT = "yyyyMMdd'T'HHmmss.SSS'Z'";
}

Set executor docker image to version 0.0.2


/*
 * Copyright (C) 2016 Turn Inc. All Rights Reserved.
 * Proprietary and confidential.
 */

package com.turn.edc.storage;

import com.turn.edc.exception.KeyNotFoundException;
import com.turn.edc.router.StoreRequest;

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

import com.google.common.eventbus.Subscribe;
import com.orbitz.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ConnectionFactory layer connector interface
 *
 * @author tshiou
 */
public abstract class StorageConnector {
	private static final Logger LOG = LoggerFactory.getLogger(StorageConnector.class);

	public abstract void set(String key, byte[] value, int ttl, int timeout) throws IOException;

	public abstract void set(String key, String subkey, byte[] value, int ttl, int timeout) throws IOException;

	public abstract byte[] get(String key, int timeout) throws KeyNotFoundException, TimeoutException, IOException;

	public abstract byte[] get(String key, String subkey, int timeout) throws KeyNotFoundException, TimeoutException, IOException;

	public abstract void close();

	@Subscribe
	public void handleStoreRequest(StoreRequest request) {
		try {
			this.set(request.getKey(), request.getSubkey(), request.getPayload(), request.getTtl(), 10);
		} catch (IOException e) {
			LOG.error("Store request failed");
			LOG.debug(ExceptionUtils.getStackTrace(e));
		}
	}
}

/*
 * Copyright (C) 2016 Turn Inc. All Rights Reserved.
 * Proprietary and confidential.
 */

package com.turn.edc.storage;

import com.turn.edc.exception.KeyNotFoundException;
import com.turn.edc.router.StoreRequest;

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

import com.google.common.eventbus.Subscribe;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ConnectionFactory layer connector interface
 *
 * @author tshiou
 */
public abstract class StorageConnector {
	private static final Logger LOG = LoggerFactory.getLogger(StorageConnector.class);

	public abstract void set(String key, byte[] value, int ttl, int timeout) throws IOException;

	public abstract void set(String key, String subkey, byte[] value, int ttl, int timeout) throws IOException;

	public abstract byte[] get(String key, int timeout) throws KeyNotFoundException, TimeoutException, IOException;

	public abstract byte[] get(String key, String subkey, int timeout) throws KeyNotFoundException, TimeoutException, IOException;

	public abstract void close();

	@Subscribe
	public void handleStoreRequest(StoreRequest request) {
		try {
			this.set(request.getKey(), request.getSubkey(), request.getPayload(), request.getTtl(), 10);
		} catch (IOException e) {
			LOG.error("Store request failed");
			LOG.debug(ExceptionUtils.getStackTrace(e));
		}
	}
}

Fix broken import to shaded orbitz jar

Fix broken import to shaded orbitz jar

Signed-off-by: Tommy Shiou <fd59d852321c3431be8a979962d50c7894293a47@turn.com>


package com.bloatit.framework.webserver.url;

import com.bloatit.framework.utils.Parameters;
import com.bloatit.framework.utils.SessionParameters;
import com.bloatit.framework.xcgiserver.HttpHeader;

public abstract class UrlNode implements Iterable<UrlNode>, Cloneable {

    public UrlNode() {
        super();
    }

    @Override
    public abstract UrlNode clone() throws CloneNotSupportedException;

    public final String urlString() {
        final StringBuilder sb = new StringBuilder();
        constructUrl(sb);
        return sb.toString();
    }

    public final String externalUrlString(HttpHeader header) {
        return header.getHttpHost() + urlString();
    }

    public abstract Messages getMessages();

    protected abstract void parseSessionParameters(final SessionParameters params);

    protected abstract void parseParameters(final Parameters params);

    /**
     * Begin with a '/' and no slash at the end.
     */
    protected abstract void constructUrl(final StringBuilder sb);

    @Deprecated
    public abstract void addParameter(String name, String value);
}

package com.bloatit.framework.webserver.url;

import com.bloatit.common.Log;
import com.bloatit.framework.utils.Parameters;
import com.bloatit.framework.utils.SessionParameters;
import com.bloatit.framework.xcgiserver.HttpHeader;

public abstract class UrlNode implements Iterable<UrlNode>, Cloneable {

    public UrlNode() {
        super();
    }

    @Override
    public abstract UrlNode clone() throws CloneNotSupportedException;

    public final String urlString() {
        final StringBuilder sb = new StringBuilder();
        constructUrl(sb);
        return sb.toString();
    }

    public final String externalUrlString(HttpHeader header) {
        if (header.getServerProtocol().startsWith("HTTPS")) {
            return "https://" + header.getHttpHost() + urlString();
        }
        if (header.getServerProtocol().startsWith("HTTP")) {
            return "http://" + header.getHttpHost() + urlString();
        }
        Log.framework().error("Cannot parse the server protocol: " + header.getServerProtocol());
        return "http://" + header.getHttpHost() + urlString();
    }

    public abstract Messages getMessages();

    protected abstract void parseSessionParameters(final SessionParameters params);

    protected abstract void parseParameters(final Parameters params);

    /**
     * Begin with a '/' and no slash at the end.
     */
    protected abstract void constructUrl(final StringBuilder sb);

    @Deprecated
    public abstract void addParameter(String name, String value);
}

Add the http before the externalUrlGeneration


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

import java.util.List;

class DspInsert extends DspToken implements Insert
{
	static final String NAME = "insert";

	DspInsert(String eat, List<DspArg> args)
	{
		super(eat, args);
	} // DspInsert()

	public String getPath(DspCompile comp, int index) throws DspParseException
	{
		if (args.size() != 1) throw new DspParseException("file name", "an expression", index, comp);
		DspArg arg = args.get(0);
		String expr = arg.getExpr();
		if (expr != null) throw new DspParseException("file name", expr, index, comp);
		return arg.getText();
	} // getPath()

	public String toString()
	{
		return toString(NAME);
	} // toString()

} // DspInsert

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

import java.util.List;

class DspInsert extends DspToken implements Insert
{
	static final String NAME = "insert";

	DspInsert(String eat, List<DspArg> args)
	{
		super(eat, args);
	} // DspInsert()

	public String getPath(DspCompile comp, int index) throws DspParseException
	{
		if (args.size() != 1) throw new DspParseException("file name", "an expression", index, comp);
		DspArg arg = args.get(0);
		String expr = arg.getExpr();
		if (expr != null) throw new DspParseException("file name", expr, index, comp);
		return arg.getText().trim();
	} // getPath()

	public String toString()
	{
		return toString(NAME);
	} // toString()

} // DspInsert

Trim whitespace from argument on insert

Trim whitespace from argument on insert


package com.cesca.sensors.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.cesca.sensors.entity.DHTSensor;
import com.cesca.sensors.service.DHTSensorService;

@RestController
@RequestMapping("/REST/DHTSensor")
public class DHTSensorController {

	@Autowired
	public DHTSensorService dhtSensorService;

	@RequestMapping(method = RequestMethod.GET)
	public DHTSensor getLatestData(){
		return this.dhtSensorService.getLatestData();
	}

	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public DHTSensor addData(@RequestBody DHTSensor dht){
		return this.dhtSensorService.addDHTSensorData(dht);
	}

}

package com.cesca.sensors.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.cesca.sensors.entity.DHTSensor;
import com.cesca.sensors.service.DHTSensorService;

@RestController
@RequestMapping("/REST/DHTSensor")
public class DHTSensorController {

	@Autowired
	public DHTSensorService dhtSensorService;

	private Logger log = Logger.getLogger(this.getClass());

	@RequestMapping(method = RequestMethod.GET)
	public DHTSensor getLatestData(){

		try {
			DHTSensor sensor = this.dhtSensorService.getLatestData();
			return sensor;
		} catch (Exception e) {
			log.error("Failed to get latest data from Database");
		}
		return null;
	}

	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public DHTSensor addData(@RequestBody DHTSensor dht){
		return this.dhtSensorService.addDHTSensorData(dht);
	}

}

Handle exception when getting Sensor Status from Empty Database


// Copyright 2019 Google LLC
//
// 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
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.sps.servlets;

import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.logging.Level;
import java.util.logging.Logger;

@WebServlet("/search")
public class SearchServlet extends HttpServlet {

  private static final Logger LOGGER = Logger.getLogger(SearchServlet.class.getName());

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

  }

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

  }
}

// Copyright 2019 Google LLC
//
// 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
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.sps.servlets;

import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.logging.Level;
import java.util.logging.Logger;

@WebServlet("/search")
public class SearchServlet extends HttpServlet {

  private static final Logger LOGGER = Logger.getLogger(SearchServlet.class.getName());

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    //get location
    //filter by location and cutoff outside it

    //get tags
    //drop all without first tag
    //those with most tags in common with search go to top
    //those closest to the user go to the top
  }

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

  }

  /**
   * Returns keywords from an event (currently using just the title
   * and description) based off an algorithm
   */
  public List<String> getKeywords(String title, String desc) {

  }
}

Add planning and template getKeywords function


package nl.utwente.viskell.ui.components;

import javafx.fxml.FXML;
import javafx.scene.control.Slider;
import nl.utwente.viskell.ui.CustomUIPane;

/**
 * An extension of ValueBlock.
 * The value of this Block can be changed by dragging a slider.
 * Ranges from 0 to 1 (both inclusive).
 */
public class SliderBlock extends ValueBlock {
    @FXML protected Slider slider;

    /**
     * Constructs a new SliderBlock
     * @param pane The parent pane this Block resides on.
     */
    public SliderBlock(CustomUIPane pane) {
        super(pane, pane.getEnvInstance().buildType("Fractional a => a"), "0.0", "SliderBlock");

        slider.setValue(0.0);
        setValue("0.0");

        slider.valueProperty().addListener(ev -> {
            setValue(String.format("%.5f", slider.getValue()));
            this.initiateConnectionChanges();
        });
    }
}

package nl.utwente.viskell.ui.components;

import javafx.fxml.FXML;
import javafx.scene.control.Slider;
import nl.utwente.viskell.ui.CustomUIPane;

/**
 * An extension of ValueBlock.
 * The value of this Block can be changed by dragging a slider.
 * Ranges from 0 to 1 (both inclusive).
 */
public class SliderBlock extends ValueBlock {
    @FXML protected Slider slider;

    /**
     * Constructs a new SliderBlock
     * @param pane The parent pane this Block resides on.
     */
    public SliderBlock(CustomUIPane pane) {
        super(pane, pane.getEnvInstance().buildType("Fractional a => a"), "0.0", "SliderBlock");

        slider.setValue(0.0);
        setValue("0.0");

        slider.valueProperty().addListener(ev -> {
            setValue(String.format(Locale.US, "%.5f", slider.getValue()));
            this.initiateConnectionChanges();
        });
    }
}

Fix format of slider block floats to be always valid.


package org.projectodd.nodej;

import org.dynjs.runtime.DynJS;
import org.dynjs.runtime.ExecutionContext;
import org.dynjs.runtime.GlobalObject;
import org.junit.Before;

public class NodejTestSupport {

    protected DynJS runtime;
    protected ExecutionContext context;
    protected String[] defaultArgs = { "node", "somearg" };

    @Before
    public void setUp() {
        System.setProperty("dynjs.require.path", System.getProperty("user.dir") + "/src/main/javascript/node/lib");
        runtime = new DynJS();
        context = runtime.getExecutionContext();
        GlobalObject globalObject = context.getGlobalObject();
        globalObject.defineGlobalProperty("process", new Process(globalObject, defaultArgs));
    }

}

package org.projectodd.nodej;

import org.dynjs.runtime.DynJS;
import org.dynjs.runtime.ExecutionContext;
import org.junit.Before;

public class NodejTestSupport {

    protected DynJS runtime;
    protected ExecutionContext context;
    protected String[] defaultArgs = { "node", "somearg" };

    @Before
    public void setUp() {
        System.setProperty("dynjs.require.path", System.getProperty("user.dir") + "/src/main/javascript/node/lib");
        runtime = new DynJS();
        context = runtime.getExecutionContext();
        Node node = new Node(defaultArgs);
        node.start(context);
    }

}

Initialize a Node(), which should set up process for us


package me.coley.recaf.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

import me.coley.recaf.Logging;
import picocli.CommandLine.Option;

public class LaunchParams implements Runnable {
	@Option(names = { "-i", "--input" }, description = "Jar file to read.")
	public File initialFile;
	@Option(names = { "-c", "--class" }, description = "Initial class to open.")
	public String initialClass;
	@Option(names = { "-s", "--skip" }, description = "Classes in the input to ignore.", arity = "1..*")
	public List<String> skipped = new ArrayList<>();

	@Override
	public void run() {
		if (initialFile != null) Logging.info("CLI file: " + initialFile);
		if (initialClass != null) Logging.info("CLI class: " + initialClass);
		if (skipped != null) Logging.info("CLI Skipped packages: " + skipped.size());
	}
}

package me.coley.recaf.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

import me.coley.recaf.Logging;
import picocli.CommandLine.Option;

public class LaunchParams implements Runnable {
	@Option(names = { "-i", "--input" }, description = "Jar file to read.")
	public File initialFile;
	@Option(names = { "-c", "--class" }, description = "Initial class to open.")
	public String initialClass;
	@Option(names = { "-s", "--skip" }, description = "Classes in the input to ignore.", arity = "0..*")
	public List<String> skipped = new ArrayList<>();

	@Override
	public void run() {
		if (initialFile != null) Logging.info("CLI file: " + initialFile);
		if (initialClass != null) Logging.info("CLI class: " + initialClass);
		if (skipped != null) Logging.info("CLI Skipped packages: " + skipped.size());
	}
}

Fix arity of skip param

Fix arity of skip param


package org.redalert1741.steamworks;

import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;

/**
 * The VM is configured to automatically run this class, and to call the
 * functions corresponding to each mode, as described in the IterativeRobot
 * documentation. If you change the name of this class or the package after
 * creating this project, you must also update the manifest file in the resource
 * directory.
 */
public class Robot extends IterativeRobot {
	final String defaultAuto = "Default";
	final String customAuto = "My Auto";
	String autoSelected;
	SendableChooser<String> chooser = new SendableChooser<>();

	/**
	 * This function is run when the robot is first started up and should be
	 * used for any initialization code.
	 */
	@Override
	public void robotInit() {
		chooser.addDefault("Default Auto", defaultAuto);
		chooser.addObject("My Auto", customAuto);
		SmartDashboard.putData("Auto choices", chooser);
	}

	/**
	 * This autonomous (along with the chooser code above) shows how to select
	 * between different autonomous modes using the dashboard. The sendable
	 * chooser code works with the Java SmartDashboard. If you prefer the
	 * LabVIEW Dashboard, remove all of the chooser code and uncomment the
	 * getString line to get the auto name from the text box below the Gyro
	 *
	 * You can add additional auto modes by adding additional comparisons to the
	 * switch structure below with additional strings. If using the
	 * SendableChooser make sure to add them to the chooser code above as well.
	 */
	@Override
	public void autonomousInit() {
		autoSelected = chooser.getSelected();
		// autoSelected = SmartDashboard.getString("Auto Selector",
		// defaultAuto);
		System.out.println("Auto selected: " + autoSelected);
	}

	/**
	 * This function is called periodically during autonomous
	 */
	@Override
	public void autonomousPeriodic() {
		switch (autoSelected) {
		case customAuto:
			// Put custom auto code here
			break;
		case defaultAuto:
		default:
			// Put default auto code here
			break;
		}
	}

	/**
	 * This function is called periodically during operator control
	 */
	@Override
	public void teleopPeriodic() {
	}

	/**
	 * This function is called periodically during test mode
	 */
	@Override
	public void testPeriodic() {
	}
}

package org.redalert1741.steamworks;

import edu.wpi.first.wpilibj.IterativeRobot;

public class Robot extends IterativeRobot
{
	@Override
	public void robotInit()
	{

	}

	@Override
	public void autonomousInit()
	{

	}

	@Override
	public void autonomousPeriodic()
	{

	}

	@Override
	public void teleopPeriodic()
	{

	}

	@Override
	public void testPeriodic()
	{

	}
}

Remove a bunch of stuff

Remove a bunch of stuff


/*
 * Copyright (c) 2013-2015 Falko Schumann <www.muspellheim.de>
 * Released under the terms of the MIT License.
 */

package de.muspellheim.signalslot;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * A signal act as source of data and can connect to any compatible slot.
 *
 * @param <T> value type
 * @author Falko Schumann <www.muspellheim.de>
 */
public class Signal<T> implements Slot<T> {

    private List<Slot<T>> slots = new CopyOnWriteArrayList<>();
    private boolean blocked;

    public final void connect(final Slot<T> slot) {
        if (slot == null) {
            throw new NullPointerException("slot");
        }
        slots.add(slot);
    }

    public final void disconnect(final Slot<T> slot) {
        if (slot == null) {
            throw new NullPointerException("slot");
        }
        slots.remove(slot);
    }

    public final void disconnectAll() {
        slots.clear();
    }

    public final void emit(final T value) {
        if (isBlocked()) {
            return;
        }

        for (Slot<T> e : slots) {
            e.receive(value);
        }
    }

    public final boolean isBlocked() {
        return blocked;
    }

    public final void setBlocked(final boolean blocked) {
        this.blocked = blocked;
    }

    @Override
    public final void receive(final T value) {
        emit(value);
    }

}

/*
 * Copyright (c) 2013-2015 Falko Schumann <www.muspellheim.de>
 * Released under the terms of the MIT License.
 */

package de.muspellheim.signalslot;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * A signal act as source of data and can connect to any compatible slot.
 *
 * @param <T> value type
 * @author Falko Schumann <www.muspellheim.de>
 */
public class Signal<T> implements Slot<T> {

    private List<Slot<T>> slots = new CopyOnWriteArrayList<>();
    private boolean blocked;

    public final void connect(final Slot<T> slot) {
        Objects.requireNonNull(receiver, "slot");
        slots.add(slot);
    }

    public final void disconnect(final Slot<T> slot) {
        Objects.requireNonNull(receiver, "slot");
        slots.remove(slot);
    }

    public final void disconnectAll() {
        slots.clear();
    }

    public final void emit(final T value) {
        if (isBlocked()) {
            return;
        }

        for (Slot<T> e : slots) {
            e.receive(value);
        }
    }

    public final boolean isBlocked() {
        return blocked;
    }

    public final void setBlocked(final boolean blocked) {
        this.blocked = blocked;
    }

    @Override
    public final void receive(final T value) {
        emit(value);
    }

}

Use Objects::requireNonNull instead of if-throw


package openblocks.client.gui;

import openblocks.common.container.ContainerDevNull;
import openmods.gui.BaseGuiContainer;
import openmods.gui.component.BaseComposite;
import openmods.gui.component.GuiComponentPanel;

public class GuiDevNull extends BaseGuiContainer<ContainerDevNull> {

	public GuiDevNull(ContainerDevNull container) {
		super(container, 176, 137, "item.openblocks.devnull.name");
	}

	@Override
	protected BaseComposite createRoot() {
		GuiComponentPanel panel = new GuiComponentPanel(0, 0, xSize, ySize, getContainer());
		panel.setSlotRenderer(0, GuiComponentPanel.bigSlot);
		return panel;
	}

}

package openblocks.client.gui;

import openblocks.common.container.ContainerDevNull;
import openmods.gui.BaseGuiContainer;
import openmods.gui.component.BaseComposite;
import openmods.gui.component.GuiComponentPanel;

public class GuiDevNull extends BaseGuiContainer<ContainerDevNull> {

	public GuiDevNull(ContainerDevNull container) {
		super(container, 176, 137, "item.openblocks.dev_null.name");
	}

	@Override
	protected BaseComposite createRoot() {
		GuiComponentPanel panel = new GuiComponentPanel(0, 0, xSize, ySize, getContainer());
		panel.setSlotRenderer(0, GuiComponentPanel.bigSlot);
		return panel;
	}

}

Fix inventory name on /dev/null

Fix inventory name on /dev/null


import java.util.ArrayList;
import java.lang.*;
import java.math.BigDecimal;
public class Student {
	int testVariable = 0;
	int __cleanVariable = 0;

	public int foo() {
		return 4711 + __cleanVariable + testVariable;
	}

	public double bar() {
		return 4711.0815 + testVariable;
	}

	public String baz() {
		return "I am nice.";
	}

	public String foobar() {
		return "I am dangerous.";
	}

	public static Object getNull() {
		return null;
	}

	public static String doNull() {
		return "";
	}

	public static void recur(int i) {
		if(i > 0)
			recur(i-1);
	}

	public static void recur(int i, double d) {
		if(i > 0)
			recur(i-1);
	}

	public static void ioob() {
		int a[] = new int[10];
		a[a.length + 32]++;
	}

	public Student() {
	}

	public Student(int x) {
	}
}

import java.util.ArrayList;
import java.lang.*;
import java.math.BigDecimal;
public class Student {
	int testVariable = 0;
	int __cleanVariable = 1;

	public int foo() {
		int ret = 4711 + testVariable;
		__cleanIteratorClass iterator = new __cleanIteratorClass();
		return ret + iterator.getCleanVar();
	}

	public double bar() {
		return 4711.0815 + testVariable;
	}

	public String baz() {
		return "I am nice.";
	}

	public String foobar() {
		return "I am dangerous.";
	}

	public static Object getNull() {
		return null;
	}

	public static String doNull() {
		return "";
	}

	public static void recur(int i) {
		if(i > 0)
			recur(i-1);
	}

	public static void recur(int i, double d) {
		if(i > 0)
			recur(i-1);
	}

	public static void ioob() {
		int a[] = new int[10];
		a[a.length + 32]++;
	}

	public Student() {
	}

	public Student(int x) {
	}

	private class __cleanIteratorClass {
		public int getCleanVar() {
			return __cleanVariable - 23;
		}
	}
}

Change cleanroom to use inner class.

Change cleanroom to use inner class.


package com.proxerme.library.connection;

import android.support.annotation.IntRange;
import android.support.annotation.NonNull;

/**
 * Helper class, containing all the different Urls for accessing the API.
 *
 * @author Ruben Gees
 */
public class UrlHolder {

    private static final String HOST = "http://proxer.me";
    private static final String NEWS = "/notifications?format=json&s=news&p=";
    private static final String NEWS_IMAGE = "http://cdn.proxer.me/news/";
    private static final String LOGIN = "/login?format=json&action=login";

    @NonNull
    public static String getHost() {
        return HOST;
    }

    @NonNull
    public static String getNewsUrl(@IntRange(from = 1) int page) {
        return getHost() + NEWS + page;
    }

    @NonNull
    public static String getNewsImageUrl(@NonNull String newsId, @NonNull String imageId) {
        return NEWS_IMAGE + newsId + "_" + imageId + ".png";
    }

    @NonNull
    public static String getNewsPageUrl(@NonNull String categoryId, @NonNull String threadId) {
        return getHost() + "/forum/" + categoryId + "/" + threadId + "#top";
    }

    @NonNull
    public static String getDonateUrl() {
        return getHost() + "/donate";
    }

    @NonNull
    public static String getLoginUrl() {
        return getHost() + LOGIN;
    }

}

package com.proxerme.library.connection;

import android.support.annotation.IntRange;
import android.support.annotation.NonNull;

/**
 * Helper class, containing all the different Urls for accessing the API.
 *
 * @author Ruben Gees
 */
public class UrlHolder {

    private static final String HOST = "http://proxer.me";
    private static final String NEWS = "/notifications?format=json&s=news&p=";
    private static final String NEWS_IMAGE = "http://cdn.proxer.me/news/tmp/";
    private static final String LOGIN = "/login?format=json&action=login";

    @NonNull
    public static String getHost() {
        return HOST;
    }

    @NonNull
    public static String getNewsUrl(@IntRange(from = 1) int page) {
        return getHost() + NEWS + page;
    }

    @NonNull
    public static String getNewsImageUrl(@NonNull String newsId, @NonNull String imageId) {
        return NEWS_IMAGE + newsId + "_" + imageId + ".png";
    }

    @NonNull
    public static String getNewsPageUrl(@NonNull String categoryId, @NonNull String threadId) {
        return getHost() + "/forum/" + categoryId + "/" + threadId + "#top";
    }

    @NonNull
    public static String getDonateUrl() {
        return getHost() + "/donate";
    }

    @NonNull
    public static String getLoginUrl() {
        return getHost() + LOGIN;
    }

}

Change URL for image retrieval -> better quality


import java.io.IOException;

public class Server {
	// handler default init
	public static RequestHandler rh = new RequestHandler();
}

import java.io.IOException;

public class Server {
	// handler default init
	public static RequestHandler rh = new RequestHandler();
	// one factor authentication string for Update 1.1
	public static String authenticationString = "change me";
}

Update 1.1 - Added one-factor authentication


import java.awt.Component;
import java.awt.Container;
import java.awt.event.KeyEvent;

import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.Before;

public class TestInputResponder implements InputResponder
{
	private InputResponder inputResponder;
	private KeyEvent currentKeyEvent = null;
	private static final char testKey = 'x';

	public void keyDownResponse(KeyEvent e)
	{
		currentKeyEvent = e;
	}

	public void keyUpResponse(KeyEvent e)
	{
		if ((currentKeyEvent == null) || (e.getKeyCode() != currentKeyEvent.getKeyCode()))
			throw new RuntimeException("keyUp is triggered before keyDown!");
		else
			currentKeyEvent = null;
	}

	@Before
	public void instantiate()
	{
		inputResponder = new TestInputResponder();
	}

	@Test
	public void testKeyDownUpResponse()
	{
		Component source = new Container();
		KeyEvent key = new KeyEvent(source, KeyEvent.KEY_PRESSED, System.currentTimeMillis(), 0, (int)testKey, testKey);
		inputResponder.keyDownResponse(key);

		key = new KeyEvent(source, KeyEvent.KEY_RELEASED, System.currentTimeMillis(), 0, (int)testKey, testKey);
		inputResponder.keyUpResponse(key);
	}
}

import java.awt.Component;
import java.awt.Container;
import java.awt.event.KeyEvent;

import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.Before;

public class TestInputResponder implements InputResponder
{
	private static final Component testKeyEventSource = new Container();

	private InputResponder inputResponder;
	private KeyEvent currentKeyEvent = null;
	private static final char testKey = 'x';

	private static KeyEvent generateKeyEvent(int id, char key)
	{
		return new KeyEvent(testKeyEventSource, id, System.currentTimeMillis(), 0, (int)key, key);
	}

	public static KeyEvent generateKeyDownEvent(char key)
	{
		return generateKeyEvent(KeyEvent.KEY_PRESSED, key);
	}

	public static KeyEvent generateKeyUpEvent(char key)
	{
		return generateKeyEvent(KeyEvent.KEY_RELEASED, key);
	}

	public void keyDownResponse(KeyEvent e)
	{
		currentKeyEvent = e;
	}

	public void keyUpResponse(KeyEvent e)
	{
		if ((currentKeyEvent == null) || (e.getKeyCode() != currentKeyEvent.getKeyCode()))
			throw new RuntimeException("keyUp is triggered before keyDown!");
		else
			currentKeyEvent = null;
	}

	@Before
	public void instantiate()
	{
		inputResponder = new TestInputResponder();
	}

	@Test
	public void testKeyDownUpResponse()
	{
		inputResponder.keyDownResponse(generateKeyDownEvent(testKey));
		inputResponder.keyUpResponse(generateKeyUpEvent(testKey));
	}
}

Refactor KeyEvent generation for unit tests.