package com.veyndan.redditclient.ui.recyclerview.itemdecoration;

import android.content.Context;
import android.graphics.Rect;
import android.support.annotation.DimenRes;
import android.support.v7.widget.RecyclerView;
import android.view.View;

public class MarginItemDecoration extends RecyclerView.ItemDecoration {

    private final int margin;

    public MarginItemDecoration(final Context context, @DimenRes final int marginRes) {
        margin = context.getResources().getDimensionPixelOffset(marginRes);
    }

    @Override
    public void getItemOffsets(final Rect outRect, final View view, final RecyclerView parent,
                               final RecyclerView.State state) {
        final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams();
        final int position = params.getViewLayoutPosition();
        final int marginTop = position == 0 ? margin : 0;
        outRect.set(margin, marginTop, margin, margin);
    }
}

package com.veyndan.redditclient.ui.recyclerview.itemdecoration;

import android.content.Context;
import android.graphics.Rect;
import android.support.annotation.DimenRes;
import android.support.annotation.NonNull;
import android.support.annotation.Px;
import android.support.v7.widget.RecyclerView;
import android.view.View;

public class MarginItemDecoration extends RecyclerView.ItemDecoration {

    @Px private final int margin;

    public MarginItemDecoration(@NonNull final Context context, @DimenRes final int marginRes) {
        margin = context.getResources().getDimensionPixelOffset(marginRes);
    }

    @Override
    public void getItemOffsets(final Rect outRect, final View view, final RecyclerView parent,
                               final RecyclerView.State state) {
        final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams();
        final int position = params.getViewLayoutPosition();
        final int marginTop = position == 0 ? margin : 0;
        outRect.set(margin, marginTop, margin, margin);
    }
}

Annotate parameter and field for better compiler checking


import java.util.Arrays;

public class SelectionSort {

	/**
	 *  Selection Sort is an in-place comparison sort.
	 *  It has O(n^2) time complexity.
	 */
	public int[] selection_sort(int[] arr) {
		int min, temp;
        /* find the min element in the unsorted array */
		for (int i = 0; i < arr.length; i++) {
		    /* assume the min is the first element */
			min = i;
			/* test against elements after i to find the smallest */
			for (int j = i+1; j < arr.length; j++) {
				/* if this element is less, then it is the new minimum */
				if (arr[j] < arr[min]) {
					/* found new minimum; remember its index */
					min = j;
				}
			}

			if (min != i) {
				/* swap i and min */
				temp = arr[i];
				arr[i] = arr[min];
				arr[min] = temp;
			}
		}

		return arr;
	}

}

import java.util.Arrays;

public class SelectionSort {

	/**
	 *  Selection Sort is an in-place comparison sort.
	 *  Selection Sort has O(n^2) time complexity.
	 */
	public int[] selection_sort(int[] arr) {
		int min, temp;
        /* find the min element in the unsorted array */
		for (int i = 0; i < arr.length; i++) {
		    /* assume the min is the first element */
			min = i;
			/* test against elements after i to find the smallest */
			for (int j = i+1; j < arr.length; j++) {
				/* if this element is less, then it is the new minimum */
				if (arr[j] < arr[min]) {
					/* found new minimum; remember its index */
					min = j;
				}
			}

			if (min != i) {
				/* swap i and min */
				temp = arr[i];
				arr[i] = arr[min];
				arr[min] = temp;
			}
		}

		return arr;
	}

}

Update docs on selection sort

Update docs on selection sort


package com.kickstarter.libs;

public class ApiCapabilities {
  private ApiCapabilities() {}

  public static boolean canDebugWebViews() {
    return android.os.Build.VERSION.SDK_INT >= 19;
  }

  public static boolean canEvaluateJavascript() {
    return android.os.Build.VERSION.SDK_INT >= 19;
  }
}

package com.kickstarter.libs;

public class ApiCapabilities {
  private ApiCapabilities() {}

  public static boolean canDebugWebViews() {
    return android.os.Build.VERSION.SDK_INT >= 19;
  }

  public static boolean canEvaluateJavascript() {
    return android.os.Build.VERSION.SDK_INT >= 19;
  }

  public static boolean canSetStatusBarColor() {
    return android.os.Build.VERSION.SDK_INT >= 21;
  }
}

Add check for whether we can programatically set status bar


package com.graphhopper.reader;

import java.util.Collection;

import com.graphhopper.routing.util.TurnCostEncoder;
import com.graphhopper.util.EdgeExplorer;

public interface TurnRelation {

	public abstract long getOsmIdFrom();

	public abstract long getOsmIdTo();

	/**
	 * transforms this relation into a collection of node cost entries
	 * <p>
	 * @param edgeOutExplorer an edge filter which only allows outgoing edges
	 * @param edgeInExplorer an edge filter which only allows incoming edges
	 * @return a collection of node cost entries which can be added to the graph later
	 */
	public abstract Collection<ITurnCostTableEntry> getRestrictionAsEntries(
			TurnCostEncoder encoder, EdgeExplorer edgeOutExplorer,
			EdgeExplorer edgeInExplorer, DataReader osmReader);

}

package com.graphhopper.reader;

import com.graphhopper.routing.util.TurnCostEncoder;
import com.graphhopper.util.EdgeExplorer;

import java.util.Collection;

public interface TurnRelation {

	long getOsmIdFrom();

	long getOsmIdTo();

	/**
	 * transforms this relation into a collection of node cost entries
	 * <p>
	 * @param edgeOutExplorer an edge filter which only allows outgoing edges
	 * @param edgeInExplorer an edge filter which only allows incoming edges
	 * @return a collection of node cost entries which can be added to the graph later
	 */
	Collection<ITurnCostTableEntry> getRestrictionAsEntries(
			TurnCostEncoder encoder, EdgeExplorer edgeOutExplorer,
			EdgeExplorer edgeInExplorer, DataReader osmReader);

}

Remove unused imports and modifiers implied by context.


package com.linkedin.clustermanager.monitoring.adaptors;

public class JmxSensorAdaptor
{

}

package com.linkedin.clustermanager.monitoring.adaptors;

import java.util.List;

import com.linkedin.clustermanager.monitoring.Sensor;

public class JmxSensorAdaptor
{
  final String _domain;
  final Sensor<?> _sensor;
  public JmxSensorAdaptor(Sensor<?> sensor, String domain, List<String> filters)
  {
    _domain = domain;
    _sensor = sensor;
  }
}

Add attribute tag for sensor attributes

Add attribute tag for sensor attributes


package edu.oregonstate.cope.eclipse.listeners;

import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IExecutionListener;
import org.eclipse.core.commands.NotHandledException;

public class SaveCommandExecutionListener implements IExecutionListener {

	private static long lastSaveAction = 0;

	/**
	 * Returns the time (in milliseconds since The Epoch) of the last save
	 * action.
	 *
	 * @return
	 */
	public static long getLastSaveAction() {
		return lastSaveAction;
	}

	@Override
	public void preExecute(String commandId, ExecutionEvent event) {
		if (isFileSave(commandId)) {
			lastSaveAction = System.currentTimeMillis();
		}
	}

	private boolean isFileSave(String commandId) {
		return commandId.equals("org.eclipse.ui.file.save");
	}

	@Override
	public void postExecuteSuccess(String commandId, Object returnValue) {
	}

	@Override
	public void postExecuteFailure(String commandId,
			ExecutionException exception) {
	}

	@Override
	public void notHandled(String commandId, NotHandledException exception) {
	}
}

package edu.oregonstate.cope.eclipse.listeners;

import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IExecutionListener;
import org.eclipse.core.commands.NotHandledException;

public class SaveCommandExecutionListener implements IExecutionListener {

	private static long lastSaveAction = 0;

	/**
	 * Returns the time (in milliseconds since The Epoch) of the last save
	 * action.
	 *
	 * @return
	 */
	public static long getLastSaveAction() {
		return lastSaveAction;
	}

	@Override
	public void preExecute(String commandId, ExecutionEvent event) {
		if (isFileSave(commandId)) {
			lastSaveAction = System.currentTimeMillis();
		}
	}

	private boolean isFileSave(String commandId) {
		return commandId.equals("org.eclipse.ui.file.save") || commandId.equalsIgnoreCase("org.eclipse.ui.file.saveAll");
	}

	@Override
	public void postExecuteSuccess(String commandId, Object returnValue) {
	}

	@Override
	public void postExecuteFailure(String commandId,
			ExecutionException exception) {
	}

	@Override
	public void notHandled(String commandId, NotHandledException exception) {
	}
}

Save All is also a save action

Save All is also a save action


package io.musician101.musicianlibrary.java.minecraft.gui.chest;

import java.util.List;

public abstract class ChestGUI<C, G extends ChestGUI<C, G, I, J, P, S>, I, J, P, S> {

    protected final List<GUIButton<C, G, I, J, P, S>> buttons;
    protected final I inventory;
    protected final int page;
    protected final P player;
    protected final J plugin;
    protected final G prevGUI;

    protected ChestGUI(I inventory, P player, int page, List<GUIButton<C, G, I, J, P, S>> buttons, G prevGUI, J plugin, boolean manualOpen) {
        this.inventory = inventory;
        this.player = player;
        this.page = page;
        this.buttons = buttons;
        this.prevGUI = prevGUI;
        this.plugin = plugin;
        if (!manualOpen) {
            open();
        }
    }

    public abstract void close();

    public abstract void open();
}

package io.musician101.musicianlibrary.java.minecraft.gui.chest;

import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public abstract class ChestGUI<C, G extends ChestGUI<C, G, I, J, P, S>, I, J, P, S> {

    @Nonnull
    protected final List<GUIButton<C, G, I, J, P, S>> buttons;
    @Nonnull
    protected final I inventory;
    protected final int page;
    @Nonnull
    protected final P player;
    @Nonnull
    protected final J plugin;
    @Nullable
    protected final G prevGUI;

    protected ChestGUI(@Nonnull I inventory, @Nonnull P player, int page, @Nonnull List<GUIButton<C, G, I, J, P, S>> buttons, @Nullable G prevGUI, @Nonnull J plugin, boolean manualOpen) {
        this.inventory = inventory;
        this.player = player;
        this.page = page;
        this.buttons = buttons;
        this.prevGUI = prevGUI;
        this.plugin = plugin;
        if (!manualOpen) {
            open();
        }
    }

    public abstract void close();

    @Nullable
    public G getPreviousGUI() {
        return prevGUI;
    }

    public abstract void open();
}

Add a method to get the previous GUI.

Add a method to get the previous GUI.


package edu.kit.iti.formal.pse.worthwhile;

