package arez.integration;

import arez.annotations.ArezComponent;
import arez.annotations.ComponentId;
import arez.component.Identifiable;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

@SuppressWarnings( "ConstantConditions" )
public final class IdentifiableIntegrationTest
  extends AbstractArezIntegrationTest
{
  @Test
  public void arezManagedArezId()
  {
    final Model1 model = new IdentifiableIntegrationTest_Arez_Model1();

    assertFalse( model instanceof Identifiable );
  }

  @Test
  public void componentManagedArezId()
  {
    final Model2 model = new IdentifiableIntegrationTest_Arez_Model2( 33 );

    assertTrue( model instanceof Identifiable );
    assertEquals( Identifiable.getArezId( model ), (Integer) 33 );
    assertEquals( Identifiable.asIdentifiable( model ), model );
  }

  @ArezComponent( allowEmpty = true )
  static abstract class Model1
  {
  }

  @ArezComponent( allowEmpty = true )
  static abstract class Model2
  {
    private final int id;

    Model2( final int id )
    {
      this.id = id;
    }

    @ComponentId
    int getId()
    {
      return id;
    }
  }
}

package arez.integration;

import arez.annotations.ArezComponent;
import arez.annotations.ComponentId;
import arez.annotations.Feature;
import arez.component.Identifiable;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

@SuppressWarnings( "ConstantConditions" )
public final class IdentifiableIntegrationTest
  extends AbstractArezIntegrationTest
{
  @Test
  public void requireId_DISABLE()
  {
    final Model1 model = new IdentifiableIntegrationTest_Arez_Model1();

    assertFalse( model instanceof Identifiable );
  }

  @Test
  public void requireId_ENABLE()
  {
    final Model2 model = new IdentifiableIntegrationTest_Arez_Model2( 33 );

    assertTrue( model instanceof Identifiable );
    assertEquals( Identifiable.getArezId( model ), (Integer) 33 );
    assertEquals( Identifiable.asIdentifiable( model ), model );
  }

  @Test
  public void requireId_DEFAULT()
  {
    final Model3 model = new IdentifiableIntegrationTest_Arez_Model3();

    assertTrue( model instanceof Identifiable );
    assertEquals( Identifiable.getArezId( model ), (Integer) 1 );
    assertEquals( Identifiable.asIdentifiable( model ), model );
  }

  @ArezComponent( allowEmpty = true, requireId = Feature.DISABLE )
  static abstract class Model1
  {
  }

  @ArezComponent( allowEmpty = true, requireId = Feature.ENABLE )
  static abstract class Model2
  {
    private final int id;

    Model2( final int id )
    {
      this.id = id;
    }

    @ComponentId
    int getId()
    {
      return id;
    }
  }

  @ArezComponent( allowEmpty = true, requireId = Feature.AUTODETECT )
  static abstract class Model3
  {
  }
}

Fix test to reflect current defaults

Fix test to reflect current defaults


package io.palette;

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

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

public class RNPalettePackage implements ReactPackage {
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
      return Arrays.<NativeModule>asList(new RNPaletteModule(reactContext));
    }

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

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

package io.palette;

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

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

public class RNPalettePackage implements ReactPackage {
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
      return Arrays.<NativeModule>asList(new RNPaletteModule(reactContext));
    }

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

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

Fix breaking change in RN 47

Fix breaking change in RN 47


package x1125io.initdlight;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class BootReceiver extends BroadcastReceiver {

    final String TAG = "initdlight";

    @Override
    public void onReceive(Context context, Intent intent) {

        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {

            for (String file: context.getFilesDir().list()) {

                ProcessRunner pr = new ProcessRunner();
                String fullFilePath = context.getFilesDir().toString() + "/" + file;
                int exitCode = pr.Run(new String[] { "su", "-c", "sh", fullFilePath });

                if (exitCode == 0) {
                    Log.d(TAG, "started " + file);
                } else {
                    Log.d(TAG, String.format(
                            "error starting %s; exit code: %d; stdout: %s; stderr: %s",
                            file,
                            exitCode,
                            pr.getStdout(),
                            pr.getStderr()
                    ));
                }
            }

        }
    }
}

package x1125io.initdlight;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class BootReceiver extends BroadcastReceiver {

    final String TAG = "initdlight";

    @Override
    public void onReceive(Context context, Intent intent) {

        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {

            for (String file: context.getFilesDir().list()) {

                ProcessRunner pr = new ProcessRunner();
                String fullFilePath = context.getFilesDir().toString() + "/" + file;
                int exitCode = pr.Run(new String[] { "su", "-c", "sh " + fullFilePath });

                if (exitCode == 0) {
                    Log.d(TAG, "started " + file);
                } else {
                    Log.d(TAG, String.format(
                            "error starting %s; exit code: %d; stdout: %s; stderr: %s",
                            file,
                            exitCode,
                            pr.getStdout(),
                            pr.getStderr()
                    ));
                }
            }

        }
    }
}

Fix permission problems for running scripts via sh binary


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

package com.google.android.libraries.remixer;

import com.google.android.libraries.remixer.annotation.RemixerBinder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class FailfastTest {
  @Test(expected = IllegalStateException.class)
  public void binderFailsFast() {
    RemixerBinder.bind(this);
  }

  @Test(expected = IllegalStateException.class)
  public void remixerAddFailsFast() {
    Remixer.getInstance().addItem(new Trigger.Builder().setContext(this).setKey("key").build());
  }
}

Improve formatting in failfast test

Improve formatting in failfast test


package net.sf.clirr.core;

import net.sf.clirr.core.internal.ClassChangeCheck;
import net.sf.clirr.core.Checker;

/**
 * Provides a way for check tests to create a checker via the package private
 * Checker constructor, even if the tests are not in the same package.
 */
public class CheckerFactory
{
    public static Checker createChecker(ClassChangeCheck check)
    {
        return new Checker(check);
    }
}

package net.sf.clirr.core;

import net.sf.clirr.core.internal.ClassChangeCheck;
import net.sf.clirr.core.Checker;

/**
 * Provides a way for check tests to create a checker via the package private
 * Checker constructor, even if the tests are not in the same package.
 */
public class CheckerFactory
{
    public static Checker createChecker(ClassChangeCheck check)
    {
        return new Checker(check);
    }

    public static Checker createChecker()
    {
        return new Checker();
    }
}

Add factory method for Checker instance with default set of checks.


//
// Nexus Core - a framework for developing distributed applications
// http://github.com/threerings/nexus/blob/master/LICENSE

package com.threerings.nexus.util;

/**
 * Used to communicate asynchronous results.
 */
public interface Callback<T>
{
    /** A callback that chains failure to the supplied delegate callback. */
    public static abstract class Chain<T> implements Callback<T> {
        public Chain (Callback<?> onFailure) {
            _onFailure = onFailure;
        }
        public void onFailure (Throwable cause) {
            _onFailure.onFailure(cause);
        }
        protected Callback<?> _onFailure;
    }

    public static class NoOp<T> implements Callback<T> {
        @Override public void onSuccess (T result) {
            // We're a No-Op - do nothing.
        }

        @Override public void onFailure (Throwable cause) {
            // We're a No-Op - do nothing.
        }
    }

    /**
     * Called when the asynchronous request succeeded, supplying its result.
     */
    void onSuccess (T result);

    /**
     * Called when the asynchronous request failed, supplying a cause for failure.
     */
    void onFailure (Throwable cause);
}

//
// Nexus Core - a framework for developing distributed applications
// http://github.com/threerings/nexus/blob/master/LICENSE

package com.threerings.nexus.util;

/**
 * Used to communicate asynchronous results.
 */
public interface Callback<T>
{
    /** A callback that chains failure to the supplied delegate callback. */
    public static abstract class Chain<T> implements Callback<T> {
        public Chain (Callback<?> onFailure) {
            _onFailure = onFailure;
        }
        public void onFailure (Throwable cause) {
            _onFailure.onFailure(cause);
        }
        protected Callback<?> _onFailure;
    }

    /** A callback that does nothing, including nothing in the event of failure. Don't use this if
     * doing so will result in the suppression of errors! */
    public static final Callback<Object> NOOP = new Callback<Object>() {
        @Override public void onSuccess (Object result) {} // noop!
        @Override public void onFailure (Throwable cause) {} // noop!
    };

    /**
     * Called when the asynchronous request succeeded, supplying its result.
     */
    void onSuccess (T result);

    /**
     * Called when the asynchronous request failed, supplying a cause for failure.
     */
    void onFailure (Throwable cause);
}

Switch to a singleton NOOP. With proper variance, this can be used everywhere.

Proper variance is useful in general. When you want to use it, define your
service methods thusly:

  void detonateBombs (int targetId, Callback<? super String> onResult);

Then you can pass Callback<String> or Callback<Object> to the service method in
question.

Java uses what is called "use site" variance declarations, which means that
everyone that uses Callback has to repeat this "? super" boilerplate. Java
loves boilerplate, so perhaps it's apropos.

There is an alternative approach, called "declaration site" variance, which is
used by Scala. It allows the Callback declaration to say that it is
contravariant in type parameter T:

  trait Callback[-T] {
    def onSuccess (value :T)
    def onFailure (cause :Throwable)
  }

The "-T" means that everywhere someone says they take Callback[T], they
actually mean they take (the equivalent of) Callback[? super T]. Things "just
work" for everyone who uses Callback and there is much rejoicing. If only we
could write everything in Scala.


package com.googlecode.jslint4java.cli;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;

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

import com.beust.jcommander.ParameterException;

public class CharsetConverterTest {

