package edu.berkeley.nlp;

import edu.berkeley.nlp.assignments.POSTaggerTester;

/**
 * @author Dan Klein
 */
public class Test<E> {
  public static void main(String[] args) {
      POSTaggerTester.main(new String[]{
              "-path",
              ".\\data\\wsj\\"
              //,"-verbose"
      });
      System.out.println("Test PASSED.");
  }
}

package edu.berkeley.nlp;

import edu.berkeley.nlp.assignments.POSTaggerTester;

/**
 * @author Dan Klein
 */
public class Test<E> {
  public static void main(String[] args) {
      POSTaggerTester.main(new String[]{
              "-path",
              ".\\data\\wsj\\",
              "-test", "test"
              //,"-verbose"
      });
      System.out.println("Test PASSED.");
  }
}

Add possibility to run against test

Add possibility to run against test


package org.lamport.tla.toolbox.tool;

/**
 * A superclass for Spec Lifecycle Participant implementations used for
 * registration on the org.lamport.tla.toolbox.spec extension point.

 * This class should be overridden by the extensions.

 * The overrides must provide an 0-argument constructor.
 *
 * @see {@link SpecEvent}
 * @author Simon Zambrovski
 * @version $Id$
 */
public abstract class SpecLifecycleParticipant
{
    /**
     * Marks the point in time from which on, the participant starts to receive events
     */
    public void initialize()
    {
    }

    /**
     * Is called on every spec event
     * @param event the event containing the information about what is happening
     * @return a boolean value indicating the reaction of the participant to the event.
     * Reserved for future use.
     */
    public abstract boolean eventOccured(SpecEvent event);

    /**
     * Marks the point in time from which on, the participant stops to receive events
     */
    public void terminate()
    {
    }
}

package org.lamport.tla.toolbox.tool;

/**
 * A superclass for Spec Lifecycle Participant implementations used for
 * registration on the org.lamport.tla.toolbox.spec extension point.

 * This class should be overridden by the extensions.

 * The overrides must provide an 0-argument constructor.
 *
 * @see {@link SpecEvent}
 * @author Simon Zambrovski
 * @version $Id$
 */
public abstract class SpecLifecycleParticipant
{
    /**
     * Marks the point in time from which on, the participant starts to receive events
     */
    public void initialize()
    {
    }

    /**
	 * Is called on every spec event. The event can either come from a backend
	 * thread or the UI thread. There is no guarantee whatsoever.
	 *
	 * @param event
	 *            the event containing the information about what is happening
	 * @return a boolean value indicating the reaction of the participant to the
	 *         event. Reserved for future use.
	 */
    public abstract boolean eventOccured(SpecEvent event);

    /**
     * Marks the point in time from which on, the participant stops to receive events
     */
    public void terminate()
    {
    }
}

Javadoc: Clarify that participants (listener) will be called from any
thread. There is no guarantee that the invocation originates from within
the UI thread.


package info.u_team.u_team_core.util.registry;

import java.util.function.Supplier;

import com.mojang.datafixers.DataFixUtils;

import net.minecraft.tileentity.*;
import net.minecraft.tileentity.TileEntityType.Builder;
import net.minecraft.util.SharedConstants;
import net.minecraft.util.datafix.*;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.ForgeRegistries;

public class TileEntityTypeDeferredRegister {

	public static TileEntityTypeDeferredRegister create(String modid) {
		return new TileEntityTypeDeferredRegister(modid);
	}

	private final CommonDeferredRegister<TileEntityType<?>> register;

	protected TileEntityTypeDeferredRegister(String modid) {
		register = CommonDeferredRegister.create(ForgeRegistries.TILE_ENTITIES, modid);
	}

	public <T extends TileEntity> RegistryObject<TileEntityType<T>> register(String name, Supplier<Builder<T>> supplier) {
		return register.register(name, () -> supplier.get().build(DataFixesManager.getDataFixer().getSchema(DataFixUtils.makeKey(SharedConstants.getVersion().getWorldVersion())).getChoiceType(TypeReferences.ENTITY_TYPE, register.getModid() + ":" + name)));
	}

	public void register(IEventBus bus) {
		register.register(bus);
	}

	public CommonDeferredRegister<TileEntityType<?>> getRegister() {
		return register;
	}

}

package info.u_team.u_team_core.util.registry;

import java.util.function.Supplier;

import com.mojang.datafixers.DataFixUtils;

import net.minecraft.tileentity.*;
import net.minecraft.tileentity.TileEntityType.Builder;
import net.minecraft.util.SharedConstants;
import net.minecraft.util.datafix.*;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.ForgeRegistries;

public class TileEntityTypeDeferredRegister {

	public static TileEntityTypeDeferredRegister create(String modid) {
		return new TileEntityTypeDeferredRegister(modid);
	}

	private final CommonDeferredRegister<TileEntityType<?>> register;

	protected TileEntityTypeDeferredRegister(String modid) {
		register = CommonDeferredRegister.create(ForgeRegistries.TILE_ENTITIES, modid);
	}

	public <T extends TileEntity> RegistryObject<TileEntityType<T>> register(String name, Supplier<Builder<T>> supplier) {
		return register.register(name, () -> supplier.get().build(DataFixesManager.getDataFixer().getSchema(DataFixUtils.makeKey(SharedConstants.getVersion().getWorldVersion())).getChoiceType(TypeReferences.BLOCK_ENTITY, register.getModid() + ":" + name)));
	}

	public void register(IEventBus bus) {
		register.register(bus);
	}

	public CommonDeferredRegister<TileEntityType<?>> getRegister() {
		return register;
	}

}

Fix the type in the data fixer upper to block entity


/*
 * Created on Apr 27, 2004
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
package groovy.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.PageContext;

/**
 * @author sam
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
public class ServletCategory {

    /**
     * Servlet support
     */
    public static Object get(ServletContext context, String key) {
        return context.getAttribute(key);
    }

    public static Object get(HttpSession session, String key) {
        return session.getAttribute(key);
    }

    public static Object get(ServletRequest request, String key) {
        return request.getAttribute(key);
    }

    public static Object get(PageContext context, String key) {
        return context.getAttribute(key);
    }

}

/*
 * Created on Apr 27, 2004
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
package groovy.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.PageContext;

/**
 * @author sam
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
public class ServletCategory {

    /**
     * Servlet support
     */
    public static Object get(ServletContext context, String key) {
        return context.getAttribute(key);
    }

    public static Object get(HttpSession session, String key) {
        return session.getAttribute(key);
    }

    public static Object get(ServletRequest request, String key) {
        return request.getAttribute(key);
    }

    public static Object get(PageContext context, String key) {
        return context.getAttribute(key);
    }

    public static void set(ServletContext context, String key, Object value) {
        context.setAttribute(key, value);
    }

    public static void set(HttpSession session, String key, Object value) {
        session.setAttribute(key, value);
    }

    public static void set(ServletRequest request, String key, Object value) {
        request.setAttribute(key, value);
    }

    public static void set(PageContext context, String key, Object value) {
        context.setAttribute(key, value);
    }

}

Add the setters to the servlet getters in the category.

git-svn-id: aa43ce4553b005588bb3cc6c16966320b011facb@1184 a5544e8c-8a19-0410-ba12-f9af4593a198


package com.oasisfeng.android.databinding.adapters;

import android.databinding.BindingAdapter;
import android.view.View;

/**
 * Complementary binding adapter for {@link View}
 *
 * Created by Oasis on 2016/4/25.
 */
@SuppressWarnings("unused")
public class ViewBindingAdapter {

	@BindingAdapter("visible")
	public static void setVisibility(final View view, final boolean visible) {
		view.setVisibility(visible ? View.VISIBLE : View.GONE);
	}
}

package com.oasisfeng.android.databinding.adapters;

import android.databinding.BindingAdapter;
import android.view.View;

/**
 * Complementary binding adapter for {@link View}
 *
 * Created by Oasis on 2016/4/25.
 */
@SuppressWarnings("unused")
public class ViewBindingAdapter {

	@BindingAdapter("visible")
	public static void setVisible(final View view, final boolean visible) {
		view.setVisibility(visible ? View.VISIBLE : View.INVISIBLE);
	}

	@BindingAdapter("shown")
	public static void setShown(final View view, final boolean shown) {
		view.setVisibility(shown ? View.VISIBLE : View.GONE);
	}
}

UPDATE: Split the old "visible" binding attribute into two separate attributes: "visible" and "shown".


package me.walkersneps.sneps.utils;

/**
 * Created by Walkersneps on 23/04/16
 * in package me.walkersneps.sneps.utils
 * for SnepsUtils
 */

/**
 * @author Walkersneps
 */
class PrimitiveConverter {

    /**
     * Converts a string to an int type variable
     *
     * @param str the input string
     *
     * @return first integer found in the input string
     */
    static int stringToInt (String str){
        return Integer.parseInt(str);
    }

    /**
     * Converts a string to a char type variable
     *
     * @param str the input string
     *
     * @return first character in the input string
     */
    static char stringToChar (String str) {
        return str.charAt(0);
    }

    /**
     * Converts a char to a string type variable
     *
     * @param c the input character
     *
     * @return string containing the passed character
     */
    static String charToString (char c) {
        return Character.toString(c);
    }

    /**
     * Converts an integer in a string type variable
     *
     * @param i the input integer
     *
     * @return string containing the passed integer
     */
    static String intToString (int i) {
        return Integer.toString(i);
    }

} //end of class

package me.walkersneps.sneps.utils;

/**
 * Created by Walkersneps on 23/04/16
 * in package me.walkersneps.sneps.utils
 * for SnepsUtils
 */

/**
 * @author Walkersneps
 */
public class PrimitiveConverter {

    /**
     * Converts a string to an int type variable
     *
     * @param str the input string
     *
     * @return first integer found in the input string
     */
    public static int stringToInt (String str){
        return Integer.parseInt(str);
    }