/**
 * Initialization support for running Xtext languages without equinox extension
 * registry.
 */
public class WorthwhileStandaloneSetup extends
	WorthwhileStandaloneSetupGenerated {

    public static void doSetup() {
	new WorthwhileStandaloneSetup().createInjectorAndDoEMFRegistration();
    }
}

package edu.kit.iti.formal.pse.worthwhile;

import com.google.inject.Injector;

import edu.kit.iti.formal.pse.worthwhile.model.ast.impl.AstPackageImpl;

/**
 * Initialization support for running Xtext languages without equinox extension
 * registry.
 */
public class WorthwhileStandaloneSetup extends
WorthwhileStandaloneSetupGenerated {

	public static void doSetup() {
		new WorthwhileStandaloneSetup().createInjectorAndDoEMFRegistration();
	}

	@Override
	public Injector createInjectorAndDoEMFRegistration() {
		AstPackageImpl.init();
		return super.createInjectorAndDoEMFRegistration();
	}
}

[impl] Add workaround for model resolving bug in unit tests

Stolen from http://www.eclipse.org/forums/index.php/m/735764/


package org.ovirt.engine.core.common.queries;

import javax.validation.Valid;

import org.ovirt.engine.core.common.businessentities.Provider;

public class ProviderQueryParameters extends VdcQueryParametersBase {

    private static final long serialVersionUID = 308877238121233739L;

    @Valid
    private Provider provider;

    public ProviderQueryParameters() {
    }

    public ProviderQueryParameters(Provider provider) {
        this.provider = provider;
    }

    public Provider getProvider() {
        return provider;
    }

    public void setProvider(Provider provider) {
        this.provider = provider;
    }

}

package org.ovirt.engine.core.common.queries;

import javax.validation.Valid;

import org.ovirt.engine.core.common.businessentities.Provider;

public class ProviderQueryParameters extends VdcQueryParametersBase {

    private static final long serialVersionUID = 308877238121233739L;

    @Valid
    private Provider<?> provider;

    public ProviderQueryParameters() {
    }

    public ProviderQueryParameters(Provider<?> provider) {
        this.provider = provider;
    }

    public Provider<?> getProvider() {
        return provider;
    }

    public void setProvider(Provider<?> provider) {
        this.provider = provider;
    }

}

core: Set type to Provider in query parameters class

Change-Id: Ic7a1dee7182ca5697cb1728855ac9695b32cc1e9
Signed-off-by: Moti Asayag <da1debb83a8e12b6e8822edf2c275f55cc51b720@redhat.com>


package io.mere.mortal;

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

@WebServlet(urlPatterns = {"/*"}, loadOnStartup = 1)
public class BackendServlet extends HttpServlet
{
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException
  {
  	  if ("/oops".equals(request.getRequestURI())) {
  	  	response.sendError(500);
  	  } else {
      	response.getOutputStream().print("This sometimes serves stuff: "+request.getRequestURI());
      }
  }
}

package io.mere.mortal;

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

@WebServlet(urlPatterns = {"/*"}, loadOnStartup = 1)
public class BackendServlet extends HttpServlet {
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
      response.sendError(500);
  }
}

Throw 500's, because it's in vogue

Throw 500's, because it's in vogue

- Also set up a bad version for talk.


package ru.fitgraph.rest.elements;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by melges on 19.01.15.
 */
public class DateParameter {
    private static final SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd.MM.yyyy-HH:mm:ss");

    private Date date;

    public DateParameter() {
        this.date = new Date();
    }

    public DateParameter(String date) {
        try {
            this.date = dateTimeFormat.parse(date);
        } catch (ParseException e) {
            throw new WebApplicationException(Response
                    .status(Response.Status.BAD_REQUEST)
                    .entity(new ErrorResponse("InvalidParameterException", e.getLocalizedMessage())).build());
        }
    }

    public Date getDate() {
        return date;
    }
}

package ru.fitgraph.rest.elements;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by melges on 19.01.15.
 */
public class DateParameter {
    private static final SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");

    private Date date;

    public DateParameter() {
        this.date = new Date();
    }

    public DateParameter(String date) {
        try {
            this.date = dateTimeFormat.parse(date);
        } catch (ParseException e) {
            throw new WebApplicationException(Response
                    .status(Response.Status.BAD_REQUEST)
                    .entity(new ErrorResponse("InvalidParameterException", e.getLocalizedMessage())).build());
        }
    }

    public Date getDate() {
        return date;
    }
}

Fix incorrect date format in urlencoded parameter parser.


package com.badlogic.gdx.maps.tiled;

import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.maps.Map;
import com.badlogic.gdx.utils.Array;

/**
 * @brief Represents a tiled map, adds the concept of tiles and tilesets
 *
 * @see Map
 */
public class TiledMap extends Map {
	private TiledMapTileSets tilesets;
	private Array<Texture> ownedTextures;

	/**
	 * @return collection of tilesets for this map
	 */
	public TiledMapTileSets getTileSets() {
		return tilesets;
	}

	/**
	 * Creates empty TiledMap
	 */
	public TiledMap() {
		tilesets = new TiledMapTileSets();
	}

	/**
	 * Used by TmxMapLoader to set textures when loading the map
	 * directly, without {@link AssetManager}. To be disposed in
	 * {@link #dispose()}.
	 * @param textures
	 */
	void setOwnedTextures(Array<Texture> textures) {
		this.ownedTextures = textures;
	}

	@Override
	public void dispose() {
		if(ownedTextures != null) {
			for(Texture texture: ownedTextures) {
				texture.dispose();
			}
		}
	}
}

package com.badlogic.gdx.maps.tiled;

import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.maps.Map;
import com.badlogic.gdx.utils.Array;

/**
 * @brief Represents a tiled map, adds the concept of tiles and tilesets
 *
 * @see Map
 */
public class TiledMap extends Map {
	private TiledMapTileSets tilesets;
	private Array<Texture> ownedTextures;

	/**
	 * @return collection of tilesets for this map
	 */
	public TiledMapTileSets getTileSets() {
		return tilesets;
	}

	/**
	 * Creates empty TiledMap
	 */
	public TiledMap() {
		tilesets = new TiledMapTileSets();
	}

	/**
	 * Used by TmxMapLoader to set textures when loading the map
	 * directly, without {@link AssetManager}. To be disposed in
	 * {@link #dispose()}.
	 * @param textures
	 */
	public void setOwnedTextures(Array<Texture> textures) {
		this.ownedTextures = textures;
	}

	@Override
	public void dispose() {
		if(ownedTextures != null) {
			for(Texture texture: ownedTextures) {
				texture.dispose();
			}
		}
	}
}

Enable custom map loaders to setOwnedTextures when not residing in the *.tiled namespace


package org.col.api;

/**
 * Simplified literature reference class for proof of concept only.
 */
public class Reference {
  private Integer key;
  private Object csl;
  private Serial serial;
  private Integer year;
  private String doi;

}

package org.col.api;

import java.util.Objects;

/**
 * Simplified literature reference class for proof of concept only.
 */
public class Reference {
  private Integer key;
  private Object csl;
  private Serial serial;
  private Integer year;
  private String doi;

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Reference reference = (Reference) o;
    return Objects.equals(key, reference.key) &&
        Objects.equals(csl, reference.csl) &&
        Objects.equals(serial, reference.serial) &&
        Objects.equals(year, reference.year) &&
        Objects.equals(doi, reference.doi);
  }

  @Override
  public int hashCode() {
    return Objects.hash(key, csl, serial, year, doi);
  }
}

Add reference hash & equals methods

Add reference hash & equals methods


package uk.me.mjt.ch;

import java.util.HashMap;
import org.junit.Test;
import static org.junit.Assert.*;

public class UtilTest {

    public UtilTest() {
    }

    @Test
    public void testDeepEquals_HashMap_HashMap() {
        System.out.println("deepEquals");
        MapData a = MakeTestData.makeSimpleThreeEntry();
        MapData b = MakeTestData.makeSimpleThreeEntry();
        assertTrue(Util.deepEquals(a, b, false));

        Node n = a.getNodeById(2L);
        n.edgesFrom.remove(0);

        assertFalse(Util.deepEquals(a, b, false));
    }

}

package uk.me.mjt.ch;

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

public class UtilTest {

    public UtilTest() {
    }

    @Test
    public void testDeepEquals_HashMap_HashMap() {
        System.out.println("deepEquals");
        MapData a = MakeTestData.makeSimpleThreeEntry();
        MapData b = MakeTestData.makeSimpleThreeEntry();
        assertTrue(Util.deepEquals(a, b, true));

        Node n = a.getNodeById(2L);
        n.edgesFrom.remove(0);

        assertFalse(Util.deepEquals(a, b, true));
    }

    @Test
    public void testNodeEquality() {
        MapData a = MakeTestData.makeSimpleThreeEntry();
        MapData b = MakeTestData.makeSimpleThreeEntry();

        assertTrue(Util.deepEquals(a.getNodeById(2L), b.getNodeById(2L), true));
        assertFalse(Util.deepEquals(a.getNodeById(2L), b.getNodeById(3L), true));
    }

}

Improve test coverage of util class.

Improve test coverage of util class.


/**
 * Calculates suspiciousness and confidence values according to the Op2 fault localization
 * technique.
 */
public class Op2 {
}

/**
 * Calculates suspiciousness and confidence values according to the Op2 fault localization
 * technique.
 * The usage mode is to create a coverage matrix that specifies which program
 * elements are executed by which test cases. In terms of this implementation, each program element called
 * a statement. coverage matrix is encoded as a two dimensional array where the first dimension is indexed by
 * the test case number and the second dimension is indexed by the statement number.
 */
public class Op2 {
  private boolean[][] coverageMatrix; // coverage matrix -- [test][statement]

  private int numberOfTests; // number of test cases
  private int numberOfStatements;

  public Op2(boolean[][] coverageMatrix) {
    this.coverageMatrix = coverageMatrix;
    numberOfTests = coverageMatrix.length;
    numberOfStatements = coverageMatrix[0].length;

  }

}

Create two dimensional coverage matrix where the first dimension is indexed by the test case number and the second dimension is indexed by the statement number


package model;

import io.Preface;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Weights {
	double[] weights;

	public Weights() {
	}

	public Weights(String weightsFile, int numFeatures) throws IOException {
		this.weights = new double[numFeatures];

		if (!weightsFile.equals("zero")) {
			readWeights(weightsFile);
		}
	}

	public void setWeights(double[] weights) {
		this.weights = weights;
	}

	private void readWeights(String weightsFile) throws IOException {
		int ID = 0;

		BufferedReader in = new BufferedReader(new FileReader(weightsFile));
		Preface.readPreface(in);

		String line = null;
		while ((line = in.readLine()) != null) {
			double weight = Double.parseDouble(line);
			weights[ID] = weight;
			ID++;
		}

		if (ID != weights.length) {
			throw new IllegalArgumentException("number of weights != number of features!");
		}
	}

	public double getWeight(int ID) {
		return weights[ID];
	}

	public void setWeight(int ID, double weight) {
		weights[ID] = weight;
	}
}