    private static final String UNKNOWN_CHARSET_NAME = "bob";
    private final CharsetConverter cc = new CharsetConverter();

    @Rule
    public final ExpectedException thrown = ExpectedException.none();

    @Test
    public void testConvert() throws Exception {
        assertThat(cc.convert("UTF-8"), is(Charset.forName("UTF-8")));
    }

    @Test
    public void testIllegalCharsetName() throws Exception {
        thrown.expect(ParameterException.class);
        thrown.expectMessage("unknown encoding");
        cc.convert("!@#$%^&*(");
    }

    @Test
    public void testUnknownCharset() throws Exception {
        // We only want to run this test if we can guarantee that the charset _doesn't_ exist in the
        // system first. Otherwise, we'll just have to ignore this test.
        try {
            Charset.forName(UNKNOWN_CHARSET_NAME);
        } catch (UnsupportedCharsetException e) {
            // We're good to run the test.
            thrown.expect(ParameterException.class);
            thrown.expectMessage("unknown encoding");
            cc.convert(UNKNOWN_CHARSET_NAME);
        }
    }

}

package com.googlecode.jslint4java.cli;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.junit.Assume.*;

import java.nio.charset.Charset;

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

import com.beust.jcommander.ParameterException;

public class CharsetConverterTest {

    private static final String UNKNOWN_CHARSET_NAME = "bob";
    private final CharsetConverter cc = new CharsetConverter();

    @Rule
    public final ExpectedException thrown = ExpectedException.none();

    @Test
    public void testConvert() throws Exception {
        assertThat(cc.convert("UTF-8"), is(Charset.forName("UTF-8")));
    }

    @Test
    public void testIllegalCharsetName() throws Exception {
        thrown.expect(ParameterException.class);
        thrown.expectMessage("unknown encoding");
        cc.convert("!@#$%^&*(");
    }

    @Test
    public void testUnknownCharset() throws Exception {
        // We only want to run this test if we can guarantee that the charset _doesn't_ exist in the
        // system first. Otherwise, we'll just have to ignore this test.
        assumeThat(Charset.isSupported(UNKNOWN_CHARSET_NAME), is(false));

        // We're good to run the test.
        thrown.expect(ParameterException.class);
        thrown.expectMessage("unknown encoding");
        cc.convert(UNKNOWN_CHARSET_NAME);
    }

}

Use assumption to simplify test.

Use assumption to simplify test.


package com.betato.testgame;

import java.awt.Graphics;

import com.betato.gamedisplay.Frame;
import com.betato.gamedisplay.GameLoop;
import com.betato.gamedisplay.GameWindow;

public class TestGame extends GameWindow{
	private static final long serialVersionUID = 1L;

	public TestGame() {
		start(new GameLoop(60, 120), new Frame(300, 300, "Title"));
	}

	@Override
	public void onInit() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onUpdate() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onRender(Graphics g) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onExit() {
		// TODO Auto-generated method stub

	}

}

package com.betato.testgame;

import java.awt.Color;
import java.awt.Graphics;

import com.betato.gamedisplay.Frame;
import com.betato.gamedisplay.GameLoop;
import com.betato.gamedisplay.GameWindow;

public class TestGame extends GameWindow{
	private static final long serialVersionUID = 1L;

	int acc;

	public TestGame() {
		start(new GameLoop(60, 120), new Frame(300, 300, "Title"));
	}

	@Override
	public void onInit() {
		acc = 100;
	}

	@Override
	public void onUpdate() {
		if (acc < 9999){
			acc++;
		} else {
			acc = 0;
		}
	}

	@Override
	public void onRender(Graphics g) {
		g.setColor(Color.white);
		g.fillRect(0, 0, 300, 300);
		g.setColor(Color.black);
		g.drawString("fps:" + fps + " ups:" + ups, 10, 10);
		g.drawString("lalala:" + acc, 10, 30);
	}

	@Override
	public void onExit() {
		// TODO Auto-generated method stub

	}

}

Add render and update test

Add render and update test


package com.boundary.sdk.event;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.net.URL;

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

public class ScriptUtils {

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

	public ScriptUtils() {
	}

	/**
	 * Finds a script to be tested from
	 * @param scriptName
	 * @return {@link File}
	 */
	static public FileReader getFile(String scriptPath) {
		ClassLoader loader = Thread.currentThread().getContextClassLoader();

		URL url = loader.getResource(scriptPath);
		assert(url == null);
		File f = new File(url.getFile());
		FileReader reader = null;
		try {
			reader = new FileReader(f);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			LOG.error(e.getMessage());
		}
		return reader;
	}
}

package com.boundary.sdk.event;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.net.URL;

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

/**
 * Utilities used for java script execution
 *
 * @author davidg
 *
 */
public class ScriptUtils {

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

	public ScriptUtils() {
	}

	/**
	 * Finds a script to be tested from
	 * @param scriptPath
	 * @return {@link File}
	 */
	static public FileReader getFile(String scriptPath) {
		ClassLoader loader = Thread.currentThread().getContextClassLoader();

		URL url = loader.getResource(scriptPath);
		assert(url == null);
		File f = new File(url.getFile());
		FileReader reader = null;
		try {
			reader = new FileReader(f);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			LOG.error(e.getMessage());
		}
		return reader;
	}
}

Fix warning when generating javadoc ; Add class description


package com.vtence.molecule.testing;

import com.vtence.molecule.helpers.Charsets;
import com.vtence.molecule.helpers.Joiner;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HtmlForm {

    private final Map<String, String> data = new HashMap<String, String>();
    private Charset charset = Charsets.UTF_8;

    public String contentType() {
        return "application/x-www-form-urlencoded";
    }

    public HtmlForm encoding(String charsetName) {
        return encoding(Charset.forName(charsetName));
    }

    public HtmlForm encoding(Charset charset) {
        this.charset = charset;
        return this;
    }

    public HtmlForm set(String name, String value) {
        data.put(name, value);
        return this;
    }

    public String encode() {
        List<String> pairs = new ArrayList<String>();
        URLEscaper escaper = URLEscaper.to(charset);
        for (String name : data.keySet()) {
            pairs.add(escaper.escape(name) + "=" + escaper.escape(data.get(name)));
        }
        return Joiner.on("&").join(pairs);
    }
}

package com.vtence.molecule.testing;

import com.vtence.molecule.helpers.Charsets;
import com.vtence.molecule.helpers.Joiner;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HtmlForm {

    private final Map<String, String> data = new HashMap<String, String>();
    private Charset charset = Charsets.UTF_8;

    public String contentType() {
        return "application/x-www-form-urlencoded";
    }

    public HtmlForm charset(String charsetName) {
        return charset(Charset.forName(charsetName));
    }

    public HtmlForm charset(Charset charset) {
        this.charset = charset;
        return this;
    }

    public HtmlForm set(String name, String value) {
        data.put(name, value);
        return this;
    }

    public String encode() {
        List<String> pairs = new ArrayList<String>();
        URLEscaper escaper = URLEscaper.to(charset);
        for (String name : data.keySet()) {
            pairs.add(escaper.escape(name) + "=" + escaper.escape(data.get(name)));
        }
        return Joiner.on("&").join(pairs);
    }
}

Clarify language to avoid confusing between form accepted charset and form encoding type


package org.utplsql.api;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;

/** This class is getting updated automatically by the build process.
 * Please do not update its constants manually cause they will be overwritten.
 *
 * @author pesse
 */
public class JavaApiVersionInfo {

    private JavaApiVersionInfo() { }

    private static final String MAVEN_PROJECT_NAME = "utPLSQL-java-api";
    private static String MAVEN_PROJECT_VERSION = "unknown";

    static {
        try {
            MAVEN_PROJECT_VERSION = Files.readAllLines(
                    Paths.get(JavaApiVersionInfo.class.getClassLoader().getResource("utplsql-api.version").toURI())
                    , Charset.defaultCharset())
                    .get(0);
        }
        catch ( IOException | URISyntaxException e ) {
            System.out.println("WARNING: Could not get Version information!");
        }
    }

    public static String getVersion() { return MAVEN_PROJECT_VERSION; }
    public static String getInfo() { return MAVEN_PROJECT_NAME + " " + getVersion(); }

}

package org.utplsql.api;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;

/** This class is getting updated automatically by the build process.
 * Please do not update its constants manually cause they will be overwritten.
 *
 * @author pesse
 */
public class JavaApiVersionInfo {

    private JavaApiVersionInfo() { }

    private static final String MAVEN_PROJECT_NAME = "utPLSQL-java-api";
    private static String MAVEN_PROJECT_VERSION = "unknown";

    static {
        try {

            try ( InputStream in = JavaApiVersionInfo.class.getClassLoader().getResourceAsStream("utplsql-api.version")) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                MAVEN_PROJECT_VERSION = reader.readLine();

                reader.close();
            }
        }
        catch ( IOException e ) {
            System.out.println("WARNING: Could not get Version information!");
        }
    }

    public static String getVersion() { return MAVEN_PROJECT_VERSION; }
    public static String getInfo() { return MAVEN_PROJECT_NAME + " " + getVersion(); }

}

Use ResourceStream instead of NIO File access


package com.hamishrickerby.http_server;

/**
 * Created by rickerbh on 15/08/2016.
 */
