/**
 * (c) 2014 StreamSets, Inc. All rights reserved. May not
 * be copied, modified, or distributed in whole or part without
 * written consent of StreamSets, Inc.
 */
package com.streamsets.pipeline.runner.preview;

import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.runner.Pipeline;
import com.streamsets.pipeline.runner.PipelineRuntimeException;
import com.streamsets.pipeline.runner.StageOutput;
import com.streamsets.pipeline.validation.Issues;

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

public class PreviewPipeline {
  private final Pipeline pipeline;
  private final Issues issues;

  public PreviewPipeline(Pipeline pipeline, Issues issues) {
    this.issues = issues;
    this.pipeline = pipeline;
  }

  @SuppressWarnings("unchecked")
  public PreviewPipelineOutput run() throws StageException, PipelineRuntimeException{
    return run(Collections.EMPTY_LIST);
  }

  public PreviewPipelineOutput run(List<StageOutput> stageOutputsToOverride)
      throws StageException, PipelineRuntimeException{
    pipeline.init();
    pipeline.run(stageOutputsToOverride);
    pipeline.destroy();
    return new PreviewPipelineOutput(issues, pipeline.getRunner());
  }

}

/**
 * (c) 2014 StreamSets, Inc. All rights reserved. May not
 * be copied, modified, or distributed in whole or part without
 * written consent of StreamSets, Inc.
 */
package com.streamsets.pipeline.runner.preview;

import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.runner.Pipeline;
import com.streamsets.pipeline.runner.PipelineRuntimeException;
import com.streamsets.pipeline.runner.StageOutput;
import com.streamsets.pipeline.validation.Issues;

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

public class PreviewPipeline {
  private final Pipeline pipeline;
  private final Issues issues;

  public PreviewPipeline(Pipeline pipeline, Issues issues) {
    this.issues = issues;
    this.pipeline = pipeline;
  }

  @SuppressWarnings("unchecked")
  public PreviewPipelineOutput run() throws StageException, PipelineRuntimeException{
    return run(Collections.EMPTY_LIST);
  }

  public PreviewPipelineOutput run(List<StageOutput> stageOutputsToOverride)
      throws StageException, PipelineRuntimeException{
    pipeline.init();
    try {
      pipeline.run(stageOutputsToOverride);
    } finally {
      pipeline.destroy();
    }
    return new PreviewPipelineOutput(issues, pipeline.getRunner());
  }

}

Handle exception and clean up during preview


package org.subethamail.smtp.server.io;

import java.io.File;
import java.io.IOException;

import javax.mail.util.SharedFileInputStream;

/**
 * This class uses a temporary file to store big messages and asks JVM
 * to delete them when destroyed.
 *
 * @author De Oliveira Edouard <doe_wanted@yahoo.fr>
 */
public class SharedTmpFileInputStream
	extends SharedFileInputStream
{
	private File tempFile;

	public SharedTmpFileInputStream(File f) throws IOException
	{
		super(f);
		this.tempFile = f;
	}

	public void close() throws IOException
	{
		super.close();
		if (in == null)
			this.tempFile.deleteOnExit();
	}
}

package org.subethamail.smtp.server.io;

import java.io.File;
import java.io.IOException;

import javax.mail.util.SharedFileInputStream;

/**
 * This class uses a temporary file to store big messages and asks JVM
 * to delete them when JVM is destroyed.
 *
 * @author De Oliveira Edouard <doe_wanted@yahoo.fr>
 */
public class SharedTmpFileInputStream
	extends SharedFileInputStream
{
	private File tempFile;

	public SharedTmpFileInputStream(File f) throws IOException
	{
		super(f);
		this.tempFile = f;

		// Always mark file to be deleted on exit in case streams
		// are not closed properly.
		this.tempFile.deleteOnExit();
	}
}

Fix to ensure that temp deffered file will be deleted by JVM even if shared streams are improperly closed


package com.amebame.triton.config;

public class TritonNettyConfiguration {

	// Maximum worker thread
	private int worker = 10;

	// Connect timeout for client (default 5sec)
	private int connectTimeout = 5000;

	public TritonNettyConfiguration() {
	}

	public int getWorker() {
		return worker;
	}

	public void setWorker(int worker) {
		this.worker = worker;
	}

	public int getConnectTimeout() {
		return connectTimeout;
	}

	public void setConnectTimeout(int connectTimeout) {
		this.connectTimeout = connectTimeout;
	}
}

package com.amebame.triton.config;

public class TritonNettyConfiguration {

	// Maximum worker thread
	private int worker = 100;

	// Connect timeout for client (default 5sec)
	private int connectTimeout = 5000;

	public TritonNettyConfiguration() {
	}

	public int getWorker() {
		return worker;
	}

	public void setWorker(int worker) {
		this.worker = worker;
	}

	public int getConnectTimeout() {
		return connectTimeout;
	}

	public void setConnectTimeout(int connectTimeout) {
		this.connectTimeout = connectTimeout;
	}
}

Change default worker count to 100.

Change default worker count to 100.


package com.arckenver.nations.listener;

import org.spongepowered.api.entity.EntityType;
import org.spongepowered.api.entity.EntityTypes;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.entity.SpawnEntityEvent;

import com.arckenver.nations.ConfigHandler;
import com.arckenver.nations.DataHandler;
import com.google.common.collect.ImmutableList;

public class MobSpawningListener
{
	ImmutableList<EntityType> agressiveMobs = new ImmutableList.Builder<EntityType>()
			.add(EntityTypes.BLAZE)
			.add(EntityTypes.CAVE_SPIDER)
			.add(EntityTypes.CREEPER)
			.add(EntityTypes.ENDER_DRAGON)
			.add(EntityTypes.ENDERMAN)
			.add(EntityTypes.ENDERMITE)
			.add(EntityTypes.GHAST)
			.add(EntityTypes.GIANT)
			.add(EntityTypes.GUARDIAN)
			.add(EntityTypes.MAGMA_CUBE)
			.add(EntityTypes.PIG_ZOMBIE)
			.add(EntityTypes.SKELETON)
			.add(EntityTypes.SILVERFISH)
			.add(EntityTypes.SLIME)
			.add(EntityTypes.SPIDER)
			.add(EntityTypes.WITCH)
			.add(EntityTypes.WITHER)
			.add(EntityTypes.WITHER_SKULL)
			.add(EntityTypes.ZOMBIE)
			.build();

	@Listener
	public void onPlayerRightClick(SpawnEntityEvent event)
	{
		if (!ConfigHandler.getNode("worlds").getNode(event.getTargetWorld().getName()).getNode("enabled").getBoolean())
		{
			return;
		}
		event.filterEntities(e -> !agressiveMobs.contains(e.getType()) || DataHandler.getFlag("mobs", e.getLocation()));
	}
}

package com.arckenver.nations.listener;

import org.spongepowered.api.entity.living.monster.Monster;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.entity.SpawnEntityEvent;

import com.arckenver.nations.ConfigHandler;
import com.arckenver.nations.DataHandler;

public class MobSpawningListener
{
	@Listener
	public void onEntitySpawn(SpawnEntityEvent event)
	{
		if (!ConfigHandler.getNode("worlds").getNode(event.getTargetWorld().getName()).getNode("enabled").getBoolean())
		{
			return;
		}
		event.filterEntities(e -> !(e instanceof Monster) || DataHandler.getFlag("mobs", e.getLocation()));
	}
}

Extend spawn prevention to all hostile mobs (should take hostile mobs from mods into account)


package io.github.web.springmvc;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class GreetingController {

    @RequestMapping("/greeting")
    public ModelAndView greeting() {

        return new ModelAndView("greeting_template").addObject("name", "World");
    }
}

package io.github.web.springmvc;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class GreetingController {

    @RequestMapping("/")
    public ModelAndView greeting() {

        return new ModelAndView("greeting_template").addObject("name", "World");
    }
}

Change request mapping in spring-mvc-hello-world example


package com.yahoo.squidb.test;

import com.yahoo.squidb.annotations.ColumnSpec;
import com.yahoo.squidb.annotations.PrimaryKey;
import com.yahoo.squidb.annotations.TableModelSpec;

@TableModelSpec(className = "TestNonIntegerPrimaryKey", tableName = "testNonIntegerPrimaryKey")
public class TestNonIntegerPrimaryKeySpec {

    @PrimaryKey
    @ColumnSpec(constraints = "NOT NULL")
    String key;

    String value;

}

package com.yahoo.squidb.test;

import com.yahoo.squidb.annotations.ColumnSpec;
import com.yahoo.squidb.annotations.PrimaryKey;
import com.yahoo.squidb.annotations.TableModelSpec;

@TableModelSpec(className = "TestNonIntegerPrimaryKey", tableName = "testNonIntegerPrimaryKey")
public class TestNonIntegerPrimaryKeySpec {

    @PrimaryKey
    @ColumnSpec(name = "keyCol", constraints = "NOT NULL")
    String key;

    String value;

}

Fix a column name warning in the unit tests generated by our own validation


package de.skuzzle.enforcer.restrictimports.parser;

import de.skuzzle.enforcer.restrictimports.io.RuntimeIOException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;

/**
 * Supplies lines but skips every encountered comment. Block comments that span multiple
 * lines will be replaced by the same amount of empty lines.
 *
 * @author Simon Taddiken
 */
class SkipCommentsLineSupplier implements LineSupplier {

    private final Charset charset;

    public SkipCommentsLineSupplier(Charset charset) {
        this.charset = charset;
    }