package model;

import io.Preface;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Weights {
	private double[] weights;

	public Weights() {
	}

	public Weights(String weightsFile, int numFeatures) throws IOException {
		this.weights = new double[numFeatures];

		if (!weightsFile.equals("zero")) {
			readWeights(weightsFile);
		}
	}

	public void setWeights(double[] weights) {
		this.weights = (double[]) weights.clone();
	}

	private void readWeights(String weightsFile) throws IOException {
		int ID = 0;

		BufferedReader in = new BufferedReader(new FileReader(weightsFile));
		Preface.readPreface(in);

		String line = null;
		while ((line = in.readLine()) != null) {
			double weight = Double.parseDouble(line);
			weights[ID] = weight;
			ID++;
		}

		if (ID != weights.length) {
			throw new IllegalArgumentException("number of weights != number of features!");
		}
	}

	public double getWeight(int ID) {
		return weights[ID];
	}

	public void setWeight(int ID, double weight) {
		weights[ID] = weight;
	}
}

Fix leaky abstraction by cloning double array instead of just copying reference.


/*********************************************************************
 *
 * Copyright (C) 2006,  Blekinge Institute of Technology
 *
 * Filename:      Main.java
 * Author:        Simon Kagstrom <ska@bth.se>
 * Description:   Main class for Cibyl
 *
 * $Id: Main.java 11608 2006-10-12 10:20:08Z ska $
 *
 ********************************************************************/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class Main extends MIDlet implements CommandListener
{
  private GameScreenCanvas canvas;

  public void startApp()
  {
    if (canvas == null)
      {
	canvas = new GameScreenCanvas(Display.getDisplay(this), this);
	if (!CibylConfig.disableExitCmd)
	{
	  Command exitCommand = new Command("Exit", Command.EXIT, 0);
	  canvas.addCommand(exitCommand);
	  canvas.setCommandListener(this);
	}
      }

    /* Start the canvas */
    canvas.start();
  }

  public void pauseApp()
  {
  }

  public void destroyApp(boolean unconditional)
  {
      canvas = null;
  }

  public void commandAction(Command c, Displayable s)
  {
    if (c.getCommandType() == Command.EXIT)
      {
        canvas.invokeCallback(CRunTime.CB_ATEXIT, 0, 0);
	destroyApp(true);
	notifyDestroyed();
      }
  }
}

/*********************************************************************
 *
 * Copyright (C) 2006,  Blekinge Institute of Technology
 *
 * Filename:      Main.java
 * Author:        Simon Kagstrom <ska@bth.se>
 * Description:   Main class for Cibyl
 *
 * $Id: Main.java 11608 2006-10-12 10:20:08Z ska $
 *
 ********************************************************************/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class Main extends MIDlet implements CommandListener
{
  private GameScreenCanvas canvas;
  private Display display;

  public Main()
  {
    this.display = Display.getDisplay(this);
    this.canvas = new GameScreenCanvas(this.display, this);
  }

  public void startApp()
  {
    if (!CibylConfig.disableExitCmd)
	{
            Command exitCommand = new Command("Exit", Command.EXIT, 0);
            this.canvas.addCommand(exitCommand);
            this.canvas.setCommandListener(this);
	}
    /* Start the canvas */
    this.display.setCurrent(canvas);
    canvas.start();
  }

  public void pauseApp()
  {
  }

  public void destroyApp(boolean unconditional)
  {
      System.out.println("Maboo here " + unconditional);
      canvas = null;
      CRunTime.memory = null;
  }

  public void commandAction(Command c, Displayable s)
  {
    if (c.getCommandType() == Command.EXIT)
      {
        this.canvas.invokeCallback(CRunTime.CB_ATEXIT, 0, 0);
	this.destroyApp(true);
	this.notifyDestroyed();
      }
  }
}

Add a constructor, slight cleanup

Add a constructor, slight cleanup


package matrix4j.core;
import matrix4j.core.VectorIO;

public class TestVectorIO {
    static void testLoad() {
        String filename = "testfiles/vector_src.txt";
        Vector v = VectorIO.load(filename);
        System.out.println(v);
    }

    static void testSave() {
        String filename = "testfiles/vector_dst.txt";
        Vector v = new Vector(new double[]{0, 1, 2, 3});
        VectorIO.save(filename, v);
    }

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

package matrix4j.core;

import matrix4j.core.VectorIO;
import matrix4j.core.Assert;

public class TestVectorIO {
    static void testLoad() {
        String filename = "testfiles/vector_src.txt";
        Vector v = VectorIO.load(filename);
        Vector u = new Vector(new double[]{
            1, 0, 6, 1, 9, 8, 2, 1, 6, 7
        });
        Assert.assertTrue(v.equals(u));
    }

    static void testSave() {
        String filename = "testfiles/vector_dst.txt";
        Vector v = new Vector(new double[]{0, 1, 2, 3});
        VectorIO.save(filename, v);
    }

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

Raise AssertError if test fails

Raise AssertError if test fails


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

import io.getlime.security.powerauth.lib.nextstep.model.entity.enumeration.CredentialStatus;
import lombok.Data;

import javax.validation.constraints.NotNull;

/**
 * Response object used for resetting a credential.
 *
 * @author Roman Strobl, roman.strobl@wultra.com
 */
@Data
public class ResetCredentialResponse {

    @NotNull
    private String userId;
    @NotNull
    private String credentialName;
    @NotNull
    private String credentialValue;
    @NotNull
    private CredentialStatus credentialStatus;

}

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

import io.getlime.security.powerauth.lib.nextstep.model.entity.enumeration.CredentialStatus;
import lombok.Data;

import javax.validation.constraints.NotNull;

/**
 * Response object used for resetting a credential.
 *
 * @author Roman Strobl, roman.strobl@wultra.com
 */
@Data
public class ResetCredentialResponse {

    @NotNull
    private String userId;
    @NotNull
    private String credentialName;
    private String username;
    @NotNull
    private String credentialValue;
    @NotNull
    private CredentialStatus credentialStatus;

}

Return username after credential reset

Return username after credential reset


package android.example.com.visualizerpreferences;

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

public class SettingsActivity extends AppCompatActivity {

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

package android.example.com.visualizerpreferences;

import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;

public class SettingsActivity extends AppCompatActivity {

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

        ActionBar actionBar = this.getSupportActionBar();
        if(actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if(itemId == android.R.id.home){
            NavUtils.navigateUpFromSameTask(this);
        }
        return super.onOptionsItemSelected(item);
    }
}

Fix up button in T06.01

Fix up button in T06.01


package lib.morkim.mfw.ui;

import android.content.Context;

import lib.morkim.mfw.app.AppContext;

public interface Viewable {

	public void finish();
	AppContext getMorkimContext();

	void keepScreenOn(boolean keepOn);

	Context getContext();
}

package lib.morkim.mfw.ui;

import android.content.Context;

import java.util.Observer;

import lib.morkim.mfw.app.AppContext;

public interface Viewable extends Observer {

	public void finish();
	AppContext getMorkimContext();

	void keepScreenOn(boolean keepOn);

	Context getContext();
}

Remove view model in presenter

Remove view model in presenter


package pro.beam.api;

import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import pro.beam.api.http.BeamHttpClient;
import pro.beam.api.services.AbstractBeamService;
import pro.beam.api.services.ServiceManager;
import pro.beam.api.services.impl.*;
import pro.beam.api.services.impl.UsersService;

import java.net.URI;
import java.util.concurrent.Executors;

public class BeamAPI {
    public static final URI BASE_PATH = URI.create("https://beam.pro/api/v1/");

    public final Gson gson;
    public final BeamHttpClient http;
    public final ListeningExecutorService executor;
    protected final ServiceManager services;

    public BeamAPI() {
        this.gson = new GsonBuilder().create();

        this.executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
        this.http = new BeamHttpClient(this);
        this.services = new ServiceManager();

        this.register(new UsersService(this));
        this.register(new ChatService(this));
        this.register(new ChannelsService(this));
    }

    public <T extends AbstractBeamService> T use(Class<T> service) {
        return this.services.get(service);
    }

    public boolean register(AbstractBeamService service) {
        return this.services.register(service);
    }
}

package pro.beam.api;

import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import pro.beam.api.http.BeamHttpClient;
import pro.beam.api.services.AbstractBeamService;
import pro.beam.api.services.ServiceManager;
import pro.beam.api.services.impl.*;
import pro.beam.api.services.impl.UsersService;

import java.net.URI;
import java.util.concurrent.Executors;

public class BeamAPI {
    public static final URI BASE_PATH = URI.create("https://beam.pro/api/v1/");

    public final Gson gson;
    public final BeamHttpClient http;
    public final ListeningExecutorService executor;
    protected final ServiceManager services;

    public BeamAPI() {
        this.gson = new GsonBuilder()
                        .setDateFormat("yyyy-MM-dd HH:mm:ss")
                        .create();

        this.executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
        this.http = new BeamHttpClient(this);
        this.services = new ServiceManager();

        this.register(new UsersService(this));
        this.register(new ChatService(this));
        this.register(new ChannelsService(this));
    }

    public <T extends AbstractBeamService> T use(Class<T> service) {
        return this.services.get(service);
    }