public class App {
    public static void main(String[] args) {
        AppArguments arguments = new AppArguments(args);
        Integer port = Integer.parseInt(arguments.getOrDefault("-p", "5000"));
        try {
            SocketServer server = new SocketServer(port);
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

package com.hamishrickerby.http_server;

/**
 * Created by rickerbh on 15/08/2016.
 */
public class App {
    public static void main(String[] args) {
        AppArguments arguments = new AppArguments(args);
        Integer port = Integer.parseInt(arguments.getOrDefault("-p", "5000"));
        SocketServer server = null;
        try {
            server = new SocketServer(port);
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            server.close();
        }
    }
}

Add closing of socket server on app exit


/*
 * Copyright 2000-2013 JetBrains s.r.o.
 *
 * 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.jetbrains.python;

import com.intellij.codeInsight.actions.MultiCaretCodeInsightAction;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.IdeActions;
import com.jetbrains.python.fixtures.PyTestCase;

/**
 * @author yole
 */
public class PyCommenterTest extends PyTestCase {
  public void testIndentedComment() {
    doTest();
  }

  public void testUncommentWithoutSpace() {
    doTest();
  }

  private void doTest() {
    myFixture.configureByFile("commenter/" + getTestName(true) + ".py");
    MultiCaretCodeInsightAction action = (MultiCaretCodeInsightAction) ActionManager.getInstance().getAction(IdeActions.ACTION_COMMENT_LINE);
    action.actionPerformedImpl(myFixture.getFile().getProject(), myFixture.getEditor());
    myFixture.checkResultByFile("commenter/" + getTestName(true) + "_after.py", true);

  }
}

/*
 * Copyright 2000-2013 JetBrains s.r.o.
 *
 * 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.jetbrains.python;

import com.intellij.openapi.actionSystem.IdeActions;
import com.jetbrains.python.fixtures.PyTestCase;

/**
 * @author yole
 */
public class PyCommenterTest extends PyTestCase {
  public void testIndentedComment() {
    doTest();
  }

  public void testUncommentWithoutSpace() {
    doTest();
  }

  private void doTest() {
    myFixture.configureByFile("commenter/" + getTestName(true) + ".py");
    myFixture.performEditorAction(IdeActions.ACTION_COMMENT_LINE);
    myFixture.checkResultByFile("commenter/" + getTestName(true) + "_after.py", true);
  }
}

Use simpler test API for performing actions


package net.squanchy.navigation;

import android.content.Context;
import android.content.Intent;

import net.squanchy.eventdetails.EventDetailsActivity;
import net.squanchy.search.SearchActivity;
import net.squanchy.speaker.SpeakerDetailsActivity;

public class Navigator {

    private final Context context;

    public Navigator(Context context) {
        this.context = context;
    }

    public void toEventDetails(String eventId) {
        Intent intent = EventDetailsActivity.createIntent(context, eventId);
        context.startActivity(intent);
    }

    public void toSpeakerDetails(String speakerId) {
        Intent intent = SpeakerDetailsActivity.createIntent(context, speakerId);
        context.startActivity(intent);
    }

    public void toSearch() {
        context.startActivity(new Intent(context, SearchActivity.class));
    }
}

package net.squanchy.navigation;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import net.squanchy.eventdetails.EventDetailsActivity;
import net.squanchy.search.SearchActivity;
import net.squanchy.speaker.SpeakerDetailsActivity;

public class Navigator {

    private final Context context;

    public Navigator(Context context) {
        this.context = context;
    }

    public void toEventDetails(String eventId) {
        Intent intent = EventDetailsActivity.createIntent(context, eventId);
        context.startActivity(intent);
    }

    public void toSpeakerDetails(String speakerId) {
        Intent intent = SpeakerDetailsActivity.createIntent(context, speakerId);
        context.startActivity(intent);
    }

    public void toSearch() {
        context.startActivity(new Intent(context, SearchActivity.class));
    }

    public void toTwitterProfile(String username) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("twitter://user?screen_name=" + username));
        if (canResolve(intent)) {
            context.startActivity(intent);
        } else {
            toExternalUrl("https://twitter.com/" + username);
            context.startActivity(intent);
        }
    }

    private boolean canResolve(Intent intent) {
        return context.getPackageManager()
                .queryIntentActivities(intent, 0)
                .isEmpty();
    }

    public void toExternalUrl(String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        context.startActivity(intent);
    }
}

Add support for navigating to Twitter profile and external URL


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

package org.gradle.internal.vfs;

/**
 * Identifies if a path is underneath one of Gradle's "additive caches".
 *
 * Over time more files can be added to an additive cache, but existing files
 * can never be modified. Files in additive caches can only be deleted as part
 * of cleanup.
 *
 * This quasi-immutability about additive caches allows for some
 * optimizations wrt retaining file system state in-memory.
 */
public interface AdditiveCacheLocations {

    /**
     * Checks if a given path is inside one of Gradle's additive caches.
     */
    boolean isInsideAdditiveCache(String path);
}

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

package org.gradle.internal.vfs;

/**
 * Identifies if a path is underneath one of Gradle's "additive caches".
 *
 * Over time more files can be added to an additive cache, but existing files
 * can never be modified.
 * Files in additive caches can only be deleted as part of cleanup.
 *
 * This quasi-immutability about additive caches allows for some
 * optimizations wrt retaining file system state in-memory.
 */
public interface AdditiveCacheLocations {

    /**
     * Checks if a given path is inside one of Gradle's additive caches.
     */
    boolean isInsideAdditiveCache(String path);
}

Put new sentence in Javadoc on new line

Put new sentence in Javadoc on new line


package access;

import io.restassured.http.ContentType;
import org.testng.annotations.Test;

import static io.restassured.RestAssured.get;

/**
 * Created by Vladyslav Dovhopol on 4/27/17.
 * Test Greeting Controller.
 */
public class AccessControllerTest {

    @Test
    public void GET_NoPayload_Correct() {
        get("/greeting").
        then().assertThat().
                statusCode(200).and().
                contentType(ContentType.HTML);
    }
}

package access;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.Is.is;

/**
 * Created by Vladyslav Dovhopol on 4/27/17.
 * Test Greeting Controller.
 */
@RunWith(SpringRunner.class)
public class AccessControllerTest {

    @Test
    public void assertThatNullIsNull() {
        assertThat(null, is(nullValue()));
    }
}

Write stub test to check that Travis CI runs it.


/*
 * Copyright 2011-2013, by Vladimir Kostyukov and Contributors.
 *
 * This file is part of la4j project (http://la4j.org)
 *
 * 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.
 *
 * Contributor(s): -
 *
 */

package org.la4j.matrix.sparse;

import org.la4j.matrix.AbstractMatrixTest;

public abstract class SparseMatrixTest extends AbstractMatrixTest {

    public void testCardinality() {

        double array[][] = new double[][] {
                { 1.0, 0.0, 0.0 },
                { 0.0, 5.0, 0.0 },
                { 0.0, 0.0, 9.0 }
        };

        SparseMatrix a = (SparseMatrix) factory().createMatrix(array);

        assertEquals(3, a.cardinality());
    }
}

/*
 * Copyright 2011-2013, by Vladimir Kostyukov and Contributors.
 *
 * This file is part of la4j project (http://la4j.org)
 *
 * 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.
 *
 * Contributor(s): -
 *
 */

package org.la4j.matrix.sparse;

import org.la4j.matrix.AbstractMatrixTest;

public abstract class SparseMatrixTest extends AbstractMatrixTest {

    public void testCardinality() {

        double array[][] = new double[][] {
                { 1.0, 0.0, 0.0 },
                { 0.0, 5.0, 0.0 },
                { 0.0, 0.0, 9.0 }
        };

        SparseMatrix a = (SparseMatrix) factory().createMatrix(array);

        assertEquals(3, a.cardinality());
    }

	public void testLargeMatrix()
	{
		SparseMatrix a = (SparseMatrix) factory().createMatrix(1000000, 1000000);
	}
}

Add a test case for very large sparse matrix


package net.kencochrane.raven;

import net.kencochrane.raven.connection.Connection;
import net.kencochrane.raven.event.Event;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

public class RavenTest {
    @Mock
    private Connection mockConnection;
    private Raven raven;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        raven = new Raven(mockConnection);
    }

    @Test
    public void testSendEvent() {
        Event event = mock(Event.class);
        raven.sendEvent(event);

        verify(mockConnection).send(event);
    }
}

package net.kencochrane.raven;

import net.kencochrane.raven.connection.Connection;
import net.kencochrane.raven.event.Event;
import net.kencochrane.raven.event.EventBuilder;
import net.kencochrane.raven.event.helper.EventBuilderHelper;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.not;
import static org.mockito.Mockito.*;

public class RavenTest {
    @Mock
    private Connection mockConnection;
    private Raven raven;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        raven = new Raven(mockConnection);
    }

    @Test
    public void testSendEvent() {
        Event event = mock(Event.class);
        raven.sendEvent(event);

        verify(mockConnection).send(event);
    }

    @Test
    public void testChangeConnection() {
        Event event = mock(Event.class);
        Connection mockNewConnection = mock(Connection.class);

        raven.setConnection(mockNewConnection);
        raven.sendEvent(event);

        verify(mockConnection, never()).send(event);
        verify(mockNewConnection).send(event);
    }

    @Test
    public void testAddRemoveBuilderHelpers() {
        EventBuilderHelper builderHelper = mock(EventBuilderHelper.class);
        assertThat(raven.getBuilderHelpers(), not(contains(builderHelper)));

        raven.addBuilderHelper(builderHelper);
        assertThat(raven.getBuilderHelpers(), contains(builderHelper));
        raven.removeBuilderHelper(builderHelper);
        assertThat(raven.getBuilderHelpers(), not(contains(builderHelper)));
    }

    @Test(expected = UnsupportedOperationException.class)
    public void testCantModifyBuilderHelpersDirectly() {
        EventBuilderHelper builderHelper = mock(EventBuilderHelper.class);
        raven.getBuilderHelpers().add(builderHelper);
    }

    @Test
    public void testRunBuilderHelpers() {
        EventBuilder eventBuilder = mock(EventBuilder.class);
        EventBuilderHelper builderHelper = mock(EventBuilderHelper.class);
        raven.addBuilderHelper(builderHelper);

        raven.runBuilderHelpers(eventBuilder);

        verify(builderHelper).helpBuildingEvent(eventBuilder);
    }
}

