//
// $Id: SafeScrollPane.java,v 1.3 2002/07/09 21:13:20 ray Exp $

package com.threerings.media;

import java.awt.Component;

import javax.swing.JScrollPane;
import javax.swing.JViewport;

/**
 * A scroll pane that is safe to use in frame managed views.
 */
public class SafeScrollPane extends JScrollPane
{
    public SafeScrollPane (Component view)
    {
        super(view);
    }

    protected JViewport createViewport ()
    {
        JViewport vp = new JViewport();
        vp.setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
        return vp;
    }
}

//
// $Id: SafeScrollPane.java,v 1.4 2002/10/06 20:57:36 mdb Exp $

package com.threerings.media;

import java.awt.Component;

import javax.swing.JScrollPane;
import javax.swing.JViewport;

/**
 * A scroll pane that is safe to use in frame managed views.
 */
public class SafeScrollPane extends JScrollPane
{
    public SafeScrollPane ()
    {
    }

    public SafeScrollPane (Component view)
    {
        super(view);
    }

    protected JViewport createViewport ()
    {
        JViewport vp = new JViewport();
        vp.setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
        return vp;
    }
}

Allow a safe scroll pane to be constructed without its viewport view
(which should be set later via setViewportView()).

git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@1783 542714f4-19e9-0310-aa3c-eee0fc999fb1


/*******************************************************************************
 * Copyright (c) 2010, 2013 Sonatype, Inc.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Stuart McCulloch (Sonatype, Inc.) - initial API and implementation
 *******************************************************************************/
package org.sonatype.guice.bean.binders;

import java.util.List;

import com.google.inject.Module;

@Deprecated
public class WireModule
    extends org.eclipse.sisu.wire.WireModule
{
    public WireModule( final Module... modules )
    {
        super( modules );
    }

    public WireModule( final List<Module> modules )
    {
        super( modules );
    }
}

/*******************************************************************************
 * Copyright (c) 2010, 2013 Sonatype, Inc.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Stuart McCulloch (Sonatype, Inc.) - initial API and implementation
 *******************************************************************************/
package org.sonatype.guice.bean.binders;

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

import com.google.inject.Binder;
import com.google.inject.Module;

@Deprecated
public class WireModule
    implements Module
{
    private final Module delegate;

    public WireModule( final Module... modules )
    {
        this( Arrays.asList( modules ) );
    }

    public WireModule( final List<Module> modules )
    {
        delegate = new org.eclipse.sisu.wire.WireModule( modules );
    }

    public void configure( final Binder binder )
    {
        delegate.configure( binder );
    }
}

Update to use new strategy pattern

Update to use new strategy pattern


package com.mick88.dittimetable;

import java.util.List;

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

import com.michaldabski.msqlite.MSQLiteOpenHelper;
import com.mick88.dittimetable.timetable.Timetable;

public class DatabaseHelper extends MSQLiteOpenHelper
{
	private static final String name = "timetables.db";
	private static final int version = 1;
	private static final String TAG = "SQLite";

	public DatabaseHelper(Context context) {
		super(context, name, null, version, new Class<?>[]{
				Timetable.class,
		});
	}

	public Timetable getTimetable(String course, int year, String weeks)
	{
		List<Timetable> timetables = select(Timetable.class, "course=? AND year=? and weekRange=?",
				new String[]{course, String.valueOf(year), weeks},
				null, "1");
		if (timetables.isEmpty()) return null;
		Log.d(TAG, "Timetable loaded: "+timetables.get(0).describe());
		return timetables.get(0);
	}

	public void saveTimetable(Timetable timetable)
	{
		replace(timetable);
		Log.d(TAG, "Timetable saved: "+timetable.describe());
	}
}

package com.mick88.dittimetable;

import java.util.List;

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

import com.michaldabski.msqlite.MSQLiteOpenHelper;
import com.mick88.dittimetable.timetable.Timetable;

public class DatabaseHelper extends MSQLiteOpenHelper
{
	private static final String name = "timetables.db";
	private static final int version = 1;
	private static final String TAG = "SQLite";

	public DatabaseHelper(Context context) {
		super(context, name, null, version, new Class<?>[]{
				Timetable.class,
		});
	}

	public Timetable getTimetable(String course, int year, String weeks)
	{
		List<Timetable> timetables = select(Timetable.class, "course=? AND year=? and weekRange=?",
				new String[]{course, String.valueOf(year), weeks},
				null, "1");
		if (timetables.isEmpty()) return null;
		Log.d(TAG, "Timetable loaded: "+timetables.get(0).describe());
		return timetables.get(0);
	}

	public void saveTimetable(Timetable timetable)
	{
		replace(timetable);
		Log.d(TAG, "Timetable saved: "+timetable.describe());
	}

	/**
	 * returns all timetables saved in database
	 * @return
	 */
	public List<Timetable> getSavedTimetables()
	{
		return selectAll(Timetable.class);
	}
}

Add method to get all saved timetables

Add method to get all saved timetables


package net.runelite.cache;

public enum IndexType
{
	TWO(2),
	SPRITE(8);

	private int id;

	IndexType(int id)
	{
		this.id = id;
	}

	public int getNumber()
	{
		return id;
	}
}

package net.runelite.cache;

public enum IndexType
{
	TWO(2),
	MODELS(7),
	SPRITE(8);

	private int id;

	IndexType(int id)
	{
		this.id = id;
	}

	public int getNumber()
	{
		return id;
	}
}

Index 7 appears to be models. Am able to view them in rsmv.


package com.infinityraider.agricraft.plugins.industrialforegoing;

import com.buuz135.industrial.api.plant.PlantRecollectable;
import com.google.common.collect.Lists;
import com.infinityraider.agricraft.AgriCraft;
import com.infinityraider.agricraft.api.v1.AgriApi;
import net.minecraft.core.BlockPos;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;

import java.util.List;

public class AgriPlantRecollectable extends PlantRecollectable {
    protected AgriPlantRecollectable() {
        super(AgriCraft.instance.getModId());
    }

    @Override
    public boolean canBeHarvested(Level world, BlockPos blockPos, BlockState blockState) {
        return AgriApi.getCrop(world, blockPos).map(crop -> crop.hasPlant() && crop.isMature()).orElse(false);
    }

    @Override
    public List<ItemStack> doHarvestOperation(Level world, BlockPos blockPos, BlockState blockState) {
        List<ItemStack> drops = Lists.newArrayList();
        AgriApi.getCrop(world, blockPos).ifPresent(crop -> crop.harvest(drops::add, null));
        return drops;
    }

    @Override
    public boolean shouldCheckNextPlant(Level world, BlockPos blockPos, BlockState blockState) {
        return true;
    }
}

package com.infinityraider.agricraft.plugins.industrialforegoing;

import com.buuz135.industrial.api.plant.PlantRecollectable;
import com.google.common.collect.Lists;
import com.infinityraider.agricraft.AgriCraft;
import com.infinityraider.agricraft.api.v1.AgriApi;
import net.minecraft.core.BlockPos;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;

import java.util.List;

public class AgriPlantRecollectable extends PlantRecollectable {
    protected AgriPlantRecollectable() {
        super(AgriCraft.instance.getModId());
        this.setRegistryName(AgriCraft.instance.getModId(), "plant_recollectable");
    }

    @Override
    public boolean canBeHarvested(Level world, BlockPos blockPos, BlockState blockState) {
        return AgriApi.getCrop(world, blockPos).map(crop -> crop.hasPlant() && crop.isMature()).orElse(false);
    }

    @Override
    public List<ItemStack> doHarvestOperation(Level world, BlockPos blockPos, BlockState blockState) {
        List<ItemStack> drops = Lists.newArrayList();
        AgriApi.getCrop(world, blockPos).ifPresent(crop -> crop.harvest(drops::add, null));
        return drops;
    }

    @Override
    public boolean shouldCheckNextPlant(Level world, BlockPos blockPos, BlockState blockState) {
        return true;
    }
}

Fix Industrial Foregoing Compat crash

Fix Industrial Foregoing Compat crash


package net.earthcomputer.easyeditors.api;

import java.util.regex.Pattern;

/**
 * A class containing a number of {@link Pattern}s useful to Easy Editors.
 *
 * <b>This class is a member of the Easy Editors API</b>
 *
 * @author Earthcomputer
 *
 */
public class Patterns {

	public static final Pattern partialPlayerName = Pattern.compile("\\w{0,32}");

	public static final Pattern playerName = Pattern.compile("\\w{1,32}");

	public static final Pattern UUID = Pattern.compile("[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}");

	public static final Pattern partialUUID = Pattern
			.compile("[0-9a-fA-F]{0,8}-(?:[0-9a-fA-F]{0,4}-){3}[0-9a-fA-F]{0,12}");

	public static final Pattern playerSelector = Pattern.compile("@([pare])(?:\\[([\\w=,!-]*)\\])?");

	public static final Pattern partialInteger = Pattern.compile("[+-]?[0-9]*");

	public static final Pattern integer = Pattern.compile("[+-]?[0-9]+");

}

package net.earthcomputer.easyeditors.api;

import java.util.regex.Pattern;

/**
 * A class containing a number of {@link Pattern}s useful to Easy Editors.
 *
 * <b>This class is a member of the Easy Editors API</b>
 *
 * @author Earthcomputer
 *
 */
public class Patterns {

	public static final Pattern partialPlayerName = Pattern.compile("\\w{0,32}");

	public static final Pattern playerName = Pattern.compile("\\w{1,32}");

	public static final Pattern UUID = Pattern.compile("[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}");

	public static final Pattern partialUUID = Pattern
			.compile("[0-9a-fA-F]{0,8}-(?:[0-9a-fA-F]{0,4}-){3}[0-9a-fA-F]{0,12}");

	public static final Pattern playerSelector = Pattern.compile("@([pare])(?:\\[([\\w\\.=,!-]*)\\])?");

	public static final Pattern partialInteger = Pattern.compile("[+-]?[0-9]*");

	public static final Pattern integer = Pattern.compile("[+-]?[0-9]+");

}

Allow entities with dots in their names in the player selector pattern


/* NEST (New Scala Test)
 * Copyright 2007-2013 LAMP/EPFL
 * @author Grzegorz Kossakowski
 */

package scala.tools.partest.javaagent;

import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;

/**
 * Profiling agent that instruments byte-code to insert calls to
 * {@link scala.tools.partest.instrumented.Profiler#methodCalled(String, String, String)}
 * by using ASM library for byte-code manipulation.
 */
public class ProfilingAgent {
	public static void premain(String args, Instrumentation inst) throws UnmodifiableClassException {
	  // NOTE: we are adding transformer that won't be applied to classes that are already loaded
	  // This should be ok because premain should be executed before main is executed so Scala library
	  // and the test-case itself won't be loaded yet. We rely here on the fact that ASMTransformer does
	  // not depend on Scala library. In case our assumptions are wrong we can always insert call to
	  // inst.retransformClasses.
		inst.addTransformer(new ASMTransformer(), true);
	}
}