    @Override
    public Stream<String> lines(Path path) throws IOException {
        final Reader fromFile = Files.newBufferedReader(path, charset);
        final Reader skipComments = new TransientCommentReader(fromFile, true);

        final BufferedReader lineReader = new BufferedReader(skipComments);
        return lineReader.lines().onClose(() -> close(lineReader));
    }

    private void close(Reader reader) {
        try {
            reader.close();
        } catch (final IOException e) {
            throw new RuntimeIOException("Error while closing reader", e);
        }
    }
}

package de.skuzzle.enforcer.restrictimports.parser;

import de.skuzzle.enforcer.restrictimports.io.RuntimeIOException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;

/**
 * Supplies lines but skips every encountered comment. Block comments that span multiple
 * lines will be replaced by the same amount of empty lines.
 *
 * @author Simon Taddiken
 */
class SkipCommentsLineSupplier implements LineSupplier {

    private final Charset charset;

    public SkipCommentsLineSupplier(Charset charset) {
        this.charset = charset;
    }

    @Override
    public Stream<String> lines(Path path) throws IOException {
        final Reader fromFile = Files.newBufferedReader(path, charset);
        final Reader skipComments = new TransientCommentReader(fromFile, true);

        final BufferedReader lineReader = new BufferedReader(skipComments);
        return lineReader.lines()
                .onClose(() -> close(lineReader))
                .onClose(() -> close(skipComments))
                .onClose(() -> close(fromFile));
    }

    private void close(Reader reader) {
        try {
            reader.close();
        } catch (final IOException e) {
            throw new RuntimeIOException("Error while closing reader", e);
        }
    }
}

Make sure to close all readers

Make sure to close all readers


package org.bubblecloud.zigbee;

import org.bubblecloud.zigbee.network.port.SerialPortImpl;

/**
 * Created by Chris on 25/02/15.
 */
public final class ZigBeeSerialNetworkTest extends ZigBeeNetworkTest {
	public static final String SerialPortIdentifier = "/dev/ttyACM0";
	public static final int    BaudRate             = 115200;

    /**
     * Constructor for defining the serial port implementation.
     */
	public ZigBeeSerialNetworkTest() {
		super(new SerialPortImpl(SerialPortIdentifier, BaudRate));
	}
}

package org.bubblecloud.zigbee;

import org.bubblecloud.zigbee.network.port.SerialPortImpl;

/**
 * Created by Chris on 25/02/15.
 */
public final class ZigBeeSerialNetworkTest extends ZigBeeNetworkTest {
    /**
     * The serial port identifier.
     */
    public static final String SERIAL_PORT_IDENTIFIER = "/dev/ttyACM0";
    /**
     * The baud rate.
     */
    public static final int BAUD_RATE = 115200;

    /**
     * Constructor for defining the serial port implementation.
     */
    public ZigBeeSerialNetworkTest() {
        super(new SerialPortImpl(SERIAL_PORT_IDENTIFIER, BAUD_RATE));
    }
}

Clean up of serial port implementation.

Clean up of serial port implementation.


package ch.liip.timeforcoffee.api.mappers;

import android.location.Location;

import java.util.Date;

import ch.liip.timeforcoffee.api.models.Connection;

public class ConnectionMapper {

    public static Connection fromZvv(ch.liip.timeforcoffee.zvv.CheckPoint checkPoint) {
        int checkPointId = Integer.parseInt(checkPoint.getId());
        Location checkPointLocation = new Location("reverseGeocoded");
        checkPointLocation.setLongitude(checkPoint.getLocation().getLng());
        checkPointLocation.setLatitude(checkPoint.getLocation().getLat());

        Date departureScheduled = checkPoint.getDeparture().getScheduled();
        Date departureRealtime = checkPoint.getDeparture().getRealtime();
        Date arrivalScheduled = checkPoint.getArrival().getScheduled();

        // If there is no specified departure and arrival, it is not a valid connection
        if(arrivalScheduled == null && departureScheduled == null) {
            return null;
        }

        return new Connection(checkPointId, checkPoint.getName(), checkPointLocation, departureScheduled, departureRealtime, arrivalScheduled);
    }
}

package ch.liip.timeforcoffee.api.mappers;

import android.location.Location;
import android.support.annotation.Nullable;

import java.util.Date;

import ch.liip.timeforcoffee.api.models.Connection;

public class ConnectionMapper {

    public static @Nullable Connection fromZvv(ch.liip.timeforcoffee.zvv.CheckPoint checkPoint) {
        int checkPointId = Integer.parseInt(checkPoint.getId());
        Location checkPointLocation = new Location("reverseGeocoded");
        checkPointLocation.setLongitude(checkPoint.getLocation().getLng());
        checkPointLocation.setLatitude(checkPoint.getLocation().getLat());

        Date departureScheduled = checkPoint.getDeparture().getScheduled();
        Date departureRealtime = checkPoint.getDeparture().getRealtime();
        Date arrivalScheduled = checkPoint.getArrival().getScheduled();

        // If there is no specified departure and arrival, it is not a valid connection
        if(arrivalScheduled == null && departureScheduled == null) {
            return null;
        }

        return new Connection(checkPointId, checkPoint.getName(), checkPointLocation, departureScheduled, departureRealtime, arrivalScheduled);
    }
}

Add Nullable annotation to connectionMapper


package fr.free.nrw.commons.theme;

import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import fr.free.nrw.commons.R;

public class BaseAppCompatActivity extends AppCompatActivity {
    boolean currentTheme;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("theme",false)) {
            currentTheme = true;g
            setTheme(R.style.DarkAppTheme);
        }else {
            currentTheme = false;
            setTheme(R.style.LightAppTheme); //default
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        //Restart activity if theme is changed
        Log.d("deneme","onResume Base");
        boolean newTheme = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("theme",false);
        if(currentTheme!=newTheme){ //is activity theme changed
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }
        super.onResume();
    }
}

package fr.free.nrw.commons.theme;

import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import fr.free.nrw.commons.R;

public class BaseAppCompatActivity extends AppCompatActivity {
    boolean currentTheme;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("theme",false)) {
            currentTheme = true;
            setTheme(R.style.DarkAppTheme);
        }else {
            currentTheme = false;
            setTheme(R.style.LightAppTheme); //default
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        //Restart activity if theme is changed
        Log.d("deneme","onResume Base");
        boolean newTheme = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("theme",false);
        if(currentTheme!=newTheme){ //is activity theme changed
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }
        super.onResume();
    }
}

Fix my cats press on keyboard

Fix my cats press on keyboard


package aQute.bnd.connection.settings;

import java.io.File;

import aQute.lib.xpath.XPathParser;

public class SettingsParser extends XPathParser {
	final SettingsDTO settings = new SettingsDTO();

	/*
	 * <proxies> <proxy> <id>example-proxy</id> <active>true</active>
	 * <protocol>http</protocol> <host>proxy.example.com</host>
	 * <port>8080</port> <username>proxyuser</username>
	 * <password>somepassword</password>
	 * <nonProxyHosts>www.google.com|*.example.com</nonProxyHosts> </proxy>
	 * </proxies>
	 */

	public SettingsParser(File file) throws Exception {
		super(file);

		parse("/settings/proxies/proxy", ProxyDTO.class, settings.proxies);
		parse("/settings/servers/server", ServerDTO.class, settings.servers);
	}

	public SettingsDTO getSettings() {
		return settings;
	}
}

package aQute.bnd.connection.settings;

import java.io.File;

import aQute.bnd.osgi.Macro;
import aQute.bnd.osgi.Processor;
import aQute.lib.xpath.XPathParser;

public class SettingsParser extends XPathParser {
	final SettingsDTO settings = new SettingsDTO();
	private final Macro	replacer	= new Processor().getReplacer();

	/*
	 * <proxies> <proxy> <id>example-proxy</id> <active>true</active>
	 * <protocol>http</protocol> <host>proxy.example.com</host>
	 * <port>8080</port> <username>proxyuser</username>
	 * <password>somepassword</password>
	 * <nonProxyHosts>www.google.com|*.example.com</nonProxyHosts> </proxy>
	 * </proxies>
	 */

	public SettingsParser(File file) throws Exception {
		super(file);

		parse("/settings/proxies/proxy", ProxyDTO.class, settings.proxies);
		parse("/settings/servers/server", ServerDTO.class, settings.servers);
	}

	public SettingsDTO getSettings() {
		return settings;
	}

	@Override
	protected String processValue(String value) {
		return replacer.process(value);
	}
}

connection-settings: Add support for macro replacement in file parsing

Macro replacement is limited to system properties and environment
variables. See https://maven.apache.org/settings.html

Signed-off-by: BJ Hargrave <3d26bb3930946e3370762d769a073cece444c2d8@bjhargrave.com>


package com.carpentersblocks.tileentity;

import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import com.carpentersblocks.data.GarageDoor;

public class TECarpentersGarageDoor extends TEBase {

    @Override
    /**
     * Garage door state change sounds are handled strictly
     * client-side so that only the nearest state change is
     * audible.
     *
     * @param net The NetworkManager the packet originated from
     * @param pkt The data packet
     */
    public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt)
    {
        if (getWorldObj().isRemote) {
            super.onDataPacket(net, pkt);
            new GarageDoor().playStateChangeSound(this);
        }
    }

}

package com.carpentersblocks.tileentity;

import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import com.carpentersblocks.data.GarageDoor;

public class TECarpentersGarageDoor extends TEBase {

    @Override
    /**
     * Garage door state change sounds are handled strictly
     * client-side so that only the nearest state change is
     * audible.
     *
     * @param net The NetworkManager the packet originated from
     * @param pkt The data packet
     */
    public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt)
    {
        if (getWorldObj().isRemote) {
            GarageDoor data = GarageDoor.INSTANCE;
            int oldState = data.getState(this);
            super.onDataPacket(net, pkt);
            if (data.getState(this) != oldState) {
                data.playStateChangeSound(this);
            }
        }
    }

}