    public boolean register(AbstractBeamService service) {
        return this.services.register(service);
    }
}

Update API's GSON date format to match the API spec


package util;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class UserAuthUtil {
  public static boolean isUserLoggedIn() {
    UserService userServ = UserServiceFactory.getUserService();
    return userServ.isUserLoggedIn();
  }
  public static String getLoginURL(String redirect) {
    UserService userServ = UserServiceFactory.getUserService();
    return userServ.createLoginURL(redirect);
  }
  public static String getLogoutURL(String redirect) {
    UserService userServ = UserServiceFactory.getUserService();
    return userServ.createLogoutURL(redirect);
  }
  public static String getUser() {

  }
}

package util;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class UserAuthUtil {
  public static boolean isUserLoggedIn() {
    UserService userServ = UserServiceFactory.getUserService();
    return userServ.isUserLoggedIn();
  }
  public static String getLoginURL(String redirect) {
    UserService userServ = UserServiceFactory.getUserService();
    return userServ.createLoginURL(redirect);
  }
  public static String getLogoutURL(String redirect) {
    return UserServiceFactory.getUserService().createLogoutURL(redirect);
  }
  public static User getUser() {
    return UserServiceFactory.getUserService().getCurrentUser();
  }
  public static boolean isUserAuthorized() {
    return getDomainName().equals("google.com");
  }
  private static String getDomainName() {
    String email = getUser().getEmail();
    return email.substring(email.indexOf('@') + 1);
  }
}

Add helper functions for authentication and authorization


import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class Stat implements Serializable {
    public String server;
    public List<String> items;

    public Stat() {
        this.server = new String();
        this.items = new ArrayList<String>();
    }

    public Stat(String server, List<String> items) {
        this.server = server;
        this.items = items;
    }

    public String toString() {
        String stat = new String();
        stat = stat.concat("{ " + server + ", { ");
        if (items.size() == 0) {
            stat = stat.concat(" } }");
            return stat;
        }
        int i = 0;
        for (i = 0; i < items.size() - 1; i++)
            stat = stat.concat(items.get(i) + ", ");
        stat = stat.concat(items.get(i) + " } }");
        return stat;
    }
}

Add new line at EOF

Add new line at EOF

Signed-off-by: Nuno Azevedo <7b5d26f0698b3f6c15a9789c87d309f80e3742b1@movvo.com>


package com.kickstarter.libs.utils;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import rx.functions.Func1;

public class ObjectUtils {
  private ObjectUtils(){}

  public static boolean isNull(@Nullable final Object object) {
    return object == null;
  }

  public static boolean isNotNull(@Nullable final Object object) {
    return object != null;
  }

  /**
   * Returns the first non-`null` value of its arguments.
   */
  @NonNull public static <T> T coalesce(@Nullable final T value, @NonNull final T theDefault) {
    if (value != null) {
      return value;
    }
    return theDefault;
  }

  /**
   * Returns a function `T -> T` that coalesces values with `theDefault`.
   */
  @NonNull public static <T> Func1<T, T> coalesceWith(@NonNull final T theDefault) {
    return (value) -> ObjectUtils.coalesce(value, theDefault);
  }
}

package com.kickstarter.libs.utils;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import rx.functions.Func1;

public class ObjectUtils {
  private ObjectUtils(){}

  public static boolean isNull(@Nullable final Object object) {
    return object == null;
  }

  public static boolean isNotNull(@Nullable final Object object) {
    return object != null;
  }

  /**
   * Returns the first non-`null` value of its arguments.
   */
  @NonNull public static <T> T coalesce(@Nullable final T value, @NonNull final T theDefault) {
    if (value != null) {
      return value;
    }
    return theDefault;
  }

  /**
   * Returns a function `T -> T` that coalesces values with `theDefault`.
   */
  @NonNull public static <T> Func1<T, T> coalesceWith(@NonNull final T theDefault) {
    return (value) -> ObjectUtils.coalesce(value, theDefault);
  }

  /**
   * Converts an {@link Integer} to a {@link String}, or null of the integer is also null.
   */
  public static @Nullable String toString(@Nullable final Integer n) {
    if (n != null) {
      return Integer.toString(n);
    }

    return null;
  }

  /**
   * Converts a {@link Long} to a {@link String}, or null of the long is also null.
   */
  public static @Nullable String toString(@Nullable final Long n) {
    if (n != null) {
      return Long.toString(n);
    }

    return null;
  }

  /**
   * Converts a {@link Float} to a {@link String}, or null of the float is also null.
   */
  public static @Nullable String toString(@Nullable final Float n) {
    if (n != null) {
      return Float.toString(n);
    }

    return null;
  }

  /**
   * Converts a {@link Double} to a {@link String}, or null of the double is also null.
   */
  public static @Nullable String toString(@Nullable final Double n) {
    if (n != null) {
      return Double.toString(n);
    }

    return null;
  }
}

Add some helpers to shortcut converting numbers to strings


package io.digdag.spi;

import io.digdag.client.config.Config;
import org.immutables.value.Value;

@Value.Immutable
public interface AuthenticatedUser
{
    int getSiteId();

    default boolean isAdmin()
    {
        return false;
    }

    Config getUserInfo();

    // this context will not be stored on database instead of userInfo, which is stored as part of wf revision.
    Config getUserContext();

    static ImmutableAuthenticatedUser.Builder builder()
    {
        return ImmutableAuthenticatedUser.builder();
    }
}

package io.digdag.spi;

import io.digdag.client.config.Config;
import org.immutables.value.Value;

@Value.Immutable
public interface AuthenticatedUser
{
    int getSiteId();

    @Value.Default
    default boolean isAdmin()
    {
        return false;
    }

    Config getUserInfo();

    // this context will not be stored on database instead of userInfo, which is stored as part of wf revision.
    Config getUserContext();

    static ImmutableAuthenticatedUser.Builder builder()
    {
        return ImmutableAuthenticatedUser.builder();
    }
}

Fix build error on default method with Immutable.


/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package foam.lib.json;

import foam.lib.parse.*;

public class ArrayParser
  extends ProxyParser
{
  public ArrayParser() {
    super(new Seq1(3,
      Whitespace.instance(),
      Literal.create("["),
      Whitespace.instance(),
      new Repeat(
        AnyParser.instance(),
        new Seq0(Whitespace.instance(), Literal.create(","), Whitespace.instance())),
      Whitespace.instance(),
      Literal.create("]")));
  }
}

/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package foam.lib.json;

import foam.lib.parse.*;

public class ArrayParser
  extends ProxyParser
{
  public ArrayParser() {
    super(new Seq1(3,
      Whitespace.instance(),
      Literal.create("["),
      Whitespace.instance(),
      new Repeat(
        new ProxyParser() { public Parser getDelegate() { return AnyParser.instance(); }},
        new Seq0(Whitespace.instance(), Literal.create(","), Whitespace.instance())),
      Whitespace.instance(),
      Literal.create("]")));
  }
}

Fix for infinite recursion if Array and Any Parsers.


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

import com.sun.grizzly.http.SelectorThread;
import com.sun.jersey.api.container.grizzly.GrizzlyWebContainerFactory;

public class Main {
    public static void main(String[] args) throws IOException {

        final String baseUri = "http://localhost:"+(System.getenv("PORT")!=null?System.getenv("PORT"):"9998")+"/";
        final Map<String, String> initParams = new HashMap<String, String>();

        initParams.put("com.sun.jersey.config.property.packages","resources");

        System.out.println("Starting grizzly...");
        SelectorThread threadSelector = GrizzlyWebContainerFactory.create(baseUri, initParams);
        System.out.println(String.format("Jersey started with WADL available at %sapplication.wadl.",baseUri, baseUri));
    }
}

import com.sun.jersey.api.container.grizzly.GrizzlyServerFactory;
import com.sun.jersey.api.core.PackagesResourceConfig;

import javax.ws.rs.core.UriBuilder;
import java.io.IOException;
import java.net.URI;

public class Main {

    private static final int DEFAULT_PORT = 9998;

    public static void main(String[] args) throws IOException {
        GrizzlyServerFactory.create(getBaseUri(), getResourceConfig());
    }

    private static URI getBaseUri() {
        final int port = System.getenv("PORT") != null ? Integer.parseInt(System.getenv("PORT")) : DEFAULT_PORT;
        return UriBuilder.fromUri("http://localhost/").port(port).build();
    }

    private static PackagesResourceConfig getResourceConfig() {
        return new PackagesResourceConfig("resources");
    }
}

Simplify server start in main method

Simplify server start in main method


/*
 * Copyright 2015 Higher Frequency Trading
 *
 * http://www.higherfrequencytrading.com
 *
 * 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 net.openhft.chronicle.core;

public enum Jvm {
    ;

    public static void checkInterrupted() throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
    }
}

/*
 * Copyright 2015 Higher Frequency Trading
 *
 * http://www.higherfrequencytrading.com
 *
 * 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 net.openhft.chronicle.core;

public enum Jvm {
    ;

    public static RuntimeException rethrow(Throwable throwable) {
        // blindly rethrow checked exceptions.
        UnsafeMemory.UNSAFE.throwException(throwable);

        // just to keep the compiler happy.
        return null;
    }

    public static void checkInterrupted() throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
    }
}

Add the interfaces from the Chronicle Engine Subscription RFC.


/**
 * Copyright (C) 2009 - 2010 by OpenGamma Inc.
 *
 * Please see distribution for license.
 */
package com.opengamma.engine.view.calcnode;

/**
 *
 */
public class DummyResultWriter implements ResultWriter {

  @Override
  public void write(AbstractCalculationNode node, CalculationJobResult result) {
  }

}

/**
 * Copyright (C) 2009 - 2010 by OpenGamma Inc.
 *
 * Please see distribution for license.
 */
package com.opengamma.engine.view.calcnode;

import java.io.Serializable;

/**
 *
 */
public class DummyResultWriter implements ResultWriter, Serializable {

  @Override
  public void write(AbstractCalculationNode node, CalculationJobResult result) {
  }

}

Support for partial writing of results

[ENG-150] Support for partial writing of results


package com.madhur.uml_parser;

import junit.framework.*;

public class FacadeTest extends TestCase{
	public TestCase(String testName)
    	{
        	super( testName );
    	}
	protected void setUp(){
		//TODO
	}
	public void testMain(){
		//TODO
	}
}

Update formatting of test file

Update formatting of test file


package readme;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import graphql.schema.DataFetchingFieldSelectionSet;
import graphql.schema.SelectedField;

import java.util.List;

@SuppressWarnings({"unused", "Convert2Lambda"})
public class FieldSelectionExamples {

    void usingSelectionSet() {
        DataFetcher smartUserDF = new DataFetcher() {
            @Override
            public Object get(DataFetchingEnvironment env) {
                String userId = env.getArgument("userId");

                DataFetchingFieldSelectionSet selectionSet = env.getSelectionSet();
                if (selectionSet.contains("user/*")) {
                    return getUserAndTheirFriends(userId);
                } else {
                    return getUser(userId);
                }
            }
        };
    }

    DataFetchingEnvironment env;

    void getFields() {
        DataFetchingFieldSelectionSet selectionSet = env.getSelectionSet();
        List<SelectedField> nodeFields = selectionSet.getFields("edges/nodes/*");
        nodeFields.forEach(selectedField -> {
            System.out.println(selectedField.getName());
            System.out.println(selectedField.getType());

            DataFetchingFieldSelectionSet innerSelectionSet = selectedField.getSelectionSet();
            // .. this forms a tree of selection and you can get very fancy with it
        });
    }

    private Object getUser(String userId) {
        return null;
    }