/* NEST (New Scala Test)
 * Copyright 2007-2013 LAMP/EPFL
 * @author Grzegorz Kossakowski
 */

package scala.tools.partest.javaagent;

import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;

/**
 * Profiling agent that instruments byte-code to insert calls to
 * {@link scala.tools.partest.instrumented.Profiler#methodCalled(String, String, String)}
 * by using ASM library for byte-code manipulation.
 */
public class ProfilingAgent {
	public static void premain(String args, Instrumentation inst) throws UnmodifiableClassException {
	  // NOTE: we are adding transformer that won't be applied to classes that are already loaded
	  // This should be ok because premain should be executed before main is executed so Scala library
	  // and the test-case itself won't be loaded yet. We rely here on the fact that ASMTransformer does
	  // not depend on Scala library. In case our assumptions are wrong we can always insert call to
	  // inst.retransformClasses.
	  inst.addTransformer(new ASMTransformer(), false);
	}
}

Set `canRetransform` flag to `false` in instrumentation.

We do not need to retransform classes once they are loaded.
All instrumentation byte-code is pushed at loading time.

This fixes a problem with Java 7 that was failing to add
a transformer because we did not declare retransformation
capability in `MANIFEST.MF` file in Java agent jar.
Java 6 allowed to add transformer due to a bug.


public class Ex {

	public void frotz(Object o, int y) {
		if (y == 6) {
			synchronized (o) {
				y += o.hashCode();
				if ((y & 1) == 0)
					throw new RuntimeException();
			}
		}
	}

}

public class Ex {

	public void frotz(Object o, int y) {
		if (y == 6) {
			synchronized (o) {
				y += o.hashCode();
				if ((y & 1) == 0)
					throw new RuntimeException();
			}
		}
	}

	public void alwaysThrow() {
		throw new RuntimeException();
	}

}

Add a method that always throws an unhandled exception.

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@1679 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


package ol.geom;

import ol.BaseTestCase;
import ol.Coordinate;
import ol.OLFactory;

/**
 * A test case for {@link Circle}.
 *
 * @author Tino Desjardins
 */
public class CircleTest extends BaseTestCase {

    public void test() {

        double radius = 5;

        Circle circle = OLFactory.createCircle(OLFactory.createCoordinate(10, 10), radius);
        assertNotNull(circle);
        assertTrue(circle instanceof Geometry);

        Coordinate coordinate = circle.getCenter();
        assertNotNull(coordinate);
        assert(10 == coordinate.getX());
        assert(10 == coordinate.getY());

        assert(radius == circle.getRadius());

    }

}

package ol.geom;

import ol.Coordinate;
import ol.GwtOL3BaseTestCase;
import ol.OLFactory;

/**
 * A test case for {@link Circle}.
 *
 * @author Tino Desjardins
 */
public class CircleTest extends GwtOL3BaseTestCase {

    public void testCircle() {

    	injectUrlAndTest(new TestWithInjection() {

			@Override
			public void test() {

				double radius = 5;

		        Circle circle = OLFactory.createCircle(OLFactory.createCoordinate(10, 10), radius);
		        assertNotNull(circle);
		        assertTrue(circle instanceof Geometry);

		        Coordinate coordinate = circle.getCenter();
		        assertNotNull(coordinate);
		        assert(10 == coordinate.getX());
		        assert(10 == coordinate.getY());

		        assert(radius == circle.getRadius());

			}});

    }

}

Add test for circle geometry

Add test for circle geometry


import java.awt.Image;
import java.net.URL;

public class MediaCheck {

    public static void media(URL url) {

	    Image image = null;
    }
 }

Create a method which contains URL as argument and create an Image variable


package com.darwinsys.springbootdemo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller()
public class NotAServlet {

	@RequestMapping("/notaservlet")
	protected String doWork(@RequestParam(value="name") String name, Model model) {
		model.addAttribute("greets", String.format("
Hello %s!!
", name));
		return "hello";
	}
}

package com.darwinsys.springbootdemo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller()
public class NotAServlet {

	@RequestMapping(value="/notaservlet", method=RequestMethod.GET)
	public String doWork(@RequestParam("name") String name, ModelMap model) {
		System.out.println("NotAServlet.doWork()");
		model.addAttribute("greetings", String.format("
Hello %s!!
", name));
		return "hello";
	}
}

Clean up; use ModelMap not Model; only GET method.


package net.teamio.blockunit;

/**
 * Created by oliver on 2017-07-03.
 */
public class TestingHarness {
	public void assertEquals(int a, int b) {
		if (a != b) {
			throw new TestAssertionException("AssertEquals: %d is not equal to %d", a, b);
		}
	}

	public void assertEquals(boolean a, boolean b) {
		if (a != b) {
			throw new TestAssertionException("AssertEquals: %s is not equal to %s", a, b);
		}
	}

	public void assertNull(Object o) {
		if (o != null) {
			throw new TestAssertionException("AssertNull: passed object is not null");
		}
	}

	public void assertNotNull(Object o) {
		if (o == null) {
			throw new TestAssertionException("AssertNotNull: passed object is null");
		}
	}

	public void assertTrue(boolean b) {
		if (!b) {
			throw new TestAssertionException("AssertTrue: passed value is false");
		}
	}

	public void assertFalse(boolean b) {
		if (b) {
			throw new TestAssertionException("AssertFalse: passed value is true");
		}
	}
}

package net.teamio.blockunit;

/**
 * Created by oliver on 2017-07-03.
 */
public class TestingHarness {
	public void assertEquals(int a, int b) {
		if (a != b) {
			throw new TestAssertionException("AssertEquals: %d is not equal to %d", a, b);
		}
	}

	public void assertEquals(boolean a, boolean b) {
		if (a != b) {
			throw new TestAssertionException("AssertEquals: %s is not equal to %s", a, b);
		}
	}

	public void assertNull(Object o) {
		if (o != null) {
			throw new TestAssertionException("AssertNull: passed object is not null");
		}
	}

	public void assertNotNull(Object o) {
		if (o == null) {
			throw new TestAssertionException("AssertNotNull: passed object is null");
		}
	}

	public void assertTrue(boolean b) {
		if (!b) {
			throw new TestAssertionException("AssertTrue: passed value is false");
		}
	}

	public void assertFalse(boolean b) {
		if (b) {
			throw new TestAssertionException("AssertFalse: passed value is true");
		}
	}

	public void fail() {
		throw new TestAssertionException("Test failed");
	}

	public void fail(String message) {
		throw new TestAssertionException("Test failed: %s", message);
	}
}

Add fail option to testing harness

Add fail option to testing harness


public class Prova {

	public static void main(String[] args) {
		System.out.println(42);
	}

}

public class Prova {

	public static void main(String[] args) {
		System.out.println(42);
		System.out.println("Prova di modifica");
	}

}

Test di verifica di aggiornamento

Test di verifica di aggiornamento


package org.nusco.swimmers.creature.genetics;

class OrganParser {

	private final int[] genes;
	private int index_in_genes = 0;

	public OrganParser(DNA dna) {
		genes = dna.getGenes();
	}

	public int[] nextPart() {
		int[] result = new int[OrganBuilder.GENES_PER_PART];
		int index_in_result = 0;
		while(index_in_result < result.length) {
			if(index_in_genes >= genes.length)
				return result;
			if(isTerminator(genes[index_in_genes])) {
				index_in_genes++;
				return result;
			}
			result[index_in_result] = genes[index_in_genes];
			index_in_result++;
			index_in_genes++;
		}
		return result;
	}

	private boolean isTerminator(int b) {
		// TODO: is the idea of a terminator ever useful?
		// (for sure, it wasn't working the way I implemented it)
		return false;
	}
}

package org.nusco.swimmers.creature.genetics;

class OrganParser {

	private final int[] genes;
	private int index_in_genes = 0;

	public OrganParser(DNA dna) {
		genes = dna.getGenes();
	}

	public int[] nextPart() {
		int[] result = new int[OrganBuilder.GENES_PER_PART];
		int index_in_result = 0;
		while(index_in_result < result.length) {
			if(index_in_genes >= genes.length)
				return result;
			result[index_in_result] = genes[index_in_genes];
			index_in_result++;
			index_in_genes++;
		}
		return result;
	}
}

Remove the concept of a DNA terminator

Remove the concept of a DNA terminator


package spacefront;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.util.Set;

public class Shot extends SpaceObject {

    private static final double SIZE = 8;
    private static final Shape SHAPE
        = new Ellipse2D.Double(-SIZE / 2, -SIZE / 2, SIZE, SIZE);

    private static final long serialVersionUID = 1L;

    private static final double SPEED = 8;

    public Shot(double destx, double desty) {
        super(0, 0, 0);
        double a = Math.atan2(desty, destx);
        setSpeed(Math.cos(a) * SPEED, Math.sin(a) * SPEED, 0);
        setShape(SHAPE);
    }

    public Meteoroid step(Set<Meteoroid> targets) {
        super.step();
        for (Meteoroid m : targets) {
            if (m.get().contains(getX(), getY())) {
                return m;
            }
        }
        return null;
    }

    public void paint(Graphics2D g) {
        g.setColor(Color.RED);
        g.fill(get());
    }
}

package spacefront;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.util.Set;

public class Shot extends SpaceObject {

    private static final long serialVersionUID = 1L;

    /* Appearance */
    private static final double SIZE = 8;
    public static final Color COLOR = Color.RED;
    public static final Shape SHAPE =
        new Ellipse2D.Double(-SIZE / 2, -SIZE / 2, SIZE, SIZE);
    private static final double OSCILLATION_RATE = 32;
    private static final double OSCILLATION_SCALE = 3;

    /* Behavior */
    private static final double SPEED = 8;

    public Shot(double destx, double desty) {
        super(0, 0, 0);
        double a = Math.atan2(desty, destx);
        setSpeed(Math.cos(a) * SPEED, Math.sin(a) * SPEED, 0);
        setShape(SHAPE);
    }

    public Meteoroid step(Set<Meteoroid> targets) {
        super.step();
        for (Meteoroid m : targets) {
            if (m.get().contains(getX(), getY())) {
                return m;
            }
        }
        return null;
    }

    public void paint(Graphics2D g) {
        g.setColor(COLOR);
        Shape self = get();
        long time = System.currentTimeMillis();
        double scale = Math.sin(time / OSCILLATION_RATE) /
            OSCILLATION_SCALE + 1d;
        AffineTransform at = getTransform();
        at.scale(scale, scale);
        g.fill(at.createTransformedShape(getShape()));
    }
}

Make the shots a little more interesting.


package com.sensia.tools.client.swetools.editors.sensorml.renderer.editor.panels.gml;

import com.sensia.relaxNG.RNGElement;
import com.sensia.tools.client.swetools.editors.sensorml.panels.AbstractPanel;
import com.sensia.tools.client.swetools.editors.sensorml.renderer.editor.panels.element.EditSimpleElementPanel;
import com.sensia.tools.client.swetools.editors.sensorml.utils.Utils;

public class GMLEditNamePanel extends EditSimpleElementPanel{

	public GMLEditNamePanel(RNGElement element) {
		super(element,Utils.findLabel(element.getParent()));
	}

	@Override
	protected AbstractPanel<RNGElement> newInstance() {
		// TODO Auto-generated method stub
		return null;
	}
}

package com.sensia.tools.client.swetools.editors.sensorml.renderer.editor.panels.gml;

import com.sensia.relaxNG.RNGElement;
import com.sensia.tools.client.swetools.editors.sensorml.panels.AbstractPanel;
import com.sensia.tools.client.swetools.editors.sensorml.renderer.editor.panels.element.EditSimpleElementPanel;
import com.sensia.tools.client.swetools.editors.sensorml.utils.Utils;

public class GMLEditNamePanel extends EditSimpleElementPanel{

	public GMLEditNamePanel(RNGElement element) {
		super(element,Utils.findLabel(element));
	}

	@Override
	protected AbstractPanel<RNGElement> newInstance() {
		// TODO Auto-generated method stub
		return null;
	}
}

Use findLabel on tag itself instead of parent


package com.saucelabs.common;

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

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;

public class SauceHelperTest {
    private SauceHelper sauceHelper;
    @Before
    public void runBeforeEveryTest()
    {
        sauceHelper = new SauceHelper();
    }
    @Test
    public void shouldReturnPassedForTrueResult()
    {
        assertStringsEqual("sauce:job-result=", true);
    }
    @Test
    public void shouldReturnFailedForFalseResult()
    {
        assertStringsEqual("sauce:job-result=", false);
    }
    @Test
    public void shouldReturnCorrectStringForTestName()
    {
        String testName = "MyTestName";
        assertEquals("sauce:job-name=" + testName, sauceHelper.getTestNameString(testName));
    }
    @Test
    public void shouldReturnSauceContextString()
    {
        String comment = "This is a comment";
        assertEquals("sauce:context=" + comment, sauceHelper.getCommentString(comment));
    }
    @Test
    public void shouldRunExecuteStringMethodWithoutDefaultManagerSet()
    {
        JavaScriptInvokerManager mockCustomJsManager = mock(JavaScriptInvokerManager.class);
        JavaScriptInvokerFactory.setJavaScriptInvoker(mockCustomJsManager);

        sauceHelper.setTestStatus("pass");
        verify(mockCustomJsManager, times(1)).executeScript("sauce:job-result=pass");
    }
    private void assertStringsEqual(String s, boolean b) {
        assertEquals(s + b, sauceHelper.getTestResultString(b));
    }
}

package com.saucelabs.common;

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

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;

public class SauceHelperTest {
    private SauceHelper sauceHelper;
    @Before
    public void runBeforeEveryTest()
    {
        sauceHelper = new SauceHelper();
    }
    @Test
    public void shouldReturnPassedForTrueResult()
    {
        assertStringsEqual("sauce:job-result=", true);
    }
    @Test
    public void shouldReturnFailedForFalseResult()
    {
        assertStringsEqual("sauce:job-result=", false);
    }
    @Test
    public void shouldReturnCorrectStringForTestName()
    {
        String testName = "MyTestName";
        assertEquals("sauce:job-name=" + testName, sauceHelper.getTestNameString(testName));
    }
    @Test
    public void shouldReturnSauceContextString()
    {
        String comment = "This is a comment";
        assertEquals("sauce:context=" + comment, sauceHelper.getCommentString(comment));
    }
    @Test
    public void shouldRunExecuteStringMethodWithoutDefaultManagerSet()
    {
        JavaScriptInvokerManager javascriptExecutor = mock(JavaScriptInvokerManager.class);
        JavaScriptInvokerFactory.setJavaScriptInvoker(javascriptExecutor);

        sauceHelper.setTestStatus("pass");
        verify(javascriptExecutor, times(1)).executeScript("sauce:job-result=pass");
    }
    private void assertStringsEqual(String s, boolean b) {
        assertEquals(s + b, sauceHelper.getTestResultString(b));
    }
}

Rename variable to javascriptExecutor in unit test


package sfBugs;

import edu.umd.cs.findbugs.annotations.DesireNoWarning;

public class Bug3062023 {
	private enum E {
		A, B, C, D
	}

	@DesireNoWarning("DB_DUPLICATE_SWITCH_CLAUSES")
	private void noWarning(E e) {
		switch (e) {
			case A:
				something();
				break;
			case B:
				//Nothing to report
				break;
			case C:
				something();
				break;
			case D:
				something();
				break;
			default:
				something();
				break;
		}
	}

	private void something() {
	}
}

package sfBugs;

import edu.umd.cs.findbugs.annotations.DesireNoWarning;

public class Bug3062023 {
	private enum E {
		A, B, C, D
	}

	@DesireNoWarning("DB_DUPLICATE_SWITCH_CLAUSES")
	private void noWarning(E e) {
		switch (e) {
			case A:
				something(1);
				break;
			case B:
				//Nothing to report
				break;
			case C:
				something(2);
				break;
			case D:
				break;
			default:
				something(10);
				break;
		}
	}

	private void something(int i) {
	}
}

Update test case for 3062023 to reflect actual bug being reported

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@12584 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


package com.dglogik.common;

import android.app.Application;
import android.support.multidex.MultiDex;

import org.acra.ACRA;
import org.acra.ReportingInteractionMode;
import org.acra.annotation.ReportsCrashes;

@ReportsCrashes(
        formKey = "",
        mode = ReportingInteractionMode.DIALOG,
        mailTo = "k.endfinger@dglogik.com"
)
public class DGApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        MultiDex.install(this);
        // The following line triggers the initialization of ACRA
        ACRA.init(this);
    }
}

package com.dglogik.common;

import android.app.Application;
import android.support.multidex.MultiDex;

import org.acra.ACRA;
import org.acra.ReportingInteractionMode;
import org.acra.annotation.ReportsCrashes;

@ReportsCrashes(
        formKey = "",
        mode = ReportingInteractionMode.DIALOG,
        mailTo = "k.endfinger@dglogik.com"
)
public class DGApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        // The following line triggers the initialization of ACRA
        ACRA.init(this);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}

Fix where multidex is installed.

Fix where multidex is installed.


package io.vertx.codegen;

/**
 * Describes a module.
 *
 * @author Julien Viet
 */
public class ModuleInfo {