Adjust garage door sound to only play on state changes.


package org.kumoricon.site.report.attendees;

import com.vaadin.navigator.View;
import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.spring.annotation.ViewScope;
import com.vaadin.ui.Button;
import com.vaadin.ui.Label;
import org.kumoricon.site.report.ReportView;
import org.kumoricon.site.BaseView;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;

@ViewScope
@SpringView(name = AttendeeReportView.VIEW_NAME)
public class AttendeeReportView extends BaseView implements View, ReportView {
    public static final String VIEW_NAME = "attendeeReport";
    public static final String REQUIRED_RIGHT = "view_attendance_report";
    @Autowired
    private AttendeeReportPresenter handler;

    private Button refresh = new Button("Refresh");
    private Label data = new Label();

    @PostConstruct
    public void init() {
        addComponent(refresh);
        refresh.addClickListener((Button.ClickListener) clickEvent -> handler.fetchReportData(this));
        addComponent(data);
        data.setContentMode(ContentMode.HTML);
        handler.fetchReportData(this);
        setExpandRatio(data, 1f);
        data.setSizeFull();
        data.setWidthUndefined();
    }

    @Override
    public void afterSuccessfulFetch(String data) {
        this.data.setValue(data);
    }

    public String getRequiredRight() {
        return REQUIRED_RIGHT;
    }
}

package org.kumoricon.site.report.attendees;

import com.vaadin.navigator.View;
import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.spring.annotation.ViewScope;
import com.vaadin.ui.Button;
import com.vaadin.ui.Label;
import org.kumoricon.site.report.ReportView;
import org.kumoricon.site.BaseView;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;

@ViewScope
@SpringView(name = AttendeeReportView.VIEW_NAME)
public class AttendeeReportView extends BaseView implements View, ReportView {
    public static final String VIEW_NAME = "attendeeReport";
    public static final String REQUIRED_RIGHT = "view_attendance_report";
    @Autowired
    private AttendeeReportPresenter handler;

    private Button refresh = new Button("Refresh");
    private Label data = new Label();

    @PostConstruct
    public void init() {
        addComponent(refresh);
        refresh.addClickListener((Button.ClickListener) clickEvent -> handler.fetchReportData(this));
        addComponent(data);
        data.setContentMode(ContentMode.HTML);
        handler.fetchReportData(this);
        setExpandRatio(data, 1f);
        data.setSizeFull();
        data.setWidth("100%");
    }

    @Override
    public void afterSuccessfulFetch(String data) {
        this.data.setValue(data);
    }

    public String getRequiredRight() {
        return REQUIRED_RIGHT;
    }
}

Fix text wrapping on Attendee report descriptive text


package samples;

import hex.*;

import javax.swing.JFrame;

public class NeuralNetViz extends NeuralNetMnist {
  public static void main(String[] args) throws Exception {
    Class job = Class.forName(Thread.currentThread().getStackTrace()[1].getClassName());
    samples.launchers.CloudLocal.launch(job, 1);
  }

  protected void startTraining(Layer[] ls) {
    _trainer = new Trainer.MapReduce(ls, 0, self());
    //_trainer = new Trainer.Direct(ls);

    // Basic visualization of images and weights
    JFrame frame = new JFrame("H2O");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    MnistCanvas canvas = new MnistCanvas(_trainer);
    frame.setContentPane(canvas.init());
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    //preTrain(ls);
    _trainer.start();
  }
}

package samples;

import hex.*;

import javax.swing.JFrame;

public class NeuralNetViz extends NeuralNetMnist {
  public static void main(String[] args) throws Exception {
    Class job = Class.forName(Thread.currentThread().getStackTrace()[1].getClassName());
    samples.launchers.CloudLocal.launch(job, 1);
  }

  protected void startTraining(Layer[] ls) {
    //_trainer = new Trainer.MapReduce(ls, 0, self());
    _trainer = new Trainer.Threaded(ls, 0, self());

    // Basic visualization of images and weights
    JFrame frame = new JFrame("H2O");
    frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    MnistCanvas canvas = new MnistCanvas(_trainer);
    frame.setContentPane(canvas.init());
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    //preTrain(ls);
    _trainer.start();
  }
}

Use the threaded version for NN visualization.


import java.io.File;
import org.opensim.modeling.*;

class TestXsensDataReader {
    public static void test_XsensDataReader() {
        XsensDataReaderSettings settings = new XsensDataReaderSettings();
        ExperimentalSensor  nextSensor = new ExperimentalSensor("000_00B421AF", "shank");
        settings.append_ExperimentalSensors(nextSensor);
        settings.set_trial_prefix(0, "MT_012005D6_031-");
        XsensDataReader xsensDataReader = new XsensDataReader(settings);
        StdMapStringAbstractDataTable tables = xsensDataReader.extendRead("");
        TimeSeriesTableVec3 accelTableTyped = XsensDataReader.getLinearAccelerationsTable(tables);
        assert accelTableTyped.getNumRows()    == 3369;
        assert accelTableTyped.getNumColumns() == 1;
        assert accelTableTyped.
               getTableMetaDataString("DataRate").equals("100.000000");
    }

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

import java.io.File;
import org.opensim.modeling.*;

class TestXsensDataReader {
    public static void test_XsensDataReader() {

        // Test creation and population of XsensDataReaderSettings object
        XsensDataReaderSettings settings = new XsensDataReaderSettings();
        ExperimentalSensor  nextSensor = new ExperimentalSensor("000_00B421AF",
            "shank");
        settings.append_ExperimentalSensors(nextSensor);
        settings.set_trial_prefix(0, "MT_012005D6_031-");

        // Test costruct XsensDataReader from a XsensDataReaderSettings object
        XsensDataReader xsensDataReader = new XsensDataReader(settings);
        // Make sure types returned by the xsensDataReader are usable in Java
        StdMapStringAbstractDataTable tables = xsensDataReader.extendRead("");

        // Check that custom accessors are available and return usable types
        // Only spot check of the table is done as actual testing of contents
        // lives in the C++ tests
        TimeSeriesTableVec3 accelTableTyped = XsensDataReader.getLinearAccelerationsTable(tables);
        assert accelTableTyped.getNumRows()    == 3369;
        assert accelTableTyped.getNumColumns() == 1;
        assert accelTableTyped.
               getTableMetaDataString("DataRate").equals("100.000000");
    }

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

Add comments to Java test case to explain what's being tested and why


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

package com.googlesource.gerrit.plugins.codemirror;

import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.gerrit.extensions.restapi.RestApiModule;
import com.google.gerrit.extensions.webui.JavaScriptPlugin;
import com.google.gerrit.extensions.webui.WebUiPlugin;

public class CodemirrorModule extends RestApiModule {
  @Override
  protected void configure() {
    DynamicSet.bind(binder(), WebUiPlugin.class)
        .toInstance(new JavaScriptPlugin("codemirror_editor.html"));
  }
}

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

package com.googlesource.gerrit.plugins.codemirror;

import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.gerrit.extensions.restapi.RestApiModule;
import com.google.gerrit.extensions.webui.JavaScriptPlugin;
import com.google.gerrit.extensions.webui.WebUiPlugin;

public class CodemirrorModule extends RestApiModule {
  @Override
  protected void configure() {
    DynamicSet.bind(binder(), WebUiPlugin.class)
        .toInstance(new JavaScriptPlugin("codemirror_editor.js"));
  }
}

Switch over to loading .js file

Switch over to loading .js file

Gerrit no longer supports html plugins so we have
to use the .js version.

Bug: Issue 14335
Change-Id: Ied8a2ddcd9dcc13e341dd5a108738418631afc30


package com.jeppeman.highlite.test.table;

import com.jeppeman.highlite.PrimaryKey;
import com.jeppeman.highlite.SQLiteColumn;
import com.jeppeman.highlite.SQLiteRelationship;
import com.jeppeman.highlite.SQLiteTable;

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

/**
 * @author jesper
 */
@SQLiteTable(database = TestDatabase.class, autoDeleteColumns = true)
public class TestTable {

    @SQLiteColumn(primaryKey = @PrimaryKey(autoIncrement = true))
    public long id;

    @SQLiteColumn(unique = true)
    public long unique;

    @SQLiteColumn("testFieldName")
    public String testString;

    @SQLiteColumn
    public List<String> testList;

    @SQLiteColumn
    public Boolean testBoolean;

    @SQLiteColumn
    public TestSerializable testSerializable;

    @SQLiteColumn
    public Date testDate;

    @SQLiteColumn
    public int upgradeAddTester;

    @SQLiteRelationship(table = TestTable4.class, backReference = "foreignKey")
    public List<TestTable4> table4Relation;
}

package com.jeppeman.highlite.test.table;

import com.jeppeman.highlite.PrimaryKey;
import com.jeppeman.highlite.SQLiteColumn;
import com.jeppeman.highlite.SQLiteRelationship;
import com.jeppeman.highlite.SQLiteTable;

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

/**
 * @author jesper
 */
@SQLiteTable(database = TestDatabase.class, autoDeleteColumns = true)
public class TestTable {

    @SQLiteColumn(primaryKey = @PrimaryKey(autoIncrement = true))
    public long id;

    @SQLiteColumn(unique = true)
    public long unique;

    @SQLiteColumn("testFieldName")
    public String testString;

    @SQLiteColumn
    public List<String> testList;

    @SQLiteColumn
    public Boolean testBoolean;