Add unit tests for Raven

Add unit tests for Raven


/*
 * Copyright (c) 2016 MCPhoton <http://mcphoton.org> and contributors.
 *
 * This file is part of the Photon Server Implementation <https://github.com/mcphoton/Photon-Server>.
 *
 * The Photon Server Implementation is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * The Photon Server Implementation 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.mcphoton.impl.command;

import org.mcphoton.command.Command;
import org.mcphoton.impl.server.Main;
import org.mcphoton.messaging.Messageable;

public class ListCommand implements Command {

	@Override
	public void execute(Messageable source, String[] args) {

		switch(Main.serverInstance.getOnlinePlayers().size()) {
		case 0:
			source.sendMessage("No player is connected.");
			break;
		case 1:
			source.sendMessage("There is 1 of " + Main.serverInstance.getMaxPlayers() + " player connected.");
			break;
		default:
			source.sendMessage("There are " + Main.serverInstance.getOnlinePlayers().size() + " of " + Main.serverInstance.getMaxPlayers() + " players connected.");
			break;
		}
	}

	@Override
	public String getName() {
		return "list";
	}

}

Fix problem with a build error.

Fix problem with a build error.

Error with Gradle at task 'licenseMain': "Missing header in: src\main\java\org\mcphoton\impl\command\ListCommand.java"

It's a fix.


package org.realityforge.arez.processor;

import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.processing.AbstractProcessor;
import javax.lang.model.element.Element;
import static javax.tools.Diagnostic.Kind.ERROR;

abstract class AbstractJavaPoetProcessor
  extends AbstractProcessor
{
  final void processElements( @Nonnull final Set<? extends Element> elements )
  {
    for ( final Element element : elements )
    {
      try
      {
        process( element );
      }
      catch ( final IOException ioe )
      {
        processingEnv.getMessager().printMessage( ERROR, ioe.getMessage() );
      }
      catch ( final ArezProcessorException e )
      {
        e.print( processingEnv.getMessager() );
      }
    }
  }

  protected abstract void process( @Nonnull Element element )
    throws IOException, ArezProcessorException;

  final void emitTypeSpec( @Nonnull final String packageName, @Nonnull final TypeSpec typeSpec )
    throws IOException
  {
    emitJavaFile( convertTypeSpecToJavaFile( packageName, typeSpec ) );
  }

  @Nonnull
  private JavaFile convertTypeSpecToJavaFile( @Nonnull final String packageName, @Nonnull final TypeSpec typeSpec )
  {
    return JavaFile.builder( packageName, typeSpec ).
      skipJavaLangImports( true ).
      build();
  }

  private void emitJavaFile( @Nonnull final JavaFile javaFile )
    throws IOException
  {
    javaFile.writeTo( processingEnv.getFiler() );
  }
}

package org.realityforge.arez.processor;

import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.processing.AbstractProcessor;
import javax.lang.model.element.Element;
import static javax.tools.Diagnostic.Kind.ERROR;

abstract class AbstractJavaPoetProcessor
  extends AbstractProcessor
{
  final void processElements( @Nonnull final Set<? extends Element> elements )
  {
    for ( final Element element : elements )
    {
      try
      {
        process( element );
      }
      catch ( final IOException ioe )
      {
        processingEnv.getMessager().printMessage( ERROR, ioe.getMessage(), element );
      }
      catch ( final ArezProcessorException e )
      {
        e.print( processingEnv.getMessager() );
      }
    }
  }

  protected abstract void process( @Nonnull Element element )
    throws IOException, ArezProcessorException;

  final void emitTypeSpec( @Nonnull final String packageName, @Nonnull final TypeSpec typeSpec )
    throws IOException
  {
    emitJavaFile( convertTypeSpecToJavaFile( packageName, typeSpec ) );
  }

  @Nonnull
  private JavaFile convertTypeSpecToJavaFile( @Nonnull final String packageName, @Nonnull final TypeSpec typeSpec )
  {
    return JavaFile.builder( packageName, typeSpec ).
      skipJavaLangImports( true ).
      build();
  }

  private void emitJavaFile( @Nonnull final JavaFile javaFile )
    throws IOException
  {
    javaFile.writeTo( processingEnv.getFiler() );
  }
}

Add top level element to io exception

Add top level element to io exception


/**
 * @file Counter.java
 * @author Valery Samovich
 * @version 1
 * @date 2015/01/05
 */

package com.valerysamovich.java.oop.staticex.counter;

public class Counter {

    NonStaticCounter c1 = new NonStaticCounter();
    NonStaticCounter c2 = new NonStaticCounter();
    NonStaticCounter c3 = new NonStaticCounter();
}

/**
 * @file Counter.java
 * @author Valery Samovich
 * @version 1
 * @date 2015/01/05
 */

package com.valerysamovich.java.oop.staticex.counter;

public class Counter {

    public static void main(String[] args) {

        System.out.println("Non Static Objects:");

        // Non Static Object Counters
        NonStaticCounter c1 = new NonStaticCounter();
        NonStaticCounter c2 = new NonStaticCounter();
        NonStaticCounter c3 = new NonStaticCounter();

        System.out.println(" ");

        System.out.println("Static Objects:");
        // Static Object Counters
        StaticCounter c4 = new StaticCounter();
        StaticCounter c5 = new StaticCounter();
        StaticCounter c6 = new StaticCounter();

    }

}

Add counter Static example plus non Static


package com.fatwire.gst.foundation.controller;

import javax.servlet.ServletContext;

import com.fatwire.assetapi.data.BaseController;
import com.fatwire.gst.foundation.controller.action.Injector;
import com.fatwire.gst.foundation.controller.support.WebContextUtil;

import COM.FutureTense.Interfaces.DependenciesAwareModelAndView;
import COM.FutureTense.Interfaces.ICS;

public class InjectingController extends BaseController {

	public InjectingController(ICS ics)
	{
		super();
		this.setICS(ics);

	}

	public DependenciesAwareModelAndView handleRequest()
	{

		ServletContext srvCtx = ics.getIServlet().getServlet().getServletContext();
		AppContext ctx = WebContextUtil.getWebAppContext(srvCtx);
		Injector injector = ctx.getBean("Injector",Injector.class);
		injector.inject(ics, this);

		return super.handleRequest();
	}

}

/*
 * Copyright 2016 Function1. All Rights Reserved.
 *
 * 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.fatwire.gst.foundation.controller;

import javax.servlet.ServletContext;

import com.fatwire.assetapi.data.BaseController;
import com.fatwire.gst.foundation.controller.action.Injector;
import com.fatwire.gst.foundation.controller.support.WebContextUtil;

import COM.FutureTense.Interfaces.DependenciesAwareModelAndView;

public class InjectingController extends BaseController {

	public DependenciesAwareModelAndView handleRequest() {
		ServletContext srvCtx = ics.getIServlet().getServlet().getServletContext();
		AppContext ctx = WebContextUtil.getWebAppContext(srvCtx);
		Injector injector = ctx.getBean("Injector",Injector.class);
		injector.inject(ics, this);
		return super.handleRequest();
	}
}

Add license to controller file.

Add license to controller file.


// Copyright © 2011-2015, Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0

package fi.jumi.actors.eventizers.dynamic;

import fi.jumi.actors.Promise;
import fi.jumi.actors.eventizers.Event;
import fi.jumi.actors.queue.MessageSender;

import javax.annotation.concurrent.ThreadSafe;
import java.lang.reflect.*;

@ThreadSafe
public class DynamicListenerToEvent<T> implements InvocationHandler {

    private final MessageSender<Event<T>> target;

    public DynamicListenerToEvent(MessageSender<Event<T>> target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (method.getDeclaringClass().equals(Object.class)) {
            return method.invoke(this, args);
        }
        if (method.getReturnType().isAssignableFrom(Promise.class)) {
            Promise.Deferred<T> deferred = Promise.defer();
            target.send(new DynamicEvent<>(method, args, deferred));
            return deferred.promise();
        } else {
            target.send(new DynamicEvent<>(method, args));
            return null;
        }
    }
}

// Copyright © 2011-2018, Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0

package fi.jumi.actors.eventizers.dynamic;

import fi.jumi.actors.Promise;
import fi.jumi.actors.eventizers.Event;
import fi.jumi.actors.queue.MessageSender;

import javax.annotation.concurrent.ThreadSafe;
import java.lang.reflect.*;
import java.util.concurrent.Future;

@ThreadSafe
public class DynamicListenerToEvent<T> implements InvocationHandler {

    private final MessageSender<Event<T>> target;

    public DynamicListenerToEvent(MessageSender<Event<T>> target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (method.getDeclaringClass().equals(Object.class)) {
            return method.invoke(this, args);
        }
        if (Future.class.isAssignableFrom(method.getReturnType())) {
            Promise.Deferred<T> deferred = Promise.defer();
            target.send(new DynamicEvent<>(method, args, deferred));
            return deferred.promise();
        } else {
            target.send(new DynamicEvent<>(method, args));
            return null;
        }
    }
}

Check for the Future interface instead of the custom Promise class

Fixes #5


// this needs to be modified to work with the new java 7 date class

package tap.sample;

import tap.*;
import quantbench.Candle;

public class Subscribe {
    public static main(String[] args) throws Exception {
        Tap tap = new Tap();
        tap.startTime("2011-01-03 10:40:00.000");
        tap.endTime("2011-01-03 10:50:00.000");
        Pipe<Candle> candles = tap.subscribe("//cta/candle/1min[AAPL]");
        while (candles.more()) {
            Candle m = candles.get();
            Date time = Tap.newDate(m.getStartTime());
            System.out.println(time.toString + " symbol " + m.getSymbol() +
                               " open " + m.getOpen() + " volume " + m.getVolume());
        }
    }
}

// this needs to be modified to work with the new java 7 date class

package tap.sample;

import tap.*;
import quantbench.Candle;

public class Subscribe {

    // Usage: hadoop jar yourjar.jar -s 2011-01-03 10:40:00.000 -e 2011-01-03 10:50:00.000
    public static main(String[] args) throws Exception {
        CommandOptions o = new CommandOptions(args);
        Tap tap = new Tap(o);

        Pipe<Candle> candles = tap.subscribe("//cta/candle/1min[AAPL]");
        while (candles.more()) {
            Candle m = candles.get();
            Date time = Tap.newDate(m.getStartTime());
            System.out.println(time.toString + " symbol " + m.getSymbol() +
                               " open " + m.getOpen() + " volume " + m.getVolume());
        }
    }
}

Fix Tap constructor, pass start and end time via command line arguments.


package cz.crcs.ectester.reader.output;

import cz.crcs.ectester.common.util.CardUtil;
import cz.crcs.ectester.reader.response.Response;

import java.io.PrintStream;

/**
 * @author Jan Jancar johny@neuromancer.sk
 */