    private Object getUserAndTheirFriends(String userId) {
        return null;
    }
}

package readme;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import graphql.schema.DataFetchingFieldSelectionSet;
import graphql.schema.SelectedField;

import java.util.List;

@SuppressWarnings({"unused", "Convert2Lambda"})
public class FieldSelectionExamples {

    void usingSelectionSet() {
        DataFetcher smartUserDF = new DataFetcher() {
            @Override
            public Object get(DataFetchingEnvironment env) {
                String userId = env.getArgument("userId");

                DataFetchingFieldSelectionSet selectionSet = env.getSelectionSet();
                if (selectionSet.contains("friends/*")) {
                    return getUserAndTheirFriends(userId);
                } else {
                    return getUser(userId);
                }
            }
        };
    }

    DataFetchingEnvironment env;

    void getFields() {
        DataFetchingFieldSelectionSet selectionSet = env.getSelectionSet();
        List<SelectedField> nodeFields = selectionSet.getFields("edges/nodes/*");
        nodeFields.forEach(selectedField -> {
            System.out.println(selectedField.getName());
            System.out.println(selectedField.getType());

            DataFetchingFieldSelectionSet innerSelectionSet = selectedField.getSelectionSet();
            // .. this forms a tree of selection and you can get very fancy with it
        });
    }

    private Object getUser(String userId) {
        return null;
    }

    private Object getUserAndTheirFriends(String userId) {
        return null;
    }
}

Fix typo in doco example

Fix typo in doco example


package org.perl6.rakudo;

import org.perl6.nqp.runtime.ThreadContext;
import org.perl6.nqp.sixmodel.SixModelObject;

/**
 * Contains implementation of nqp:: ops specific to Rakudo Perl 6.
 */
public final class Ops {
    public static SixModelObject p6settypes(SixModelObject conf, ThreadContext tc) {
        return conf;
    }
}

package org.perl6.rakudo;

import org.perl6.nqp.runtime.ThreadContext;
import org.perl6.nqp.sixmodel.SixModelObject;

/**
 * Contains implementation of nqp:: ops specific to Rakudo Perl 6.
 */
public final class Ops {
    private static SixModelObject False;
    private static SixModelObject True;

    public static SixModelObject p6settypes(SixModelObject conf, ThreadContext tc) {
        False = conf.at_key_boxed(tc, "False");
        True = conf.at_key_boxed(tc, "True");
        return conf;
    }

    public static SixModelObject booleanize(int x) {
        return x == 0 ? False : True;
    }
}

Implement p6bool op for JVM.

Implement p6bool op for JVM.


package com.twu.biblioteca;

import java.util.ArrayList;

public class BibliotecaApp {

    private ArrayList<Book> books;

    public static void main(String[] args) {
        System.out.println("Welcome to Biblioteca!");

    }
}

package com.twu.biblioteca;

import java.util.ArrayList;

public class BibliotecaApp {

    public static void main(String[] args) {
        ArrayList<Book> books = new ArrayList<Book>();
        books.add(new Book("Harry Potter"));
        books.add(new Book("Lord of the Rings"));
        System.out.println("Welcome to Biblioteca!");
        for (Book book : books)
            System.out.println(book.getName());

    }
}

Print books on startup of biblioteca

Print books on startup of biblioteca


package net.gpdev.gameoflife;

public class GameOfLife {
    private Grid current;
    private Grid next;

    public GameOfLife(int xDim, int yDim) {
        current = new Grid(xDim, yDim);
        next = new Grid(xDim, yDim);
    }

    public void populateCell(int x, int y) {
        current.set(x, y);
    }

    public boolean isCellPopulated(int x, int y) {
        return !current.isEmpty(x, y);
    }

    public void tick() {

    }
}

package net.gpdev.gameoflife;

public class GameOfLife {
    private Grid current;
    private Grid next;

    public GameOfLife(int xDim, int yDim) {
        current = new Grid(xDim, yDim);
        next = new Grid(xDim, yDim);
    }

    public void populateCell(int x, int y) {
        current.set(x, y);
    }

    public boolean isCellPopulated(int x, int y) {
        return !current.isEmpty(x, y);
    }

    public void tick() {
        current = next;
    }
}

Make first test case pass

Make first test case pass


package codechicken.lib.lighting;

import net.minecraft.client.renderer.Tessellator;
import codechicken.lib.colour.Colour;
import codechicken.lib.colour.ColourRGBA;
import codechicken.lib.render.CCModel;
import codechicken.lib.render.CCRenderState;
import codechicken.lib.render.IVertexModifier;
import codechicken.lib.render.UV;
import codechicken.lib.vec.Vector3;

/**
 * Faster precomputed version of LightModel that only works for axis planar sides
 */
public class PlanarLightModel implements IVertexModifier
{
    public ColourRGBA[] colours;

    public PlanarLightModel(int[] colours)
    {
        this.colours = new ColourRGBA[6];
        for(int i = 0; i < 6; i++)
            this.colours[i] = new ColourRGBA(colours[i]);
    }

    @Override
    public void applyModifiers(CCModel m, Tessellator tess, Vector3 vec, UV uv, Vector3 normal, int i)
    {
        ColourRGBA light = colours[CCModel.findSide(normal)];
        int colour = (m == null || m.colours == null) ? -1 : m.colours[i];
        Colour res = new ColourRGBA(colour).multiply(light);
        CCRenderState.vertexColour(res.r&0xFF, res.g&0xFF, res.b&0xFF, res.a&0xFF) ;
    }

    @Override
    public boolean needsNormals()
    {
        return true;
    }
}

package codechicken.lib.lighting;

import net.minecraft.client.renderer.Tessellator;
import codechicken.lib.colour.Colour;
import codechicken.lib.colour.ColourRGBA;
import codechicken.lib.render.CCModel;
import codechicken.lib.render.CCRenderState;
import codechicken.lib.render.IVertexModifier;
import codechicken.lib.render.UV;
import codechicken.lib.vec.Vector3;

/**
 * Faster precomputed version of LightModel that only works for axis planar sides
 */
public class PlanarLightModel implements IVertexModifier
{
    public static PlanarLightModel standardLightModel = LightModel.standardLightModel.reducePlanar();

    public ColourRGBA[] colours;

    public PlanarLightModel(int[] colours)
    {
        this.colours = new ColourRGBA[6];
        for(int i = 0; i < 6; i++)
            this.colours[i] = new ColourRGBA(colours[i]);
    }

    @Override
    public void applyModifiers(CCModel m, Tessellator tess, Vector3 vec, UV uv, Vector3 normal, int i)
    {
        ColourRGBA light = colours[CCModel.findSide(normal)];
        int colour = (m == null || m.colours == null) ? -1 : m.colours[i];
        Colour res = new ColourRGBA(colour).multiply(light);
        CCRenderState.vertexColour(res.r&0xFF, res.g&0xFF, res.b&0xFF, res.a&0xFF) ;
    }

    @Override
    public boolean needsNormals()
    {
        return true;
    }
}

Add standard planar light model

Add standard planar light model


/*
 * Kurento Android Media: Android Media Library based on FFmpeg.
 * Copyright (C) 2011  Tikal Technologies
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.kurento.kas.media.rx;

public interface AudioRx {

	/**
	 * Receive a set of audio samples.
	 *
	 * @param audio
	 *            audio samples in PCM16.
	 * @param length
	 *            number of audio samples.
	 * @param nFrame
	 *            audio frame id.
	 */
	public void putAudioSamplesRx(byte[] audio, int length, int nFrame);

}

/*
 * Kurento Android Media: Android Media Library based on FFmpeg.
 * Copyright (C) 2011  Tikal Technologies
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.kurento.kas.media.rx;

public interface AudioRx {

	/**
	 * Receive audio samples
	 *
	 * @param audioSamples
	 */
	public void putAudioSamplesRx(AudioSamples audioSamples);

}

Use AudioSamples object as param in putAudioSamplesRx method.


package com.rabenauge.gl;

import javax.microedition.khronos.opengles.GL11;

/*
 * Wrapper class for point sprites (requires GL_OES_point_sprite).
 */
public class PointSprite extends Texture2D {
    public PointSprite(GL11 gl) {
        super(gl);
    }

    public void enable(boolean state) {
        super.enable(state);
        if (state) {
            gl.glEnable(GL11.GL_POINT_SPRITE_OES);
            gl.glTexEnvx(GL11.GL_POINT_SPRITE_OES, GL11.GL_COORD_REPLACE_OES, 1);
        }
        else {
            gl.glDisable(GL11.GL_POINT_SPRITE_OES);
            gl.glTexEnvx(GL11.GL_POINT_SPRITE_OES, GL11.GL_COORD_REPLACE_OES, 0);
        }
    }

    public void setSize(float size) {
        gl.glPointSize(size);
    }
}

package com.rabenauge.gl;

import javax.microedition.khronos.opengles.GL11;

/*
 * Wrapper class for point sprites (requires GL_OES_point_sprite).
 */
public class PointSprite extends Texture2D {
    public PointSprite(GL11 gl) {
        super(gl);
    }

    public void enable(boolean state) {
        enable(state, state);
    }

    public void enable(boolean spriting, boolean texturing) {
        super.enable(texturing);
        if (spriting) {
            gl.glEnable(GL11.GL_POINT_SPRITE_OES);
            gl.glTexEnvx(GL11.GL_POINT_SPRITE_OES, GL11.GL_COORD_REPLACE_OES, 1);
        }
        else {
            gl.glDisable(GL11.GL_POINT_SPRITE_OES);
            gl.glTexEnvx(GL11.GL_POINT_SPRITE_OES, GL11.GL_COORD_REPLACE_OES, 0);
        }
    }

    public void setSize(float size) {
        gl.glPointSize(size);
    }
}

Add an argument allowing to toggle point sprites and texturing separately


package com.paperfly.instantjio.contacts;

import android.net.Uri;

/**
 * Entity model that represents a contact
 */
final public class Contact {
    final private String photoUri;
    final private String displayName;
    final private Uri contactUri;

    public Contact(String photoUri, String displayName, Uri contactUri) {
        this.photoUri = photoUri;
        this.displayName = displayName;
        this.contactUri = contactUri;
    }

    public String getPhotoUri() {
        return photoUri;
    }

    public String getDisplayName() {
        return displayName;
    }

    public Uri getContactUri() {
        return contactUri;
    }
}

package com.paperfly.instantjio.contacts;

import android.net.Uri;

/**
 * Entity model that represents a contact
 */
public class Contact {
    String photoUri;
    String displayName;
    Uri contactUri;

    public Contact() {
    }