    @SQLiteColumn
    public TestSerializable testSerializable;

    @SQLiteColumn
    public Date testDate;

    @SQLiteColumn
    public int upgradeAddTester;

    @SQLiteRelationship(table = TestTable4.class, backReference = "foreignKey")
    public List<TestTable4> table4Relation;

    @SQLiteRelationship(table = TestTable10.class, backReference = "fk1")
    public List<TestTable10> table10rel1;

    @SQLiteRelationship(table = TestTable10.class, backReference = "fk2")
    public List<TestTable10> table10rel2;
}

Add multiple relationships to test classes


package com.adaptionsoft.games.uglytrivia;

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

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.mock;

public class CurrentPlayerTest {

    public static final String PLAYER_ONE = "Thomas";
    public static final String PLAYER_TWO = "Peter";

    private CurrentPlayer currentPlayer;

    @Before
    public void addPlayers() {
        PlayerUi ui = mock(PlayerUi.class);
        Players players = new Players(ui);
        players.add(PLAYER_ONE);
        players.add(PLAYER_TWO);
        currentPlayer = new CurrentPlayer(players);
    }

    @Test
    public void shouldGiveFirstPlayer() {
        assertThat(currentPlayer.getName(), is(PLAYER_ONE));
    }

    @Test
    public void shouldIteratePlayers() {
        currentPlayer.nextPlayer();

        assertThat(currentPlayer.getName(), is(PLAYER_TWO));
    }

    @Test
    public void shouldStartWithFirstPlayerAgain() {
        currentPlayer.nextPlayer();
        currentPlayer.nextPlayer();

        assertThat(currentPlayer.getName(), is(PLAYER_ONE));
    }

}

package com.adaptionsoft.games.uglytrivia;

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

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.mock;

public class CurrentPlayerTest {

    private static final String PLAYER_ONE = "Thomas";
    private static final String PLAYER_TWO = "Peter";

    private CurrentPlayer currentPlayer;

    @Before
    public void addPlayers() {
        PlayerUi ui = mock(PlayerUi.class);
        Players players = new Players(ui);
        players.add(PLAYER_ONE);
        players.add(PLAYER_TWO);
        currentPlayer = new CurrentPlayer(players);
    }

    @Test
    public void shouldGiveFirstPlayer() {
        assertThat(currentPlayer.getName(), is(PLAYER_ONE));
    }

    @Test
    public void shouldIteratePlayers() {
        currentPlayer.nextPlayer();

        assertThat(currentPlayer.getName(), is(PLAYER_TWO));
    }

    @Test
    public void shouldStartWithFirstPlayerAgain() {
        currentPlayer.nextPlayer();
        currentPlayer.nextPlayer();

        assertThat(currentPlayer.getName(), is(PLAYER_ONE));
    }

}

Reduce visibility (as proposed by inspection).


package com.thoughtworks.xstream.core;

import com.thoughtworks.acceptance.AbstractAcceptanceTest;
import com.thoughtworks.xstream.XStream;

public class TreeMarshallerTest extends AbstractAcceptanceTest {

    class Thing {
        Thing thing;
    }

    protected void setUp() throws Exception {
        super.setUp();
        xstream.setMode(XStream.NO_REFERENCES);
    }

    public void testThrowsExceptionWhenDetectingCircularReferences() {
        Thing a = new Thing();
        Thing b = new Thing();
        a.thing = b;
        b.thing = a;

        try {
            xstream.toXML(a);
            fail("expected exception");
        } catch (TreeMarshaller.CircularReferenceException expected) {
            // good
        }
    }
}

package com.thoughtworks.xstream.core;

import com.thoughtworks.acceptance.AbstractAcceptanceTest;
import com.thoughtworks.xstream.XStream;

public class TreeMarshallerTest extends AbstractAcceptanceTest {

    static class Thing {
        Thing thing;
    }

    protected void setUp() throws Exception {
        super.setUp();
        xstream.setMode(XStream.NO_REFERENCES);
    }

    public void testThrowsExceptionWhenDetectingCircularReferences() {
        Thing a = new Thing();
        Thing b = new Thing();
        a.thing = b;
        b.thing = a;

        try {
            xstream.toXML(a);
            fail("expected exception");
        } catch (TreeMarshaller.CircularReferenceException expected) {
            // good
        }
    }
}

Fix unit test for JDK 1.3.

Fix unit test for JDK 1.3.

git-svn-id: fe6d842192ccfb78748eb71580d1ce65f168b559@701 9830eeb5-ddf4-0310-9ef7-f4b9a3e3227e


package <%=packageName%>.security;

/**
 * Constants for Spring Security authorities.
 */
public final class AuthoritiesConstants {

    private AuthoritiesConstants() {
    }

    public static final String ADMIN = "ROLE_ADMIN";

    public static final String USER = "ROLE_USER";

    public static final String ANONYMOUS = "ROLE_ANONYMOUS";
}

package <%=packageName%>.security;

/**
 * Constants for Spring Security authorities.
 */
public final class AuthoritiesConstants {

    public static final String ADMIN = "ROLE_ADMIN";

    public static final String USER = "ROLE_USER";

    public static final String ANONYMOUS = "ROLE_ANONYMOUS";

    private AuthoritiesConstants() {
    }
}

Move constructor after the public fields


package org.nwapw.abacus.number;

public abstract class Function {

    public int arity;

    protected abstract Number applyInternal(Number...params);

    public Number apply(Number...params) throws IllegalArgumentException {
        if(params.length != arity)
            throw new IllegalArgumentException("Invalid number of arguments: Function takes "
                    + arity + ", " + params.length + " provided.");
        return applyInternal(params);
    }

}

package org.nwapw.abacus.number;

public abstract class Function {

    protected abstract boolean matchesParams(Number[] params);
    protected abstract Number applyInternal(Number[] params);

    public Number apply(Number...params) {
        if(!matchesParams(params)) return null;
        return applyInternal(params);
    }

}

Change function to return null on error, and change arity checks.


/*
 * Copyright 2020, 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.code.gen.java;

import com.squareup.javapoet.MethodSpec;

import static javax.lang.model.element.Modifier.PRIVATE;

public final class EmptyPrivateCtor {

    private static final MethodSpec PRIVATE_CTOR = privateCtorSpec();

    private EmptyPrivateCtor() {
    }

    public static MethodSpec spec() {
        return PRIVATE_CTOR;
    }

    private static MethodSpec privateCtorSpec() {
        MethodSpec result = MethodSpec
                .constructorBuilder()
                .addModifiers(PRIVATE)
                .build();
        return result;
    }
}

/*
 * Copyright 2020, 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.code.gen.java;

import com.squareup.javapoet.MethodSpec;

import static javax.lang.model.element.Modifier.PRIVATE;

public final class EmptyPrivateCtor {

    private static final MethodSpec PRIVATE_CTOR = privateCtorSpec();

    private EmptyPrivateCtor() {
    }

    public static MethodSpec spec() {
        return PRIVATE_CTOR;
    }

    private static MethodSpec privateCtorSpec() {
        MethodSpec result = MethodSpec
                .constructorBuilder()
                .addModifiers(PRIVATE)
                .addJavadoc("Prevents instantiation of this class.")
                .build();
        return result;
    }
}

Add Javadoc to the generated private c-tor


package com.kduda.battleships;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

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

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("views/battleshipsScene.fxml"));
        setUserAgentStylesheet(STYLESHEET_CASPIAN);
        primaryStage.setTitle("Battleships");
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }
}

package com.kduda.battleships;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

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

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("views/battleshipsScene.fxml"));
//        setUserAgentStylesheet(STYLESHEET_CASPIAN);
        primaryStage.setTitle("Battleships");
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }
}

Change to default look and feel

Change to default look and feel


package pl.mbaleczny.instalike.dagger.domain;

import dagger.Component;
import pl.mbaleczny.instalike.dagger.app.AppComponent;
import pl.mbaleczny.instalike.dagger.scope.DomainScope;
import pl.mbaleczny.instalike.util.scheduler.BaseSchedulerProvider;

@DomainScope
@Component(dependencies = AppComponent.class, modules = DomainModule.class)
public interface DomainComponent {

    BaseSchedulerProvider scheduler();
}

package pl.mbaleczny.instalike.dagger.domain;

import dagger.Component;
import pl.mbaleczny.instalike.dagger.app.AppComponent;
import pl.mbaleczny.instalike.dagger.scope.DomainScope;
import pl.mbaleczny.instalike.domain.DataSource;

@DomainScope
@Component(dependencies = AppComponent.class, modules = DomainModule.class)
public interface DomainComponent {

    DataSource dataSource();
}

Swap scheduler method with dataSource

Swap scheduler method with dataSource


package br.com.nossolixo.nossolixo.services;

import java.util.List;

import br.com.nossolixo.nossolixo.models.Place;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

public interface PlaceService {
    @GET("places")
    Call<List<Place>> listPlaces();

    @GET("places")
    Call<List<Place>> listPlacesByCategory(@Query("category") String category);
}

package br.com.nossolixo.nossolixo.services;

import java.util.List;

import br.com.nossolixo.nossolixo.models.Place;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;

public interface PlaceService {
    @GET("places")
    Call<List<Place>> listPlaces();

    @GET("places")
    Call<List<Place>> listPlacesByCategory(@Query("category") String category);

    @GET("place/{id}")
    Call<Place> find(@Path("id") String placeId);
}

Add method to find a place

Add method to find a place


/*
 * 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.logging.log4j.spi;

import java.io.Closeable;

/**
 * A basic registry for {@link LoggerContext} objects and their associated external
 * Logger classes. This registry should not be used for Log4j Loggers; it is instead used for creating bridges to
 * other external log systems.
 *
 * @param <L> the external logger class for this registry (e.g., {@code org.slf4j.Logger})
 * @since 2.1
 */
public interface LoggerAdapter<L> extends Closeable {