public class ResponseWriter {
    private PrintStream output;

    public ResponseWriter(PrintStream output) {
        this.output = output;
    }

    public String responseSuffix(Response r) {
        StringBuilder suffix = new StringBuilder();
        for (int j = 0; j < r.getNumSW(); ++j) {
            short sw = r.getSW(j);
            if (sw != 0) {
                suffix.append(" ").append(CardUtil.getSWString(sw));
            }
        }
        if (suffix.length() == 0) {
            suffix.append(" [").append(CardUtil.getSW(r.getNaturalSW())).append("]");
        }
        return String.format("%4d ms ┃ %s", r.getDuration() / 1000000, suffix);
    }

    public String responseString(Response r) {
        String out = "";
        out += String.format("%-70s", r.getDescription()) + " ┃ ";
        out += responseSuffix(r);
        return out;
    }

    public void outputResponse(Response r) {
        output.println(responseString(r));
        output.flush();
    }
}

package cz.crcs.ectester.reader.output;

import cz.crcs.ectester.common.util.CardUtil;
import cz.crcs.ectester.reader.response.Response;

import java.io.PrintStream;

/**
 * @author Jan Jancar johny@neuromancer.sk
 */
public class ResponseWriter {
    private PrintStream output;

    public ResponseWriter(PrintStream output) {
        this.output = output;
    }

    public String responseSuffix(Response r) {
        StringBuilder suffix = new StringBuilder();
        for (int j = 0; j < r.getNumSW(); ++j) {
            short sw = r.getSW(j);
            if (sw != 0) {
                suffix.append(" ").append(CardUtil.getSWString(sw));
            }
        }
        if (suffix.length() == 0) {
            suffix.append(" [").append(CardUtil.getSW(r.getNaturalSW())).append(String.format(" 0x%04x", r.getNaturalSW())).append("]");
        }
        return String.format("%4d ms ┃ %s", r.getDuration() / 1000000, suffix);
    }

    public String responseString(Response r) {
        String out = "";
        out += String.format("%-70s", r.getDescription()) + " ┃ ";
        out += responseSuffix(r);
        return out;
    }

    public void outputResponse(Response r) {
        output.println(responseString(r));
        output.flush();
    }
}

Make test output show natural sw.

Make test output show natural sw.


package Controllers;

import java.util.List;

import javax.persistence.EntityManager;

import flexjson.JSONSerializer;
import MVC.Controller;

/**
 * @author Alexander
 *
 */
public class UserCtl extends Controller {

    @Override
    public void doRequest(String actionName, Integer id) throws Exception {

        EntityManager em = this.getServletContext().getEM();

        // if(actionName.equals("create")) {
        //
        // User u = new User();
        //
        // // u.setEmail(getRequest().getParameter("email"));
        //
        // em.getTransaction().begin();
        // em.persist(u);
        // em.getTransaction().commit();

        //
        if (actionName.equals("get")) {
            List<?> list = em.createNamedQuery("User.findAll").getResultList();

            JSONSerializer serializer = new JSONSerializer();
            this.getRequest().setAttribute("json",
                    serializer.serialize(list));

            forward("/json.jsp");

        }

    }

}

package Controllers;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import toolbox.JSONResponse;
import toolbox.Sha;
import models.User;
import flexjson.JSONSerializer;
import MVC.Controller;

/**
 * @author Alexander
 *
 */
public class UserCtl extends Controller {

    @Override
    public void doRequest(String actionName, Integer id) throws Exception {

        EntityManager em = this.getServletContext().getEM();
        JSONSerializer serializer = new JSONSerializer();

        // if(actionName.equals("create")) {
        //
        // User u = new User();
        //
        // // u.setEmail(getRequest().getParameter("email"));
        //
        // em.getTransaction().begin();
        // em.persist(u);
        // em.getTransaction().commit();

        //
        if (actionName.equals("get")) {
            List<?> list = em.createNamedQuery("User.findAll").getResultList();

            this.getRequest().setAttribute("json",
                    serializer.serialize(list));

            forward("/json.jsp");

        }

        if(actionName.equals("login"))
        {
            JSONResponse response = null;
            try
            {
                Query qry = em.createNamedQuery("User.findByEmailAndPassword");
                qry.setParameter("email", this.getRequest().getParameter("email"));
                qry.setParameter("password", Sha.hash256(this.getRequest().getParameter("password")));
                this.getRequest().getSession().setAttribute("user", (User) qry.getSingleResult());
                response = new JSONResponse(true, null, null);
            }
            catch (NoResultException ex)
            {
                response = new JSONResponse("Invalid email address or password");
            }
            catch (Exception ex)
            {
                response = new JSONResponse(ex.getMessage());
            }

            this.getRequest().setAttribute("json", serializer.serialize(response));
            forward("/json.jsp");
        }

    }

}

Write login action for User controller

Write login action for User controller


package com.conveyal.taui.models;

import java.util.List;

/**
 * Created by matthewc on 3/28/16.
 */
public class Reroute extends Modification {
    public String name;

    public String feed;
    public String[] routes;
    public String[] trips;

    public String fromStop;
    public String toStop;

    public List<AddTripPattern.Segment> segments;

    /** speed of the adjusted segment, km/h, per segment */
    public int[] speed;

    /** dwell time at adjusted stops, seconds */
    public int dwell;

    @Override
    public String getType() {
        return "reroute";
    }
}

package com.conveyal.taui.models;

import java.util.List;

/**
 * Created by matthewc on 3/28/16.
 */
public class Reroute extends Modification {
    public String name;

    public String feed;
    public String[] routes;
    public String[] trips;

    public String fromStop;
    public String toStop;

    public List<AddTripPattern.Segment> segments;

    /** speed of the adjusted segment, km/h, per segment */
    public int[] segmentSpeeds;

    /** dwell time at adjusted stops, seconds */
    public int dwellTime;

    @Override
    public String getType() {
        return "reroute";
    }
}

Rename speed to segmentSpeeds & dwell to dwellTime


package eic.beike.projectx.util;

/**
 * Created by Simon on 2015-10-06.
 */
public enum Colour {
    GREEN,
    BLUE,
    RED;

    public static Colour colour(int val) {
    if (val == 0) {
        return GREEN;
    } else if(val == 1) {
        return BLUE;
    } else if (val == 2) {
        return RED;
    }
    return GREEN;
   }
}

package eic.beike.projectx.util;

import eic.beike.projectx.R;

/**
 * Created by Simon on 2015-10-06.
 */
public enum Colour {

    GREEN(R.color.green),
    BLUE(R.color.blue),
    RED(R.color.red);

    /**
     * Carried color code initiated at first use.
     */
    private  int androidColor;
    Colour(int androidColor){
        this.androidColor = androidColor;
    }

    /**
     * @return the value of the android color.
     */
    public int getAndroidColor(){ return  this.androidColor; }

    public static Colour colour(int val) {
    if (val == 0) {
        return GREEN;
    } else if(val == 1) {
        return BLUE;
    } else if (val == 2) {
        return RED;
    }
    return GREEN;
   }
}

Make colours carry color codes.

Make colours carry color codes.


package com.gettyimages.connectsdk;

import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Map;

public class Download {
    private String MustSpecifyAtLeastOneImageIdMessage = "Must specify at least one image id.";
    private String AutoDownloadString = "auto_download";
    private String DownloadsPathString = "/downloads/";
    private String FalseString = "false";

    private String baseUrl;
    private Credentials credentials;
    private String assetId;

    private Download(Credentials credentials, String baseUrl)
    {
        this.credentials = credentials;
        this.baseUrl = baseUrl;
    }

    public static Download GetInstance(Credentials credentials, String baseUrl)
    {
        return new Download(credentials, baseUrl);
    }

    public Download WithId(String val)
    {
        assetId = val;
        return this;
    }