  private final String fqn;
  private final String name;

  public ModuleInfo(String fqn, String name) {
    this.fqn = fqn;
    this.name = name;
  }

  /**
   * @return the module fqn, i.e the name of the package annotated with the {@link io.vertx.codegen.annotations.GenModule} annotation
   */
  public String getFqn() {
    return fqn;
  }

  /**
   * @return the module name
   */
  public String getName() {
    return name;
  }
}

package io.vertx.codegen;

/**
 * Describes a module.
 *
 * @author Julien Viet
 */
public class ModuleInfo {

  private final String fqn;
  private final String name;

  public ModuleInfo(String fqn, String name) {
    this.fqn = fqn;
    this.name = name;
  }

  /**
   * @return the module fqn, i.e the name of the package annotated with the {@link io.vertx.codegen.annotations.GenModule} annotation
   */
  public String getFqn() {
    return fqn;
  }

  /**
   * @return the module name
   */
  public String getName() {
    return name;
  }

  /**
   * @param _case the formatting case
   * @return the module name in the specified case
   */
  public String getName(Case _case) {
    return _case.format(Case.CAMEL.parse(name));
  }
}

Allow to format a module name with a case


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

package ch.myniva.gradle.caching.s3;

import org.gradle.api.Action;
import org.gradle.api.credentials.AwsCredentials;
import org.gradle.caching.configuration.AbstractBuildCache;

public class AwsS3BuildCache extends AbstractBuildCache {

  private AwsCredentials credentials;
  private String region;
  private String bucket;

  /**
   * Returns the credentials used to access the AWS S3 bucket.
   */
  public AwsCredentials getCredentials() {
    return credentials;
  }

  /**
   * Configures the credentials used to access the AWS S3 bucket.
   */
  public void credentials(Action<? super AwsCredentials> configuration) {
    configuration.execute(credentials);
  }

  public String getRegion() {
    return region;
  }

  public void setRegion(String region) {
    this.region = region;
  }

  public String getBucket() {
    return bucket;
  }

  public void setBucket(String bucket) {
    this.bucket = bucket;
  }
}

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

package ch.myniva.gradle.caching.s3;

import org.gradle.caching.configuration.AbstractBuildCache;

public class AwsS3BuildCache extends AbstractBuildCache {

  private String region;
  private String bucket;

  public String getRegion() {
    return region;
  }

  public void setRegion(String region) {
    this.region = region;
  }

  public String getBucket() {
    return bucket;
  }

  public void setBucket(String bucket) {
    this.bucket = bucket;
  }
}

Remove AWS credentioals from build cache config

The plugin uses the AWS CLI default credentials chain to find
the necessary AWS access and secret keys.


package com.rcarrillocruz.android.openstackdroid;

import android.app.Application;

public class OpenstackdroidApplication extends Application {
	private String token;

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
	}
	@Override
	public void onTerminate() {
		// TODO Auto-generated method stub
		super.onTerminate();
	}
	public String getToken() {
		return token;
	}
	public void setToken(String token) {
		this.token = token;
	}

}

package com.rcarrillocruz.android.openstackdroid;

import android.app.Application;

public class OpenstackdroidApplication extends Application {
	private String token;
	private String computeEndpoint;
	private String volumeEndpoint;
	private String identityEndpoint;
	private String imageEndpoint;

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
	}
	@Override
	public void onTerminate() {
		// TODO Auto-generated method stub
		super.onTerminate();
	}
	public String getToken() {
		return token;
	}
	public void setToken(String token) {
		this.token = token;
	}
	public String getComputeEndpoint() {
		return computeEndpoint;
	}
	public void setComputeEndpoint(String computeEndpoint) {
		this.computeEndpoint = computeEndpoint;
	}
	public String getVolumeEndpoint() {
		return volumeEndpoint;
	}
	public void setVolumeEndpoint(String volumeEndpoint) {
		this.volumeEndpoint = volumeEndpoint;
	}
	public String getIdentityEndpoint() {
		return identityEndpoint;
	}
	public void setIdentityEndpoint(String identityEndpoint) {
		this.identityEndpoint = identityEndpoint;
	}
	public String getImageEndpoint() {
		return imageEndpoint;
	}
	public void setImageEndpoint(String imageEndpoint) {
		this.imageEndpoint = imageEndpoint;
	}

}

Add endpoints variables to reuse values among fragments


package water.api;