    /**
     * Gets a named logger. Implementations should defer to the abstract methods in {@link AbstractLoggerAdapter}.
     *
     * @param name the name of the logger to get
     * @return the named logger
     */
    L getLogger(String name);
}

/*
 * 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.logging.log4j.spi;

import java.io.Closeable;

/**
 * A basic registry for {@link LoggerContext} objects and their associated external
 * Logger classes. This registry should not be used for Log4j Loggers; it is instead used for creating bridges to
 * other external log systems.
 *
 * @param <T> the external logger class for this registry (e.g., {@code org.slf4j.Logger})
 * @since 2.1
 */
public interface LoggerAdapter<T> extends Closeable {

    /**
     * Gets a named logger. Implementations should defer to the abstract methods in {@link AbstractLoggerAdapter}.
     *
     * @param name the name of the logger to get
     * @return the named logger
     */
    T getLogger(String name);
}

Use the more common type name T instead of L.


package org.metaborg.meta.nabl2.solver;

import java.io.Serializable;
import java.util.Map;

import com.google.common.collect.Maps;

public class Fresh implements Serializable {

    private static final long serialVersionUID = 42L;

    private final Map<String,Integer> counters;

    public Fresh() {
        counters = Maps.newConcurrentMap();
    }

    public String fresh(String base) {
        // to prevent accidental name clashes, ensure the base contains no dashes,
        // and then use dashes as our connecting character.
        base = base.replaceAll("-", "_");
        int k = counters.getOrDefault(base, 0) + 1;
        counters.put(base, k);
        return base + "-" + k;
    }

    public void reset() {
        counters.clear();
    }

}

package org.metaborg.meta.nabl2.solver;

import java.io.Serializable;
import java.util.Map;

import com.google.common.collect.Maps;

public class Fresh implements Serializable {

    private static final long serialVersionUID = 42L;

    private final Map<String,Integer> counters;

    public Fresh() {
        counters = Maps.newConcurrentMap();
    }

    public String fresh(String base) {
        // remove any number suffix from the base
        base = base.replaceFirst("-[0-9]+$", "");
        // to prevent accidental name clashes, ensure the base contains no dashes,
        // and then use dashes as our connecting character.
        base = base.replaceAll("-", "_");
        int k = counters.getOrDefault(base, 0) + 1;
        counters.put(base, k);
        return base + "-" + k;
    }

    public void reset() {
        counters.clear();
    }

}

Remove trailing numbers from base.

Remove trailing numbers from base.


package com.google.sps.data;

public class Invariants {
  private float minCredits;
  private float maxCredits;

  public Invariants(float minCredits, float maxCredits){
    this.minCredits = minCredits;
    this.maxCredits = maxCredits;
  }

  public float getMinCredits(){
    return this.minCredits;
  }

  public float getMaxCredits(){
    return this.maxCredits;
  }
}

package com.google.sps.data;

public class Invariants {
  private float minCredits;
  private float maxCredits;

  public Invariants(float minCredits, float maxCredits) {
    this.minCredits = minCredits;
    this.maxCredits = maxCredits;
  }

  public float getMinCredits() {
    return this.minCredits;
  }

  public float getMaxCredits() {
    return this.maxCredits;
  }
}

Add newline re: comments and add whitespace before "{" chars


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

package com.google.gcloud;

/**
 * Base service exception.
 */
public class BaseServiceException extends RuntimeException {

  private static final long serialVersionUID = 5028833760039966178L;

  private final int code;
  private final boolean retryable;

  public BaseServiceException(int code, String message, boolean retryable) {
    super(message);
    this.code = code;
    this.retryable = retryable;
  }

  public BaseServiceException(int code, String message, boolean retryable, Exception cause) {
    super(message, cause);
    this.code = code;
    this.retryable = retryable;
  }

  /**
   * Returns the code associated with this exception.
   */
  public int code() {
    return code;
  }

  public boolean retryable() {
    return retryable;
  }
}

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

package com.google.gcloud;

/**
 * Base class for all service exceptions.
 */
public class BaseServiceException extends RuntimeException {

  private static final long serialVersionUID = 5028833760039966178L;

  private final int code;
  private final boolean retryable;

  public BaseServiceException(int code, String message, boolean retryable) {
    super(message);
    this.code = code;
    this.retryable = retryable;
  }

  public BaseServiceException(int code, String message, boolean retryable, Exception cause) {
    super(message, cause);
    this.code = code;
    this.retryable = retryable;
  }

  /**
   * Returns the code associated with this exception.
   */
  public int code() {
    return code;
  }

  /**
   * Returns {@code true} when it is safe to retry the operation that caused this exception.
   */
  public boolean retryable() {
    return retryable;
  }
}

Rename enum, fix docs, and make accessors package private


package nl.homeserver.energie;

import static java.math.RoundingMode.HALF_UP;

import java.math.BigDecimal;

import lombok.Getter;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
public class VerbruikKosten {

    private static final int KOSTEN_SCALE = 3;

    @Getter
    private final BigDecimal verbruik;

    private final BigDecimal kosten;

    public static final VerbruikKosten UNKNOWN = new VerbruikKosten(null, null);

    public BigDecimal getKosten() {
        if (kosten == null) {
            return null;
        }
        return kosten.setScale(KOSTEN_SCALE, HALF_UP);
    }
}

package nl.homeserver.energie;

import static java.math.RoundingMode.HALF_UP;

import java.math.BigDecimal;

import javax.annotation.Nullable;

import lombok.Getter;

class VerbruikKosten {

    private static final int KOSTEN_SCALE = 3;

    @Getter
    private final BigDecimal verbruik;

    private final BigDecimal kosten;

    static final VerbruikKosten UNKNOWN = new VerbruikKosten(null, null);

    VerbruikKosten(@Nullable final BigDecimal verbruik, @Nullable final BigDecimal kosten) {
        this.verbruik = verbruik;
        this.kosten = kosten;
    }

    BigDecimal getKosten() {
        if (kosten == null) {
            return null;
        }
        return kosten.setScale(KOSTEN_SCALE, HALF_UP);
    }
}

Fix issues found by SonarCloud

Fix issues found by SonarCloud


package com.spotify.jni;

public class ClassWrapperTest {
    static {
        System.loadLibrary("JniHelpersTest");
    }
}

package com.spotify.jni;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class ClassWrapperTest {
    static {
        System.loadLibrary("JniHelpersTest");
    }

    static final double TEST_FLOAT_TOLERANCE = 0.01;

    @Test
    native public void createClassWrapper() throws Exception;

    @Test
    native public void getCanonicalName() throws Exception;

    @Test
    native public void getSimpleName() throws Exception;

    @Test
    native public void merge() throws Exception;

    native public void nativeSetJavaObject(TestObject object);
    @Test
    public void setJavaObject() throws Exception {
        TestObject object = new TestObject("hello", 1, 3.14f);
        nativeSetJavaObject(object);
    }

    native public TestObject nativeToJavaObject();
    @Test
    public void toJavaObject() throws Exception {
        TestObject object = nativeToJavaObject();
        assertEquals("hello", object.s);
        assertEquals(1, object.i);
        assertEquals(3.14, object.f, TEST_FLOAT_TOLERANCE);
    }

    @Test
    native public void getCachedMethod() throws Exception;

    @Test
    native public void getCachedField() throws Exception;
}

Add test cases for ClassWrapper

Add test cases for ClassWrapper


package com.johnstarich.ee461l;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Handles all requests sent to the root ("/") of this server.
 * Created by johnstarich on 1/30/16.
 */
public class RootServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		response.setContentType("text/html; charset=utf-8");
		response.setStatus(HttpServletResponse.SC_OK);
		response.getWriter().println("
Hey there!

This is our EE461L design project

This is the request path we received: " + request.getPathInfo() + "
");
	}
}

package com.johnstarich.ee461l;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Handles all requests sent to the root ("/") of this server.
 * Created by johnstarich on 1/30/16.
 */
public class RootServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		response.setContentType("text/html; charset=utf-8");
		response.setStatus(HttpServletResponse.SC_OK);
		response.getWriter().println("
Hey there!

This is our EE461L design project

This is the request path we received: " + request.getPathInfo() + "
");
		System.out.println("Request was = GET " + request.getPathInfo());
	}
}

Add print statement for request URL

Add print statement for request URL


package org.hildan.fx.components;

import java.util.function.Predicate;

import javafx.scene.control.cell.TextFieldListCell;
import javafx.util.StringConverter;

import org.hildan.fxlog.themes.Css;

public class ValidatingTextFieldListCell<T> extends TextFieldListCell<T> {

    private final Predicate<String> validator;

    public ValidatingTextFieldListCell(StringConverter<T> converter, Predicate<String> validator) {
        super(converter);
        this.validator = validator;
    }

    public void commitEdit(T item) {
        if (!isEditing()) {
            return;
        }
        boolean itemIsValid = validator.test(getText());
        pseudoClassStateChanged(Css.INVALID, !itemIsValid);
        if (itemIsValid) {
            // only commit if the item is valid, otherwise we stay in edit state
            super.commitEdit(item);
        }
    }
}

package org.hildan.fx.components;

import java.util.function.Predicate;

import javafx.scene.control.*;
import javafx.scene.control.cell.TextFieldListCell;
import javafx.util.StringConverter;

import org.hildan.fxlog.themes.Css;

public class ValidatingTextFieldListCell<T> extends TextFieldListCell<T> {