    public String ExecuteAsync() throws SdkException {
        if (assetId == null || assetId.length() == 0)
        {
            throw new SdkException(MustSpecifyAtLeastOneImageIdMessage);
        }
        WebHelper helper = new WebHelper(credentials, baseUrl);

        Map<String,String> queryParameters = new Hashtable<String, String>();

         queryParameters.put(AutoDownloadString, FalseString);

        return (helper.PostQuery(queryParameters, DownloadsPathString +  assetId));
    }
}

Test commit : remove CR

Test commit : remove CR


import java.io.IOException;
import org.jruby.Ruby;
import org.jruby.debug.DebuggerDef;
import org.jruby.runtime.load.BasicLibraryService;

public final class RubyDebugBaseService implements BasicLibraryService {

    public boolean basicLoad(Ruby runtime) throws IOException {
        DebuggerDef.createDebuggerModule(runtime);
        return true;
    }

}

import java.io.IOException;
import org.jruby.Ruby;
import org.jruby.debug.RubyDebugger;
import org.jruby.runtime.load.BasicLibraryService;

public final class RubyDebugBaseService implements BasicLibraryService {

    public boolean basicLoad(Ruby runtime) throws IOException {
        RubyDebugger.createDebuggerModule(runtime);
        return true;
    }

}

Rename DebuggerDef to RubyDebugger for more consistency with core (missed in previous commit)

git-svn-id: 8850203dacb018657321cab25f9d8751b6efacda@315 81809f3d-796b-46d8-ad85-64d9ccf65f30


package seedu.emeraldo.model.task;

import seedu.emeraldo.commons.exceptions.IllegalValueException;

/**
 * Represents a Task's date and time in Emeraldo.
 * Guarantees: immutable; is valid as declared in {@link #isValidDateTime(String)}
 */
public class DateTime {

    public static final String MESSAGE_ADDRESS_CONSTRAINTS = "Task date and time can be in any format";
    public static final String ADDRESS_VALIDATION_REGEX = "(.+)?";

    public final String value;

    /**
     * Validates given date and time.
     *
     * @throws IllegalValueException if given address string is invalid.
     */
    public DateTime(String dateTime) throws IllegalValueException {
        assert dateTime != null;
        if (!isValidDateTime(dateTime)) {
            throw new IllegalValueException(MESSAGE_ADDRESS_CONSTRAINTS);
        }
        this.value = dateTime;
    }

    private static boolean isValidDateTime(String test) {
        return test.matches(ADDRESS_VALIDATION_REGEX);
    }

    @Override
    public String toString() {
        return value;
    }

    @Override
    public boolean equals(Object other) {
        return other == this // short circuit if same object
                || (other instanceof DateTime // instanceof handles nulls
                && this.value.equals(((DateTime) other).value)); // state check
    }

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

}

package seedu.emeraldo.model.task;

import seedu.emeraldo.commons.exceptions.IllegalValueException;

/**
 * Represents a Task's date and time in Emeraldo.
 * Guarantees: immutable; is valid as declared in {@link #isValidDateTime(String)}
 */
public class DateTime {

    public static final String MESSAGE_ADDRESS_CONSTRAINTS = "Task date and time must follow this format YY/MM/DD HH:MM";
    public static final String ADDRESS_VALIDATION_REGEX = "(.+)?";

    public final String value;

    /**
     * Validates given date and time.
     *
     * @throws IllegalValueException if given address string is invalid.
     */
    public DateTime(String dateTime) throws IllegalValueException {
        assert dateTime != null;
        if (!isValidDateTime(dateTime)) {
            throw new IllegalValueException(MESSAGE_ADDRESS_CONSTRAINTS);
        }
        this.value = dateTime;
    }

    private static boolean isValidDateTime(String test) {
        return test.matches(ADDRESS_VALIDATION_REGEX);
    }

    @Override
    public String toString() {
        return value;
    }

    @Override
    public boolean equals(Object other) {
        return other == this // short circuit if same object
                || (other instanceof DateTime // instanceof handles nulls
                && this.value.equals(((DateTime) other).value)); // state check
    }

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

}

Change the constraints for dateTime class


package mars.mips.instructions.syscalls;
import mars.util.*;
import mars.mips.hardware.*;
import mars.simulator.*;
import mars.*;

import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.Arrays;

public class SyscallSocketRead extends AbstractSyscall {
    public SyscallSocketRead() {
        super(102, "SocketRead");
    }

    public void simulate(ProgramStatement statement) throws ProcessingException {
        int fd =  RegisterFile.getValue(4);
        int buffAddr = RegisterFile.getValue(5);
        int maxLen = RegisterFile.getValue(6);

        byte[] buff = new byte[maxLen];

        try {
            int bytesRead = Sockets.getSocket(fd).getInputStream().read(buff);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.toString());
            throw new ProcessingException();
        }

        for (int i = 0; i < maxLen; i++) {
            // TODO: Make sure this actually writes as expected. May be limited to byte-aligned writing, which
            // will require some fancy bit-string flicking
            try {
                Globals.memory.setByte(buffAddr++, buff[i]);
            } catch (Exception e) {
                System.out.println("Choked on address: " + buffAddr);
                e.printStackTrace();
                throw new ProcessingException();
            }
        }
    }
}

package mars.mips.instructions.syscalls;
import mars.util.*;
import mars.mips.hardware.*;
import mars.simulator.*;
import mars.*;

import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.Arrays;

public class SyscallSocketRead extends AbstractSyscall {
    public SyscallSocketRead() {
        super(102, "SocketRead");
    }

    public void simulate(ProgramStatement statement) throws ProcessingException {
        int fd =  RegisterFile.getValue(4);
        int buffAddr = RegisterFile.getValue(5);
        int maxLen = RegisterFile.getValue(6);

        byte[] buff = new byte[maxLen];

        try {
            int bytesRead = Sockets.getSocket(fd).getInputStream().read(buff);
            RegisterFile.updateRegister(3, bytesRead);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.toString());
            throw new ProcessingException();
        }

        for (int i = 0; i < maxLen; i++) {
            // TODO: Make sure this actually writes as expected. May be limited to byte-aligned writing, which
            // will require some fancy bit-string flicking
            try {
                Globals.memory.setByte(buffAddr++, buff[i]);
            } catch (Exception e) {
                System.out.println("Choked on address: " + buffAddr);
                e.printStackTrace();
                throw new ProcessingException();
            }
        }
    }
}

Make sock_read return the number of bytes read (value in )


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

package org.gluu.model;

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

import org.gluu.persist.annotation.AttributeEnum;

/**
 * Specify type of script location
 *
 * @author Yuriy Movchan Date: 10/07/2015
 */
public enum ScriptLocationType implements AttributeEnum {

    LDAP("ldap", "Ldap"), FILE("file", "File");

    private String value;
    private String displayName;

    private static Map<String, ScriptLocationType> MAP_BY_VALUES = new HashMap<String, ScriptLocationType>();

    static {
        for (ScriptLocationType enumType : values()) {
            MAP_BY_VALUES.put(enumType.getValue(), enumType);
        }
    }

    ScriptLocationType(String value, String displayName) {
        this.value = value;
        this.displayName = displayName;
    }

    public String getValue() {
        return value;
    }

    public String getDisplayName() {
        return displayName;
    }

    public static ScriptLocationType getByValue(String value) {
        return MAP_BY_VALUES.get(value);
    }

    public Enum<? extends AttributeEnum> resolveByValue(String value) {
        return getByValue(value);
    }

    @Override
    public String toString() {
        return value;
    }

}

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

package org.gluu.model;

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

import org.gluu.persist.annotation.AttributeEnum;

/**
 * Specify type of script location
 *
 * @author Yuriy Movchan Date: 10/07/2015
 */
public enum ScriptLocationType implements AttributeEnum {

    DB("db", "Database"), FILE("file", "File");

    private String value;
    private String displayName;

    private static Map<String, ScriptLocationType> MAP_BY_VALUES = new HashMap<String, ScriptLocationType>();

    static {
        for (ScriptLocationType enumType : values()) {
            MAP_BY_VALUES.put(enumType.getValue(), enumType);
        }
    }

    ScriptLocationType(String value, String displayName) {
        this.value = value;
        this.displayName = displayName;
    }

    public String getValue() {
        return value;
    }

    public String getDisplayName() {
        return displayName;
    }

    public static ScriptLocationType getByValue(String value) {
        return MAP_BY_VALUES.get(value);
    }

    public Enum<? extends AttributeEnum> resolveByValue(String value) {
        return getByValue(value);
    }

    @Override
    public String toString() {
        return value;
    }

}

Replace LDAP enum with DB

Replace LDAP enum with DB


package gov.nih.nci.calab.dto.workflow;

public class AssayBean {

	private String assayId;
	private String assayName;
	private String assayType;

	public AssayBean(String assayId, String assayName, String assayType) {
		super();
		// TODO Auto-generated constructor stub
		this.assayId = assayId;
		this.assayName = assayName;
		this.assayType = assayType;
	}
	public String getAssayId() {
		return assayId;
	}
	public void setAssayId(String assayId) {
		this.assayId = assayId;
	}
	public String getAssayName() {
		return assayName;
	}
	public void setAssayName(String assayName) {
		this.assayName = assayName;
	}
	public String getAssayType() {
		return assayType;
	}
	public void setAssayType(String assayType) {
		this.assayType = assayType;
	}

}

package gov.nih.nci.calab.dto.workflow;

public class AssayBean {

	private String assayId;
	private String assayName;
	private String assayType;
	private String assayStr;