    public Contact(String photoUri, String displayName, Uri contactUri) {
        this.photoUri = photoUri;
        this.displayName = displayName;
        this.contactUri = contactUri;
    }

    public String getPhotoUri() {
        return photoUri;
    }

    public String getDisplayName() {
        return displayName;
    }

    public Uri getContactUri() {
        return contactUri;
    }
}

Change to fit Firebase model class style


package com.seventh_root.atherna;

import com.seventh_root.atherna.character.AthernaCharacterManager;
import com.seventh_root.atherna.command.CharacterCommand;
import com.seventh_root.atherna.player.AthernaPlayerManager;
import org.bukkit.plugin.java.JavaPlugin;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import static java.util.logging.Level.SEVERE;

public class Atherna extends JavaPlugin {

    private Connection databaseConnection;

    private AthernaCharacterManager characterManager;
    private AthernaPlayerManager playerManager;

    @Override
    public void onEnable() {
        try {
            databaseConnection = DriverManager.getConnection(
                    "jdbc:mysql://" + getConfig().getString("url") + "/" + getConfig().getString("database"),
                    getConfig().getString("username"),
                    getConfig().getString("password")
            );
        } catch (SQLException exception) {
            getLogger().log(SEVERE, "Failed to connect to database", exception);
        }
        characterManager = new AthernaCharacterManager(this);
        playerManager = new AthernaPlayerManager(this);
        getCommand("character").setExecutor(new CharacterCommand(this));
    }

    public Connection getDatabaseConnection() {
        return databaseConnection;
    }

    public AthernaCharacterManager getCharacterManager() {
        return characterManager;
    }

    public AthernaPlayerManager getPlayerManager() {
        return playerManager;
    }

}

package com.seventh_root.atherna;

import com.seventh_root.atherna.character.AthernaCharacterManager;
import com.seventh_root.atherna.command.CharacterCommand;
import com.seventh_root.atherna.player.AthernaPlayerManager;
import org.bukkit.plugin.java.JavaPlugin;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import static java.util.logging.Level.SEVERE;

public class Atherna extends JavaPlugin {

    private Connection databaseConnection;

    private AthernaCharacterManager characterManager;
    private AthernaPlayerManager playerManager;

    @Override
    public void onEnable() {
        saveDefaultConfig();
        try {
            databaseConnection = DriverManager.getConnection(
                    "jdbc:mysql://" + getConfig().getString("url") + "/" + getConfig().getString("database"),
                    getConfig().getString("username"),
                    getConfig().getString("password")
            );
        } catch (SQLException exception) {
            getLogger().log(SEVERE, "Failed to connect to database", exception);
        }
        characterManager = new AthernaCharacterManager(this);
        playerManager = new AthernaPlayerManager(this);
        getCommand("character").setExecutor(new CharacterCommand(this));
    }

    public Connection getDatabaseConnection() {
        return databaseConnection;
    }

    public AthernaCharacterManager getCharacterManager() {
        return characterManager;
    }

    public AthernaPlayerManager getPlayerManager() {
        return playerManager;
    }

}

Save default config before starting

Save default config before starting


package cats;

import java.awt.*;
import javax.swing.*;

public class WikiWiki extends JApplet{
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	public void paint(Graphics g) {
		super.paint(g);
		g.drawString("I AM SIR STRING, THE NOBLE!",25,25);
		g.drawString("Hey, Man!",25,40);
		g.drawString("The cat says 'Meow'.",25,55);
	}
}

package cats;

import java.awt.*;
import javax.swing.*;

public class WikiWiki extends JApplet{
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	public void paint(Graphics g) {
		super.paint(g);
		g.drawString("I AM SIR STRING, THE NOBLE!",25,25);
		g.drawString("Hey, Man!",25,35);
		g.drawString("The cat says 'Meow'.",25,45);
	}
}

Revert "The Aesthetically Pleasing Update (v0.25)"


package net.darkmorford.btweagles.block;

import net.darkmorford.btweagles.BetterThanWeagles;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class BlockMemeOre extends Block
{
	public BlockMemeOre()
	{
		super(Material.ROCK);

		setRegistryName(BetterThanWeagles.MODID, "meme_ore");
		setUnlocalizedName("meme_ore");
		setCreativeTab(BetterThanWeagles.tabBTWeagles);
	}

	@SideOnly(Side.CLIENT)
	public void initModel()
	{
		ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(this), 0, new ModelResourceLocation(getRegistryName(), "inventory"));
	}
}

package net.darkmorford.btweagles.block;

import net.darkmorford.btweagles.BetterThanWeagles;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class BlockMemeOre extends Block
{
	public BlockMemeOre()
	{
		super(Material.ROCK);

		setRegistryName(BetterThanWeagles.MODID, "meme_ore");
		setUnlocalizedName("meme_ore");
		setCreativeTab(BetterThanWeagles.tabBTWeagles);

		setHardness(1.5F);
		setResistance(1000.0F);
		setHarvestLevel("pickaxe", 2);
	}

	@SideOnly(Side.CLIENT)
	public void initModel()
	{
		ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(this), 0, new ModelResourceLocation(getRegistryName(), "inventory"));
	}
}

Set mining characteristics for meme ore.


package water;

import water.api.JStack;
import org.junit.*;

public class JStackTest extends TestUtil {

  @BeforeClass public static void stall() { stall_till_cloudsize(3); }

  @Test public void testJStack() {
    for( int i=0; i<100; i++ ) {
      JStack js = new JStack();
      js.serve();
      Assert.assertEquals(js.nodes.length,H2O.CLOUD.size());
    }
  }
}

package water;

import water.api.JStack;
import org.junit.*;

public class JStackTest extends TestUtil {

  @BeforeClass public static void stall() { stall_till_cloudsize(3); }

  @Test public void testJStack() {
    for( int i=0; i<10; i++ ) {
      JStack js = new JStack();
      js.serve();
      Assert.assertEquals(js.nodes.length,H2O.CLOUD.size());
    }
  }
}

Decrease number of iteration in the test.


package com.eyekabob;

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

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

/**
 * © Copyright 2012 Brien Coffield
 * All rights reserved
 * <p/>
 * This file is subject to the terms and conditions defined in
 * file 'LICENSE.txt', which is part of this source code package.
 */
@Path("/main")
public class Main {
    @GET
    @Produces("application/json")
    public String helloWorld() throws JSONException {
        JSONObject response = new JSONObject();
        response.put("response", "Hello, world!");
        return response.toString();
    }
}

package com.eyekabob;

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

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

/**
 * © Copyright 2012 Brien Coffield
 * All rights reserved
 * <p/>
 * This file is subject to the terms and conditions defined in
 * file 'LICENSE.txt', which is part of this source code package.
 */
@Path("/main")
public class Main {
    @GET
    @Produces("application/json")
    public String helloWorld(@QueryParam("param") String param) throws JSONException {
        JSONObject response = new JSONObject();
        response.put("response", "Hello, world! " + param);
        return response.toString();
    }
}

Add query param to the hello world web service


package ca.intelliware.ihtsdo.mlds.search;

import java.io.File;

import org.springframework.core.io.FileSystemResourceLoader;
import org.springframework.mock.web.MockServletContext;

public class AngularTranslateServiceSetup {
	MockServletContext mockServletContext;
	AngularTranslateService angularTranslateService;

	public void setup() {
		System.out.println("AngularTranslateServiceSetup - working directory is " + new File(".").getAbsolutePath());
		mockServletContext = new MockServletContext("src/main/webapp", new FileSystemResourceLoader());
		angularTranslateService = new AngularTranslateService();
		angularTranslateService.setServletContext(mockServletContext);
	}
}

package ca.intelliware.ihtsdo.mlds.search;

import org.springframework.core.io.FileSystemResourceLoader;
import org.springframework.mock.web.MockServletContext;

public class AngularTranslateServiceSetup {
	MockServletContext mockServletContext;
	AngularTranslateService angularTranslateService;

	public void setup() {
		if (AngularTranslateService.getInstance() == null) {
			angularTranslateService = new AngularTranslateService();
		} else {
			angularTranslateService = AngularTranslateService.getInstance();
		}

		mockServletContext = new MockServletContext("src/main/webapp", new FileSystemResourceLoader());
		angularTranslateService.setServletContext(mockServletContext);
	}
}

Patch AngularTranslateService during test to avoid odd servlet resource location behaviour


package com.fasterxml.jackson.databind.jsontype.impl;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.jsontype.TypeIdResolver;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;

public abstract class TypeSerializerBase extends TypeSerializer
{
    protected final TypeIdResolver _idResolver;

    protected final BeanProperty _property;

    protected TypeSerializerBase(TypeIdResolver idRes, BeanProperty property)
    {
        _idResolver = idRes;
        _property = property;
    }

    @Override
    public abstract JsonTypeInfo.As getTypeInclusion();

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

    @Override
    public TypeIdResolver getTypeIdResolver() { return _idResolver; }

    /*
    /**********************************************************
    /* Helper methods for subclasses
    /**********************************************************
     */

    protected String idFromValue(Object value) {
        return _idResolver.idFromValue(value);
    }

    protected String idFromValueAndType(Object value, Class<?> type) {
        return _idResolver.idFromValueAndType(value, type);
    }
}

package com.fasterxml.jackson.databind.jsontype.impl;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.jsontype.TypeIdResolver;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;

public abstract class TypeSerializerBase extends TypeSerializer
{
    protected final TypeIdResolver _idResolver;

    protected final BeanProperty _property;

    protected TypeSerializerBase(TypeIdResolver idRes, BeanProperty property)
    {
        _idResolver = idRes;
        _property = property;
    }

    @Override
    public abstract JsonTypeInfo.As getTypeInclusion();

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

    @Override
    public TypeIdResolver getTypeIdResolver() { return _idResolver; }

    /*
    /**********************************************************
    /* Helper methods for subclasses
    /**********************************************************
     */

    protected String idFromValue(Object value) {
        String id = _idResolver.idFromValue(value);
        if (id == null) {
            String typeDesc = (value == null) ? "NULL" : value.getClass().getName();
            throw new IllegalArgumentException("Can not resolve type id for "
                    +typeDesc+" (using "+_idResolver.getClass().getName()+")");
        }
        return id;
    }

    protected String idFromValueAndType(Object value, Class<?> type) {
        String id = _idResolver.idFromValueAndType(value, type);
        if (id == null) {
            String typeDesc = (value == null) ? "NULL" : value.getClass().getName();
            throw new IllegalArgumentException("Can not resolve type id for "
                    +typeDesc+" (using "+_idResolver.getClass().getName()+")");
        }
        return id;
    }
}

Add more consistency checks for type id generation