    private final Predicate<String> validator;

    public ValidatingTextFieldListCell(StringConverter<T> converter, Predicate<String> validator) {
        super(converter);
        this.validator = validator;
    }

    public void commitEdit(T item) {
        if (!isEditing()) {
            return;
        }

        // the edited text is not in getText() but in the TextField used as Graphic for this cell
        TextField textField = (TextField) getGraphic();
        String editedText = textField.getText();

        boolean itemIsValid = validator.test(editedText);
        pseudoClassStateChanged(Css.INVALID, !itemIsValid);
        if (itemIsValid) {
            // only commit if the item is valid, otherwise we stay in edit state
            super.commitEdit(item);
        }
    }
}

Fix ValidatedTextFieldListCell to use the actual edited text


package org.oskari.admin.model;

import java.util.Map;

/**
 * Used as ouput data model for layers in the admin UI.
 */
public class MapLayerAdminOutput extends MapLayer {

    private Map<String, Object> capabilities;

    public Map<String, Object> getCapabilities() {
        return capabilities;
    }

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

package org.oskari.admin.model;

import java.util.Map;

/**
 * Used as ouput data model for layers in the admin UI.
 */
public class MapLayerAdminOutput extends MapLayer {

    private String warn;
    private Map<String, Object> capabilities;

    public Map<String, Object> getCapabilities() {
        return capabilities;
    }

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

    /**
     * Possible warning message that capabilities coulnt' be updated
     * @return
     */
    public String getWarn() {
        return warn;
    }

    public void setWarn(String warn) {
        this.warn = warn;
    }
}

Add placeholder for possible warning for frontend


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

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class GuavaUtilsTest {
  @Test
  public static void testToImmutableSet() {
    assertEquals(
        ImmutableSet.of("b", "c", "a"),
        ImmutableList.of("a", "b", "c").stream().collect(GuavaUtils.toImmutableSet()));
  }
}

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

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class GuavaUtilsTest {
  @Test
  public void testToImmutableSet() {
    assertEquals(
        ImmutableSet.of("b", "c", "a"),
        ImmutableList.of("a", "b", "c").stream().collect(GuavaUtils.toImmutableSet()));
  }
}

Remove static modifier from test case.

Remove static modifier from test case.

Remove static modifier from test case, which was introduced in the
last revision to https://reviews.apache.org/r/35842/

This fixes

[ant:checkstyle]
/home/ksweeney/workspace/aurora/src/test/java/org/apache/aurora/GuavaUtilsTest.java:23:1:
Utility classes should not have a public or default constructor.

Testing Done:
./gradlew -Pq build

Reviewed at https://reviews.apache.org/r/35886/


package com.jakewharton.trakt;

import junit.framework.TestCase;

public abstract class BaseTestCase extends TestCase {
	private final ServiceManager manager = new ServiceManager();

	@Override
	public void setUp() {
		manager.setApiKey("de8bc5e9866c77d655310bb0c8ab9a83");
	}

	protected final ServiceManager getManager() {
		return manager;
	}
}

package com.jakewharton.trakt;

import junit.framework.TestCase;

public abstract class BaseTestCase extends TestCase {
	private final ServiceManager manager = new ServiceManager();

	@Override
	public void setUp() {
		manager.setApiKey("de8bc5e9866c77d655310bb0c8ab9a83");
		manager.setAuthentication("trakt-java", "e00e0e31fe07213b59e5784c9942cfe220771827");
	}

	protected final ServiceManager getManager() {
		return manager;
	}
}

Add authentication for our test user.

Add authentication for our test user.


package name.abuchen.portfolio.ui.views.dashboard;

import java.util.List;

import com.ibm.icu.text.MessageFormat;

import name.abuchen.portfolio.model.Dashboard.Widget;
import name.abuchen.portfolio.snapshot.trades.Trade;
import name.abuchen.portfolio.ui.views.trades.TradeDetailsView;
import name.abuchen.portfolio.util.TextUtil;

public class TradesWidget extends AbstractTradesWidget
{
    public TradesWidget(Widget widget, DashboardData dashboardData)
    {
        super(widget, dashboardData);
    }

    @Override
    public void update(TradeDetailsView.Input input)
    {
        this.title.setText(TextUtil.tooltip(getWidget().getLabel()));

        List<Trade> trades = input.getTrades();
        long positive = trades.stream().filter(t -> t.getIRR() > 0).count();
        String text = MessageFormat.format("{0} <green>↑{1}</green> <red>↓{2}</red>", //$NON-NLS-1$
                        trades.size(), positive, trades.size() - positive);

        this.indicator.setText(text);
    }
}

package name.abuchen.portfolio.ui.views.dashboard;

import java.util.List;

import com.ibm.icu.text.MessageFormat;

import name.abuchen.portfolio.model.Dashboard.Widget;
import name.abuchen.portfolio.snapshot.trades.Trade;
import name.abuchen.portfolio.ui.views.trades.TradeDetailsView;
import name.abuchen.portfolio.util.TextUtil;

public class TradesWidget extends AbstractTradesWidget
{
    public TradesWidget(Widget widget, DashboardData dashboardData)
    {
        super(widget, dashboardData);
    }

    @Override
    public void update(TradeDetailsView.Input input)
    {
        this.title.setText(TextUtil.tooltip(getWidget().getLabel()));

        List<Trade> trades = input.getTrades();
        long positive = trades.stream().filter(t -> t.getProfitLoss().isPositive()).count();
        String text = MessageFormat.format("{0} <green>↑{1}</green> <red>↓{2}</red>", //$NON-NLS-1$
                        trades.size(), positive, trades.size() - positive);

        this.indicator.setText(text);
    }
}

Fix Trades Widget to count by isPositive rather than IRR


package edu.northwestern.bioinformatics.studycalendar.web;

import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import org.springframework.mock.web.MockServletContext;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

/**
 * @author Rhett Sutphin
 */
public class WebTestCase extends StudyCalendarTestCase {
    protected MockHttpServletRequest request;
    protected MockHttpServletResponse response;
    protected MockServletContext servletContext;
    protected MockHttpSession session;

    protected void setUp() throws Exception {
        super.setUp();
        servletContext = new MockServletContext();
        session = new MockHttpSession(servletContext);
        request = new MockHttpServletRequest(servletContext);
        request.setMethod("POST");
        request.setSession(session);
        response = new MockHttpServletResponse();
    }
}

package edu.northwestern.bioinformatics.studycalendar.web;

import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import org.springframework.mock.web.MockServletContext;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

/**
 * @author Rhett Sutphin
 */
public abstract class WebTestCase extends StudyCalendarTestCase {
    protected MockHttpServletRequest request;
    protected MockHttpServletResponse response;
    protected MockServletContext servletContext;
    protected MockHttpSession session;

    protected void setUp() throws Exception {
        super.setUp();
        servletContext = new MockServletContext();
        session = new MockHttpSession(servletContext);
        request = new MockHttpServletRequest(servletContext);
        request.setMethod("POST");
        request.setSession(session);
        response = new MockHttpServletResponse();
    }
}

Mark abstract since it isn't separately runnable


package cucumber.examples.java.calculator;

import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
public class RunCukesTest {
}

package cucumber.examples.java.calculator;

import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@Cucumber.Options(format = "json:target/cucumber-report.json")
public class RunCukesTest {
}

Enable JSON formater for a little bit of regression testing


/*
  Copyright 2016, Google, Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package com.example.storage;

// [START storage_quickstart]
// Imports the Google Cloud client library
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    Storage storage = StorageOptions.defaultInstance().service();

    // The name for the new bucket
    String bucketName = args[0];

    // Creates the new bucket
    Bucket bucket = storage.create(BucketInfo.of(bucketName));

    System.out.printf("Bucket %s created.%n", bucket.name());
  }
}
// [END storage_quickstart]

/*
  Copyright 2016, Google, Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package com.example.storage;

// [START storage_quickstart]
// Imports the Google Cloud client library
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    Storage storage = StorageOptions.defaultInstance().service();

    // The name for the new bucket
    String bucketName = args[0];  // "my-new-bucket";

    // Creates the new bucket
    Bucket bucket = storage.create(BucketInfo.of(bucketName));

    System.out.printf("Bucket %s created.%n", bucket.name());
  }
}
// [END storage_quickstart]

Add system tests to Translate sample.

Add system tests to Translate sample.


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

package org.xdi.oxauth.load.benchmark;

import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;

/**
 * @author Yuriy Movchan
 * @version 0.1, 03/17/2015
 */
public class BenchmarkTestListener implements ITestListener {

	@Override
	public void onTestStart(ITestResult result) {
	}

	@Override
	public void onTestSuccess(ITestResult result) {
	}

	@Override
	public void onTestFailure(ITestResult result) {
	}

	@Override
	public void onTestSkipped(ITestResult result) {
	}

	@Override
	public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
	}

	@Override
	public void onStart(ITestContext context) {
        System.out.println("Test '" + context.getName() + "' started ...");
	}

	@Override
	public void onFinish(ITestContext context) {
        final long takes = (context.getEndDate().getTime() - context.getStartDate().getTime()) / 1000;
        System.out.println("Suite '" + context.getName() + "' finished in " + takes + " seconds");
	}
}

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

package org.xdi.oxauth.load.benchmark;

import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;

/**
 * @author Yuriy Movchan
 * @version 0.1, 03/17/2015
 */
public class BenchmarkTestListener implements ITestListener {

	@Override
	public void onTestStart(ITestResult result) {
	}

	@Override
	public void onTestSuccess(ITestResult result) {
	}

	@Override
	public void onTestFailure(ITestResult result) {
	}