import hex.SplitFrame;
import water.Key;
import water.fvec.Frame;

public class SplitFrameV2 extends JobV2<SplitFrame, SplitFrameV2> {
  @API(help="dataset")
  public Key<Frame> dataset;

  @API(help="Split ratios - resulting number of split is ratios.length+1", json=true)
  public double[] ratios;

  @API(help="Destination keys for each output frame split.")
  public Key[] destKeys;

  @Override public SplitFrame createImpl() { return new SplitFrame(Key.make(), null); }
}

package water.api;

import hex.SplitFrame;
import water.Key;
import water.fvec.Frame;

public class SplitFrameV2 extends JobV2<SplitFrame, SplitFrameV2> {
  @API(help="dataset")
  public KeyV1.FrameKeyV1 dataset;

  @API(help="Split ratios - resulting number of split is ratios.length+1", json=true)
  public double[] ratios;

  @API(help="Destination keys for each output frame split.")
  public KeyV1[] destKeys;

  @Override public SplitFrame createImpl() { return new SplitFrame(Key.make(), null); }
}

Fix a schema warning in split frame

Fix a schema warning in split frame


package uk.ac.ebi.quickgo.annotation.service.statistics;

import java.util.ArrayList;
import java.util.List;
import org.junit.Test;

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

/**
 * Test the operation of the RequiredStatisticsWithGeneProduct class.
 * @author Tony Wardell
 * Date: 22/12/2017
 * Time: 11:05
 * Created with IntelliJ IDEA.
 */
public class RequiredStatisticsWithGeneProductTest {

    private StatisticsTypeConfigurer configurer = mock(StatisticsTypeConfigurer.class);

    @Test
    public void isConstructedProperly() {
        List<RequiredStatisticType> requiredStatisticTypes = new ArrayList<>();
        when(configurer.getConfiguredStatsTypes(anyList())).thenReturn(requiredStatisticTypes);

        RequiredStatisticsWithGeneProduct withGeneProduct = new RequiredStatisticsWithGeneProduct(configurer);
        assertThat(withGeneProduct.getStatsTypes(), hasSize(8));
    }
}

package uk.ac.ebi.quickgo.annotation.service.statistics;

import java.util.ArrayList;
import java.util.List;
import org.junit.Test;

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

/**
 * Test the operation of the RequiredStatisticsWithGeneProduct class.
 * @author Tony Wardell
 * Date: 22/12/2017
 * Time: 11:05
 * Created with IntelliJ IDEA.
 */
public class RequiredStatisticsWithGeneProductTest {

    private StatisticsTypeConfigurer configurer = mock(StatisticsTypeConfigurer.class);

    @Test
    public void isConstructedProperly() {
        List<RequiredStatisticType> requiredStatisticTypes = new ArrayList<>();
        when(configurer.getConfiguredStatsTypes(anyList())).thenReturn(requiredStatisticTypes);

        RequiredStatisticsWithGeneProduct withGeneProduct = new RequiredStatisticsWithGeneProduct(configurer);
        assertThat(withGeneProduct.getStatsTypes(), hasSize(7));
    }
}

Fix test, the expected number was wrong.


package utils;

public class Benchmark {
	public static long getTime() {
		return System.nanoTime();
	}

	public static long getMemory() {
		return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
	}

	public static void printTime(String description, long startTime, long endTime) {
		long elapsedTime = endTime - startTime;
		double elapsedTimeSecs = elapsedTime/Math.pow(10,9);
		double elapsedTimeMins = elapsedTimeSecs/60;
		System.out.println("# TIME # " + description + ": " + elapsedTime + " ns (" + elapsedTimeSecs + " s) (" + elapsedTimeMins + " mins)");
	}

	public static void printMemory(String description, long startMemory, long endMemory) {
		long usedMemory = endMemory - startMemory;
		double usedMemoryMega = usedMemory/(1024L * 1024L);
		System.out.println("# MEMORY # " + description + ": " + usedMemory + " B (" + usedMemoryMega + " MB)");
	}
}

package utils;

public class Benchmark {
	public static long getTime() {
		return System.nanoTime();
	}

	public static long getMemory() {
		return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
	}

	public static void printTime(String description, long startTime, long endTime) {
		long elapsedTime = endTime - startTime;
		double elapsedTimeSecs = elapsedTime/Math.pow(10,9);
		double elapsedTimeMins = elapsedTimeSecs/60;
		System.out.println("# TIME # " + description + ": " + elapsedTime + " ns (" + elapsedTimeSecs + " s) (" + elapsedTimeMins + " mins)");
	}

	public static void printMemory(String description, long startMemory, long endMemory) {
		long usedMemory = endMemory - startMemory;
		double usedMemoryMega = ((double) usedMemory/(double) (1024L * 1024L));
		System.out.println("# MEMORY # " + description + ": " + usedMemory + " B (" + usedMemoryMega + " MB)");
	}
}

Change integral division to double division.


package org.fundacionjala.automation.scenario.steps.tablet.editMeeting;

import org.fundacionjala.automation.framework.utils.api.managers.MeetingAPIManager;
import org.fundacionjala.automation.framework.utils.api.objects.admin.Meeting;
import org.fundacionjala.automation.framework.utils.common.PropertiesReader;
import org.fundacionjala.automation.framework.utils.common.RMGenerator;

import cucumber.api.java.en.Given;

public class EditMeetingGivenSteps {

    @Given("^I had a created meeting with \"([^\"]*)\" organizer, with \"([^\"]*)\" subject in the \"([^\"]*)\" room$")
    public void IHadAMeetingCreated(String organizer, String subject,
	    String room) throws Throwable {

	String startDate = RMGenerator.getIsoTime(0);
	String endDate = RMGenerator.getIsoTime(1);
	String roomEmail = room + "@" + PropertiesReader.getExchangeDomain();
       Meeting meeting = new Meeting(organizer, subject, startDate, endDate,
	       room, roomEmail, roomEmail, PropertiesReader.getExchangeInviteUser());
       MeetingAPIManager.postRequest(room, meeting);
    }
}

package org.fundacionjala.automation.scenario.steps.tablet.editMeeting;

import org.fundacionjala.automation.framework.utils.api.managers.MeetingAPIManager;
import org.fundacionjala.automation.framework.utils.api.objects.admin.Meeting;
import org.fundacionjala.automation.framework.utils.common.PropertiesReader;
import org.fundacionjala.automation.framework.utils.common.RMGenerator;

import cucumber.api.java.en.Given;

public class EditMeetingGivenSteps {

    @Given("^I had a created meeting with \"([^\"]*)\" organizer, with \"([^\"]*)\" subject in the \"([^\"]*)\" room$")
    public void IHadAMeetingCreated(String organizer, String subject,
	    String room) throws Throwable {

	String startDate = RMGenerator.getIsoTime(0);
	String endDate = RMGenerator.getIsoTime(1);
	String roomEmail = room + "@" + PropertiesReader.getExchangeDomain();
       Meeting meeting = new Meeting(organizer, subject, startDate, endDate,
	       room, roomEmail, roomEmail, PropertiesReader.getExchangeInviteMail());
       MeetingAPIManager.postRequest(room, meeting);
    }
}

FIx scenario: Step editMeetingSteps change the attendee value in create meeting with api


package seedu.task.model.task;

import seedu.task.commons.exceptions.IllegalValueException;

/**
 * Represents a Task's name in the task manager.
 * Guarantees: immutable; is valid as declared in {@link #isValidName(String)}
 */
public class TaskName {

    public static final String MESSAGE_NAME_CONSTRAINTS = "Task names should be spaces or alphanumeric characters";
    public static final String NAME_VALIDATION_REGEX = "[\\p{Alnum} ]+";

    public final String fullName;

    /**
     * Validates given name.
     *
     * @throws IllegalValueException if given name string is invalid.
     */
    public TaskName(String name) throws IllegalValueException {
        assert name != null;
        name = name.trim();
        if (!isValidName(name)) {
            throw new IllegalValueException(MESSAGE_NAME_CONSTRAINTS);
        }
        this.fullName = name;
    }

    /**
     * Returns true if a given string is a valid task name.
     */
    public static boolean isValidName(String test) {
        return test.matches(NAME_VALIDATION_REGEX);
    }

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

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

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

}

package seedu.task.model.task;

import seedu.task.commons.exceptions.IllegalValueException;

/**
 * Represents a Task's name in the task manager.
 * Guarantees: immutable; is valid as declared in {@link #isValidName(String)}
 */
public class TaskName {

    public static final String MESSAGE_NAME_CONSTRAINTS = "Task names should be spaces or alphanumeric characters";
    public static final String NAME_VALIDATION_REGEX = "[\\p{Alnum} ]+";

    public final String fullName;

    /**
     * Validates given name.
     *
     * @throws IllegalValueException if given name string is invalid.
     */
    public TaskName(String name) throws IllegalValueException {
        assert name != null ;
        if (name != null)
            name = name.trim();
        if (name == null || !isValidName(name)) {
            throw new IllegalValueException(MESSAGE_NAME_CONSTRAINTS);
        }
        this.fullName = name;
    }

    /**
     * Returns true if a given string is a valid task name.
     */
    public static boolean isValidName(String test) {
        return test.matches(NAME_VALIDATION_REGEX);
    }

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

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

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

}

Fix nullPointerException on "edit" command


package coderefactory.net.popmovies;

import android.app.Activity;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.List;

public class MovieAdapter extends ArrayAdapter<Movie> {

    public MovieAdapter(final Activity context, final List<Movie> movies) {
        super(context, 0, movies);
    }

    @NonNull
    @Override
    public View getView(final int position, final View convertView, final ViewGroup parent) {
        final View rootView;
        if (convertView == null) {
            rootView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_movie, parent, false);
        } else {
            rootView = convertView;
        }
        final Movie movie = getItem(position);

        final TextView titleView = (TextView) rootView.findViewById(R.id.movie_title);
        titleView.setText(movie.getTitle());

        final TextView releaseView = (TextView) rootView.findViewById(R.id.movie_released);
        releaseView.setText(String.valueOf(movie.getReleased()));

        return rootView;
    }
}

package coderefactory.net.popmovies;

import android.app.Activity;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.List;

public class MovieAdapter extends ArrayAdapter<Movie> {

    private ViewHolder viewHolder;

    public MovieAdapter(final Activity context, final List<Movie> movies) {
        super(context, 0, movies);
    }

    @NonNull
    @Override
    public View getView(final int position, final View convertView, final ViewGroup parent) {
        final View itemView;
        if (convertView == null) {
            itemView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_movie, parent, false);
            viewHolder = new ViewHolder(itemView);
            itemView.setTag(viewHolder);
        } else {
            itemView = convertView;
            viewHolder = (ViewHolder) convertView.getTag();
        }

        populateView(position);