    /**
     * Converts a string to a char type variable
     *
     * @param str the input string
     *
     * @return first character in the input string
     */
    public static char stringToChar (String str) {
        return str.charAt(0);
    }

    /**
     * Converts a char to a string type variable
     *
     * @param c the input character
     *
     * @return string containing the passed character
     */
    public static String charToString (char c) {
        return Character.toString(c);
    }

    /**
     * Converts an integer in a string type variable
     *
     * @param i the input integer
     *
     * @return string containing the passed integer
     */
    public static String intToString (int i) {
        return Integer.toString(i);
    }

} //end of class

Make methods and class public

Make methods and class public


package com.nikolak.weatherapp.ForecastIO;

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

public class Forecast {
    public Currently currently = new Currently();
    public Minutely minutely = new Minutely();
    public Hourly hourly = new Hourly();
    public Daily daily = new Daily();

    private ForecastAPI forecastAPI = new ForecastAPI();

    public Boolean updateForecast(String lat, String lon) throws JSONException {
        JSONObject response = forecastAPI.getDefault(lat, lon);
        if (response==null) {
            return false;
        }

        JSONObject currentlyJObject = response.getJSONObject("currently");
        this.currently.ConstructFromJson(currentlyJObject);

        try{
            JSONObject minutelyJObject = response.getJSONObject("minutely");
            if (minutelyJObject!=null){
                minutely.constructFromJson(minutelyJObject);
            } else{
                minutely = null;
            }
        } catch (JSONException e){
            Log.d("Json", "Minutely not available");
        }

        JSONObject hourlyJObject = response.getJSONObject("hourly");
        this.hourly.constructFromJson(hourlyJObject);
        return true;
    }

}

package com.nikolak.weatherapp.ForecastIO;

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

public class Forecast {
    public Currently currently = new Currently();
    public Minutely minutely = new Minutely();
    public Hourly hourly = new Hourly();
    public Daily daily = new Daily();

    private ForecastAPI forecastAPI = new ForecastAPI();

    public Boolean updateForecast(String lat, String lon) throws JSONException {
        JSONObject response = forecastAPI.getDefault(lat, lon);
        if (response == null) {
            return false;
        }

        JSONObject currentlyJObject = response.getJSONObject("currently");
        this.currently.ConstructFromJson(currentlyJObject);

        try {
            JSONObject minutelyJObject = response.getJSONObject("minutely");
            if (minutelyJObject != null) {
                minutely.constructFromJson(minutelyJObject);
            } else {
                minutely = null;
            }
        } catch (JSONException e) {
            Log.d("Json", "Minutely not available");
        }

        JSONObject hourlyJObject = response.getJSONObject("hourly");
        this.hourly.constructFromJson(hourlyJObject);

        JSONObject dailyObject = response.getJSONObject("daily");
        this.daily.constructFromJson(dailyObject);

        return true;
    }

}

Add Daily forecast class initalization and parsing


package annotations.util;

/*>>>
import org.checkerframework.checker.nullness.qual.*;
*/

/**
 * {@link Strings} provides useful static methods related to strings.
 */
public abstract class Strings {
    private Strings() {}

    /**
     * Returns the given string, escaped and quoted according to Java
     * conventions.  Currently, only newlines, backslashes, tabs, and
     * single and double quotes are escaped.  Perhaps nonprinting
     * characters should also be escaped somehow.
     */
    public static String escape(String in) {
        StringBuilder out = new StringBuilder("\"");
        for (int pos = 0; pos < in.length(); pos++) {
            switch (in.charAt(pos)) {
            case '\n':
                out.append("\\n");
                break;
            case '\t':
                out.append("\\t");
                break;
            case '\\':
                out.append("\\\\");
                break;
            case '\'':
                out.append("\\\'");
                break;
            case '\"':
                out.append("\\\"");
                break;
            default:
                out.append(in.charAt(pos));
            }
            out.append('\"');
            return out.toString();
        }
    }
}

package annotations.util;

/*>>>
import org.checkerframework.checker.nullness.qual.*;
*/

/**
 * {@link Strings} provides useful static methods related to strings.
 */
public abstract class Strings {
    private Strings() {}

    /**
     * Returns the given string, escaped and quoted according to Java
     * conventions.  Currently, only newlines, backslashes, tabs, and
     * single and double quotes are escaped.  Perhaps nonprinting
     * characters should also be escaped somehow.
     */
    public static String escape(String in) {
        StringBuilder out = new StringBuilder("\"");
        for (int pos = 0; pos < in.length(); pos++) {
            switch (in.charAt(pos)) {
            case '\n':
                out.append("\\n");
                break;
            case '\t':
                out.append("\\t");
                break;
            case '\\':
                out.append("\\\\");
                break;
            case '\'':
                out.append("\\\'");
                break;
            case '\"':
                out.append("\\\"");
                break;
            default:
                out.append(in.charAt(pos));
            }
        }
        out.append('\"');
        return out.toString();
    }
}

Fix position of curly brace

Fix position of curly brace


package com.mads256c.betterchat;

import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;

public class ClientProxy
        extends CommonProxy
{
    public void preInit(FMLPreInitializationEvent e)
    {
        super.preInit(e);
    }

    public void init(FMLInitializationEvent e)
    {
        super.init(e);
    }

    public void postInit(FMLPostInitializationEvent e)
    {
        super.postInit(e);
        BetterChat.bLog.info("BetterChat has loaded client-side.");
    }
}

package com.mads256c.betterchat;

import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import java.io.PrintStream;

public class ClientProxy
        extends CommonProxy
{
    public void preInit(FMLPreInitializationEvent e)
    {
        super.preInit(e);
    }

    public void init(FMLInitializationEvent e)
    {
        super.init(e);
    }

    public void postInit(FMLPostInitializationEvent e)
    {
        super.postInit(e);
        BetterChat.bLog.info("BetterChat has loaded client-side.");
    }
}

Revert "Todo: clean code 2/?"

Revert "Todo: clean code 2/?"

This reverts commit 376a39e93949b71708bf6284d4468d0a8156c332.


package spark.staticfiles;

import static spark.utils.StringUtils.removeLeadingAndTrailingSlashesFrom;

/**
 * Created by Per Wendel on 2016-11-05.
 */
public class StaticFilesFolder {

    private static volatile String local;
    private static volatile String external;

    public static final void localConfiguredTo(String folder) {

        local = removeLeadingAndTrailingSlashesFrom(folder);
    }

    public static final void externalConfiguredTo(String folder) {

        external = removeLeadingAndTrailingSlashesFrom(folder);
    }

    public static final String local() {
        return local;
    }

    public static final String external() {
        return external;
    }

}

package spark.staticfiles;

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

/**
 * Created by Per Wendel on 2016-11-05.
 */
public class StaticFilesFolder {

    private static volatile String local;
    private static volatile String external;

    public static final void localConfiguredTo(String folder) {

        local = removeLeadingAndTrailingSlashesFrom(folder);
    }

    public static final void externalConfiguredTo(String folder) {

        external = removeLeadingAndTrailingSlashesFrom(
            Paths.get(folder).toAbsolutePath().toString().replace("\\", "/")
        );
    }

    public static final String local() {
        return local;
    }

    public static final String external() {
        return external;
    }

}

Make external static folder be *nix like