	@Override
	public void onTestSkipped(ITestResult result) {
	}

	@Override
	public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
	}

	@Override
	public void onStart(ITestContext context) {
        System.out.println("Test '" + context.getName() + "' started ...");
	}

	@Override
	public void onFinish(ITestContext context) {
        final long takes = (context.getEndDate().getTime() - context.getStartDate().getTime()) / 1000;
        System.out.println("Test '" + context.getName() + "' finished in " + takes + " seconds");
	}
}

Fix benchmark test listener comment

Fix benchmark test listener comment


package org.gem.log;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

import org.junit.Test;

import static org.junit.Assert.assertThat;

import static org.junit.matchers.JUnitMatchers.*;

import static org.hamcrest.CoreMatchers.*;

public class AMQPAppenderTest {
    private DummyChannel dummyChannel;
    private DummyAppender dummyAppender;
    private Logger logger = Logger.getLogger(AMQPAppenderTest.class);

    void tearDown() {
        dummyChannel = null;
        dummyAppender = null;

        // this closes the RabbitMQ connections
        BasicConfigurator.resetConfiguration();
    }

    private void setUpDummyAppender() {
        dummyAppender = new DummyAppender();
        dummyAppender.setLayout(new PatternLayout());

        BasicConfigurator.configure(dummyAppender);
    }

    @Test
    public void basicLogging() {
        setUpDummyAppender();

        logger.info("Test");

        dummyChannel = (DummyChannel) dummyAppender.getChannel();

        assertThat(dummyChannel.entries.size(), is(equalTo(1)));

        DummyChannel.Entry entry = dummyChannel.entries.get(0);

        assertThat(entry.exchange, is(equalTo("")));
        assertThat(entry.routingKey, is(equalTo("")));
        assertThat(entry.properties.getType(), is(equalTo("INFO")));
        assertThat(entry.body, is(equalTo("Test\n")));
    }
}

package org.gem.log;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

import org.junit.Test;

import static org.junit.Assert.assertThat;

import static org.junit.matchers.JUnitMatchers.*;

import static org.hamcrest.CoreMatchers.*;

public class AMQPAppenderTest {
    private DummyChannel dummyChannel;
    private DummyAppender dummyAppender;
    private Logger logger = Logger.getLogger(AMQPAppenderTest.class);

    void tearDown() {
        dummyChannel = null;
        dummyAppender = null;

        // this closes the RabbitMQ connections
        BasicConfigurator.resetConfiguration();
    }

    private void setUpDummyAppender() {
        dummyAppender = new DummyAppender();
        dummyAppender.setLayout(new PatternLayout());

        BasicConfigurator.configure(dummyAppender);
    }

    @Test
    public void basicLogging() {
        setUpDummyAppender();

        logger.info("Test1");
        logger.warn("Test2");

        dummyChannel = (DummyChannel) dummyAppender.getChannel();

        assertThat(dummyChannel.entries.size(), is(equalTo(2)));

        DummyChannel.Entry entry1 = dummyChannel.entries.get(0);

        assertThat(entry1.exchange, is(equalTo("")));
        assertThat(entry1.routingKey, is(equalTo("")));
        assertThat(entry1.properties.getType(), is(equalTo("INFO")));
        assertThat(entry1.body, is(equalTo("Test1\n")));

        DummyChannel.Entry entry2 = dummyChannel.entries.get(1);

        assertThat(entry2.exchange, is(equalTo("")));
        assertThat(entry2.routingKey, is(equalTo("")));
        assertThat(entry2.properties.getType(), is(equalTo("WARN")));
        assertThat(entry2.body, is(equalTo("Test2\n")));
    }
}

Test that .info() and .warn() set the correct event type.


package org.jboss.loom.migrators._ext;

import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
import org.eclipse.persistence.oxm.annotations.XmlDiscriminatorNode;
import org.eclipse.persistence.oxm.annotations.XmlLocation;
import org.xml.sax.Locator;

/**
 *  Serves as a common base for all stackable items which contain each other.
 *
 *  @author Ondrej Zizka, ozizka at redhat.com
 */
@XmlDiscriminatorNode("@type")
public class ContainerOfStackableDefs {

    @XmlElement
    public String filter;   // A Groovy expression to filter the items.

    @XmlElement
    public String warning;  // Warning to add to the current action.

    @XmlElement(name = "action")
    List<MigratorDefinition.ActionDef> actionDefs;

    @XmlElement(name = "forEach")
    List<MigratorDefinition.ForEachDef> forEachDefs;

    @XmlLocation
    @XmlTransient
    public Locator location;

    public boolean hasForEachDefs(){ return forEachDefs != null && ! forEachDefs.isEmpty(); }
    public List<MigratorDefinition.ForEachDef> getForEachDefs() { return forEachDefs; }

    public boolean hasActionDefs(){ return actionDefs != null && ! actionDefs.isEmpty(); };
    public List<MigratorDefinition.ActionDef> getActionDefs() { return actionDefs; }

}// class

package org.jboss.loom.migrators._ext;

import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
import org.eclipse.persistence.oxm.annotations.XmlDiscriminatorNode;
import org.eclipse.persistence.oxm.annotations.XmlLocation;
import org.xml.sax.Locator;

/**
 *  Serves as a common base for all stackable items which contain each other.
 *
 *  @author Ondrej Zizka, ozizka at redhat.com
 */
@XmlDiscriminatorNode("@type")
public class ContainerOfStackableDefs {

    @XmlElement
    public String filter;   // A Groovy expression to filter the items.

    @XmlElement
    public String warning;  // Warning to add to the current action.

    @XmlElement(name = "action")
    List<MigratorDefinition.ActionDef> actionDefs;

    @XmlElement(name = "forEach")
    List<MigratorDefinition.ForEachDef> forEachDefs;

    //@XmlLocation
    //@XmlTransient
    //public Locator location;

    public boolean hasForEachDefs(){ return forEachDefs != null && ! forEachDefs.isEmpty(); }
    public List<MigratorDefinition.ForEachDef> getForEachDefs() { return forEachDefs; }

    public boolean hasActionDefs(){ return actionDefs != null && ! actionDefs.isEmpty(); };
    public List<MigratorDefinition.ActionDef> getActionDefs() { return actionDefs; }

}// class

Comment out @XmlLocation as we load it using Node acquired by XSLT.


package org.jboss.weld.tests.ejb;

import javax.ejb.Stateless;
import javax.inject.Inject;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(Arquillian.class)
public class EJBCallTest {
	@Deployment
	public static JavaArchive createTestArchive() {
		return ShrinkWrap
				.create(JavaArchive.class, "test.jar")
				.addAsManifestResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml"));
	}

	@Stateless
	public static class SomeService {
		public String someMethod() {
			return "test";
		}
	}

	@Inject
	SomeService someService;

	@Test
	public void testStatelessCall() {
		Assert.assertEquals("test", someService.someMethod());
	}
}

package org.jboss.weld.tests.ejb;

import javax.ejb.Stateless;
import javax.inject.Inject;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(Arquillian.class)
public class EJBCallTest {
	@Deployment
	public static JavaArchive createTestArchive() {
		return ShrinkWrap
				.create(JavaArchive.class, "test.jar")
				.addAsManifestResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml"));
	}

	@Stateless
	public static class SomeService {
		public String someMethod() {
			return "test";
		}
	}

	@Inject
	SomeService someService;

	@Test
	@Ignore("WELD-1086")
	public void testStatelessCall() {
		Assert.assertEquals("test", someService.someMethod());
	}
}

Exclude the test for WELD-1086 temporarily


package com.akexorcist.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

package com.akexorcist.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

Use constrain layout in activity

Use constrain layout in activity


package com.hubspot.singularity.data;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.utils.ZKPaths;

import com.codahale.metrics.MetricRegistry;
import com.google.common.base.Optional;
import com.google.inject.Inject;
import com.hubspot.singularity.SingularityUserSettings;
import com.hubspot.singularity.config.SingularityConfiguration;
import com.hubspot.singularity.data.transcoders.Transcoder;

public class UserManager extends CuratorManager {

  private final Transcoder<SingularityUserSettings> settingsTranscoder;

  private static final String USER_ROOT = "/users";

  private static final String SETTINGS_ROOT = USER_ROOT + "/settings";

  @Inject
  public UserManager(CuratorFramework curator, SingularityConfiguration configuration, MetricRegistry metricRegistry,
                     Transcoder<SingularityUserSettings> settingsTranscoder) {
    super(curator, configuration, metricRegistry);
    this.settingsTranscoder = settingsTranscoder;
  }

  private String getUserSettingsPath(String id) {
    return ZKPaths.makePath(SETTINGS_ROOT, id);
  }

  public void deleteUserSettings(String id) {
    delete(getUserSettingsPath(id));
  }

  public Optional<SingularityUserSettings> getUserSettings(String id) {
    return getData(getUserSettingsPath(id), settingsTranscoder);
  }

  public void updateUserSettings(String id, SingularityUserSettings userSettings) {
    save(getUserSettingsPath(id), userSettings, settingsTranscoder);
  }

}

package com.hubspot.singularity.data;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.utils.ZKPaths;

import com.codahale.metrics.MetricRegistry;
import com.google.common.base.Optional;
import com.google.inject.Inject;
import com.hubspot.singularity.SingularityUserSettings;
import com.hubspot.singularity.config.SingularityConfiguration;
import com.hubspot.singularity.data.transcoders.Transcoder;

public class UserManager extends CuratorManager {

  private final Transcoder<SingularityUserSettings> settingsTranscoder;

  private static final String USER_ROOT = "/users";