        return itemView;
    }

    private void populateView(final int position) {
        final Movie movie = getItem(position);

        viewHolder.titleView.setText(movie.getTitle());
        viewHolder.releaseView.setText(String.valueOf(movie.getReleased()));
    }

    private static class ViewHolder {
        private final TextView titleView;
        private final TextView releaseView;

        private ViewHolder(final View itemView) {
            titleView = (TextView) itemView.findViewById(R.id.movie_title);
            releaseView = (TextView) itemView.findViewById(R.id.movie_released);
        }
    }
}

Introduce ViewHolder pattern into ArrayAdapter


package io.undertow.server.handlers;

import java.util.Date;

import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.DateUtils;
import io.undertow.util.Headers;

/**
 * Class that adds the Date: header to a HTTP response.
 *
 * The current date string is cached, and is updated every second in a racey
 * manner (i.e. it is possible for two thread to update it at once).
 *
 * @author Stuart Douglas
 */
public class DateHandler implements HttpHandler {

    private final HttpHandler next;
    private volatile String cachedDateString;
    private volatile long nextUpdateTime = -1;

    public DateHandler(final HttpHandler next) {
        this.next = next;
    }

    @Override
    public void handleRequest(final HttpServerExchange exchange) throws Exception {
        long time = System.currentTimeMillis();
        if(time < nextUpdateTime) {
            exchange.getResponseHeaders().put(Headers.DATE, cachedDateString);
        } else {
            nextUpdateTime = time + 1000;
            String dateString = DateUtils.toDateString(new Date(time));
            cachedDateString = dateString;
            exchange.getResponseHeaders().put(Headers.DATE, dateString);
        }
        next.handleRequest(exchange);
    }

}

package io.undertow.server.handlers;

import java.util.Date;

import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.DateUtils;
import io.undertow.util.Headers;

/**
 * Class that adds the Date: header to a HTTP response.
 *
 * The current date string is cached, and is updated every second in a racey
 * manner (i.e. it is possible for two thread to update it at once).
 *
 * @author Stuart Douglas
 */
public class DateHandler implements HttpHandler {

    private final HttpHandler next;
    private volatile String cachedDateString;
    private volatile long nextUpdateTime = -1;

    public DateHandler(final HttpHandler next) {
        this.next = next;
    }

    @Override
    public void handleRequest(final HttpServerExchange exchange) throws Exception {
        long time = System.currentTimeMillis();
        if(time < nextUpdateTime) {
            exchange.getResponseHeaders().put(Headers.DATE, cachedDateString);
        } else {
            String dateString = DateUtils.toDateString(new Date(time));
            cachedDateString = dateString;
            nextUpdateTime = time + 1000;
            exchange.getResponseHeaders().put(Headers.DATE, dateString);
        }
        next.handleRequest(exchange);
    }

}

Change order that fields are updated

Change order that fields are updated


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

public final class Help
{
    private Help() {}

    public static String getHelpText()
    {
        return "" +
                "Supported commands:\n" +
                "QUIT\n" +
                "CLEAR\n" +
                "EXPLAIN [ ( option [, ...] ) ] <query>\n" +
                "    options: FORMAT { TEXT | GRAPHVIZ | JSON }\n" +
                "             TYPE { LOGICAL | DISTRIBUTED | VALIDATE | IO }\n" +
                "DESCRIBE <table>\n" +
                "SHOW COLUMNS FROM <table>\n" +
                "SHOW FUNCTIONS\n" +
                "SHOW CATALOGS [LIKE <pattern>]\n" +
                "SHOW SCHEMAS [FROM <catalog>] [LIKE <pattern>]\n" +
                "SHOW TABLES [FROM <schema>] [LIKE <pattern>]\n" +
                "USE [<catalog>.]<schema>\n" +
                "";
    }
}

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

public final class Help
{
    private Help() {}

    public static String getHelpText()
    {
        return "" +
                "Supported commands:\n" +
                "QUIT\n" +
                "EXIT\n" +
                "CLEAR\n" +
                "EXPLAIN [ ( option [, ...] ) ] <query>\n" +
                "    options: FORMAT { TEXT | GRAPHVIZ | JSON }\n" +
                "             TYPE { LOGICAL | DISTRIBUTED | VALIDATE | IO }\n" +
                "DESCRIBE <table>\n" +
                "SHOW COLUMNS FROM <table>\n" +
                "SHOW FUNCTIONS\n" +
                "SHOW CATALOGS [LIKE <pattern>]\n" +
                "SHOW SCHEMAS [FROM <catalog>] [LIKE <pattern>]\n" +
                "SHOW TABLES [FROM <schema>] [LIKE <pattern>]\n" +
                "USE [<catalog>.]<schema>\n" +
                "";
    }
}

Add exit command to the help text

Add exit command to the help text


package io.qala.datagen;

public class Vocabulary {
    /** Can be globally overwritten for your particular project. */
    public static String SPECIAL_SYMBOLS = "!@#$%^&*()_+{}[]'\"|:?><~`§\\,";

    static char[] specialSymbols() {
        return SPECIAL_SYMBOLS.toCharArray();
    }
}

package io.qala.datagen;

public class Vocabulary {
    /** Can be globally overwritten for your particular project. */
    public static String SPECIAL_SYMBOLS = "!@#$%^&*()_+{}[]'\"|:?><~`§\\,/;.";

    static char[] specialSymbols() {
        return SPECIAL_SYMBOLS.toCharArray();
    }
}

Add couple of special symbols to vocabulary


package shared;
/**
 *
 */

/**
 *
 * @author David Lecoconnier david.lecoconnier@gmail.com
 * @author Jean-Luc Amitousa-Mankoy jeanluc.amitousa.mankoy@gmail.com
 * @version 1.0
 */
public class Constants {

	/**
	 * Socket port for objects transmission
	 */
	public static int SOCKET_OBJECT_PORT = 2000;

	/**
	 * Socket port for commands transmission
	 */
	public static int SOCKET_INSTRUCTION_PORT = 2001;

}

package shared;
/**
 *
 */

/**
 *
 * @author David Lecoconnier david.lecoconnier@gmail.com
 * @author Jean-Luc Amitousa-Mankoy jeanluc.amitousa.mankoy@gmail.com
 * @version 1.0
 */
public class Constants {

	/**
	 * Socket port for objects transmission
	 */
	public static int SOCKET_OBJECT_PORT = 2000;

	/**
	 * Socket port for commands transmission
	 */
	public static int SOCKET_COMMAND_PORT = 2001;

}

Change name to improve comprehension

Change name to improve comprehension


package me.jjm_223.pt;

import me.jjm_223.pt.listeners.EggClick;
import me.jjm_223.pt.listeners.EggHit;
import me.jjm_223.pt.listeners.ItemDespawn;
import me.jjm_223.pt.utils.DataStorage;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;

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

/**
 * Main class for PetTransportation.
 */
public class PetTransportation extends JavaPlugin {

    private DataStorage storage;

    @Override
    public void onEnable() {
        //Register relevant events.
        PluginManager pm = getServer().getPluginManager();
        pm.registerEvents(new EggHit(this), this);
        pm.registerEvents(new EggClick(this), this);
        pm.registerEvents(new ItemDespawn(this), this);

        storage = new DataStorage(this);
    }