	public AssayBean(String assayId, String assayName, String assayType) {
		super();
		// TODO Auto-generated constructor stub
		this.assayId = assayId;
		this.assayName = assayName;
		this.assayType = assayType;
	}
	public String getAssayId() {
		return assayId;
	}
	public void setAssayId(String assayId) {
		this.assayId = assayId;
	}
	public String getAssayName() {
		return assayName;
	}
	public void setAssayName(String assayName) {
		this.assayName = assayName;
	}
	public String getAssayType() {
		return assayType;
	}
	public void setAssayType(String assayType) {
		this.assayType = assayType;
	}
	public String getAssayStr() {
		return this.assayType + " : " + this.assayName;
	}
//	public void setAssayStr(String assayStr) {
//		this.assayStr = assayStr;
//	}

}

Add an additional property assayStr

Add an additional property assayStr

SVN-Revision: 609


/**
 * Date Modified: $Date: 2010-01-18 10:22:16 +1100 (Mon, 18 Jan 2010) $
 * Version: $Revision: 288 $
 *
 * Copyright 2008 The Australian National University (ANU)
 *
 * 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.ands.rifcs.ch;

import org.w3c.dom.Document;
/**
 * Interface which any RIF-CS Content Handler must implement.
 *
 * @author Scott Yeadon
 */
public interface RIFCSHandler {
    /**
     * Get a DOM document resulting from a SAX parse.
     *
     *  @return
     *      The DOM document. May be null if called before parsing and empty
     *      if parsing exception caught.
     */
    public Document getDocument();
}

/**
 * Date Modified: $Date: 2010-01-18 10:22:16 +1100 (Mon, 18 Jan 2010) $
 * Version: $Revision: 288 $
 *
 * Copyright 2008 The Australian National University (ANU)
 *
 * 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.ands.rifcs.ch;

import org.w3c.dom.Document;
/**
 * Interface which any RIF-CS Content Handler must implement.
 *
 * @author Scott Yeadon
 */
public interface RIFCSHandler {
    /**
     * Get a DOM document resulting from a SAX parse.
     *
     *  @return
     *      The DOM document. May be null if called before parsing and empty
     *      if parsing exception caught.
     */
    Document getDocument();
}

Remove redundant public from interface constructor


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

package org.apache.jmeter.visualizers.backend;

import java.io.Serializable;

/**
 * Identifies Backend components
 * @since 3.2
 */
public interface Backend extends Serializable {
    // NOOP
}

Add License header + svn:eol

Add License header + svn:eol

git-svn-id: 5ccfe34f605a6c2f9041ff2965ab60012c62539a@1781739 13f79535-47bb-0310-9956-ffa450edef68


/**
 * Created with IntelliJ IDEA.
 * User: andrey
 * Date: 2014-03-18
 * Time: 8:53 PM
 * To change this template use File | Settings | File Templates.
 */
public class Main {

        public static void main(String[] args) {

            System.out.println("This is trinangle");

        }

}

Test triangle commit from console

Test triangle commit from console


package com.lyubenblagoev.postfixrest.entity;

import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name="domains")
public class Domain extends BaseEntity {

	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

package com.lyubenblagoev.postfixrest.entity;

import javax.persistence.*;
import java.util.Collections;
import java.util.List;

@Entity
@Table(name="domains")
public class Domain extends BaseEntity {

	@Column(nullable = false)
	private String name;

	@OneToMany(orphanRemoval = true, cascade = CascadeType.ALL, mappedBy = "domain")
	private List<Account> accounts = Collections.emptyList();

	@OneToMany(orphanRemoval = true, cascade = CascadeType.ALL, mappedBy = "domain")
	private List<Alias> aliases = Collections.emptyList();

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public List<Account> getAccounts() {
		return accounts;
	}

	public void setAccounts(List<Account> accounts) {
		this.accounts = accounts;
	}

	public List<Alias> getAliases() {
		return aliases;
	}

	public void setAliases(List<Alias> aliases) {
		this.aliases = aliases;
	}
}

Make domain - alias/account mapping bidirectional cascade remove operations


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

import org.junit.Test;

/**
 * Really not a lot to do here, but checking that no
 * Exceptions are thrown.
 *
 */
public class NullWriterTest {

    @Test
    public void testNull() {
        final char[] chars = new char[] { 'A', 'B', 'C' };
        try (final NullWriter writer = new NullWriter()) {
            writer.write(1);
            writer.write(chars);
            writer.write(chars, 1, 1);
            writer.write("some string");
            writer.write("some string", 2, 2);
            writer.flush();
        }
    }

}

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

import org.junit.Test;

/**
 * Really not a lot to do here, but checking that no
 * Exceptions are thrown.
 *
 */
public class NullWriterTest {

    @Test
    public void testNull() {
        final char[] chars = new char[] { 'A', 'B', 'C' };
        try (final NullWriter writer = NullWriter.NULL_WRITER) {
            writer.write(1);
            writer.write(chars);
            writer.write(chars, 1, 1);
            writer.write("some string");
            writer.write("some string", 2, 2);
            writer.flush();
        }
    }

}

Use constant instead of new instance.

Use constant instead of new instance.


package com.amee.restlet;

import org.restlet.Filter;
import org.restlet.data.Request;
import org.restlet.data.Response;

/**
 * Filter to manage {@link RequestContext}s. Will create the {@link RequestContext} for the transaction log.
 */
public class AMEERequestFilter extends Filter {

    protected int doHandle(Request request, Response response) {
        RequestContext requestContext = new RequestContext();
        try {
            // Create the RequestContext.
            requestContext.setRequest(request);
            request.getAttributes().put("requestContext", requestContext);
            // Delegate request handling to the super class.
            return super.doHandle(request, response);
        } catch (Throwable t) {
            // Record the exception in the RequestContext.
            requestContext.setError(t.getMessage());
            requestContext.error();
            // Wrap and re-throw the exception.
            throw new RuntimeException(t);
        } finally {
            // Update and record the RequestContext at the end of the request.
            requestContext.setStatus(response.getStatus());
            requestContext.record();
        }
    }
}

package com.amee.restlet;

import org.restlet.Filter;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.slf4j.MDC;

/**
 * Filter to manage {@link RequestContext}s. Will create the {@link RequestContext} for the transaction log.
 */
public class AMEERequestFilter extends Filter {

    protected int doHandle(Request request, Response response) {
        RequestContext requestContext = new RequestContext();
        try {

            // Create the RequestContext.
            requestContext.setRequest(request);
            request.getAttributes().put("requestContext", requestContext);

            // Add the client IP address for logging.
            MDC.put("ipAddress", request.getClientInfo().getAddress());

            // Delegate request handling to the super class.
            return super.doHandle(request, response);
        } catch (Throwable t) {

            // Record the exception in the RequestContext.
            requestContext.setError(t.getMessage());
            requestContext.error();

            // Wrap and re-throw the exception.
            throw new RuntimeException(t);
        } finally {

            // Update and record the RequestContext at the end of the request.
            requestContext.setStatus(response.getStatus());
            requestContext.record();
            MDC.remove("ipAddress");

            // User UID is added in CollectCredentialsGuard.
            MDC.remove("userUid");
        }
    }
}

Add client IP address to MDC for logging. PL-11395.


package in.twizmwaz.cardinal.util;

import org.bukkit.ChatColor;
import org.bukkit.entity.Player;

public class ChatUtils {

    public static void sendWarningMessage(Player player, String msg) {
        if (msg != null) player.sendMessage(ChatColor.YELLOW + " \u26A0 " + ChatColor.RED + msg);
    }

    public static String getWarningMessage(String msg) {
        if (msg == null) return null;
        else return ChatColor.YELLOW + " \u26A0 " + ChatColor.RED + msg;
    }

}

package in.twizmwaz.cardinal.util;

import org.bukkit.ChatColor;
import org.bukkit.entity.Player;

public class ChatUtils {

    public static void sendWarningMessage(Player player, String msg) {
        if (msg != null) player.sendMessage(ChatColor.YELLOW + " \u26A0 " + ChatColor.RED + msg);
    }

    public static String getWarningMessage(String msg) {
        if (msg == null) return null;
        else return ChatColor.YELLOW + " \u26A0 " + ChatColor.RED + ChatColor.translateAlternateColorCodes('`', msg);
    }

}

Allow warning message to accept text formatting codes


package org.realityforge.arez;

import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class DisposableTest
{
  static class TestDisposable
    implements Disposable
  {
    private boolean _disposed;

    @Override
    public void dispose()
    {
      _disposed = true;
    }

    @Override
    public boolean isDisposed()
    {
      return _disposed;
    }
  }

  @Test
  public void randomObject()
    throws Exception
  {
    //No exception but no action
    final Object object = new Object();
    assertEquals( Disposable.isDisposed( object ), false );
    Disposable.dispose( object );
    assertEquals( Disposable.isDisposed( object ), false );
  }

  @Test
  public void disposable()
    throws Exception
  {
    final TestDisposable object = new TestDisposable();
    assertEquals( object.isDisposed(), false );
    assertEquals( Disposable.isDisposed( object ), false );
    Disposable.dispose( object );
    assertEquals( object.isDisposed(), true );
    assertEquals( Disposable.isDisposed( object ), true );
  }

  @Test
  public void asDisposable()
    throws Exception
  {
    final TestDisposable object = new TestDisposable();
    assertEquals( Disposable.asDisposable( object ), object );

    final Object element = new Object();
    final IllegalStateException exception =
      expectThrows( IllegalStateException.class, () -> Disposable.asDisposable( element ) );
    assertEquals( exception.getMessage(),
                  "Object passed to asDisposable does not implement Disposable. Object: " + element );
  }
}

package org.realityforge.arez;

import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class DisposableTest
  extends AbstractArezTest
{
  static class TestDisposable
    implements Disposable
  {
    private boolean _disposed;

    @Override
    public void dispose()
    {
      _disposed = true;
    }

    @Override
    public boolean isDisposed()
    {
      return _disposed;
    }
  }

  @Test
  public void randomObject()
    throws Exception
  {
    //No exception but no action
    final Object object = new Object();
    assertEquals( Disposable.isDisposed( object ), false );
    Disposable.dispose( object );
    assertEquals( Disposable.isDisposed( object ), false );
  }

  @Test
  public void disposable()
    throws Exception
  {
    final TestDisposable object = new TestDisposable();
    assertEquals( object.isDisposed(), false );
    assertEquals( Disposable.isDisposed( object ), false );
    Disposable.dispose( object );
    assertEquals( object.isDisposed(), true );
    assertEquals( Disposable.isDisposed( object ), true );
  }

  @Test
  public void asDisposable()
    throws Exception
  {
    final TestDisposable object = new TestDisposable();
    assertEquals( Disposable.asDisposable( object ), object );

    final Object element = new Object();
    final IllegalStateException exception =
      expectThrows( IllegalStateException.class, () -> Disposable.asDisposable( element ) );
    assertEquals( exception.getMessage(),
                  "Object passed to asDisposable does not implement Disposable. Object: " + element );
  }
}

Extend AbstractArezTest otherwise invariant checking state is not controlled and thus some tests may fail


package moe.tristan.easyfxml.util;

import org.junit.Test;
import org.testfx.framework.junit.ApplicationTest;

import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

public class NodesTest extends ApplicationTest {