  private static final String SETTINGS_ROOT = USER_ROOT + "/settings";

  @Inject
  public UserManager(CuratorFramework curator, SingularityConfiguration configuration, MetricRegistry metricRegistry,
                     Transcoder<SingularityUserSettings> settingsTranscoder) {
    super(curator, configuration, metricRegistry);
    this.settingsTranscoder = settingsTranscoder;
  }

  private String getUserSettingsPath(String id) {
    return ZKPaths.makePath(SETTINGS_ROOT, id);
  }

  public void updateUserSettings(String id, SingularityUserSettings userSettings) {
    save(getUserSettingsPath(id), userSettings, settingsTranscoder);
  }

  public Optional<SingularityUserSettings> getUserSettings(String id) {
    return getData(getUserSettingsPath(id), settingsTranscoder);
  }

  public void deleteUserSettings(String id) {
    delete(getUserSettingsPath(id));
  }

}

Reorder UserSettings ZK methods more sensibly


package org.wikipedia.feed.aggregated;

import android.support.annotation.NonNull;

import org.wikipedia.feed.model.CardPageItem;
import org.wikipedia.feed.mostread.MostReadArticles;

public class AggregatedFeedContent {
    @SuppressWarnings("NullableProblems") @NonNull private CardPageItem tfa;
    @SuppressWarnings("NullableProblems") @NonNull private MostReadArticles mostread;
    @SuppressWarnings("NullableProblems") @NonNull private CardPageItem random;

    public CardPageItem tfa() {
        return tfa;
    }

    public MostReadArticles mostRead() {
        return mostread;
    }
}

package org.wikipedia.feed.aggregated;

import android.support.annotation.NonNull;

import org.wikipedia.feed.model.CardPageItem;

public class AggregatedFeedContent {
    @SuppressWarnings("NullableProblems") @NonNull private CardPageItem tfa;
    @SuppressWarnings("NullableProblems") @NonNull private CardPageItem random;

    public CardPageItem tfa() {
        return tfa;
    }
}

Remove most-read field from aggregated content model

This is unused, since we get most-read results from MostReadClient.

We can put it back in if and when we move to using the most-read results
from the aggregated response.

Change-Id: I0f31d1b9a6dd772f9c997ae17bfa18dfdbd8c310


package pt.fccn.saw.selenium;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by mehmetgerceker on 12/7/15.
 */
public class RetryRule implements TestRule {

    private AtomicInteger retryCount;

    public RetryRule(int retries){
        super();
        this.retryCount = new AtomicInteger(retries);
    }

    @Override
    public Statement apply(final Statement base, final Description description) {
        //statement is a private method which will return a new statement
        //here Statement is taken as abstract for your test which includes test method and before/after methods )
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                System.out.println("Evaluating retry ...");
                Throwable caughtThrowable = null;

                // implement retry logic here
                while (retryCount.getAndDecrement() > 0) {
                    try {
                        base.evaluate();
                        return;
                    } catch (Throwable t) {
                    	t.printStackTrace();

                        if (retryCount.get() > 0 && description.getAnnotation(Retry.class)!= null) {
                            caughtThrowable = t;
                            System.err.println(description.getDisplayName() +
                                    ": Failed, " +
                                    retryCount.toString() +
                                    " retries remain");
                        } else {
                            throw caughtThrowable;
                        }
                    }
                }
            }
        };
    }
}

package pt.fccn.saw.selenium;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by mehmetgerceker on 12/7/15.
 */
public class RetryRule implements TestRule {

    private AtomicInteger retryCount;

    public RetryRule(int retries){
        super();
        this.retryCount = new AtomicInteger(retries);
    }

    @Override
    public Statement apply(final Statement base, final Description description) {
        //statement is a private method which will return a new statement
        //here Statement is taken as abstract for your test which includes test method and before/after methods )
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                System.out.println("Evaluating retry ...");
                Throwable firstCaughtThrowable = null;

                // implement retry logic here
                while (retryCount.getAndDecrement() > 0) {
                    try {
                        base.evaluate();
                        return;
                    } catch (Throwable t) {
                    	t.printStackTrace();

                    	if (firstCaughtThrowable == null) {
                    		firstCaughtThrowable = t;
                    	}

                        if (retryCount.get() > 0 && description.getAnnotation(Retry.class)!= null) {
                            System.err.println(description.getDisplayName() +
                                    ": Failed, " +
                                    retryCount.toString() +
                                    " retries remain");
                        } else {
                            throw firstCaughtThrowable;
                        }
                    }
                }
            }
        };
    }
}

Fix NPE on retry rule.

Fix NPE on retry rule.


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

import android.app.Application;
import com.github.pedrovgs.sample.di.MainModule;
import dagger.ObjectGraph;

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class DraggablePanelApplication extends Application {

    private ObjectGraph objectGraph;

    @Override
    public void onCreate() {
        super.onCreate();
        MainModule mainModule = new MainModule(this);
        objectGraph = ObjectGraph.create(mainModule);
        objectGraph.inject(this);
        objectGraph.injectStatics();
    }

    public void inject(Object object) {
        objectGraph.inject(object);
    }
}

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

import android.app.Application;
import com.github.pedrovgs.sample.di.MainModule;
import dagger.ObjectGraph;

/**
 * Application implementation created to handle the dependency container implementation provided by the ObjectGraph
 * entity.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class DraggablePanelApplication extends Application {

    private ObjectGraph objectGraph;

    /**
     * Override method used to initialize the dependency container graph with the MainModule.
     */
    @Override
    public void onCreate() {
        super.onCreate();
        MainModule mainModule = new MainModule(this);
        objectGraph = ObjectGraph.create(mainModule);
        objectGraph.inject(this);
        objectGraph.injectStatics();
    }

    /**
     * Inject an object to provide all the needed dependencies.
     *
     * @param object
     */
    public void inject(Object object) {
        objectGraph.inject(object);
    }
}

Add javadoc to DraggablePanel application class


package com.github.cosmo0920.fluentd.flume.plugins;
import org.apache.flume.Event;

import org.komamitsu.fluency.Fluency;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;

class FluencyPublisher {
	private Fluency fluency;
	private String tag;

	public FluencyPublisher(String tag) {
		this.tag = tag;
	}

	public void setup(String hostname, int port) throws  IOException {
		fluency = Fluency.defaultFluency(hostname, port, new Fluency.Config());
	}

	public void close() {
		if (fluency != null) {
			try {
				fluency.close();
			} catch (IOException e) {
				// Do nothing.
			}
		}

		fluency = null;
	}

	// TODO: JSON encoded body support.
	public void send(Event event) throws IOException {
		String body = new String(event.getBody());
		Map<String, Object> fluencyEvent = new HashMap<String, Object>();
		fluencyEvent.put("message", body);
		fluency.emit(tag, fluencyEvent);
	}
}

package com.github.cosmo0920.fluentd.flume.plugins;
import org.apache.flume.Event;

import org.komamitsu.fluency.Fluency;

import java.nio.charset.StandardCharsets;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;

class FluencyPublisher {
	private Fluency fluency;
	private String tag;

	public FluencyPublisher(String tag) {
		this.tag = tag;
	}

	public void setup(String hostname, int port) throws  IOException {
		fluency = Fluency.defaultFluency(hostname, port, new Fluency.Config());
	}

	public void close() {
		if (fluency != null) {
			try {
				fluency.close();
			} catch (IOException e) {
				// Do nothing.
			}
		}

		fluency = null;
	}

	// TODO: JSON encoded body support.
	public void send(Event event) throws IOException {
		String body = new String(event.getBody(), StandardCharsets.UTF_8);
		Map<String, Object> fluencyEvent = new HashMap<String, Object>();
		fluencyEvent.put("message", body);
		fluency.emit(tag, fluencyEvent);
	}
}

Fix a findbugs reported warning

Fix a findbugs reported warning


package info.u_team.u_team_core.util.registry;

import java.util.function.Supplier;

import info.u_team.u_team_core.api.registry.IUBlockRegistryType;
import net.minecraft.block.Block;
import net.minecraft.item.*;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.*;

public class BlockDeferredRegister {

	public final DeferredRegister<Block> blocks;

	public BlockDeferredRegister(String modid) {
		blocks = DeferredRegister.create(ForgeRegistries.BLOCKS, modid);
	}

	public <B extends Block & IUBlockRegistryType, I extends BlockItem> BlockRegistryObject<B, I> register(String name, Supplier<? extends B> supplier) {
		final RegistryObject<B> block = blocks.register(name, supplier);
		final RegistryObject<I> item = RegistryObject.of(new ResourceLocation(name), ForgeRegistries.ITEMS);

		return new BlockRegistryObject<B, I>(block, item);
	}

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

}

package info.u_team.u_team_core.util.registry;

import java.util.function.Supplier;

import info.u_team.u_team_core.api.registry.IUBlockRegistryType;
import net.minecraft.block.Block;
import net.minecraft.item.*;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.*;

public class BlockDeferredRegister {

	private final DeferredRegister<Block> blocks;

	protected BlockDeferredRegister(String modid) {
		blocks = DeferredRegister.create(ForgeRegistries.BLOCKS, modid);
	}

	public <B extends Block & IUBlockRegistryType, I extends BlockItem> BlockRegistryObject<B, I> register(String name, Supplier<? extends B> supplier) {
		final RegistryObject<B> block = blocks.register(name, supplier);
		final RegistryObject<I> item = RegistryObject.of(new ResourceLocation(name), ForgeRegistries.ITEMS);

		return new BlockRegistryObject<B, I>(block, item);
	}

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

}

Make the fields private and make the ctor protected (need a create method)