package bakatxt.log;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

public class BakaLogFormatter extends Formatter {

    private static final int MAX_BUFFER = 1000;
    private static final String DATE_FORMAT = "HH:mm:ss:SSS";
    private static final String SPACE = " ";
    private static final String COLON = ":";
    private static final String LINE_SEPARATOR = System
            .getProperty("line.separator");

    @Override
    public String format(LogRecord record) {
        StringBuffer output = new StringBuffer(MAX_BUFFER);

        output.append(calculateDate(record.getMillis()));
        output.append(SPACE);
        output.append(record.getSourceClassName());
        output.append(SPACE);
        output.append(record.getSourceMethodName());
        output.append("\t");
        output.append(record.getLevel());
        output.append(COLON + SPACE);
        output.append(formatMessage(record));
        output.append(LINE_SEPARATOR);

        return output.toString();
    }

    private static String calculateDate(long ms) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
        Date rawDate = new Date(ms);
        return dateFormat.format(rawDate);
    }

    @Override
    public String getHead(Handler handler) {
        Date now = new Date();
        return "Session: " + now.toString() + LINE_SEPARATOR;
    }

    @Override
    public String getTail(Handler h) {
        return "End Session" + LINE_SEPARATOR + LINE_SEPARATOR;
    }
}

package bakatxt.log;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

public class BakaLogFormatter extends Formatter {

    private static final int MAX_BUFFER = 1000;
    private static final String DATE_FORMAT = "HH:mm:ss:SSS";
    private static final String SPACE = " ";
    private static final String COLON = ":";
    private static final String LINE_SEPARATOR = System
            .getProperty("line.separator");

    @Override
    public String format(LogRecord record) {
        StringBuffer output = new StringBuffer(MAX_BUFFER);

        output.append(calculateDate(record.getMillis()));
        output.append(SPACE);
        output.append(record.getSourceClassName());
        output.append(SPACE);
        output.append(record.getSourceMethodName());
        output.append(LINE_SEPARATOR + "\t");
        output.append(record.getLevel());
        output.append(COLON + SPACE);
        output.append(formatMessage(record));
        output.append(LINE_SEPARATOR);

        return output.toString();
    }

    private static String calculateDate(long ms) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
        Date rawDate = new Date(ms);
        return dateFormat.format(rawDate);
    }

    @Override
    public String getHead(Handler handler) {
        Date now = new Date();
        return "Session: " + now.toString() + LINE_SEPARATOR;
    }

    @Override
    public String getTail(Handler h) {
        return "End Session" + LINE_SEPARATOR + LINE_SEPARATOR;
    }
}

Change formatting of log file to enhance readability


package htmlflow;

import java.io.PrintStream;

public interface HtmlWriter<T>{
	/**
	 * Writes into an internal PrintStream the HTML content
	 * if this element.
	 *
	 * @param depth The number of tabs indentation.
	 * @param model An optional object model that could be bind to this element.
	 */
	void write(int depth, T model);

	/**
	 * Sets the current PrintStream.
	 * @param out
	 */
	HtmlWriter<T> setPrintStream(PrintStream out);
}

package htmlflow;

import java.io.PrintStream;

public interface HtmlWriter<T>{
	/**
	 * Writes into an internal PrintStream the HTML content
	 * of this element with initial indentation of zero.
	 *
	 * @param model An optional object model that could be bind to this element.
	 */
	default void write(T model) {
		write(0, model);
	}
	/**
	 * Writes into an internal PrintStream the HTML content
	 * of this element.
	 *
	 * @param depth The number of tabs indentation.
	 * @param model An optional object model that could be bind to this element.
	 */
	void write(int depth, T model);

	/**
	 * Sets the current PrintStream.
	 * @param out
	 */
	HtmlWriter<T> setPrintStream(PrintStream out);
}

Add write(T model) method without indentation parameter


package replicant;

import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static org.realityforge.braincheck.Guards.*;

/**
 * A base class that interacts with ReplicantContext.
 */
abstract class ReplicantService
{
  /**
   * Reference to the context to which this service belongs.
   */
  @Nullable
  private final ReplicantContext _context;

  ReplicantService( @Nullable final ReplicantContext context )
  {
    if ( Replicant.shouldCheckInvariants() )
    {
      apiInvariant( () -> Replicant.areZonesEnabled() || null == context,
                    () -> "Replicant-0134: ReplicantService passed a context but Replicant.areZonesEnabled() is false" );
    }
    _context = Replicant.areZonesEnabled() ? Objects.requireNonNull( context ) : null;
  }

  @Nonnull
  protected final ReplicantContext getReplicantContext()
  {
    return Replicant.areZonesEnabled() ? Objects.requireNonNull( _context ) : Replicant.context();
  }
}

package replicant;

import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static org.realityforge.braincheck.Guards.*;

/**
 * A base class that interacts with ReplicantContext.
 */
abstract class ReplicantService
{
  /**
   * Reference to the context to which this service belongs.
   */
  @Nullable
  private final ReplicantContext _context;

  ReplicantService( @Nullable final ReplicantContext context )
  {
    if ( Replicant.shouldCheckInvariants() )
    {
      invariant( () -> Replicant.areZonesEnabled() || null == context,
                 () -> "Replicant-0134: ReplicantService passed a context but Replicant.areZonesEnabled() is false" );
    }
    _context = Replicant.areZonesEnabled() ? Objects.requireNonNull( context ) : null;
  }

  @Nonnull
  protected final ReplicantContext getReplicantContext()
  {
    return Replicant.areZonesEnabled() ? Objects.requireNonNull( _context ) : Replicant.context();
  }
}

Align invarint check with guard

Align invarint check with guard


Update API version for previous IElectricCart bugfix


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package wge3.model.audio;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;

/**
 *
 * @author Teemu
 */
public class DefaultGun implements MySound {

    private Sound sound;

    public DefaultGun() {
        try {
            sound = Gdx.audio.newSound(Gdx.files.internal("sounds/defaultGun2-16.wav"));
        } catch (Exception ex) {
            System.out.println("Error with playing sound.");
            ex.printStackTrace();
        }
    }

    @Override
    public void play() {
        sound.play();
    }
}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package wge3.model.audio;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;

/**
 *
 * @author Teemu
 */
public class DefaultGun implements MySound {

    private Sound sound;

    public DefaultGun() {
        try {
            sound = Gdx.audio.newSound(Gdx.files.internal("sounds/defaultGun.wav"));
        } catch (Exception ex) {
            System.out.println("Error with playing sound.");
            ex.printStackTrace();
        }
    }

    @Override
    public void play() {
        sound.play();
    }
}

Use correct sound file name

Use correct sound file name


/*
 * Copyright (C) 2011 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.
 */

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

public class Main implements Runnable {
    public static void main(String[] args) throws Exception {
        Thread[] threads = new Thread[16];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(new Main(i));
        }
        for (Thread thread : threads) {
            thread.start();
        }
        for (Thread thread : threads) {
            thread.join();
        }
    }

    private final int id;

    private Main(int id) {
        this.id = id;
    }

    public void run() {
        List l = new ArrayList();
        for (int i = 0; i < 1000; i++) {
            l.add(new ArrayList(i));
        }
    }
}

/*
 * Copyright (C) 2011 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.
 */

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

public class Main implements Runnable {
    public static void main(String[] args) throws Exception {
        Thread[] threads = new Thread[16];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(new Main(i));
        }
        for (Thread thread : threads) {
            thread.start();
        }
        for (Thread thread : threads) {
            thread.join();
        }
    }

    private final int id;

    private Main(int id) {
        this.id = id;
    }

    public void run() {
        List l = new ArrayList();
        for (int i = 0; i < 500; i++) {
            l.add(new ArrayList(i));
        }
    }
}

Reduce allocations in ParallelGC test.

Reduce allocations in ParallelGC test.

Fixes GC stress test mode.

Bug: 16406852
Change-Id: I86c8fd7516c3f41075bca00c7d5b4dab2bb7b1d4


package dk.dtu.brainfuckcomp;

import java.util.Scanner;

public class Main {

	private static final String HELLO = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.";

	public static void main(String[] args) {
		int n;
		if (args.length == 0) {
			System.out.println("Length of Brainfuck array not specified. Defaulting to 8.");
			n = 8;
		} else {
			n = Integer.parseInt(args[0]);
		}

		Brainfuck bf = new Brainfuck(n);
		Scanner sc = new Scanner(System.in);

        System.out.println("Enter Brainfuck (Leave blank for \"Hello World!\"):");
        String str = sc.nextLine();
		if (str.equals("")) {
			str = HELLO;
		}
		sc.close();

		try {
			bf.parse(str);
		} catch (UnknownSymbolExeption e) {
			e.printStackTrace();
		}

		System.out.println(bf.toString());
	}
}

package dk.dtu.brainfuckcomp;

import java.util.Scanner;

public class Main {

	private static final String HELLO = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.";

	public static void main(String[] args) {
		int n;
		if (args.length == 0) {
			System.out.println("Length of Brainfuck array not specified. Defaulting to 8.");
			n = 8;
		} else {
			n = Integer.parseInt(args[0]);
		}

		Brainfuck bf = new Brainfuck(n);
		Scanner sc = new Scanner(System.in);

        System.out.println("Enter Brainfuck (Leave blank for \"Hello World!\"):");
        String str = sc.nextLine();
		if (str.equals("")) {
			str = HELLO;
		}

		try {
			bf.parse(str);
		} catch (UnknownSymbolExeption e) {
			e.printStackTrace();
		}

		System.out.println(bf.toString());
		sc.close();
	}
}

Move sv.close as it causes trouble when Brainfuck tries to read


package com.rabenauge.parandroid;

import android.app.Activity;
import com.rabenauge.demo.*;
import com.rabenauge.gl.*;
import javax.microedition.khronos.opengles.GL11;

public class ColorFade extends EffectManager {
    private boolean in;
    private float r, g, b;

    private class Fade extends Effect {
        public void onRender(GL11 gl, long t, long e, float s) {
            // Set OpenGL states.
            gl.glDisable(GL11.GL_TEXTURE_2D);

            float a=in?1-s:s;
            gl.glColor4f(r, g, b, a);
            Helper.drawScreenSpaceQuad(gl);
            gl.glColor4f(1, 1, 1, 1);

            // Restore OpenGL states.
            gl.glEnable(GL11.GL_TEXTURE_2D);
        }
    }

    public ColorFade(Activity activity, GL11 gl, long t, boolean in, float r, float g, float b) {
        super(gl);

        this.in=in;

        this.r=r;
        this.g=g;
        this.b=b;

        add(new Fade(), t);
    }
}