    private static final double MARGIN = 5d;
    private static final int WIDTH_PANE = 200;
    private static final int HEIGHT_PANE = 200;

    private Button testButton;

    @Override
    public void start(final Stage stage) {
        this.testButton = new Button();
        final AnchorPane testPane = new AnchorPane(this.testButton);
        stage.setScene(new Scene(testPane, WIDTH_PANE, HEIGHT_PANE));
        stage.show();
    }

    @Test
    public void centerNode() {
        Nodes.centerNode(this.testButton, MARGIN);
    }
}

package moe.tristan.easyfxml.util;

import org.junit.Test;
import org.testfx.framework.junit.ApplicationTest;

import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

import static org.testfx.assertions.api.Assertions.assertThat;

public class NodesTest extends ApplicationTest {

    private static final double MARGIN = 5d;

    private Pane container;
    private Button testButton;

    @Override
    public void start(final Stage stage) {
        this.testButton = new Button();
        container = new AnchorPane(this.testButton);
        stage.setScene(new Scene(container));
        stage.show();
    }

    @Test
    public void centerNode() {
        Nodes.centerNode(this.testButton, MARGIN);
    }

    @Test
    public void testAutosizeHelpers() {
        final BooleanProperty shouldDisplay = new SimpleBooleanProperty(true);
        final Button testButton = new Button();
        Nodes.hideAndResizeParentIf(testButton, shouldDisplay);

        assertThat(testButton.isManaged()).isTrue();
        assertThat(testButton.isVisible()).isTrue();

        shouldDisplay.setValue(false);
        assertThat(testButton.isManaged()).isFalse();
        assertThat(testButton.isVisible()).isFalse();
    }
}

Add tests for new node utility methods

Add tests for new node utility methods


package com.ceco.gm2.gravitybox;

import android.content.res.XModuleResources;
import android.content.res.XResources;
import de.robv.android.xposed.XSharedPreferences;
import de.robv.android.xposed.XposedBridge;

public class SystemWideResources {

    public static void initResources(final XSharedPreferences prefs) {
        try {
            XModuleResources modRes = XModuleResources.createInstance(GravityBox.MODULE_PATH, null);

            XResources.setSystemWideReplacement("android", "bool", "config_animateScreenLights", true);

            boolean holoBgDither = prefs.getBoolean(GravityBoxSettings.PREF_KEY_HOLO_BG_DITHER, false);
            if (prefs.getBoolean(GravityBoxSettings.PREF_KEY_HOLO_BG_SOLID_BLACK, false)) {
                XResources.setSystemWideReplacement(
                    "android", "drawable", "background_holo_dark", modRes.fwd(R.drawable.background_holo_dark_solid));
            } else if (holoBgDither) {
                XResources.setSystemWideReplacement(
                        "android", "drawable", "background_holo_dark", modRes.fwd(R.drawable.background_holo_dark));
            }
            if (holoBgDither) {
                XResources.setSystemWideReplacement(
                        "android", "drawable", "background_holo_light", modRes.fwd(R.drawable.background_holo_light));
            }
        } catch (Throwable t) {
            XposedBridge.log(t);
        }
    }

}

package com.ceco.gm2.gravitybox;

import android.content.res.XModuleResources;
import android.content.res.XResources;
import android.os.Build;
import de.robv.android.xposed.XSharedPreferences;
import de.robv.android.xposed.XposedBridge;

public class SystemWideResources {

    public static void initResources(final XSharedPreferences prefs) {
        try {
            XModuleResources modRes = XModuleResources.createInstance(GravityBox.MODULE_PATH, null);

            if (Build.VERSION.SDK_INT > 16) {
                XResources.setSystemWideReplacement("android", "bool", "config_animateScreenLights", true);
            }

            boolean holoBgDither = prefs.getBoolean(GravityBoxSettings.PREF_KEY_HOLO_BG_DITHER, false);
            if (prefs.getBoolean(GravityBoxSettings.PREF_KEY_HOLO_BG_SOLID_BLACK, false)) {
                XResources.setSystemWideReplacement(
                    "android", "drawable", "background_holo_dark", modRes.fwd(R.drawable.background_holo_dark_solid));
            } else if (holoBgDither) {
                XResources.setSystemWideReplacement(
                        "android", "drawable", "background_holo_dark", modRes.fwd(R.drawable.background_holo_dark));
            }
            if (holoBgDither) {
                XResources.setSystemWideReplacement(
                        "android", "drawable", "background_holo_light", modRes.fwd(R.drawable.background_holo_light));
            }
        } catch (Throwable t) {
            XposedBridge.log(t);
        }
    }

}

Enable animateScreenLights only for devices running 4.2+ animateScreenLights is needed for CRT effect which is not currently available for 4.1 devices, anyway... This fixes some weird display on/off issues on these devices.


package no.geonorge.nedlasting.data;

import org.apache.cayenne.Cayenne;
import org.apache.cayenne.ObjectContext;

import no.geonorge.nedlasting.data.auto._Projection;

public class Projection extends _Projection {

    public no.geonorge.nedlasting.data.client.Projection forClient() {
        no.geonorge.nedlasting.data.client.Projection p = new no.geonorge.nedlasting.data.client.Projection();
        p.setCode(getSrid().toString());
        p.setCodespace(getCodespace());
        p.setName(getName());
        return p;
    }

    public String getAuthorityAndCode() {
        return "EPSG:" + getSrid();
    }

    public String getScheme() {
        return "http://www.opengis.net/def/crs/";
    }

    public static Projection getForSrid(ObjectContext ctxt, int srid) {
        return Cayenne.objectForPK(ctxt, Projection.class, srid);
    }

}

package no.geonorge.nedlasting.data;

import org.apache.cayenne.Cayenne;
import org.apache.cayenne.ObjectContext;

import no.geonorge.nedlasting.data.auto._Projection;

public class Projection extends _Projection {

    public no.geonorge.nedlasting.data.client.Projection forClient() {
        no.geonorge.nedlasting.data.client.Projection p = new no.geonorge.nedlasting.data.client.Projection();
        p.setCode(getSrid().toString());
        p.setCodespace(getCodespace());
        p.setName(getName());
        return p;
    }

    public String getAuthorityAndCode() {
        return "EPSG:" + getSrid();
    }

    public String getScheme() {
        return "https://register.geonorge.no/api/epsg-koder.xml";
    }

    public static Projection getForSrid(ObjectContext ctxt, int srid) {
        return Cayenne.objectForPK(ctxt, Projection.class, srid);
    }

}

Update taxonomyUrl to machine readable XML endpoint


/**
 * Copyright 2015 Palantir Technologies
 *
 * Licensed under the BSD-3 License (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://opensource.org/licenses/BSD-3-Clause
 *
 * 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.palantir.atlasdb.table.api;

import java.util.concurrent.ExecutorService;

import com.google.common.collect.Multimap;

/*
 * All dynamic atlasdb tables should implement this interface.
 */
public interface AtlasDbDynamicImmutableTable<ROW, COLUMN, COLUMN_VALUE, ROW_RESULT> extends
            AtlasDbImmutableTable<ROW, COLUMN_VALUE, ROW_RESULT> {
    Multimap<ROW,COLUMN_VALUE> get(Multimap<ROW,COLUMN> cells);
    Multimap<ROW,COLUMN_VALUE> getAsync(Multimap<ROW,COLUMN> cells, ExecutorService exec);
}

/**
 * Copyright 2015 Palantir Technologies
 *
 * Licensed under the BSD-3 License (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://opensource.org/licenses/BSD-3-Clause
 *
 * 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.palantir.atlasdb.table.api;

import java.util.concurrent.ExecutorService;

import com.google.common.collect.Multimap;

/*
 * All dynamic atlasdb tables should implement this interface.
 */
public interface AtlasDbDynamicImmutableTable<ROW, COLUMN, COLUMN_VALUE, ROW_RESULT> extends
            AtlasDbImmutableTable<ROW, COLUMN_VALUE, ROW_RESULT> {
    Multimap<ROW,COLUMN_VALUE> get(Multimap<ROW,COLUMN> cells);
}

Remove additional unused method declaration