When Windows paths are received, like `C:\Users\USERNAME\AppData\Local\Temp\external\`, they will be changed to `C:/Users/USERNAME/AppData/Local/Temp/external`.


/**
 * Package of test cases.
 *

 *     Spring test must extends {@link com.saintdan.framework.BaseTest}
 *

 *
 * @author Liao Yifan
 * @date 10/30/15
 * @since JDK1.8
 */
package com.saintdan.framework;

Change code style to google code style.

Change code style to google code style.


package org.realityforge.tarrabah;

import javax.inject.Inject;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;

public class SyslogUDPServer
  extends AbstractUDPServer
{
  @Inject
  private SyslogHandler _syslogHandler;

  protected ChannelPipelineFactory newPipelineFactory()
  {
    return new ChannelPipelineFactory()
    {
      public ChannelPipeline getPipeline()
        throws Exception
      {
        _syslogHandler = new SyslogHandler();
        return Channels.pipeline( _syslogHandler );
      }
    };
  }
}

package org.realityforge.tarrabah;

import javax.inject.Inject;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;

public class SyslogUDPServer
  extends AbstractUDPServer
{
  @Inject
  private SyslogHandler _syslogHandler;

  protected ChannelPipelineFactory newPipelineFactory()
  {
    return new ChannelPipelineFactory()
    {
      public ChannelPipeline getPipeline()
        throws Exception
      {
        return Channels.pipeline( _syslogHandler );
      }
    };
  }
}

Remove explicit instantiation as bean is CDI managed


package com.github.britter.beanvalidators.file;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.ValidationException;
import java.io.File;
import java.lang.annotation.Annotation;

import org.apache.commons.lang3.StringUtils;

abstract class AbstractFileConstraintValidator<A extends Annotation> implements ConstraintValidator<A, Object> {

    private Class<? extends Annotation> constraintAnnotation;

    @Override
    public void initialize(A constraintAnnotation) {
        this.constraintAnnotation = constraintAnnotation.annotationType();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }
        if (value instanceof File) {
            return isValid((File) value, context);
        } else if (value instanceof String) {
            String str = (String) value;
            return StringUtils.isBlank(str) || isValid(new File(str), context);
        } else {
            throw new ValidationException("@" + constraintAnnotation.getSimpleName()
                    + " can not be applied to instances of " + value.getClass());
        }
    }

    public abstract boolean isValid(File value, ConstraintValidatorContext context);
}

package com.github.britter.beanvalidators.file;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.ValidationException;
import java.io.File;
import java.lang.annotation.Annotation;

import org.apache.commons.lang3.StringUtils;

abstract class AbstractFileConstraintValidator<A extends Annotation> implements ConstraintValidator<A, Object> {

    private Class<? extends Annotation> annotationType;

    @Override
    public void initialize(A constraintAnnotation) {
        this.annotationType = constraintAnnotation.annotationType();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }
        if (value instanceof File) {
            return isValid((File) value, context);
        } else if (value instanceof String) {
            String str = (String) value;
            return StringUtils.isBlank(str) || isValid(new File(str), context);
        } else {
            throw new ValidationException("@" + annotationType.getSimpleName()
                    + " can not be applied to instances of " + value.getClass());
        }
    }

    public abstract boolean isValid(File value, ConstraintValidatorContext context);
}

Fix checkstyle issue: parameter constraintAnnotation hides field


/*
 * ServerManagerTest.java
 * JUnit 4.x based test
 *
 */

package com.dmdirc.parser;

import com.dmdirc.parser.callbacks.CallbackNotFoundException;
import com.dmdirc.parser.callbacks.interfaces.IAwayState;
import junit.framework.TestCase;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author Chris
 */
public class IRCParserTest extends TestCase {

    public IRCParserTest() {
    }

    @Test
    public void testIssue042() {
        boolean res = false;

        try {
            final IRCParser myParser = new IRCParser();
            myParser.getCallbackManager().addCallback("non-existant",new IAwayState() {
                public void onAwayState(IRCParser tParser, boolean currentState, String reason) {
                    throw new UnsupportedOperationException("Not supported yet.");
                }
            });
        } catch (CallbackNotFoundException ex) {
            res = true;
        }

        assertTrue("addCallback() should throw exception for non-existant callbacks", res);
    }

}

/*
 * ServerManagerTest.java
 * JUnit 4.x based test
 *
 */

package com.dmdirc.parser;

import com.dmdirc.parser.callbacks.CallbackNotFoundException;
import com.dmdirc.parser.callbacks.interfaces.IAwayState;
import junit.framework.TestCase;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author Chris
 */
public class IRCParserTest extends TestCase {

    public IRCParserTest() {
    }

    @Test
    public void testIssue042() {
        boolean res = false;

        try {
            final IRCParser myParser = new IRCParser();
            myParser.getCallbackManager().addCallback("non-existant",new IAwayState() {
                public void onAwayState(IRCParser tParser, boolean currentState, String reason) {
                    throw new UnsupportedOperationException("Not supported yet.");
                }
            });
        } catch (CallbackNotFoundException ex) {
            res = true;
        }

        assertTrue("addCallback() should throw exception for non-existant callbacks", res);
    }

    @Test
    public void testTokeniser() {
        final IRCParser myParser = new IRCParser();

        final String line1 = "a b c d e";
        final String line2 = "a b c :d e";
        final String line3 = ":a b:c :d e";

        final String[] res1 = myParser.tokeniseLine(line1);
        final String[] res2 = myParser.tokeniseLine(line2);
        final String[] res3 = myParser.tokeniseLine(line3);

        arrayEquals(res1, new String[]{"a", "b", "c", "d", "e"});
        arrayEquals(res2, new String[]{"a", "b", "c", "d e"});
        arrayEquals(res3, new String[]{":a", "b:c", "d e"});
    }

    private void arrayEquals(final String[] a1, final String[] a2) {
        assertEquals(a1.length, a2.length);

        for (int i = 0; i < a1.length; i++) {
            assertEquals(a1[i], a2[i]);
        }
    }

}

Add unit test for the parser's tokeniser

git-svn-id: 50f83ef66c13f323b544ac924010c921a9f4a0f7@2144 00569f92-eb28-0410-84fd-f71c24880f43


package com.thaiopensource.relaxng;

import org.relaxng.datatype.ValidationContext;

import org.xml.sax.SAXException;

class AttributeAtom extends Atom {
  String namespaceURI;
  String localName;
  StringAtom value;

  AttributeAtom(String namespaceURI, String localName, String value, ValidationContext vc) {
    this.namespaceURI = namespaceURI;
    this.localName = localName;
    this.value = value == null ? null : new StringAtom(value, vc);
  }
  boolean matchesAttribute(PatternBuilder b, NameClass nc, Pattern valuePattern) {
    return (nc.contains(namespaceURI, localName)
	    && (value == null
		|| valuePattern.residual(b, value).isNullable()));
  }
  boolean isAttribute() {
    return true;
  }
}

package com.thaiopensource.relaxng;

import org.relaxng.datatype.ValidationContext;

import org.xml.sax.SAXException;

class AttributeAtom extends Atom {
  String namespaceURI;
  String localName;
  StringAtom value;

  AttributeAtom(String namespaceURI, String localName, String value, ValidationContext vc) {
    this.namespaceURI = namespaceURI;
    this.localName = localName;
    this.value = value == null ? null : new StringAtom(value, vc);
  }
  boolean matchesAttribute(PatternBuilder b, NameClass nc, Pattern valuePattern) {
    if (!nc.contains(namespaceURI, localName))
      return false;
    if (value == null)
      return true;
    if (value.isEmpty() && valuePattern.isNullable())
      return true;
    return valuePattern.residual(b, value).isNullable();
  }
  boolean isAttribute() {
    return true;
  }
}

Allow an empty attribute value to match <empty/>.


package com.enjin.averian_roleplay.core;

import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

public class SetNameCommand implements CommandExecutor {

	private AverianCore plugin;

	public SetNameCommand(AverianCore plugin) {
		this.plugin = plugin;
	}

	@Override
	public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
		if (sender instanceof Player) {
			if (args.length >= 1) {
				Player player = (Player) sender;
				plugin.getCharacterCard(player).setName(args[0]);
				player.setDisplayName(args[0]);
				player.setCustomName(args[0]);
				player.setCustomNameVisible(true);
				sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("messages.setname.success")));
			} else {
				sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("messages.setname.more-arguments-needed")));
			}
		} else {
			sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("messages.setname.not-a-player")));
		}
		return true;
	}

}

package com.enjin.averian_roleplay.core;

import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

public class SetNameCommand implements CommandExecutor {

	private AverianCore plugin;

	public SetNameCommand(AverianCore plugin) {
		this.plugin = plugin;
	}

	@Override
	public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
		if (sender instanceof Player) {
			if (args.length >= 1) {
				StringBuilder nameBuilder = new StringBuilder();
				for (int i = 0; i < args.length; i++) {
					nameBuilder.append(args[i]);
					nameBuilder.append(" ");
				}
				String name = nameBuilder.toString();
				Player player = (Player) sender;
				plugin.getCharacterCard(player).setName(name);
				player.setDisplayName(name);
				sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("messages.setname.success")));
			} else {
				sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("messages.setname.more-arguments-needed")));
			}
		} else {
			sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("messages.setname.not-a-player")));
		}
		return true;
	}

}

Allow names with more than one word

Allow names with more than one word


package com.aemreunal.helper.json;

/*
 * *********************** *
 * Copyright (c) 2015      *
 *                         *
 * This code belongs to:   *
 *                         *
 * @author Ahmet Emre Ünal *
 * S001974                 *
 *                         *
 * aemreunal@gmail.com     *
 * emre.unal@ozu.edu.tr    *
 *                         *
 * aemreunal.com           *
 * *********************** *
 */

import net.minidev.json.JSONArray;

import java.util.ArrayList;

public class JsonArrayBuilder {
    private ArrayList<Object> jsonList = new ArrayList<>();

    JsonArrayBuilder() {
    }

    public JsonArrayBuilder add(Object value) {
        jsonList.add(value);
        return this;
    }

    public JSONArray build() {
        JSONArray array = new JSONArray();
        array.addAll(jsonList);
        return array;
    }
}

package com.aemreunal.helper.json;

/*
 * *********************** *
 * Copyright (c) 2015      *
 *                         *
 * This code belongs to:   *
 *                         *
 * @author Ahmet Emre Ünal *
 * S001974                 *
 *                         *
 * aemreunal@gmail.com     *
 * emre.unal@ozu.edu.tr    *
 *                         *
 * aemreunal.com           *
 * *********************** *
 */

import net.minidev.json.JSONArray;

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

public class JsonArrayBuilder {
    private ArrayList<Object> jsonList = new ArrayList<>();

    JsonArrayBuilder() {
    }

    public JsonArrayBuilder add(Object item) {
        jsonList.add(item);
        return this;
    }

    public JsonArrayBuilder addAll(Collection items) {
        jsonList.addAll(items);
        return this;
    }

    public JSONArray build() {
        JSONArray array = new JSONArray();
        array.addAll(jsonList);
        return array;
    }
}

Add collections to JSON arrays

Add collections to JSON arrays


package uk.gov.register.presentation;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonPropertyOrder({"proof-identifier", "root-hash"})
public class RegisterProof {

    private static final String proofIdentifier = "merkle:sha-256";
    private final String rootHash;

    public RegisterProof(String rootHash) {
        this.rootHash = rootHash;
    }

    @SuppressWarnings("unused, used from template")
    @JsonProperty("proof-identifier")
    public String getProofIdentifier() {
        return proofIdentifier;
    }

    @SuppressWarnings("unused, used from template")
    @JsonProperty("root-hash")
    public String getRootHash() {
        return rootHash;
    }
}

package uk.gov.register.presentation;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonPropertyOrder({"proof-identifier", "root-hash"})
public class RegisterProof {

    private static final String proofIdentifier = "merkle:sha-256";
    private final String rootHash;

    public RegisterProof(String rootHash) {
        this.rootHash = rootHash;
    }

    @SuppressWarnings("unused, used as jsonproperty")
    @JsonProperty("proof-identifier")
    public String getProofIdentifier() {
        return proofIdentifier;
    }

    @SuppressWarnings("unused, used as jsonproperty")
    @JsonProperty("root-hash")
    public String getRootHash() {
        return rootHash;
    }
}

Use more accurate comment to suppress warning


package com.bugsnag;

import org.json.JSONObject;
import org.json.JSONException;

import com.bugsnag.utils.JSONUtils;

public class Diagnostics {
    protected Configuration config;
    protected JSONObject deviceData = new JSONObject();
    protected JSONObject appData = new JSONObject();

    public Diagnostics(Configuration config) {
        this.config = config;

        JSONUtils.safePutOpt(deviceData, "osName", System.getProperty("os.name"));
    }

    public JSONObject getAppData() {
        JSONUtils.safePutOpt(appData, "version", config.appVersion.get());
        JSONUtils.safePutOpt(appData, "releaseStage", config.releaseStage.get());
        return appData;
    }

    public JSONObject getAppState() {
        return new JSONObject();
    }

    public JSONObject getDeviceData() {
        JSONUtils.safePutOpt(deviceData, "osVersion", config.osVersion.get());
        return deviceData;
    }

    public JSONObject getDeviceState() {
        return new JSONObject();
    }

    public String getContext() {
        return config.context.get();
    }

    public JSONObject getUser() {
        return config.user;
    }

    public JSONObject getMetrics() {
        JSONObject metrics = new JSONObject();

        JSONUtils.safePutOpt(metrics, "user", getUser());
        JSONUtils.safePutOpt(metrics, "app", getAppData());
        JSONUtils.safePutOpt(metrics, "device", getDeviceData());

        return metrics;
    }
}

package com.bugsnag;

import java.net.InetAddress;

import org.json.JSONObject;
import org.json.JSONException;

import com.bugsnag.utils.JSONUtils;

public class Diagnostics {
    protected Configuration config;
    protected JSONObject deviceData = new JSONObject();
    protected JSONObject appData = new JSONObject();

    public Diagnostics(Configuration config) {
        this.config = config;

        JSONUtils.safePutOpt(deviceData, "osName", System.getProperty("os.name"));
        JSONUtils.safePutOpt(deviceData, "name", InetAddress.getLocalHost().getHostName());
    }

    public JSONObject getAppData() {
        JSONUtils.safePutOpt(appData, "version", config.appVersion.get());
        JSONUtils.safePutOpt(appData, "releaseStage", config.releaseStage.get());
        return appData;
    }

    public JSONObject getAppState() {
        return new JSONObject();
    }

    public JSONObject getDeviceData() {
        JSONUtils.safePutOpt(deviceData, "osVersion", config.osVersion.get());
        return deviceData;
    }

    public JSONObject getDeviceState() {
        return new JSONObject();
    }

    public String getContext() {
        return config.context.get();
    }

    public JSONObject getUser() {
        return config.user;
    }

    public JSONObject getMetrics() {
        JSONObject metrics = new JSONObject();

        JSONUtils.safePutOpt(metrics, "user", getUser());
        JSONUtils.safePutOpt(metrics, "app", getAppData());
        JSONUtils.safePutOpt(metrics, "device", getDeviceData());

        return metrics;
    }
}

Send hostname from java client

Send hostname from java client


package org.ohdsi.webapi;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;

/**
 * Launch as java application or deploy as WAR (@link {@link WebApplication} will source this file).
 */
@SpringBootApplication(exclude=HibernateJpaAutoConfiguration.class)
public class WebApi extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
        return application.sources(WebApi.class);
    }

    public static void main(final String[] args) throws Exception {
        new SpringApplicationBuilder(WebApi.class).run(args);
    }
}

package org.ohdsi.webapi;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.autoconfigure.velocity.VelocityAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;

/**
 * Launch as java application or deploy as WAR (@link {@link WebApplication} will source this file).
 */
@SpringBootApplication(exclude={HibernateJpaAutoConfiguration.class,VelocityAutoConfiguration.class})
public class WebApi extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
        return application.sources(WebApi.class);
    }

    public static void main(final String[] args) throws Exception {
        new SpringApplicationBuilder(WebApi.class).run(args);
    }
}

Exclude velocity auto config. Problematic in multi webapp deployments. Further review necessary to determine why the class linkage problem exists. Since WebAPI is headless, seemed appropriate to exclude.


package com.sailthru.client;

/**
 * API calls
 * @author Prajwal Tuladhar <praj@sailthru.com>
 */
public enum ApiAction {
    event,
    settings,
    email,
    send,
    blast,
    blast_repeat,
    preview,
    template,
    list,
    content,
    alert,
    stats,
    purchase,
    horizon,
    job,
    trigger,
    inbox,
    user,
    return
}

package com.sailthru.client;

/**
 * API calls
 * @author Prajwal Tuladhar <praj@sailthru.com>
 */
public enum ApiAction {
    event,
    settings,
    email,
    send,
    blast,
    blast_repeat,
    preview,
    template,
    list,
    content,
    alert,
    stats,
    purchase,
    horizon,
    job,
    trigger,
    inbox,
    user,
    RETURN // the case is inconsistent, but "return" is a reserved keyword
}

Fix return reserved keyword error

Fix return reserved keyword error


package sc.iview.ui;

import graphics.scenery.Node;

import javax.swing.*;

public class ContextPopUp extends JPopupMenu {

    JMenuItem anItem;
    public ContextPopUp(Node n) {
        anItem = new JMenuItem("I'm a " + n.getNodeType());
        add(anItem);
    }

}

package sc.iview.ui;

import graphics.scenery.Node;

import javax.swing.*;

public class ContextPopUp extends JPopupMenu {

    public ContextPopUp(Node n) {
        add( new JMenuItem("Name: " + n.getName()) );
        add( new JMenuItem("Type: " + n.getNodeType()) );
    }

}

Make context menu look a little more reasonable


package com.jakewharton.trakt.entities;

import com.jakewharton.trakt.TraktEntity;

public class Share implements TraktEntity {

    boolean facebook;
    boolean twitter;
    boolean tumblr;
    boolean path;

}

package com.jakewharton.trakt.entities;

import com.jakewharton.trakt.TraktEntity;

public class Share implements TraktEntity {

    public boolean facebook;
    public boolean twitter;
    public boolean tumblr;
    public boolean path;

}

Make all share fields public.

Make all share fields public.


package leetcode;

import java.util.Arrays;

/**
 * https://leetcode.com/problems/set-matrix-zeroes/
 */
public class Problem73 {
    public void setZeroes(int[][] matrix) {

    }

    public static void main(String[] args) {
        Problem73 prob = new Problem73();
        int[][] matrix = new int[][] {
            new int[]{1, 0, 1, 1},
            new int[]{0, 1, 1, 1},
            new int[]{0, 1, 1, 1}
        };
        prob.setZeroes(matrix);
        for (int i = 0; i < matrix.length; i++) {
            System.out.println(Arrays.toString(matrix[i]));
        }
    }
}

package leetcode;

import java.util.Arrays;

/**
 * https://leetcode.com/problems/set-matrix-zeroes/
 */
public class Problem73 {
    public void setZeroes(int[][] matrix) {
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                if (matrix[i][j] == 0) {
                    setRowZeroes(matrix, i);
                    setColZeroes(matrix, j);
                }
            }
        }
    }

    private void setRowZeroes(int[][] matrix, int row) {
        for (int i = 0; i < matrix[row].length; i++) {
            matrix[row][i] = 0;
        }
    }

    private void setColZeroes(int[][] matrix, int col) {
        for (int i = 0; i < matrix.length; i++) {
            matrix[i][col] = 0;
        }
    }

    public static void main(String[] args) {
        Problem73 prob = new Problem73();
        int[][] matrix = new int[][] {
            new int[]{1, 0, 1, 1},
            new int[]{0, 1, 1, 1},
            new int[]{1, 1, 1, 1}
        };
        prob.setZeroes(matrix);
        for (int i = 0; i < matrix.length; i++) {
            System.out.println(Arrays.toString(matrix[i]));
        }
    }
}

Update problem 73 (not finished yet)

Update problem 73 (not finished yet)


package editor.util;

import java.util.function.Supplier;

/**
 * This class represents an action that can be undone, which is done by simply
 * using two actions that are semantically supposed to be opposites.  Each
 * action can optionally return a value.
 *
 * @param <R> information to be returned by the action
 * @param <U> information to be returned by the undone action
 * @author Alec Roelke
 */
public interface UndoableAction<R, U>
{
    /**
     * Create a new undoable action from the given functions.
     *
     * @param <R> return type of the forward action
     * @param <U> return type of the reverse action
     * @param forward forward action to perform
     * @param reverse reverse action to perform
     * @return The new UndoableAction.
     */
    public static <R, U> UndoableAction<R, U> createAction(Supplier<R> forward, Supplier<U> reverse)
    {
        return new UndoableAction<>()
        {
            public R redo() { return forward.get(); }
            public U undo() { return reverse.get(); }
        };
    }

    /**
     * Perform the action (or redo it if it has been undone).
     *
     * @return a value containing information about the result of performing
     * the action.
     */
    R redo();

    /**
     * Undo the action.
     *
     * @return a value containing information about the result undoing the action.
     */
    U undo();
}

package editor.util;

import java.util.function.Supplier;

/**
 * This class represents an action that can be undone, which is done by simply
 * using two actions that are semantically supposed to be opposites.  Each
 * action can optionally return a value.
 *
 * @param <R> information to be returned by the action
 * @param <U> information to be returned by the undone action
 * @author Alec Roelke
 */
public interface UndoableAction<R, U>
{
    /**
     * Create a new undoable action from the given functions.
     *
     * @param <R> return type of the forward action
     * @param <U> return type of the reverse action
     * @param forward forward action to perform
     * @param reverse reverse action to perform
     * @return The new UndoableAction.
     */
    public static <R, U> UndoableAction<R, U> createAction(Supplier<R> forward, Supplier<U> reverse)
    {
        return new UndoableAction<>()
        {
            @Override
            public R redo() { return forward.get(); }
            @Override
            public U undo() { return reverse.get(); }
        };
    }

    /**
     * Perform the action (or redo it if it has been undone).
     *
     * @return a value containing information about the result of performing
     * the action.
     */
    R redo();

    /**
     * Undo the action.
     *
     * @return a value containing information about the result undoing the action.
     */
    U undo();
}

Add @Override where it's needed

Add @Override where it's needed


package org.rmatil.sync.core;

import java.util.Comparator;

/**
 * Compares two strings by their length.
 */
public class StringLengthComparator implements Comparator<String> {

    /**
     * Compares the strings by their length.
     *

     *

     * {@inheritDoc}
     */
    @Override
    public int compare(String o1, String o2) {
        if (o1.length() < o2.length()) {
            return - 1;
        }

        if (o1.length() > o2.length()) {
            return 1;
        }

        return 0;
    }
}

package org.rmatil.sync.core;

import java.util.Comparator;

/**
 * Compares two strings by their length.
 */
public class StringLengthComparator implements Comparator<String> {

    /**
     * Compares the strings by their length.
     *

     *

     * {@inheritDoc}
     */
    @Override
    public int compare(String o1, String o2) {
        if (o1.length() < o2.length()) {
            return - 1;
        }

        if (o1.length() > o2.length()) {
            return 1;
        }

        return o1.compareTo(o2);
    }
}

Fix string length comparer when attempting to get the same length (A comparator for a tree map can not have the return value 0, since the key is not inserted then)


package com.palantir.atlasdb.keyvalue.partition;

public class PartitionedKeyValueConstants {
    private PartitionedKeyValueConstants() {
    }

    public static final String NO_RACK = "";
}

/**
 * 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.keyvalue.partition;

public class PartitionedKeyValueConstants {
    private PartitionedKeyValueConstants() {
    }

    // Endpoints with this value for rack will be treated
    // as if each were in its own separate rack.
    public static final String NO_RACK = "";
}

Comment and licence header for PartitionedKVConstants.


package com.codeaffine.eclipse.swt.widget.scrollable;

import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;

import com.codeaffine.eclipse.swt.widget.scrollable.context.AdaptionContext;
import com.codeaffine.eclipse.swt.widget.scrollbar.FlatScrollBar;

class HorizontalSelectionListener extends SelectionAdapter {

  private final AdaptionContext<?> context;

  HorizontalSelectionListener( AdaptionContext<?> context ) {
    this.context = context;
  }

  @Override
  public void widgetSelected( SelectionEvent event ) {
    updateLocation( new Point( -getSelection( event ), computeHeight() ) );
  }

  private int computeHeight() {
    if( context.isScrollableReplacedByAdapter() ) {
      return -context.getBorderWidth();
    }
    return context.getScrollable().getLocation().y - context.getBorderWidth();
  }

  private int getSelection( SelectionEvent event ) {
    return ( ( FlatScrollBar )event.widget ).getSelection() + context.getBorderWidth();
  }

  private void updateLocation( final Point result ) {
    context.getReconciliation().runWhileSuspended( new Runnable() {
      @Override
      public void run() {
        context.getScrollable().setLocation( result );
      }
    } );
  }
}

package com.codeaffine.eclipse.swt.widget.scrollable;

import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;

import com.codeaffine.eclipse.swt.widget.scrollable.context.AdaptionContext;
import com.codeaffine.eclipse.swt.widget.scrollbar.FlatScrollBar;

class HorizontalSelectionListener extends SelectionAdapter {

  private final AdaptionContext<?> context;

  HorizontalSelectionListener( AdaptionContext<?> context ) {
    this.context = context;
  }

  @Override
  public void widgetSelected( SelectionEvent event ) {
    updateLocation( new Point( -getSelection( event ), computeHeight() ) );
  }

  private int computeHeight() {
    if( context.isScrollableReplacedByAdapter() ) {
      return -context.getBorderWidth();
    }
    return context.getScrollable().getLocation().y - context.getBorderWidth();
  }

  private int getSelection( SelectionEvent event ) {
    return ( ( FlatScrollBar )event.widget ).getSelection() + context.getBorderWidth();
  }

  private void updateLocation( final Point result ) {
    context.getReconciliation().runWhileSuspended( () -> context.getScrollable().setLocation( result ) );
  }
}

Replace anonymous Runnable with lambda expression


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

package sample.actuator;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@EnableConfigurationProperties(ServiceProperties.class)
public class SampleActuatorApplication {

	public static void main(String[] args) throws Exception {
		SpringApplication.run(SampleActuatorApplication.class, args).close();
	}

	@Bean
	public HealthIndicator helloHealthIndicator() {
		return new HealthIndicator() {
			@Override
			public Health health() {
				return Health.up().withDetail("hello", "world").build();
			}
		};
	}

}

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

package sample.actuator;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@EnableConfigurationProperties(ServiceProperties.class)
public class SampleActuatorApplication {

	public static void main(String[] args) throws Exception {
		SpringApplication.run(SampleActuatorApplication.class, args);
	}

	@Bean
	public HealthIndicator helloHealthIndicator() {
		return new HealthIndicator() {
			@Override
			public Health health() {
				return Health.up().withDetail("hello", "world").build();
			}
		};
	}

}

Revert accidental call to `.close()`

Revert accidental call to `.close()`

Remove call to `.close()` which was accidentally left in after some
performance testing.


package org.ovirt.engine.core.bll.storage;

import org.ovirt.engine.core.bll.context.CommandContext;

import java.util.Date;

import org.ovirt.engine.core.bll.InternalCommandAttribute;
import org.ovirt.engine.core.bll.NonTransactiveCommandAttribute;
import org.ovirt.engine.core.common.action.StorageDomainPoolParametersBase;

@InternalCommandAttribute
@NonTransactiveCommandAttribute
public class ConnectDomainToStorageCommand<T extends StorageDomainPoolParametersBase> extends StorageDomainCommandBase<T> {

    public ConnectDomainToStorageCommand(T parameters, CommandContext cmdContext) {
        super(parameters, cmdContext);
    }

    @Override
    protected void executeCommand() {
        log.infoFormat("ConnectDomainToStorage. Before Connect all hosts to pool. Time:{0}", new Date());
        connectAllHostsToPool();
        log.infoFormat("ConnectDomainToStorage. After Connect all hosts to pool. Time:{0}", new Date());
    }
}

package org.ovirt.engine.core.bll.storage;

import org.ovirt.engine.core.bll.context.CommandContext;

import java.util.Date;

import org.ovirt.engine.core.bll.InternalCommandAttribute;
import org.ovirt.engine.core.bll.NonTransactiveCommandAttribute;
import org.ovirt.engine.core.common.action.StorageDomainPoolParametersBase;

@InternalCommandAttribute
@NonTransactiveCommandAttribute
public class ConnectDomainToStorageCommand<T extends StorageDomainPoolParametersBase> extends StorageDomainCommandBase<T> {

    public ConnectDomainToStorageCommand(T parameters) {
        super(parameters, null);
    }

    public ConnectDomainToStorageCommand(T parameters, CommandContext cmdContext) {
        super(parameters, cmdContext);
    }

    @Override
    protected void executeCommand() {
        log.infoFormat("ConnectDomainToStorage. Before Connect all hosts to pool. Time:{0}", new Date());
        connectAllHostsToPool();
        log.infoFormat("ConnectDomainToStorage. After Connect all hosts to pool. Time:{0}", new Date());
    }
}

core: Modify constructor to be compatible with caller method

ConnectDomainToStorageCommand is being called without context
although its constructor is only supported with context parameter,
so we will always get runtime exception when the command is being
called.

The proposed fix is to add a constructor which also supports to get only
paramteres

Change-Id: Ic120c4b33b40a122895c2088b8365f26c05eb517
Signed-off-by: Maor Lipchuk <37a323a8cadba73c2b6c8d3f850c79092d0199e6@redhat.com>


package com.gemstone.gemfire.test.golden;

import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.gemstone.gemfire.test.process.ProcessWrapper;
import com.gemstone.gemfire.test.junit.categories.IntegrationTest;

@Category(IntegrationTest.class)
public class FailWithTimeoutOfWaitForOutputToMatchJUnitTest extends FailOutputTestCase {

  private static final long timeoutMillis = 1000;

  private ProcessWrapper process;

  public void subTearDown() throws Exception {
    this.process.waitFor();
    assertFalse(this.process.isAlive());
  }

  @Override
  String problem() {
    return "This is an extra line";
  }

  @Override
  void outputProblemInProcess(final String message) {
    System.out.println(message);
  }

  /**
   * Process output has an extra line and should fail
   */
  @Test
  public void testFailWithTimeoutOfWaitForOutputToMatch() throws Exception {
    this.process = createProcessWrapper(new ProcessWrapper.Builder().timeoutMillis(timeoutMillis), getClass());
    this.process.execute(createProperties());
    this.process.waitForOutputToMatch("Begin " + name() + "\\.main");

    try {
      this.process.waitForOutputToMatch(problem());
      fail("assertOutputMatchesGoldenFile should have failed due to " + problem());
    } catch (AssertionError expected) {
      assertTrue(expected.getMessage().contains(problem()));
    }
  }

  public static void main(String[] args) throws Exception {
    new FailWithTimeoutOfWaitForOutputToMatchJUnitTest().executeInProcess();
  }
}

package com.gemstone.gemfire.test.golden;

import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.gemstone.gemfire.test.process.ProcessWrapper;
import com.gemstone.gemfire.test.junit.categories.IntegrationTest;

@Category(IntegrationTest.class)
public class FailWithTimeoutOfWaitForOutputToMatchJUnitTest extends FailOutputTestCase {

  private static final long timeoutMillis = 1000;

  private ProcessWrapper process;

  public void subTearDown() throws Exception {
    this.process.destroy();
  }

  @Override
  String problem() {
    return "This is an extra line";
  }

  @Override
  void outputProblemInProcess(final String message) {
    System.out.println(message);
  }

  /**
   * Process output has an extra line and should fail
   */
  @Test
  public void testFailWithTimeoutOfWaitForOutputToMatch() throws Exception {
    this.process = createProcessWrapper(new ProcessWrapper.Builder().timeoutMillis(timeoutMillis), getClass());
    this.process.execute(createProperties());
    this.process.waitForOutputToMatch("Begin " + name() + "\\.main");

    try {
      this.process.waitForOutputToMatch(problem());
      fail("assertOutputMatchesGoldenFile should have failed due to " + problem());
    } catch (AssertionError expected) {
      assertTrue(expected.getMessage().contains(problem()));
    }
  }

  public static void main(String[] args) throws Exception {
    new FailWithTimeoutOfWaitForOutputToMatchJUnitTest().executeInProcess();
  }
}

Change subTearDown to destroy process

GEODE-209: Change subTearDown to destroy process


package com.microsoft.azure.services.blob.implementation;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/*
 * TODO: Move to some other common package?
 *
 * "not quite" ISO 8601 date time conversion routines
 */
public class ContainerACLDateConverter {
    // Note: because of the trailing "0000000", this is not quite ISO 8601 compatible
    private static final String DATETIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'.0000000Z'";

    public String format(Date date) {
        return getFormat().format(date);
    }

    public Date parse(String date) throws ParseException {
        return getFormat().parse(date);
    }

    public Date parseNoThrow(String date) {
        try {
            return parse(date);
        }
        catch (ParseException e) {
            //TODO: Is it better to return null or throw a runtime exception?
            return null;
        }
    }

    private DateFormat getFormat() {
        DateFormat iso8601Format = new SimpleDateFormat(DATETIME_PATTERN, Locale.US);
        iso8601Format.setTimeZone(TimeZone.getTimeZone("GMT"));
        return iso8601Format;
    }
}

package com.microsoft.azure.services.blob.implementation;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/*
 * TODO: Move to some other common package?
 *
 * "not quite" ISO 8601 date time conversion routines
 */
public class ContainerACLDateConverter {
    // Note: because of the trailing "0000000", this is not quite ISO 8601 compatible
    private static final String DATETIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'";

    public String format(Date date) {
        return getFormat().format(date);
    }

    public Date parse(String date) throws ParseException {
        return getFormat().parse(date);
    }

    public Date parseNoThrow(String date) {
        try {
            return parse(date);
        }
        catch (ParseException e) {
            //TODO: Is it better to return null or throw a runtime exception?
            return null;
        }
    }

    private DateFormat getFormat() {
        DateFormat iso8601Format = new SimpleDateFormat(DATETIME_PATTERN, Locale.US);
        iso8601Format.setTimeZone(TimeZone.getTimeZone("GMT"));
        return iso8601Format;
    }
}

Fix ISO 8601 date format to confrom to Blob Storage REST API implementation


package com.growthpush;

public class GrowthPushException extends RuntimeException {

	private static final long serialVersionUID = 1L;

	public GrowthPushException() {
		super();
	}

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

	public GrowthPushException(Throwable throwable) {
		super(throwable);
	}

	public GrowthPushException(String message, Throwable throwable) {
		super(message, throwable);
	}

}

package com.growthpush;

import com.growthbeat.GrowthbeatException;

public class GrowthPushException extends GrowthbeatException {

	private static final long serialVersionUID = 1L;

	public GrowthPushException() {
		super();
	}

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

	public GrowthPushException(Throwable throwable) {
		super(throwable);
	}

	public GrowthPushException(String message, Throwable throwable) {
		super(message, throwable);
	}

}

Make GrowthPusException subclass of GrowthbeatException


import dto.LiveNode;
import java.util.List;

public class Client {
    public static void main(String[] args) {

        String ips = "109.231.122.0-100";//"109.231.122.54";
        CommandExecutor commandExecutor = new CommandExecutor();
        String nmapOutput = commandExecutor.execute("nmap --open " + ips + " -p 50070 -oX -");

        XmlToJsonConverter converter = new XmlToJsonConverter();
        PotentialNameNodeDiscoverer pnd = new PotentialNameNodeDiscoverer();
        String jsonString = converter.process(nmapOutput);
        List<String> potentialNameNodes = pnd.getPotentialNameNodes(jsonString);

        for (String ip : potentialNameNodes) {
            String url = "http://" + ip + ":50070/jmx?qry=Hadoop:service=NameNode,name=NameNodeInfo";
            HdfsNodeExtractor hdfsNodeExtractor = new HdfsNodeExtractor(url);
            List<LiveNode> liveDataNodes = hdfsNodeExtractor.getLiveDataNodes();
            //hdfsNodeExtractor.prettyPrint();
            System.out.print(liveDataNodes);
        }

        //"nmap --open 109.231.122.240 109.231.122.54 -p 50070"
    }
}

import dto.LiveNode;
import java.util.List;

public class Client {
    public static void main(String[] args) {

        StringBuilder ipList = new StringBuilder();
        for (String arg : args) {
            ipList.append(arg + " ");
        }
        String ips = ipList.toString().trim();
        CommandExecutor commandExecutor = new CommandExecutor();
        String nmapOutput = commandExecutor.execute("nmap --open " + ips + " -p 50070 -oX -");

        XmlToJsonConverter converter = new XmlToJsonConverter();
        PotentialNameNodeDiscoverer pnd = new PotentialNameNodeDiscoverer();
        String jsonString = converter.process(nmapOutput);
        List<String> potentialNameNodes = pnd.getPotentialNameNodes(jsonString);

        for (String ip : potentialNameNodes) {
            String url = "http://" + ip + ":50070/jmx?qry=Hadoop:service=NameNode,name=NameNodeInfo";
            HdfsNodeExtractor hdfsNodeExtractor = new HdfsNodeExtractor(url);
            List<LiveNode> liveDataNodes = hdfsNodeExtractor.getLiveDataNodes();
            //hdfsNodeExtractor.prettyPrint();
            System.out.print(liveDataNodes);
        }
    }
}

Use program arguments to specify ip and ip ranges.


package seedu.address.logic.parser;

import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.logic.parser.CliSyntax.PREFIX_DEADLINE;

import java.util.Date;
import java.util.List;

import seedu.address.logic.commands.Command;
import seedu.address.logic.commands.IncorrectCommand;
import seedu.address.logic.commands.ListCommand;

public class ListCommandParser {

    /**
     * Parses the given {@code String} of arguments in the context of the
     * FindCommand and returns an FindCommand object for execution.
     */
    public Command parse(String args) {
        try {
            if (!args.isEmpty() && args.contains("by ")) {
                ArgumentTokenizer argsTokenizer = new ArgumentTokenizer(PREFIX_DEADLINE);
                argsTokenizer.tokenize(args);
                List<Date> endDateList = new DateTimeParser().parse(
                        argsTokenizer.getValue(PREFIX_DEADLINE).get()).get(0).getDates();
                List<Date> startDateList = new DateTimeParser().parse("now").get(0).getDates();
                return new ListCommand(startDateList.get(0), endDateList.get(0));
            }
        } catch (Exception e) {
            return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListCommand.MESSAGE_USAGE));
        }

        return new ListCommand();
    }

}

package seedu.address.logic.parser;

import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.logic.parser.CliSyntax.PREFIX_DEADLINE;
import static seedu.address.logic.parser.CliSyntax.PREFIX_TIMEINTERVAL_END;
import static seedu.address.logic.parser.CliSyntax.PREFIX_TIMEINTERVAL_START;

import seedu.address.logic.commands.Command;
import seedu.address.logic.commands.IncorrectCommand;
import seedu.address.logic.commands.ListCommand;

public class ListCommandParser {

    /**
     * Parses the given {@code String} of arguments in the context of the
     * FindCommand and returns an FindCommand object for execution.
     */
    public Command parse(String args) {
        try {
            ArgumentTokenizer argsTokenizer = new ArgumentTokenizer(PREFIX_DEADLINE,
                    PREFIX_TIMEINTERVAL_START, PREFIX_TIMEINTERVAL_END);
            argsTokenizer.tokenize(args);
            if (args.trim().contains(PREFIX_TIMEINTERVAL_START.getPrefix())
                    && args.trim().contains(PREFIX_TIMEINTERVAL_END.getPrefix())) {
                return new ListCommand(argsTokenizer.getValue(PREFIX_TIMEINTERVAL_START).get(),
                        argsTokenizer.getValue(PREFIX_TIMEINTERVAL_END).get());
            } else if (args.trim().contains(PREFIX_DEADLINE.getPrefix())) {
                return new ListCommand(argsTokenizer.getValue(PREFIX_DEADLINE).get());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListCommand.MESSAGE_USAGE));
        }

        return new ListCommand();
    }

}

Rename edit task descriptor set address method to set deadline


package org.springframework.ide.vscode.commons.languageserver.java;

import org.springframework.ide.vscode.commons.java.IJavaProject;
import org.springframework.ide.vscode.commons.languageserver.util.IDocument;

public class DefaultJavaProjectFinder implements JavaProjectFinder {

	private final IJavaProjectFinderStrategy[] STRATEGIES = new IJavaProjectFinderStrategy[] {
		new JavaProjectWithClasspathFileFinderStrategy(),
		new MavenProjectFinderStrategy()
	};

	@Override
	public IJavaProject find(IDocument d) {
		for (IJavaProjectFinderStrategy strategy : STRATEGIES) {
			try {
				return strategy.find(d);
			} catch (Throwable t) {
				// Log perhaps?
			}
		}
		return null;
	}
}

package org.springframework.ide.vscode.commons.languageserver.java;

import org.springframework.ide.vscode.commons.java.IJavaProject;
import org.springframework.ide.vscode.commons.languageserver.util.IDocument;

public class DefaultJavaProjectFinder implements JavaProjectFinder {

	private final IJavaProjectFinderStrategy[] STRATEGIES = new IJavaProjectFinderStrategy[] {
		new JavaProjectWithClasspathFileFinderStrategy(),
		new MavenProjectFinderStrategy()
	};

	@Override
	public IJavaProject find(IDocument d) {
		for (IJavaProjectFinderStrategy strategy : STRATEGIES) {
			try {
				IJavaProject project = strategy.find(d);
				if (project != null) {
					return project;
				}
			} catch (Throwable t) {
				// Log perhaps?
			}
		}
		return null;
	}
}

Handle null found project for default java project finder


package org.qpt.receipt;

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Created by Sora on 2016/7/6.
 */
public class ItemTest {

    private static Goods getGoods() {
        Goods goods = new Goods("ITEM000001", "可口可乐");
        goods.setCategory("食品", "饮料");
        goods.setPrice(3.00f, "瓶");
        return goods;
    }

    @Test
    public void shouldStoreRightQuantity() throws Exception {
        Item item = new Item(ItemTest.getGoods());
        assertEquals(0, item.getQuantity());

        item.add(1);
        assertEquals(1, item.getQuantity());

        item.setQuantity(3);
        assertEquals(3, item.getQuantity());

        item.add(2);
        assertEquals(5, item.getQuantity());

        item.remove(3);
        assertEquals(2, item.getQuantity());

        assertEquals(2, new Item(ItemTest.getGoods(), 2));
    }

}

package org.qpt.receipt;

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Created by Sora on 2016/7/6.
 */
public class ItemTest {

    private static Goods getGoods() {
        Goods goods = new Goods("ITEM000001", "可口可乐");
        goods.setCategory("食品", "饮料");
        goods.setPrice(3.00f, "瓶");
        return goods;
    }

    @Test
    public void shouldStoreRightQuantity() throws Exception {
        Item item = new Item(ItemTest.getGoods());
        assertEquals(0, item.getQuantity());

        item.add(1);
        assertEquals(1, item.getQuantity());

        item.setQuantity(3);
        assertEquals(3, item.getQuantity());

        item.add(2);
        assertEquals(5, item.getQuantity());

        item.remove(3);
        assertEquals(2, item.getQuantity());

        item = new Item(ItemTest.getGoods(), 2);
        assertEquals(2, item.getQuantity());
    }

}

Fix bugs in item test case

Fix bugs in item test case


package ch.ethz.scu.obit.common.version;

public class VersionInfo {

	// Program version
	public static final String version = "0.5.1";

	// Version status: "alpha", "beta", or "" for a stable release
	public static final String status = "alpha";

	// Properties (XML) file version
	public static final int propertiesVersion = 4;

}

package ch.ethz.scu.obit.common.version;

public class VersionInfo {

	// Program version
	public static final String version = "0.5.1";

	// Version status: "alpha", "beta", or "" for a stable release
	public static final String status = "alpha 2";

	// Properties (XML) file version
	public static final int propertiesVersion = 4;

}

Increase version to 0.5.1 alpha 2.

Increase version to 0.5.1 alpha 2.


package application.Actions;

import javafx.geometry.Point2D;
import application.SLogoCanvas;
import application.Turtle;

public class ForwardAction extends AbstractAction {

	public ForwardAction(double distance) {
		myValue = distance;
	}

	@Override
	public void update(Turtle turtle, SLogoCanvas canvas) {
		Point2D previousLocation = turtle.getLocation();

		double remainder = myValue;
		while (remainder > 0) {
			//I PROMISE I WILL COME UP WITH A BETTER SOLUTION
			//BUT MAYBE THIS IDEA WILL BE COOL FOR ANIMATING
			//PROBABLY SHOULDN'T BE IN THE FORWARD ACTION THOUGH
			if (turtle.getPen().isDashed() && remainder >= 30) {
				canvas.displayLine(turtle.move(30));
				remainder -= 30;
			} else if (turtle.getPen().isDotted() && remainder >= 5) {
				canvas.displayLine(turtle.move(5));
				remainder -= 5;
			} else {
				canvas.displayLine(turtle.move(1));
				remainder -= 1;
			}
		}
		// System.out.println("***Prior Location: " + prevLoc);
		// System.out.println("***Prior Location: " + turt.getLocation());
	}

	@Override
	public String toString() {
		return "fwd " + myValue;
	}

}

package application.Actions;

import javafx.geometry.Point2D;
import application.SLogoCanvas;
import application.Turtle;

public class ForwardAction extends AbstractAction {

	public ForwardAction(double distance) {
		myValue = distance;
	}

	@Override
	public void update(Turtle turtle, SLogoCanvas canvas) {
		Point2D previousLocation = turtle.getLocation();

		double remainder = myValue;
		while (remainder > 0) {
			//I PROMISE I WILL COME UP WITH A BETTER SOLUTION
			//BUT MAYBE THIS IDEA WILL BE COOL FOR ANIMATING
			//PROBABLY SHOULDN'T BE IN THE FORWARD ACTION THOUGH
			if (turtle.getPen().isDashed() && myValue > 30) {
				canvas.displayLine(turtle.move(30));
				remainder -= 20;
			} else if (turtle.getPen().isDotted() && myValue > 5) {
				canvas.displayLine(turtle.move(5));
				remainder -= 5;
			} else {
				canvas.displayLine(turtle.move(1));
				remainder -= 1;
			}
		}
		// System.out.println("***Prior Location: " + prevLoc);
		// System.out.println("***Prior Location: " + turt.getLocation());
	}

	@Override
	public String toString() {
		return "fwd " + myValue;
	}

}

Revert "fixed pen styling bug"

Revert "fixed pen styling bug"

This reverts commit 2acf214f5479ca2a691e0f4b09bcef8a28f99e2a.


package com.dragonheart.dijkstra;

import java.util.ArrayList;

public class DijkstraGraph {
	private ArrayList<Edge> listOfEdges;
	private ArrayList<Point> listOfPoints, sourceNodes;

	public DijkstraGraph() {
		this.listOfEdges = new ArrayList<Edge>();
		this.listOfPoints = new ArrayList<Point>();
		this.sourceNodes = new ArrayList<Point>();
	}

	public void addPoint(Point point) {
		listOfPoints.add(point);
	}

	public void addEdge(Edge edge) {
		listOfEdges.add(edge);
	}
}

package com.dragonheart.dijkstra;

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

public class DijkstraGraph {
	private ArrayList<Edge> listOfEdges;
	private ArrayList<Point> listOfPoints, sourcePoints;

	public DijkstraGraph() {
		this.listOfEdges = new ArrayList<Edge>();
		this.listOfPoints = new ArrayList<Point>();
		this.sourcePoints = new ArrayList<Point>();
	}

	public void addPoint(Point point) {
		listOfPoints.add(point);
	}

	public void addEdge(Edge edge) {
		listOfEdges.add(edge);
	}

	public void addSource(Point point, Double cost) {
		if(listOfPoints.contains(point)) {
			point.aggregateCost = cost;
			sourcePoints.add(point);
		}
	}

	public void addSources(List<Point> points, Double cost) {
		for(Point point : points) {
			addSource(point, cost);
		}
	}

	public void setSource(Point point, Double cost) {
		sourcePoints = new ArrayList<Point>();
		addSource(point, cost);
	}

	public void setSources(List<Point> points, Double cost) {
		sourcePoints = new ArrayList<Point>();
		addSources(points, cost);
	}
}

Add sources 4 different ways!

Add sources 4 different ways!


package org.wikipedia.settings;

import android.os.Bundle;
import android.support.v7.preference.PreferenceFragmentCompat;

abstract class PreferenceLoaderFragment extends PreferenceFragmentCompat
        implements PreferenceLoader {
    @Override
    public void onCreatePreferences(Bundle bundle, String s) {
        loadPreferences();
    }
}

package org.wikipedia.settings;

import android.os.Bundle;
import android.support.v7.preference.PreferenceFragmentCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import org.wikipedia.R;
import org.wikipedia.util.ResourceUtil;

abstract class PreferenceLoaderFragment extends PreferenceFragmentCompat
        implements PreferenceLoader {
    @Override
    public void onCreatePreferences(Bundle bundle, String s) {
        loadPreferences();
    }

    @Override
    public RecyclerView onCreateRecyclerView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
        RecyclerView v = super.onCreateRecyclerView(inflater, parent, savedInstanceState);
        v.setBackgroundColor(ResourceUtil.getThemedColor(getContext(), R.attr.paper_color));
        return v;
    }
}

Set correct background color in Settings.

Bug: T186104
Change-Id: I44e2a1276fb208b20e7ff54bd7bb19d4ceaae2c7


package com.simplenote.android.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import com.simplenote.android.Constants;

/**
 * Collection of methods to fire Intents
 * @author bryanjswift
 */
public class FireIntent {
	/**
	 * Start the SimpleNoteList Activity
	 * @param context in which the intent is firing
	 */
	public static void SimpleNoteList(final Context context) {
		Intent i = new Intent(context, SimpleNoteList.class);
		context.startActivity(i);
	}
	/**
	 * Start the LoginDialog Activity expecting a result
	 * @param context Activity for which the intent is firing
	 */
	public static void SigninDialog(final Activity context) {
		Intent i = new Intent(context, LoginDialog.class);
		context.startActivityForResult(i, Constants.REQUEST_LOGIN);
	}
}

package com.simplenote.android.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.provider.BaseColumns;

import com.simplenote.android.Constants;
import com.simplenote.android.persistence.SimpleNoteDao;

/**
 * Collection of methods to fire Intents
 * @author bryanjswift
 */
public class FireIntent {
	/**
	 * Start the SimpleNoteList Activity
	 * @param context in which the intent is firing
	 */
	public static void SimpleNoteList(final Context context) {
		Intent i = new Intent(context, SimpleNoteList.class);
		context.startActivity(i);
	}
	/**
	 * Starts the SimpleNoteEdit Activity
	 * @param context in which the intent is firing
	 * @param id of the note to edit
	 * @param originalBody of the note as retrieved from saved state
	 */
	public static void EditNote(final Activity context, final long id, final String originalBody) {
		Intent intent = new Intent(context, SimpleNoteEdit.class);
		intent.putExtra(BaseColumns._ID, id);
		if (originalBody != null) {
			intent.putExtra(SimpleNoteDao.BODY, originalBody);
		}
		context.startActivityForResult(intent, Constants.REQUEST_EDIT);
	}
	/**
	 * Start the LoginDialog Activity expecting a result
	 * @param context Activity for which the intent is firing
	 */
	public static void SigninDialog(final Activity context) {
		Intent i = new Intent(context, LoginDialog.class);
		context.startActivityForResult(i, Constants.REQUEST_LOGIN);
	}
}

Add method to fire the EditNote activity


package acceptance;

import cucumber.api.CucumberOptions;
import net.serenitybdd.cucumber.CucumberWithSerenity;
import org.junit.runner.RunWith;

@RunWith(CucumberWithSerenity.class)
@CucumberOptions(features={"src/test/specs/design-r3"} , glue={"steps"})

public class AcceptanceTests {
}

package acceptance;

import cucumber.api.CucumberOptions;
import net.serenitybdd.cucumber.CucumberWithSerenity;
import org.junit.runner.RunWith;

@RunWith(CucumberWithSerenity.class)
@CucumberOptions(features={"src/test/specs/design-r4"} , glue={"steps"})

public class AcceptanceTests {
}

Change default features files to r4

Change default features files to r4


public class Wift {

  /**
   *  Wift - The BASIC Programming Language
   *
   *        BASIC FUNCTIONALITY:
   *            - STRINGS []
   *            - INTEGERS []
   *            - ARITHMETIC []
   *            - VARIABLES []
   *
   *        FUNCTIONS:
   *            - PRINT []
   *            - INPUT []
   *            - IF []
   *            - FOR []
   *
   *
   */

  public static void main(String...args){}

  //        #readFile() -> char content
  //        #tokenize() -> list
  //        #parse()    -> symbol table

}

public class Wift {

  /**
   *  Wift - The BASIC Programming Language
   *
   *        BASIC FUNCTIONALITY:
   *            - STRINGS []
   *            - INTEGERS []
   *            - ARITHMETIC []
   *            - VARIABLES []
   *
   *        FUNCTIONS:
   *            - PRINT []
   *            - INPUT []
   *            - IF []
   *            - FOR []
   *
   *
   */

  public static void main(String...args){}

  public static String readFile()

  //        #readFile() -> char content
  //        #tokenize() -> list
  //        #parse()    -> symbol table

}

Set "public static String readFile()" :book:


/*
 * Copyright 2019, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package io.spine.tools.gradle;

/**
 * A name of a source set scope.
 */
public enum SourceScope {

    MAIN("main"),
    TEST("test");

    private final String value;

    SourceScope(String value) {
        this.value = value;
    }

    public String value() {
        return value;
    }

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

/*
 * Copyright 2019, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package io.spine.tools.gradle;

import static org.gradle.api.tasks.SourceSet.MAIN_SOURCE_SET_NAME;
import static org.gradle.api.tasks.SourceSet.TEST_SOURCE_SET_NAME;

/**
 * A name of a source set scope.
 */
public enum SourceScope {

    MAIN(MAIN_SOURCE_SET_NAME),
    TEST(TEST_SOURCE_SET_NAME);

    private final String value;

    SourceScope(String value) {
        this.value = value;
    }

    public String value() {
        return value;
    }

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

Use constants from Gradle rather than custom.


package com.example.zipper.customview;

import com.example.zipper.R;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import se.snylt.zipper.annotations.BindToView;
import se.snylt.zipper.viewbinder.Binding;
import se.snylt.zipper.viewbinder.Zipper;

public class CustomViewFragment extends Fragment {

    private Binding binding;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.custom_view_fragment, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        CustomViewModel model = new CustomViewModel("@BindView\nid = R.id.123, view = CustomView.class, set = \"property\"");
        binding = Zipper.bind(model, view);
        binding = Zipper.bind(model, view);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding.unBind();
    }

    public static class CustomViewModel {

        @BindToView(id=R.id.custom_view_fragment_custom_view, view = CustomView.class, set = "myData")
        public final String data;

        public CustomViewModel(String data) {
            this.data = data;
        }
    }
}

package com.example.zipper.customview;

import com.example.zipper.R;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import se.snylt.zipper.annotations.BindToView;
import se.snylt.zipper.viewbinder.Binding;
import se.snylt.zipper.viewbinder.Zipper;

public class CustomViewFragment extends Fragment {

    private Binding binding;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.custom_view_fragment, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        CustomViewModel model = new CustomViewModel("@BindView\nid = R.id.123, view = CustomView.class, set = \"property\"");
        binding = Zipper.bind(model, view);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding.unBind();
    }

    public static class CustomViewModel {

        @BindToView(id=R.id.custom_view_fragment_custom_view, view = CustomView.class, set = "myData")
        public final String data;

        public CustomViewModel(String data) {
            this.data = data;
        }
    }
}

Remove double binding in custom view example.


/* Copyright 2008-2012 Nokia Siemens Networks Oyj
 *
 * 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.robotframework;

import org.python.core.PyObject;
import org.python.core.PySystemState;
import org.python.util.PythonInterpreter;

/**
 *
 * Helper class to create an Jython object and coerce it so that it can be used
 * from Java.
 *
 */
public class RunnerFactory {

    private PyObject runnerClass;

    public RunnerFactory() {
        runnerClass = importRunnerClass();
    }

    private PyObject importRunnerClass() {
        PythonInterpreter interpreter = new PythonInterpreter(null, new PySystemState());
        interpreter.exec("import robot; from robot.jarrunner import JarRunner");
        return interpreter.get("JarRunner");
    }

    /**
     * Creates and returns an instance of the robot.JarRunner (implemented in
     * Python), which can be used to execute tests.
     */
    public RobotRunner createRunner() {
        PyObject runnerObject = runnerClass.__call__();
        return (RobotRunner) runnerObject.__tojava__(RobotRunner.class);
    }
}

/* Copyright 2008-2012 Nokia Siemens Networks Oyj
 *
 * 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.robotframework;

import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

/**
 *
 * Helper class to create an Jython object and coerce it so that it can be used
 * from Java.
 *
 */
public class RunnerFactory {

    private PyObject runnerClass;

    public RunnerFactory() {
        runnerClass = importRunnerClass();
    }

    private PyObject importRunnerClass() {
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.exec("import robot; from robot.jarrunner import JarRunner");
        return interpreter.get("JarRunner");
    }

    /**
     * Creates and returns an instance of the robot.JarRunner (implemented in
     * Python), which can be used to execute tests.
     */
    public RobotRunner createRunner() {
        PyObject runnerObject = runnerClass.__call__();
        return (RobotRunner) runnerObject.__tojava__(RobotRunner.class);
    }
}

Revert change 00342e052b17 to fix sshlibrary on standalone jar.

Update issue 1311
Status: Done

Revert change 00342e052b17 to fix sshlibrary on standalone jar.


/*
 * 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.bcel;

public class NanoTimer {

    private long time = 0;

    public NanoTimer start() {
        time -= System.nanoTime();
        return this;
    }

    public void stop() {
        time += System.nanoTime();
    }

    public void subtract(final NanoTimer o) {
        time -= o.time;
    }

    public void reset() {
        time = 0;
    }

    /**
     * May ony be called after stop has been called as many times as start.
     */
    @Override
    public String toString() {
        return ((double) time / 1000000000) + " s";
    }

}

/*
 * 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.bcel;

public class NanoTimer {

    private long timeNanos = 0;

    public NanoTimer start() {
        timeNanos -= System.nanoTime();
        return this;
    }

    public void stop() {
        timeNanos += System.nanoTime();
    }

    public void subtract(final NanoTimer o) {
        timeNanos -= o.timeNanos;
    }

    public void reset() {
        timeNanos = 0;
    }

    /**
     * May ony be called after stop has been called as many times as start.
     */
    @Override
    public String toString() {
        return ((double) timeNanos / 1000000000) + " s";
    }

}

Use the scale in the var name.

Use the scale in the var name.


package info.u_team.u_team_core.util.registry;

import net.minecraft.client.renderer.tileentity.TileEntityRenderer;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.*;
import net.minecraft.tileentity.*;
import net.minecraftforge.api.distmarker.*;
import net.minecraftforge.fml.client.registry.*;

@OnlyIn(Dist.CLIENT)
public class ClientRegistry {

	public static <T extends Entity> void registerEntityRenderer(EntityType<T> clazz, IRenderFactory<? super T> rendererFactory) {
		RenderingRegistry.registerEntityRenderingHandler(clazz, rendererFactory);
	}

	public static <T extends TileEntity> void registerSpecialTileEntityRenderer(TileEntityType<T> clazz, TileEntityRenderer<? super T> renderer) {
		net.minecraftforge.fml.client.registry.ClientRegistry.bindTileEntityRenderer(clazz, renderer);
	}

	public static void registerKeybinding(KeyBinding key) {
		net.minecraftforge.fml.client.registry.ClientRegistry.registerKeyBinding(key);
	}

}

package info.u_team.u_team_core.util.registry;

import java.util.function.Function;

import net.minecraft.client.renderer.tileentity.*;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.*;
import net.minecraft.tileentity.*;
import net.minecraftforge.api.distmarker.*;
import net.minecraftforge.fml.client.registry.*;

@OnlyIn(Dist.CLIENT)
public class ClientRegistry {

	public static <T extends Entity> void registerEntityRenderer(EntityType<T> clazz, IRenderFactory<? super T> rendererFactory) {
		RenderingRegistry.registerEntityRenderingHandler(clazz, rendererFactory);
	}

	public static <T extends TileEntity> void registerSpecialTileEntityRenderer(TileEntityType<T> clazz, TileEntityRenderer<? super T> renderer) {
		registerSpecialTileEntityRenderer(clazz, dispatcher -> renderer);
	}

	public static <T extends TileEntity> void registerSpecialTileEntityRenderer(TileEntityType<T> clazz, Function<? super TileEntityRendererDispatcher, ? extends TileEntityRenderer<? super T>> rendererFactory) {
		net.minecraftforge.fml.client.registry.ClientRegistry.bindTileEntityRenderer(clazz, rendererFactory);
	}

	public static void registerKeybinding(KeyBinding key) {
		net.minecraftforge.fml.client.registry.ClientRegistry.registerKeyBinding(key);
	}

}

Fix changes in the registry of tile entity renderer in the latest forge updates (30.0.19)