    @Override
    public void onDisable() {
        try {
            storage.save();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public DataStorage getStorage()
    {
        return this.storage;
    }
}

package me.jjm_223.pt;

import me.jjm_223.pt.listeners.EggClick;
import me.jjm_223.pt.listeners.EggHit;
import me.jjm_223.pt.listeners.ItemDespawn;
import me.jjm_223.pt.utils.DataStorage;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;

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

/**
 * Main class for PetTransportation.
 */
public class PetTransportation extends JavaPlugin {

    private DataStorage storage;

    @Override
    public void onEnable() {
        storage = new DataStorage(this);

        PluginManager pm = getServer().getPluginManager();
        pm.registerEvents(new EggHit(this), this);
        pm.registerEvents(new EggClick(this), this);
        pm.registerEvents(new ItemDespawn(this), this);
    }

    @Override
    public void onDisable() {
        try {
            storage.save();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public DataStorage getStorage()
    {
        return this.storage;
    }
}

Fix NPE on item despawn or destroy.

Fix NPE on item despawn or destroy.


package appstore;

import static org.junit.Assert.*;

import org.junit.Ignore;
import org.junit.Test;

public class TestThisWillFailAbunch {
    @Test
    public void aFailingTest() {
         assertTrue("I expected this to pass!", true);
    }

    @Ignore
    @Test
    public void aFailingTest2() {
         assertTrue("I expected this to pass!", true);
    }

    @Ignore
    @Test
    public void aFailingTest3() {
         assertTrue("I expected this to pass!", false);
    }

    //@Ignore
    @Test
    public void aFailingTest4() {
        doSomething();
    }

    @Ignore
    @Test
    public void aNewFailingTest31() {
         assertTrue("I expected this to pass!", true);
    }

    @Test
    public void aNotherNewFailingTest4() {
         assertTrue("I expected this to pass!", true);
    }

    @Test
    public void aFailingTest5() {
        doSomething();
    }

    @Test
    public void aFailingTest6() {
         assertTrue("I expected this to pass!", false);
    }

    @Test
    public void aPassingTest3() {
         assertTrue("Success!", true);
    }

    @Test
    public void aPassingTest4() {
         assertTrue("Success!", true);
    }

    private void doSomething() {
        interesting();
    }
    private void interesting() {
        RubeGoldburgMachine machine = new RubeGoldburgMachine();
        machine.processPayment();
    }

    private class RubeGoldburgMachine {
        void processPayment() {
            throw new IllegalStateException("bad payment code");
        }
    }
}

package appstore;

import static org.junit.Assert.*;

import org.junit.Ignore;
import org.junit.Test;

public class TestThisWillFailAbunch {
    @Test
    public void aFailingTest() {
         assertTrue("I expected this to pass!", true);
    }

    @Ignore
    @Test
    public void aFailingTest2() {
         assertTrue("I expected this to pass!", true);
    }

    @Ignore
    @Test
    public void aFailingTest3() {
         assertTrue("I expected this to pass!", false);
    }

    //@Ignore
    @Test
    public void aFailingTest4() {
        assertTrue("I expected this to pass!", true);
    }

    @Ignore
    @Test
    public void aNewFailingTest31() {
         assertTrue("I expected this to pass!", true);
    }

    @Test
    public void aNotherNewFailingTest4() {
         assertTrue("I expected this to pass!", true);
    }

    @Test
    public void aFailingTest5() {
        assertTrue("I expected this to pass!", true);
    }

    @Test
    public void aFailingTest6() {
         assertTrue("I expected this to pass!", false);
    }

    @Test
    public void aPassingTest3() {
         assertTrue("Success!", true);
    }

    @Test
    public void aPassingTest4() {
         assertTrue("Success!", true);
    }

    private void doSomething() {
        interesting();
    }
    private void interesting() {
        RubeGoldburgMachine machine = new RubeGoldburgMachine();
        machine.processPayment();
    }

    private class RubeGoldburgMachine {
        void processPayment() {
            throw new IllegalStateException("bad payment code");
        }
    }
}

Fix payment processor test failures

Fix payment processor test failures


package seedu.geekeep.model.task;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class TitleTest {

    @Test
    public void isValidTitle() {
        // invalid name
        assertFalse(Title.isValidTitle("")); // empty string
        assertFalse(Title.isValidTitle(" ")); // spaces only
        assertFalse(Title.isValidTitle("^")); // only non-alphanumeric characters
        assertFalse(Title.isValidTitle("peter*")); // contains non-alphanumeric characters

        // valid name
        assertTrue(Title.isValidTitle("peter jack")); // alphabets only
        assertTrue(Title.isValidTitle("12345")); // numbers only
        assertTrue(Title.isValidTitle("peter the 2nd")); // alphanumeric characters
        assertTrue(Title.isValidTitle("Capital Tan")); // with capital letters
        assertTrue(Title.isValidTitle("David Roger Jackson Ray Jr 2nd")); // long names
    }
}

package seedu.geekeep.model.task;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class TitleTest {

    @Test
    public void isValidTitle() {
        // invalid title
        assertFalse(Title.isValidTitle("")); // empty string
        assertFalse(Title.isValidTitle(" ")); // spaces only
        assertFalse(Title.isValidTitle("^")); // only non-alphanumeric characters
        assertFalse(Title.isValidTitle("peter*")); // contains non-alphanumeric characters

        // valid title
        assertTrue(Title.isValidTitle("peter jack")); // alphabets only
        assertTrue(Title.isValidTitle("12345")); // numbers only
        assertTrue(Title.isValidTitle("peter the 2nd")); // alphanumeric characters
        assertTrue(Title.isValidTitle("Capital Tan")); // with capital letters
        assertTrue(Title.isValidTitle("David Roger Jackson Ray Jr 2nd")); // long names
    }
}

Rename "[in]valid name" to "[in]valid title"


/**
 * Copyright (c) 2012-2012 Malhar, Inc.
 * All rights reserved.
 */
package com.malhartech.util;

import java.io.Serializable;

public class Pair<F, S> implements Serializable {
  private static final long serialVersionUID = 731157267102567944L;

  private F first;
  private S second;

  public Pair(F first, S second) {
      this.first = first;
      this.second = second;
  }

  public void setFirst(F first) {
      this.first = first;
  }

  public void setSecond(S second) {
      this.second = second;
  }

  public F getFirst() {
      return first;
  }

  public S getSecond() {
      return second;
  }

  @Override
  public String toString() {
    return "[" + first + "," + second + "]";
  }

}

/**
 * Copyright (c) 2012-2012 Malhar, Inc.
 * All rights reserved.
 */
package com.malhartech.util;

import java.io.Serializable;

public class Pair<F, S> implements Serializable
{
  private static final long serialVersionUID = 731157267102567944L;
  public final F first;
  public final S second;

  @Override
  public int hashCode()
  {
    int hash = 7;
    hash = 41 * hash + (this.first != null ? this.first.hashCode() : 0);
    hash = 41 * hash + (this.second != null ? this.second.hashCode() : 0);
    return hash;
  }

  @Override
  public boolean equals(Object obj)
  {
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    @SuppressWarnings("unchecked")
    final Pair<F, S> other = (Pair<F, S>)obj;
    if (this.first != other.first && (this.first == null || !this.first.equals(other.first))) {
      return false;
    }
    if (this.second != other.second && (this.second == null || !this.second.equals(other.second))) {
      return false;
    }
    return true;
  }

  public Pair(F first, S second)
  {
    this.first = first;
    this.second = second;
  }

  public F getFirst()
  {
    return first;
  }

  public S getSecond()
  {
    return second;
  }

  @Override
  public String toString()
  {
    return "[" + first + "," + second + "]";
  }

}

Introduce hashcode and equals property.

Introduce hashcode and equals property.


/*
Copyright 2011-2015 Stefano Cappa

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 gui.kcomponent;

import gui.image.ImageLoader;

import javax.swing.JFrame;

import update.Version;

/**
 *	Classe che crea un JFrame personalizzato con icona, dimensione preferita, titolo,
 *	posizione e soprattutto lo sfondo, richiamando il PanelPersonalizzato.
 */
public class KFrame extends JFrame{
	private static final long serialVersionUID = 6729366260424934194L;
	private static final String NOME = "BYAManager - " +  Version.VERSION + " - by Stefano Cappa";

	public KFrame() {
		setTitle(NOME);
		setIconImage(ImageLoader.getInstance().getIconaBya());
		getLayeredPane().setOpaque(false);
		getRootPane().setOpaque(false);

		this.setContentPane(new KPanel());
	}
}

/*
Copyright 2011-2015 Stefano Cappa

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 gui.kcomponent;

import gui.image.ImageLoader;

import javax.swing.JFrame;

import update.Version;

/**
 *	Classe che crea un JFrame personalizzato con icona, dimensione preferita, titolo,
 *	posizione e soprattutto lo sfondo, richiamando il PanelPersonalizzato.
 */
public class KFrame extends JFrame{
	private static final long serialVersionUID = 6729366260424934194L;
	private static final String NOME = "BYAManager - " +  "0.5.6" + " - by Stefano Cappa";

	public KFrame() {
		setTitle(NOME);
		setIconImage(ImageLoader.getInstance().getIconaBya());
		getLayeredPane().setOpaque(false);
		getRootPane().setOpaque(false);

		this.setContentPane(new KPanel());
	}
}

Fix versione nel Frame della gui

Fix versione nel Frame della gui


package mazegenerator;

import java.util.ArrayList;
import java.util.Arrays;
import util.MathUtil;

/**
 *
 * @author mallory
 */
public class MazeGenerator {

    public static void main(String[] args) throws Exception {
//        byte value = 0;
//        for(; value < 33; value++){
//            MazeTile tile = new MazeTile(value);
//            System.out.println(tile + " " + value);
//            System.out.println();
//        }
//        MazeTile[][] maze = new MazeTile[2][2];
//        maze[0][0] = new MazeTile(true,false,true,false);
//        maze[0][1] = new MazeTile(false,true,true,false);
//        maze[1][0] = new MazeTile(true,false,false,true);
//        maze[1][1] = new MazeTile(false,true,false,true);
        Maze maze = new Maze(47, 11, 1,1);
        //Test
        maze.generate();

        System.out.print(maze.toString());
    }

}

package mazegenerator;

import java.util.ArrayList;
import java.util.Arrays;
import util.MathUtil;

/**
 *
 * @author mallory
 */
public class MazeGenerator {

    public static void main(String[] args) throws Exception {
//        byte value = 0;
//        for(; value < 33; value++){
//            MazeTile tile = new MazeTile(value);
//            System.out.println(tile + " " + value);
//            System.out.println();
//        }
//        MazeTile[][] maze = new MazeTile[2][2];
//        maze[0][0] = new MazeTile(true,false,true,false);
//        maze[0][1] = new MazeTile(false,true,true,false);
//        maze[1][0] = new MazeTile(true,false,false,true);
//        maze[1][1] = new MazeTile(false,true,false,true);
        Maze maze = new Maze(47, 11, 1,1);
        //Test
        //Test 2
        maze.generate();

        System.out.print(maze.toString());
    }

}

Test Commit. Attempt to fix username.

Test Commit. Attempt to fix username.


package cn.hjmao.dao.minor;

import org.testng.annotations.Test;

import static org.testng.Assert.*;

/**
 * Created by hjmao on 3/24/16.
 */
public class MainTest {

  @Test
  public void testAdd() throws Exception {
    int a = 3;
    int b = 4;
    assertEquals(Main.add(a, b), a + b);
  }
}

package cn.hjmao.dao.minor;

import org.testng.annotations.Test;

import static org.testng.Assert.*;

/**
 * Created by hjmao on 3/24/16.
 */
public class MainTest {

  @Test
  public void testConstruct() throws Exception {
    assertNotNull(new Main());
  }

  @Test
  public void testAdd() throws Exception {
    int a = 3;
    int b = 4;
    assertEquals(Main.add(a, b), a + b);
  }
}

Make test coverage to 100%.

Make test coverage to 100%.


package org.apache.cordova.firebase;

import com.google.firebase.messaging.RemoteMessage;

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

public class FirebasePluginMessageReceiverManager {
    private static List<FirebasePluginMessageReceiver> receivers = new ArrayList<>();

    public static void register(FirebasePluginMessageReceiver receiver){
        receivers.add(receiver);
    }

    public static boolean onMessageReceived(RemoteMessage remoteMessage){
        boolean handled = false;
        for(FirebasePluginMessageReceiver receiver : receivers){
            boolean wasHandled = receiver.onMessageReceived(remoteMessage);
            if(wasHandled){
                handled = true;
            }
        }
        return handled;
    }
}

package org.apache.cordova.firebase;

import com.google.firebase.messaging.RemoteMessage;

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

public class FirebasePluginMessageReceiverManager {
    private static List<FirebasePluginMessageReceiver> receivers = new ArrayList<FirebasePluginMessageReceiver>();

    public static void register(FirebasePluginMessageReceiver receiver){
        receivers.add(receiver);
    }

    public static boolean onMessageReceived(RemoteMessage remoteMessage){
        boolean handled = false;
        for(FirebasePluginMessageReceiver receiver : receivers){
            boolean wasHandled = receiver.onMessageReceived(remoteMessage);
            if(wasHandled){
                handled = true;
            }
        }
        return handled;
    }
}

Replace <> operator to make code compatible with JDK 1.6


package de.swm.nis.logicaldecoding;

import org.springframework.stereotype.Component;

@Component
public class VersionHelper {

	public String determineVersion() {
		return "LogicalDeoding v.1.0.1-SNAPSHOT";
	}

}

package de.swm.nis.logicaldecoding;

import java.io.IOException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Component;

@Component
public class VersionHelper {

	@Autowired
	ApplicationContext ctx;

	private static final Logger log = LoggerFactory.getLogger(RefreshCacheService.class);

	public String determineVersion() {
		return "LogicalDecoding v("+ determineMavenVersion() + ") - git: "+determineGitVersion();
	}

	public String determineGitVersion() {
		String gitVersion = "";
		Resource resource = ctx.getResource("classpath:git.properties");
		try {
			Properties gitProperties = PropertiesLoaderUtils.loadProperties(resource);
			gitVersion = (String) gitProperties.get("git.commit.id.describe");
		} catch (IOException e) {
			log.warn("IOException while determining git version", e);
		}
		return gitVersion;
	}

	public String determineMavenVersion() {
		String mavenVersion = "";
		Resource resource = ctx.getResource("classpath:META-INF/MANIFEST.MF");
		try {
			Properties mavenProperties = PropertiesLoaderUtils.loadProperties(resource);
			mavenVersion = (String) mavenProperties.get("Implementation-Version");
		} catch (IOException e) {
			log.warn("IOException while determining maven version", e);
		}
		return mavenVersion;
	}

}

Determine Version and hash of Build on startup


package seedu.address.logic.commands;

/**
 * Lists all persons in the address book to the user.
 */
public class ListCommand extends Command {

    public static final String COMMAND_WORD = "list";

    public static final String MESSAGE_SUCCESS = "Listed all tasks";

    public ListCommand() {}

    @Override
    public CommandResult execute() {
        model.updateFilteredListToShowAll();
        return new CommandResult(MESSAGE_SUCCESS);
    }
}

package seedu.address.logic.commands;

/**
 * Lists all persons in the address book to the user.
 */
public class ListCommand extends Command {

    public static final String COMMAND_WORD = "listall";

    public static final String MESSAGE_SUCCESS = "Listed all tasks";

    public ListCommand() {}

    @Override
    public CommandResult execute() {
        model.updateFilteredListToShowAll();
        return new CommandResult(MESSAGE_SUCCESS);
    }
}

Update list command to use the keyword list all


package org.kohsuke.github;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;

/**
 * Content of reactions.
 *
 * @author Kohsuke Kawaguchi
 * @see API documentation
 * @see GHReaction
 */
public enum ReactionContent {
    PLUS_ONE("+1"), MINUS_ONE("-1"), LAUGH("laugh"), CONFUSED("confused"), HEART("heart"), HOORAY("hooray");

    private final String content;

    ReactionContent(String content) {
        this.content = content;
    }

    /**
     * Gets content.
     *
     * @return the content
     */
    @JsonValue
    public String getContent() {
        return content;
    }

    /**
     * For content reaction content.
     *
     * @param content
     *            the content
     * @return the reaction content
     */
    @JsonCreator
    public static ReactionContent forContent(String content) {
        for (ReactionContent c : ReactionContent.values()) {
            if (c.getContent().equals(content))
                return c;
        }
        return null;
    }
}

package org.kohsuke.github;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;

/**
 * Content of reactions.
 *
 * @author Kohsuke Kawaguchi
 * @see API documentation
 * @see GHReaction
 */
public enum ReactionContent {
    PLUS_ONE("+1"),
    MINUS_ONE("-1"),
    LAUGH("laugh"),
    CONFUSED("confused"),
    HEART("heart"),
    HOORAY("hooray"),
    ROCKET("rocket"),
    EYES("eyes");

    private final String content;

    ReactionContent(String content) {
        this.content = content;
    }

    /**
     * Gets content.
     *
     * @return the content
     */
    @JsonValue
    public String getContent() {
        return content;
    }

    /**
     * For content reaction content.
     *
     * @param content
     *            the content
     * @return the reaction content
     */
    @JsonCreator
    public static ReactionContent forContent(String content) {
        for (ReactionContent c : ReactionContent.values()) {
            if (c.getContent().equals(content))
                return c;
        }
        return null;
    }
}

Add support for rocket and eyes reactions.


package rabbit;

public class CommandCreator {

    public String createCommand(String userCommand) {
        String[] tokens =  userCommand.split("\\s+");

        switch(tokens[0]) {
            case "availability":
                return "nmap -sV " + tokens[1];
            case "security":
                switch (tokens[1]) {
                    case "tls":
                        return "nmap --script ssl-enum-ciphers -p 443 " + tokens[2];
                    case "ecrypt2lvl":
                        return "nmap --script ssl-enum-ciphers -p 443" + tokens[2];
                    case "open_ports":
                        return "nmap " + tokens[2];
                    default :
                        return null;
                }
            default :
                return null;
        }
    }
}

package rabbit;

public class CommandCreator {

    public String createCommand(String userCommand) {
        String[] tokens =  userCommand.split("\\s+");

        switch(tokens[0]) {
            case "security":
                switch (tokens[1]) {
                    case "tls":
                        return "nmap --script ssl-enum-ciphers -p 443 " + tokens[2];
                    case "ecrypt2lvl":
                        return "nmap --script ssl-enum-ciphers -p 443" + tokens[2];
                    case "open_ports":
                        return "nmap " + tokens[2];
                    default :
                        return null;
                }
            default :
                return null;
        }
    }
}

Remove check for "availability" command because this case is treated separately.


/**
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
package com.codeup.auth.filters;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AuthenticationFilter implements Filter {
    private String redirectTo;

    public void doFilter(
        ServletRequest req,
        ServletResponse resp,
        FilterChain chain
    ) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpSession session = request.getSession(false);

        if (session == null || session.getAttribute("user") == null) {
            ((HttpServletResponse) resp).sendRedirect(redirectTo);
        } else {
            chain.doFilter(req, resp);
        }
    }

    public void destroy() {
    }

    public void init(FilterConfig config) throws ServletException {
        redirectTo = config.getInitParameter("redirectTo");
    }
}

/**
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
package com.codeup.auth.filters;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AuthenticationFilter implements Filter {
    private String redirectTo;

    public void doFilter(
        ServletRequest request,
        ServletResponse response,
        FilterChain chain
    ) throws ServletException, IOException {
        HttpSession session = ((HttpServletRequest) request).getSession(false);

        if (session == null || session.getAttribute("user") == null) {
            ((HttpServletResponse) response).sendRedirect(redirectTo);
        } else {
            chain.doFilter(request, response);
        }
    }

    public void destroy() {
    }

    public void init(FilterConfig config) throws ServletException {
        redirectTo = config.getInitParameter("redirectTo");
    }
}

Fix naming in authentication filter.

Fix naming in authentication filter.


package SimpleWriteAndRead;

import com.continuuity.api.data.*;
import com.continuuity.api.flow.flowlet.*;
import com.continuuity.api.flow.flowlet.builders.*;

public class ReaderFlowlet extends AbstractComputeFlowlet {

  @Override
  public void configure(StreamsConfigurator configurator) {
    TupleSchema in = new TupleSchemaBuilder().
        add("key", byte[].class).
        create();
    configurator.getDefaultTupleInputStream().setSchema(in);
  }

  @Override
  public void process(Tuple tuple, TupleContext tupleContext, OutputCollector outputCollector) {
    if (Common.debug)
      System.out.println(this.getClass().getSimpleName() + ": Received tuple " + tuple);

    // perform inline read of key
    byte [] key = tuple.get("key");
    Read read = new Read(key);
    ReadOperationExecutor executor =
      getFlowletLaunchContext().getReadExecutor();
    byte [] value = executor.execute(read).getKeyResult();

    if (Common.debug)
      System.out.println(this.getClass().getSimpleName() + ": Read value (" +
          new String(value) + ") for key (" + new String(key) + ")");

  }
}

package SimpleWriteAndRead;

import com.continuuity.api.data.*;
import com.continuuity.api.flow.flowlet.*;
import com.continuuity.api.flow.flowlet.builders.*;

public class ReaderFlowlet extends AbstractComputeFlowlet {

  @Override
  public void configure(StreamsConfigurator configurator) {
    TupleSchema in = new TupleSchemaBuilder().
        add("key", byte[].class).
        create();
    configurator.getDefaultTupleInputStream().setSchema(in);
  }

  @Override
  public void process(Tuple tuple, TupleContext tupleContext, OutputCollector outputCollector) {
    if (Common.debug)
      System.out.println(this.getClass().getSimpleName() + ": Received tuple " + tuple);

    // perform inline read of key
    byte [] key = tuple.get("key");
    ReadKey read = new ReadKey(key);
    ReadOperationExecutor executor =
      getFlowletLaunchContext().getReadExecutor();
    byte [] value = executor.execute(read);

    if (Common.debug)
      System.out.println(this.getClass().getSimpleName() + ": Read value (" +
          new String(value) + ") for key (" + new String(key) + ")");

  }
}

Change read-write flow to use ReadKey

Change read-write flow to use ReadKey


package co.phoenixlab.discord.api;

/**
 * Contains various useful API URLs and paths
 */
public class ApiConst {

    /**
     * Utility class
     */
    private ApiConst() {
    }

    /**
     * The base URL from which Discord runs
     */
    public static final String BASE_URL = "https://discordapp.com/";
    /**
     * Base API path
     */
    public static final String API_BASE_PATH = BASE_URL + "api";
    /**
     * WebSocket gateway
     */
    public static final String WEBSOCKET_GATEWAY = API_BASE_PATH + "/gateway";
    /**
     * The endpoint for accessing user information
     */
    public static final String USERS_ENDPOINT = API_BASE_PATH + "/users/";
    /**
     * The endpoint for logging in
     */
    public static final String LOGIN_ENDPOINT = API_BASE_PATH + "/auth/login";
    /**
     * The endpoint for logging out
     */
    public static final String LOGOUT_ENDPOINT = API_BASE_PATH + "/auth/logout";
    /**
     * The endpoint for accessing server information
     */
    public static final String SERVERS_ENDPOINT = API_BASE_PATH + "/guilds/";
    /**
     * The endpoint for accessing channel information
     */
    public static final String CHANNELS_ENDPOINT = API_BASE_PATH + "/channels/";
    /**
     * The endpoint for accepting invites
     */
    public static final String INVITE_ENDPOINT = API_BASE_PATH + "/invite/";
    /**
     * The format string for avatar URLs
     */
    public static final String AVATAR_URL_PATTERN = "https://cdn.discordapp.com/avatars/%1$s/%2$s.jpg";

}

package co.phoenixlab.discord.api;

/**
 * Contains various useful API URLs and paths
 */
public class ApiConst {

    /**
     * Utility class
     */
    private ApiConst() {
    }

    /**
     * The base URL from which Discord runs
     */
    public static final String BASE_URL = "https://discordapp.com/";
    /**
     * Base API path
     */
    public static final String API_BASE_PATH = BASE_URL + "api";
    /**
     * WebSocket gateway
     */
    public static final String WEBSOCKET_GATEWAY = API_BASE_PATH + "/gateway";
    /**
     * The endpoint for accessing user information
     */
    public static final String USERS_ENDPOINT = API_BASE_PATH + "/users/";
    /**
     * The endpoint for logging in
     */
    public static final String LOGIN_ENDPOINT = API_BASE_PATH + "/auth/login";
    /**
     * The endpoint for logging out
     */
    public static final String LOGOUT_ENDPOINT = API_BASE_PATH + "/auth/logout";
    /**
     * The endpoint for accessing server information
     */
    public static final String SERVERS_ENDPOINT = API_BASE_PATH + "/guilds/";
    /**
     * The endpoint for accessing channel information
     */
    public static final String CHANNELS_ENDPOINT = API_BASE_PATH + "/channels/";
    /**
     * The endpoint for accepting invites
     */
    public static final String INVITE_ENDPOINT = API_BASE_PATH + "/invite";
    /**
     * The format string for avatar URLs
     */
    public static final String AVATAR_URL_PATTERN = "https://cdn.discordapp.com/avatars/%1$s/%2$s.jpg";

}

Remove trailing slash b/c invite ID has leading one


package cms.qermit.prototype;

import cms.qermit.prototype.mongo.TokenRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class PrototypeApplication {

    @Autowired
    private TokenRepository tokenRepository;

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

}

package cms.qermit.prototype;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class PrototypeApplication {

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

}

Remove unused dependency in application class


package seedu.doit.logic.parser;

import static seedu.doit.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;

import seedu.doit.logic.commands.Command;
import seedu.doit.logic.commands.IncorrectCommand;
import seedu.doit.logic.commands.SortCommand;

/**
 * Parses input arguments and creates a new SortCommand object
 */
public class SortCommandParser {
    public static final String SORT_VALIDATION_REGEX = "(priority)|(deadline)|(start time)";

    /**
     * Parses the given {@code String} of arguments in the context of the FindCommand
     * and returns an FindCommand object for execution.
     */
    public Command parse(String args) {
        if (args.matches(SORT_VALIDATION_REGEX)) {
            return new SortCommand(args);
        } else {
            return new IncorrectCommand(
                String.format(MESSAGE_INVALID_COMMAND_FORMAT, SortCommand.MESSAGE_USAGE));
        }
    }
}

package seedu.doit.logic.parser;

import static seedu.doit.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;

import seedu.doit.logic.commands.Command;
import seedu.doit.logic.commands.IncorrectCommand;
import seedu.doit.logic.commands.SortCommand;

/**
 * Parses input arguments and creates a new SortCommand object
 */
public class SortCommandParser {
    public static final String SORT_VALIDATION_REGEX = "(priority)|(deadline)|(start time)";

    /**
     * Parses the given {@code String} of arguments in the context of the FindCommand
     * and returns an FindCommand object for execution.
     */
    public Command parse(String args) {
        if (args.trim().matches(SORT_VALIDATION_REGEX)) {
            return new SortCommand(args.trim());
        } else {
            return new IncorrectCommand(
                String.format(MESSAGE_INVALID_COMMAND_FORMAT, SortCommand.MESSAGE_USAGE));
        }
    }
}

Trim argument for sort command

Trim argument for sort command


package com.github.NewsBotIRC;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Geronimo on 11/6/16.
 */
public class UrlShortener {

    public static String shortenUrl(String myUrl)
    {
        String shortenedUrl = myUrl;
        try {
            String encoded = URLEncoder.encode(myUrl, "UTF-8");

            URL url = new URL("http://qurl.org/api/url?url=" + encoded);
            HttpURLConnection http = (HttpURLConnection) url.openConnection();

            BufferedReader reader = new BufferedReader(new InputStreamReader(http.getInputStream()));

            JSONObject json = new JSONObject( reader.readLine() );
            shortenedUrl = json.optString("url");

        } catch (IOException | JSONException e) {
            System.out.println(e.getMessage());
        }
        return shortenedUrl;
    }
}

package com.github.NewsBotIRC;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by Geronimo on 11/6/16.
 */
public class UrlShortener {

    public static String shortenUrl(String myUrl)
    {
        String shortenedUrl = myUrl;
        try {
            String encoded = URLEncoder.encode(myUrl, "UTF-8");

            URL url = new URL("https://tinyurl.com/api-create.php?url=" + encoded);
            HttpURLConnection http = (HttpURLConnection) url.openConnection();

            BufferedReader reader = new BufferedReader(new InputStreamReader(http.getInputStream()));

            shortenedUrl = reader.readLine();

        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return shortenedUrl;
    }
}

Change qurl.org for tinyurl.com as URL shortener service


package com.maddenabbott.jenny;

/**
 * The main entry point for Jenny.
 */
public class Application {
  public static void main(String[] args) {
  }
  }

package com.maddenabbott.jenny;

/**
 * The main entry point for Jenny.
 */
public class Application {
  private static final String defaultCommand = "help";

  public static void main(String[] args) {
    String commandName = getCommandName(args, defaultCommand);
  }

  private static String getCommandName(final String[] args, final String defaultCommandName) {
    if (args.length > 0 && args[0] != null) {
      return args[0];
    } else {
      return defaultCommandName;
    }
  }
  }

Add method to extract command name from command line args.


package com.skelril.aurora.util;

import java.util.Random;

/**
 * @author Turtle9598
 */
public class ChanceUtil {

    private static Random r = new Random(8888);

    public static int getRandom(int highestValue) {

        return highestValue < 0 ? (r.nextInt(highestValue * -1) + 1) * -1 : r.nextInt(highestValue) + 1;
    }

    public static int getRangedRandom(int lowestValue, int highestValue) {

        if (lowestValue == highestValue) return lowestValue;
        return lowestValue + getRandom(highestValue - lowestValue) - 1;
    }

    public static double getRandom(double highestValue) {

        if (highestValue < 0) {
            return (r.nextDouble() * (highestValue * -1) + 1) * -1;
        }
        return (r.nextDouble() * highestValue) + 1;
    }

    public static double getRangedRandom(double lowestValue, double highestValue) {

        if (lowestValue == highestValue) return lowestValue;
        return lowestValue + getRandom(highestValue - lowestValue) - 1;
    }

    public static boolean getChance(int outOf) {

        return getChance(1, outOf);
    }

    public static boolean getChance(int chance, int outOf) {

        return getRandom(outOf) <= chance;
    }

}

package com.skelril.aurora.util;

import java.util.Random;

/**
 * @author Turtle9598
 */
public class ChanceUtil {

    private static Random r = new Random(1374633257);

    public static int getRandom(int highestValue) {

        return highestValue < 0 ? (r.nextInt(highestValue * -1) + 1) * -1 : r.nextInt(highestValue) + 1;
    }

    public static int getRangedRandom(int lowestValue, int highestValue) {

        if (lowestValue == highestValue) return lowestValue;
        return lowestValue + getRandom(highestValue - lowestValue) - 1;
    }

    public static double getRandom(double highestValue) {

        if (highestValue < 0) {
            return (r.nextDouble() * (highestValue * -1) + 1) * -1;
        }
        return (r.nextDouble() * highestValue) + 1;
    }

    public static double getRangedRandom(double lowestValue, double highestValue) {

        if (lowestValue == highestValue) return lowestValue;
        return lowestValue + getRandom(highestValue - lowestValue) - 1;
    }

    public static boolean getChance(int outOf) {

        return getChance(1, outOf);
    }

    public static boolean getChance(int chance, int outOf) {

        return getRandom(outOf) <= chance;
    }

}

Use a more randomly made number for the system


package tests;

import static org.fest.assertions.Assertions.assertThat;

import org.fest.assertions.GenericAssert;
import org.kercoin.magrit.Configuration;
import org.kercoin.magrit.Configuration.Authentication;

public class ConfigurationAssert extends GenericAssert<ConfigurationAssert, Configuration> {

	ConfigurationAssert(Class<ConfigurationAssert> selfType,
			Configuration actual) {
		super(selfType, actual);
	}

	public ConfigurationAssert onPort(int expected) {
		assertThat(actual.getSshPort()).isEqualTo(expected);
		return this;
	}

	public ConfigurationAssert hasHomeDir(String absolutePath) {
		assertThat(actual.getRepositoriesHomeDir().getAbsolutePath()).isEqualTo(absolutePath);
		return this;
	}

	public ConfigurationAssert hasWorkDir(String absolutePath) {
		assertThat(actual.getWorkHomeDir().getAbsolutePath()).isEqualTo(absolutePath);
		return this;
	}

	public ConfigurationAssert hasPublickeyDir(String absolutePath) {
		assertThat(actual.getPublickeyRepositoryDir().getAbsolutePath()).isEqualTo(absolutePath);
		return this;
	}

	public ConfigurationAssert hasAuthentication(Authentication expected) {
		assertThat(actual.getAuthentication()).isEqualTo(expected);
		return this;
	}

	public ConfigurationAssert isRemoteAllowed(boolean expected) {
		assertThat(actual.isRemoteAllowed()).isEqualTo(expected);
		return this;
	}

}

package tests;

import static org.fest.assertions.Assertions.assertThat;

import java.io.File;

import org.fest.assertions.GenericAssert;
import org.kercoin.magrit.Configuration;
import org.kercoin.magrit.Configuration.Authentication;

public class ConfigurationAssert extends GenericAssert<ConfigurationAssert, Configuration> {

	ConfigurationAssert(Class<ConfigurationAssert> selfType,
			Configuration actual) {
		super(selfType, actual);
	}

	public ConfigurationAssert onPort(int expected) {
		assertThat(actual.getSshPort()).isEqualTo(expected);
		return this;
	}

	public ConfigurationAssert hasHomeDir(String absolutePath) {
		assertThat(actual.getRepositoriesHomeDir().getAbsolutePath()).isEqualTo(cleanPath(absolutePath));
		return this;
	}

	public ConfigurationAssert hasWorkDir(String absolutePath) {
		assertThat(actual.getWorkHomeDir().getAbsolutePath()).isEqualTo(cleanPath(absolutePath));
		return this;
	}

	public ConfigurationAssert hasPublickeyDir(String absolutePath) {
		assertThat(actual.getPublickeyRepositoryDir().getAbsolutePath()).isEqualTo(cleanPath(absolutePath));
		return this;
	}

	public ConfigurationAssert hasAuthentication(Authentication expected) {
		assertThat(actual.getAuthentication()).isEqualTo(expected);
		return this;
	}

	public ConfigurationAssert isRemoteAllowed(boolean expected) {
		assertThat(actual.isRemoteAllowed()).isEqualTo(expected);
		return this;
	}

	private static String cleanPath(String absolutePath) {
		return new File(absolutePath).getPath();
	}

}

Clean paths containing double /

Clean paths containing double /


package smowton;

public class Test {

  private String field;

  public Test fluentNoop() {
    return this;
  }

  public Test indirectlyFluentNoop() {
    return this.fluentNoop();
  }

  public Test fluentSet(String x) {
    this.field = x;
    return this;
  }

  public static Test identity(Test t) {
    return t;
  }

  public String get() {
    return field;
  }

  public static String source() {
    return "taint";
  }

  public static void sink(String s) {}

  public static void test1() {
    Test t = new Test();
    t.fluentNoop().fluentSet(source()).fluentNoop();
    sink(t.get()); // $hasTaintFlow=y
  }

  public static void test2() {
    Test t = new Test();
    Test.identity(t).fluentNoop().fluentSet(source()).fluentNoop();
    sink(t.get()); // $hasTaintFlow=y
  }

  public static void test3() {
    Test t = new Test();
    t.indirectlyFluentNoop().fluentSet(source()).fluentNoop();
    sink(t.get()); // $hasTaintFlow=y
  }

}

Remove package from test Java file

Remove package from test Java file