package com.rabenauge.parandroid;

import android.app.Activity;
import com.rabenauge.demo.*;
import com.rabenauge.gl.*;
import javax.microedition.khronos.opengles.GL11;

public class ColorFade extends EffectManager {
    private boolean in;
    private float r, g, b;

    private class Fade extends Effect {
        public void onRender(GL11 gl, long t, long e, float s) {
            // Set OpenGL states.
            gl.glDisable(GL11.GL_TEXTURE_2D);

            float a=in?1-s:s;
            gl.glColor4f(r, g, b, a);
            Helper.drawScreenSpaceQuad(gl);
            gl.glColor4f(1, 1, 1, 1);

            // Restore OpenGL states.
            gl.glEnable(GL11.GL_TEXTURE_2D);
        }
    }

    public ColorFade(Activity activity, GL11 gl, long t, boolean in, float r, float g, float b) {
        super(gl);

        this.in=in;

        this.r=r;
        this.g=g;
        this.b=b;

        // Schedule the effects in this part.
        add(new Fade(), t);
    }
}

Add a comment for consistency

Add a comment for consistency


package {{package}};

import org.robovm.cocoatouch.foundation.NSAutoreleasePool;
import org.robovm.cocoatouch.uikit.UIApplication;

import com.badlogic.gdx.backends.iosrobovm.IOSApplication;
import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration;

public class {{ios-class-name}} extends IOSApplication.Delegate {
	protected IOSApplication createApplication() {
		IOSApplicationConfiguration config = new IOSApplicationConfiguration();
		return new IOSApplication(new {{class-name}}(), config);
	}

	public static void main(String[] argv) {
		NSAutoreleasePool pool = new NSAutoreleasePool();
		UIApplication.main(argv, null, {{ios-class-name}}.class);
		pool.drain();
	}
}

package {{package}};

import com.badlogic.gdx.*;
import com.badlogic.gdx.backends.iosrobovm.*;

import org.robovm.apple.foundation.*;
import org.robovm.apple.uikit.*;

public class {{ios-class-name}} extends IOSApplication.Delegate {
	protected IOSApplication createApplication() {
		IOSApplicationConfiguration config = new IOSApplicationConfiguration();
		return new IOSApplication(new {{class-name}}(), config);
	}

	public static void main(String[] argv) {
		NSAutoreleasePool pool = new NSAutoreleasePool();
		UIApplication.main(argv, null, {{ios-class-name}}.class);
		pool.close();
	}
}

Update java game template for RoboVM 0.0.11


/*
 * Copyright (c) OSGi Alliance (2014, 2016). 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 org.osgi.converter;

import org.osgi.annotation.versioning.ConsumerType;

/**
 * A function that accepts a single argument and produces a result.
 * <p>
 * This is a functional interface and can be used as the assignment target for a
 * lambda expression or method reference.
 *
 * @param <F> The type of the function input.
 * @param <T> The type of the function output.
 * @ThreadSafe
 * @author $Id$
 */
@ConsumerType
@FunctionalInterface
public interface Function<F, T> {
	/**
	 * Applies this function to the specified argument.
	 *
	 * @param t The input to this function.
	 * @return The output of this function.
	 * @throws Exception An exception thrown by the method.
	 */
	T convert(F t) throws Exception;
}

/*
 * Copyright (c) OSGi Alliance (2014, 2016). 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 org.osgi.converter;

import org.osgi.annotation.versioning.ConsumerType;

/**
 * An functional interface with a single convert method that is passed the
 * object to be converted.
 *
 * @param <F> Type parameter for the source object.
 * @param <T> Type parameter for the converted object.
 * @ThreadSafe
 * @author $Id$
 */
@ConsumerType
@FunctionalInterface
public interface Function<F, T> {
	/**
	 * /** Convert the object into the target type.
	 *
	 * @param obj The object to be converted. This object will never be
	 *            {@code null} as the convert function will not be invoked for
	 *            null values.
	 * @return The conversion result or {@code null} to indicate that the
	 *         convert function cannot handle this conversion. In this case the
	 *         next matching rule or adapter will be given a opportunity to
	 *         convert.
	 * @throws Exception
	 */
	T convert(F obj) throws Exception;
}

Refactor Javadoc on converter API

Refactor Javadoc on converter API


package api.requests;

import api.son.MySon;
import api.soup.MySoup;

/**
 * The Class Request.
 * For using the API related to viewing Requests
 *
 * @author Gwindow
 */
public class Request {
	/** The API response. */
	private Response response;

	/** The response status */
	private String status;

	/**
	 * Get a request from the request id
	 *
	 * @param id
	 *      the request id
	 * @return the request
	 */
	public static Request fromId(int id) {
		String authkey = MySoup.getAuthKey();
		String url = "ajax.php?action=request&id=" + id + "&auth=" + authkey;
		return (Request) MySon.toObject(url, Request.class);
	}

	/**
	 * Get the API response
	 *
	 * @return the response
	 */
	public Response getResponse() {
		return response;
	}

	/**
	 * Get the status of the request
	 *
	 * @return True if success
	 */
	public boolean getStatus() {
        return status.equalsIgnoreCase("success");
	}

	@Override
	public String toString() {
		return "Request [getResponse=" + getResponse() + ", getStatus=" + getStatus() + "]";
	}
}

package api.requests;

import api.son.MySon;
import api.soup.MySoup;

/**
 * The Class Request.
 * For using the API related to viewing Requests
 *
 * @author Gwindow
 */
public class Request {
	/** The API response. */
	private Response response;

	/** The response status */
	private String status;

	/**
	 * Get a request from the request id
	 *
	 * @param id
	 *      the request id
	 * @return the request
	 */
	public static Request fromId(int id) {
		String url = "ajax.php?action=request&id=" + id + "&auth=" + MySoup.getAuthKey();
		return (Request) MySon.toObject(url, Request.class);
	}

	/**
	 * Add some bounty to the request
	 * @param amount bounty to add in bytes
	 */
	public void vote(long amount){
		String url = "requests.php?action=takevote&id=" + response.getRequestId()
			+ "&auth=" + MySoup.getAuthKey() + "&amount=" + Long.toString(amount);
		MySoup.pressLink(url);
	}

	/**
	 * Get the API response
	 *
	 * @return the response
	 */
	public Response getResponse() {
		return response;
	}

	/**
	 * Get the status of the request
	 *
	 * @return True if success
	 */
	public boolean getStatus() {
        return status.equalsIgnoreCase("success");
	}

	@Override
	public String toString() {
		return "Request [getResponse=" + getResponse() + ", getStatus=" + getStatus() + "]";
	}
}

Add ability to vote on a request

Add ability to vote on a request


package flyway.asdi;

import java.sql.Connection;
import java.util.List;

import org.flywaydb.core.api.migration.jdbc.JdbcMigration;

import fi.nls.oskari.db.BundleHelper;
import fi.nls.oskari.domain.map.view.Bundle;
import fi.nls.oskari.util.FlywayHelper;

public class V1_19_0__remove_asdi_guided_tour implements JdbcMigration {

	private static final String BUNDLE_NAME = "asdi-guided-tour";

	@Override
	public void migrate(Connection connection) throws Exception {

		Bundle bundle = new Bundle();
		bundle.setName(BUNDLE_NAME);

		final List<Long> views = FlywayHelper.getUserAndDefaultViewIds(connection);
		for (Long viewId : views) {
			if (FlywayHelper.viewContainsBundle(connection, BUNDLE_NAME, viewId)) {
				FlywayHelper.removeBundleFromView(connection, BUNDLE_NAME, viewId);
			}

		}
		BundleHelper.removeBundle(bundle, connection);
	}

}

package flyway.asdi;

import java.sql.Connection;
import java.util.List;

import org.flywaydb.core.api.migration.jdbc.JdbcMigration;

import fi.nls.oskari.db.BundleHelper;
import fi.nls.oskari.util.FlywayHelper;

public class V1_19_0__remove_asdi_guided_tour implements JdbcMigration {

	private static final String BUNDLE_NAME = "asdi-guided-tour";

	@Override
	public void migrate(Connection connection) throws Exception {

		final List<Long> views = FlywayHelper.getUserAndDefaultViewIds(connection);
		for (Long viewId : views) {
			if (FlywayHelper.viewContainsBundle(connection, BUNDLE_NAME, viewId)) {
				FlywayHelper.removeBundleFromView(connection, BUNDLE_NAME, viewId);
			}

		}
		BundleHelper.unregisterBundle(BUNDLE_NAME, connection);
	}

}

Update helper method call to unregister bundle


package stray.util.render;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;

public class StencilMaskUtil {

	/**
	 * call this BEFORE rendering with ShapeRenderer and BEFORE drawing sprites, and AFTER what you want in the background rendered
	 */
	public static void prepareMask() {
		Gdx.gl20.glDepthFunc(GL20.GL_LESS);

		Gdx.gl20.glEnable(GL20.GL_DEPTH_TEST);

		Gdx.gl20.glDepthMask(true);
		Gdx.gl20.glColorMask(false, false, false, false);
	}

	/**
	 * call this AFTER batch.begin() and BEFORE drawing sprites
	 */
	public static void useMask() {
		Gdx.gl20.glDepthMask(false);
		Gdx.gl20.glColorMask(true, true, true, true);

		Gdx.gl20.glEnable(GL20.GL_DEPTH_TEST);

		Gdx.gl20.glDepthFunc(GL20.GL_EQUAL);
	}

	/**
	 * call this AFTER batch.flush/end
	 */
	public static void resetMask(){
		Gdx.gl20.glDisable(GL20.GL_DEPTH_TEST);
	}
}

package stray.util.render;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;

public class StencilMaskUtil {

	/**
	 * call this BEFORE rendering with ShapeRenderer and BEFORE drawing sprites, and AFTER what you want in the background rendered
	 */
	public static void prepareMask() {
		Gdx.gl.glDepthFunc(GL20.GL_LESS);

		Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);

		Gdx.gl.glDepthMask(true);
		Gdx.gl.glColorMask(false, false, false, false);
	}

	/**
	 * call this AFTER batch.begin() and BEFORE drawing sprites
	 */
	public static void useMask() {
		Gdx.gl.glDepthMask(false);
		Gdx.gl.glColorMask(true, true, true, true);

		Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);

		Gdx.gl.glDepthFunc(GL20.GL_EQUAL);
	}

	/**
	 * call this AFTER batch.flush/end
	 */
	public static void resetMask(){
		Gdx.gl.glDisable(GL20.GL_DEPTH_TEST);
	}
}

Refactor to use gdx GL instead of GL20

Refactor to use gdx GL instead of GL20