package bj.pranie.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * Created by noon on 03.02.17.
 */
public class TimeUtil {
    private static final SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm");

    private static TimeZone timeZone = TimeZone.getTimeZone("Europe/Warsaw");
    private static Calendar calendar = Calendar.getInstance(timeZone);

    public static String getTime() {
        return calendar.get(Calendar.HOUR_OF_DAY) + ":"+ calendar.get(Calendar.MINUTE);
    }

    public static Calendar getCalendar(){
        return (Calendar) calendar.clone();
    }

    public static boolean isPast(String time, String date) {
        Calendar now = TimeUtil.getCalendar();
        now.setTime(new Date());

        Calendar calendar = TimeUtil.getCalendar();
        try {
            calendar.setTime(format.parse(date + " " + time));
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }

        if (now.before(calendar)) {
            return false;
        } else {
            return true;
        }
    }
}

package bj.pranie.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * Created by noon on 03.02.17.
 */
public class TimeUtil {
    private static final SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm");

    private static TimeZone timeZone = TimeZone.getTimeZone("Europe/Warsaw");
    private static Calendar calendar = Calendar.getInstance(timeZone);

    public static String getTime() {
        return calendar.get(Calendar.HOUR_OF_DAY) + ":"+ calendar.get(Calendar.MINUTE);
    }

    public static Calendar getCalendar(){
        return (Calendar) calendar.clone();
    }

    public static boolean isPast(String time, String date) {
        Calendar now = TimeUtil.getCalendar();

        Calendar calendar = TimeUtil.getCalendar();
        try {
            calendar.setTime(format.parse(date + " " + time));
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }

        if (now.before(calendar)) {
            return false;
        } else {
            return true;
        }
    }
}

Remove unnecessary set time to calendar.


package com.letscode.lcg;

import java.util.Random;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;

public class Main {
	public static void main(String[] args) {
		LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
		String hostname = args.length > 0 ? args[0] : "localhost";
		int port = args.length > 1 ? Integer.parseInt(args[1]) : g;
		String nickname = args.length > 2 ? args[2] : "Player " + (new Random().nextInt(12415124));

		cfg.title = "Lambda Cipher Genesis - " + nickname;
		cfg.useGL20 = false;

		{
			cfg.width = 1024;
			cfg.height = 600;
		}
		new LwjglApplication(new LcgApp(hostname, port, nickname), cfg);
	}
}

package com.letscode.lcg;

import java.util.Random;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;

public class Main {
	public static void main(String[] args) {
		LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
		String hostname = args.length > 0 ? args[0] : "localhost";
		int port = args.length > 1 ? Integer.parseInt(args[1]) : 80;
		String nickname = args.length > 2 ? args[2] : "Player " + (new Random().nextInt(12415124));

		cfg.title = "Lambda Cipher Genesis - " + nickname;
		cfg.useGL20 = false;

		{
			cfg.width = 1024;
			cfg.height = 600;
		}
		new LwjglApplication(new LcgApp(hostname, port, nickname), cfg);
	}
}

Fix to fix to fix a fix.

Fix to fix to fix a fix.


package com.mssngvwls;

import org.springframework.stereotype.Service;

@Service
public class GameFactory {

    private final GamePhraseSelector phraseSelector;

    public GameFactory(final GamePhraseSelector phraseSelector) {
        this.phraseSelector = phraseSelector;
    }

    public GameState startGame(final int numberOfCategories, final int numberOfPhrasesPerCategory) {
        return new Game(phraseSelector).startGame(numberOfCategories, numberOfPhrasesPerCategory);
    }
}

package com.mssngvwls;

import org.springframework.stereotype.Service;

@Service
public class GameFactory {

    private final GamePhraseSelector phraseSelector;

    public GameFactory(final GamePhraseSelector phraseSelector) {
        this.phraseSelector = phraseSelector;
    }

    public Game createGame() {
        return new Game(phraseSelector);
    }
}

Return the Game object from the factory as we need it to be able to guess phrases


package org.reldb.dbrowser.hooks;

import java.util.ArrayList;

import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.reldb.dbrowser.DBrowser;

public class OpenDocumentEventProcessor implements Listener {
	private ArrayList<String> filesToOpen = new ArrayList<String>(1);
	private boolean retrieved = false;

	public synchronized void handleEvent(Event event) {
		if (event.text != null)
			if (retrieved)
				DBrowser.openFile(event.text);
			else
				filesToOpen.add(event.text);
	}

	public synchronized String[] retrieveFilesToOpen() {
		try {
			return filesToOpen.toArray(new String[filesToOpen.size()]);
		} finally {
			filesToOpen.clear();
			retrieved = true;
		}
	}
}

package org.reldb.dbrowser.hooks;

import java.util.ArrayList;

import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.reldb.dbrowser.DBrowser;

public class OpenDocumentEventProcessor implements Listener {
	private ArrayList<String> filesToOpen = new ArrayList<String>(1);
	private boolean retrieved = false;

	public synchronized void handleEvent(Event event) {
		if (event.text != null)
			if (retrieved)
				DBrowser.openFile(event.text);
			else
				filesToOpen.add(event.text);
	}

	public synchronized String[] retrieveFilesToOpen() {
		try {
			return filesToOpen.toArray(new String[filesToOpen.size()]);
		} finally {
			filesToOpen.clear();
			retrieved = true;
		}
	}

	public synchronized void addFilesToOpen(String[] fileNames) {
		for (String argument: fileNames)
			filesToOpen.add(argument);
	}
}

Support explicit adding of file names.

Support explicit adding of file names.


package model.solvers.problems;

import model.population.Population;
import model.population.PopulationFactory;
import model.solvers.fitness.Fitness;

public class MultiplexProblem extends Problem {

	private int numA;
	private int creationMethod;
	private int maxDepth;
	private boolean ifsAllowed;

	public MultiplexProblem(int populationSize, int numberGenerations, Fitness fitness, int numA, int treeCreationMethod, boolean ifsAllowed, int maxTreeDepth) {
		super(populationSize, numberGenerations, fitness, 1, true);
		this.numA = numA;
		this.creationMethod = treeCreationMethod;
		this.ifsAllowed = false;
		this.maxDepth = maxTreeDepth;
	}

	@Override
	public Population createRandomPopulation(int seed) {
		switch(creationMethod) {
		case 0:
			return PopulationFactory.createProgramIncremental(ifsAllowed, maxDepth, populationSize, numA);
		case 1:
			return PopulationFactory.createProgramComplete(ifsAllowed, maxDepth, populationSize, numA);
		case 2:
			return PopulationFactory.createProgramRampAndHalf(ifsAllowed, maxDepth, populationSize, numA);
		case 3:
			return PopulationFactory.createProgramWeighed(ifsAllowed, maxDepth, populationSize, numA);
		default:
			throw new RuntimeException("No known tree creation method selected");
		}
	}

}

package model.solvers.problems;

import model.population.Population;
import model.population.PopulationFactory;
import model.solvers.fitness.Fitness;

public class MultiplexProblem extends Problem {

	private int numA;
	private int creationMethod;
	private int maxDepth;
	private boolean ifsAllowed;

	public MultiplexProblem(int populationSize, int numberGenerations, Fitness fitness, int numA, int treeCreationMethod, boolean ifsAllowed, int maxTreeDepth) {
		super(populationSize, numberGenerations, fitness, 1, true);
		this.numA = numA;
		this.creationMethod = treeCreationMethod;
		this.ifsAllowed = ifsAllowed;
		this.maxDepth = maxTreeDepth;
	}

	@Override
	public Population createRandomPopulation(int seed) {
		switch(creationMethod) {
		case 0:
			return PopulationFactory.createProgramIncremental(ifsAllowed, maxDepth, populationSize, numA);
		case 1:
			return PopulationFactory.createProgramComplete(ifsAllowed, maxDepth, populationSize, numA);
		case 2:
			return PopulationFactory.createProgramRampAndHalf(ifsAllowed, maxDepth, populationSize, numA);
		case 3:
			return PopulationFactory.createProgramWeighed(ifsAllowed, maxDepth, populationSize, numA);
		default:
			throw new RuntimeException("No known tree creation method selected");
		}
	}

}

Solve small issue with ifs

Solve small issue with ifs


package mn.devfest.persistence;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import mn.devfest.api.model.Conference;

/**
 * Stores and provides information about the conference. The app is shipped with a local copy of
 * the latest conference information. As we get newer information from the API, this is updated.
 *
 * @author pfuentes
 */
public class ConferenceRepository {

    Context mContext;
    SharedPreferences mSharedPreferences;

    public ConferenceRepository(@NonNull Context context) {
        mContext = context;
        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
    }

    /**
     * Removes any existing persisted conference data and replaces it with the passed value
     *
     * @param conference most up-to-date conference information available
     */
    public void setConference(@Nullable Conference conference) {
        //TODO implement
    }

    /**
     * Provides the most recently persisted conference data
     *
     * @return persisted conference data
     */
    @NonNull
    public Conference getConference() {
        //TODO implement and remove dummy return
        return new Conference();
    }

}

package mn.devfest.persistence;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.google.gson.Gson;

import mn.devfest.api.model.Conference;

/**
 * Stores and provides information about the conference. The app is shipped with a local copy of
 * the latest conference information. As we get newer information from the API, this is updated.
 * TODO evaluate if we want to use another persistence method, rather than SharedPreferences
 *
 * @author pfuentes
 */
public class ConferenceRepository {
    private static final String CONFERENCE_KEY = "CONFERENCE";

    Context mContext;
    SharedPreferences mSharedPreferences;
    Gson mGson;

    public ConferenceRepository(@NonNull Context context) {
        mContext = context;
        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
        mGson = new Gson();
    }

    /**
     * Removes any existing persisted conference data and replaces it with the passed value
     * If you try to pass null as an argument, the data is not updated.
     * To delete all existing conference data, pass an empty {@link Conference} object
     *
     * @param conference most up-to-date conference information available
     */
    public void setConference(@Nullable Conference conference) {
        if (conference == null) {
            return;
        }
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        String jsonString = mGson.toJson(conference);
        editor.putString(CONFERENCE_KEY, jsonString);
        editor.apply();
    }

    /**
     * Provides the most recently persisted conference data
     * If no conference data is persisted, an empty {@link Conference} object is returned
     *
     * @return persisted conference data
     */
    @NonNull
    public Conference getConference() {
        String jsonString = mSharedPreferences.getString(CONFERENCE_KEY, null);
        if (jsonString == null) {
            //TODO update this to return the locally stored conference data & update the documentation
            return new Conference();
        }
        return mGson.fromJson(jsonString, Conference.class);
    }

}

Implement accessor and modifier for persisted conference data


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

package com.akiban.sql.optimizer;

import com.akiban.sql.compiler.TypeComputer;

import com.akiban.sql.parser.*;

import com.akiban.sql.StandardException;
import com.akiban.sql.types.DataTypeDescriptor;

/** Calculate types from schema information. */
public class AISTypeComputer extends TypeComputer
{
    public AISTypeComputer() {
    }

    protected DataTypeDescriptor computeType(ValueNode node) throws StandardException {
        switch (node.getNodeType()) {
        case NodeTypes.COLUMN_REFERENCE:
            return columnReference((ColumnReference)node);
        default:
            return super.computeType(node);
        }
    }

    protected DataTypeDescriptor columnReference(ColumnReference node)
            throws StandardException {
        ColumnBinding columnBinding = (ColumnBinding)node.getUserData();
        assert (columnBinding != null) : "column is not bound yet";
        return columnBinding.getType();
    }

}

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

package com.akiban.sql.optimizer;

import com.akiban.sql.compiler.TypeComputer;

import com.akiban.sql.parser.*;

import com.akiban.sql.StandardException;
import com.akiban.sql.types.DataTypeDescriptor;

/** Calculate types from schema information. */
public class AISTypeComputer extends TypeComputer
{
    public AISTypeComputer() {
    }

    @Override
    protected DataTypeDescriptor computeType(ValueNode node) throws StandardException {
        switch (node.getNodeType()) {
        case NodeTypes.COLUMN_REFERENCE:
            return columnReference((ColumnReference)node);
        default:
            return super.computeType(node);
        }
    }

    protected DataTypeDescriptor columnReference(ColumnReference node)
            throws StandardException {
        ColumnBinding columnBinding = (ColumnBinding)node.getUserData();
        assert (columnBinding != null) : "column is not bound yet";
        return columnBinding.getType();
    }

}

Add unit tests for update with a parameter.


package net.kotek.jdbm;

import java.io.File;
import java.io.IOException;
import java.util.Set;

public class StorageZipTest extends TestCaseWithTestFile {

    public void test_archive_creation() throws IOException {

        File tmp = File.createTempFile("JDBM_TEST_ZIP", "zip");
        String dbpath = tmp.getPath() + "!/test/db";
        tmp.deleteOnExit();

        //first create archie and put it in zip file
        DBStore r = new DBStore(newTestFile(), false, true);
        Set<Long> h = r.createHashSet("hash");
        for (Long l = 0L; l < 1e5; l++) {
            h.add(l);
        }
        r.commit();
        r.copyToZipStore(dbpath);
        r.close();

        System.out.println("Zip file created, size: " + tmp.length());

        //open zip file and check it contains all data
        DB r2 = new DBMaker(dbpath).readonly().build();
        Set<Long> h2 = r2.getHashSet("hash");
        for (Long l = 0L; l < 1e5; l++) {
            assertTrue(h2.contains(l));
        }

    }

}

package net.kotek.jdbm;

import java.io.File;
import java.io.IOException;
import java.util.Set;

public class StorageZipTest extends TestCaseWithTestFile {

    public void test_archive_creation() throws IOException {

        File tmp = File.createTempFile("JDBM_TEST_ZIP", "zip");
        String dbpath = tmp.getPath() + "!/test/db";
        tmp.deleteOnExit();

        //first create archie and put it in zip file
        DBStore r = new DBStore(newTestFile(), false, true);
        Set<Long> h = r.createHashSet("hash");
        for (Long l = 0L; l < 1e3; l++) {
            h.add(l);
        }
        r.commit();
        r.copyToZipStore(dbpath);
        r.close();

        System.out.println("Zip file created, size: " + tmp.length());

        //open zip file and check it contains all data
        DB r2 = new DBMaker(dbpath).readonly().build();
        Set<Long> h2 = r2.getHashSet("hash");
        for (Long l = 0L; l < 1e3; l++) {
            assertTrue(h2.contains(l));
        }

    }

}

Make test smaller so it runs faster

Make test smaller so it runs faster


package com.darrenforsythe.jackson.ignore.model;

import java.util.Date;

import com.fasterxml.jackson.annotation.JsonProperty;

public class MyObject {

	private int id;
	@JsonProperty
	private String name;
	private Date date;

	public MyObject(){
		setId(1);
		setName("thing");
		setDate(new Date());
	}

	public String getName() {
		return name;
	}

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

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

}

package com.darrenforsythe.jackson.ignore.model;

import java.util.Date;

import com.fasterxml.jackson.annotation.JsonProperty;

public class MyObject {

	private int id;
	@JsonProperty
	private String name;
	private Date date;

	public MyObject(){
		setId(1);
		setName("thing");
		setDate(new Date());
	}

	public String getName() {
		System.out.println("Name just got get!");
		return name;
	}

	public void setName(String name) {
		System.out.println("Name just got set!");
		this.name = name;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

}

Update with systemout to verify that the getters/setters are used.


package fr.nelaupe.spreadsheetlib;

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

/**
 * Created by lucas34990 on 16/2/16.
 */
public abstract class FieldBinder<TSelf> {

    private List<AnnotationFields> fields;

    public FieldBinder() {
        this.fields = init();
    }

    protected abstract List<AnnotationFields> fill();

    public abstract Object getValueAt(String fieldName, TSelf data);

    public List<AnnotationFields> fields() {
        return fields;
    }

    private List<AnnotationFields> init() {
        List<AnnotationFields> fields = fill();
        Collections.sort(fields, new Comparator<AnnotationFields>() {
            @Override
            public int compare(AnnotationFields lhs, AnnotationFields rhs) {
                Integer positionL = lhs.getPosition();
                Integer positionR = rhs.getPosition();

                return positionL.compareTo(positionR);
            }
        });
        return Collections.unmodifiableList(fields);
    }

}

package fr.nelaupe.spreadsheetlib;

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

/**
 * Created by lucas34990 on 16/2/16.
 */
public abstract class FieldBinder<TSelf> {

    private List<AnnotationFields> fields;

    private boolean mSortingDESC;
    private int mColumnSortSelected;

    public FieldBinder() {
        this.fields = init();
    }

    protected abstract List<AnnotationFields> fill();

    public abstract Object getValueAt(String fieldName, TSelf data);

    public List<AnnotationFields> fields() {
        return fields;
    }

    private List<AnnotationFields> init() {
        List<AnnotationFields> fields = fill();
        Collections.sort(fields, new Comparator<AnnotationFields>() {
            @Override
            public int compare(AnnotationFields lhs, AnnotationFields rhs) {
                Integer positionL = lhs.getPosition();
                Integer positionR = rhs.getPosition();

                return positionL.compareTo(positionR);
            }
        });
        return Collections.unmodifiableList(fields);
    }

    boolean isSortingDESC() {
        return mSortingDESC;
    }

    int getSortingColumnSelected() {
        return mColumnSortSelected;
    }

    void setIsDESC(boolean mIsDESC) {
        this.mSortingDESC = mIsDESC;
    }

    void invertSorting() {
        this.mSortingDESC = !this.mSortingDESC;
    }

    public void setColumnSortSelected(int mColumnSortSelected) {
        this.mColumnSortSelected = mColumnSortSelected;
    }
}

Add sorting state to the binder

Add sorting state to the binder


package net.openhft.chronicle.wire;

import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.assertEquals;

/**
 * Created by peter on 17/05/2017.
 */
public class TextMethodTesterTest {
    @Test
    public void run() throws IOException {
        TextMethodTester test = new TextMethodTester<>(
                "methods-in.yaml",
                MockMethodsImpl::new,
                MockMethods.class,
                "methods-in.yaml")
                .setup("methods-in.yaml") // calls made here are ignored.
                .run();
        assertEquals(test.expected(), test.actual());
    }
}

class MockMethodsImpl implements MockMethods {
    private final MockMethods out;

    public MockMethodsImpl(MockMethods out) {
        this.out = out;
    }

    @Override
    public void method1(MockDto dto) {
        out.method1(dto);
    }

    @Override
    public void method2(MockDto dto) {
        out.method2(dto);
    }
}

package net.openhft.chronicle.wire;

import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.assertEquals;

/**
 * Created by peter on 17/05/2017.
 */
public class TextMethodTesterTest {
    @Test
    public void run() throws IOException {
        TextMethodTester test = new TextMethodTester<>(
                "methods-in.yaml",
                MockMethodsImpl::new,
                MockMethods.class,
                "methods-in.yaml")
                .setup("methods-in.yaml") // calls made here are not validated in the output.
                .run();
        assertEquals(test.expected(), test.actual());
    }
}

class MockMethodsImpl implements MockMethods {
    private final MockMethods out;

    public MockMethodsImpl(MockMethods out) {
        this.out = out;
    }

    @Override
    public void method1(MockDto dto) {
        out.method1(dto);
    }

    @Override
    public void method2(MockDto dto) {
        out.method2(dto);
    }
}

Add support for a setup phase which is not recorded.


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

package org.apache.tapestry5.func;

/**
 * A reducer takes an accumulator value and a single value from a collection and computes a new
 * accumulator value.
 * <A> type of accumulator
 * <T> type of collection value
 *
 * @since 5.2.0
 */
public interface Reducer<A, T>
{
    /**
     * Run a computation using the current value of the accumulator and a value (from a Flow),
     * and return the new accumulator.
     */
    A reduce(A accumulator, T value);
}

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

package org.apache.tapestry5.func;

/**
 * A reducer takes an accumulator value and a single value from a collection and computes a new
 * accumulator value.
 * <A> type of accumulator
 * <T> type of collection value
 *
 * @since 5.2.0
 */
public interface Reducer<A, T>
{
    /**
     * Run a computation using the current value of the accumulator and an element (from a Flow),
     * and return the new accumulator.
     */
    A reduce(A accumulator, T element);
}

Rename parameter "value" to "element" for consistency

git-svn-id: d9b8539636d91aff9cd33ed5cd52a0cf73394897@1183040 13f79535-47bb-0310-9956-ffa450edef68


package com.thoughtworks.xstream.core.util;

public final class FastStack {

    private Object[] stack;
    private int pointer;

    public FastStack(int initialCapacity) {
        stack = new Object[initialCapacity];
    }

    public Object push(Object value) {
        if (pointer + 1 >= stack.length) {
            resizeStack(stack.length * 2);
        }
        stack[pointer++] = value;
        return value;
    }

    public void popSilently() {
        pointer--;
    }

    public Object pop() {
        return stack[--pointer];
    }

    public Object peek() {
        return pointer == 0 ? null : stack[pointer - 1];
    }

    public int size() {
        return pointer;
    }

    public boolean hasStuff() {
        return pointer > 0;
    }

    public Object get(int i) {
        return stack[i];
    }

    private void resizeStack(int newCapacity) {
        Object[] newStack = new Object[newCapacity];
        System.arraycopy(stack, 0, newStack, 0, Math.min(stack.length, newCapacity));
        stack = newStack;
    }

    public String toString() {
        StringBuffer result = new StringBuffer("[");
        for (int i = 0; i < pointer; i++) {
            if (i > 0) {
                result.append(", ");
            }
            result.append(stack[i]);
        }
        result.append(']');
        return result.toString();
    }
}

package com.thoughtworks.xstream.core.util;

public final class FastStack {

    private Object[] stack;
    private int pointer;

    public FastStack(int initialCapacity) {
        stack = new Object[initialCapacity];
    }

    public Object push(Object value) {
        if (pointer + 1 >= stack.length) {
            resizeStack(stack.length * 2);
        }
        stack[pointer++] = value;
        return value;
    }

    public void popSilently() {
        stack[--pointer] = null;
    }

    public Object pop() {
        final Object result = stack[--pointer];
        stack[pointer] = null;
        return result;
    }

    public Object peek() {
        return pointer == 0 ? null : stack[pointer - 1];
    }

    public int size() {
        return pointer;
    }

    public boolean hasStuff() {
        return pointer > 0;
    }

    public Object get(int i) {
        return stack[i];
    }

    private void resizeStack(int newCapacity) {
        Object[] newStack = new Object[newCapacity];
        System.arraycopy(stack, 0, newStack, 0, Math.min(stack.length, newCapacity));
        stack = newStack;
    }

    public String toString() {
        StringBuffer result = new StringBuffer("[");
        for (int i = 0; i < pointer; i++) {
            if (i > 0) {
                result.append(", ");
            }
            result.append(stack[i]);
        }
        result.append(']');
        return result.toString();
    }
}

Drop unnecessary reference to popped elements to allow finalization through GC (XSTR-264).

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


package codechicken.lib.raytracer;

import net.minecraft.entity.Entity;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;

public class ExtendedMOP extends MovingObjectPosition
{
    public Object data;

    public ExtendedMOP(Entity entity, Object data)
    {
        super(entity);
        setData(data);
    }

    public ExtendedMOP(int x, int y, int z, int side, Vec3 hit, Object data)
    {
        super(x, y, z, side, hit);
        setData(data);
    }

    public ExtendedMOP(MovingObjectPosition mop, Object data)
    {
        super(0, 0, 0, 0, mop.hitVec);
        typeOfHit = mop.typeOfHit;
        blockX = mop.blockX;
        blockY = mop.blockY;
        blockZ = mop.blockZ;
        sideHit = mop.sideHit;
        subHit = mop.subHit;
        setData(data);
    }

    public void setData(Object data)
    {
        if(data instanceof Integer)
            subHit = ((Integer) data).intValue();
        this.data = data;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getData(MovingObjectPosition mop)
    {
        if(mop instanceof ExtendedMOP)
            return (T)((ExtendedMOP)mop).data;

        return (T)Integer.valueOf(mop.subHit);
    }
}

package codechicken.lib.raytracer;

import net.minecraft.entity.Entity;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;

public class ExtendedMOP extends MovingObjectPosition implements Comparable<ExtendedMOP>
{
    public Object data;
    public double dist;

    public ExtendedMOP(Entity entity, Object data)
    {
        super(entity);
        setData(data);
    }

    public ExtendedMOP(int x, int y, int z, int side, Vec3 hit, Object data)
    {
        super(x, y, z, side, hit);
        setData(data);
    }

    public ExtendedMOP(MovingObjectPosition mop, Object data, double dist)
    {
        super(0, 0, 0, 0, mop.hitVec);
        typeOfHit = mop.typeOfHit;
        blockX = mop.blockX;
        blockY = mop.blockY;
        blockZ = mop.blockZ;
        sideHit = mop.sideHit;
        subHit = mop.subHit;
        setData(data);
        this.dist = dist;
    }

    public void setData(Object data)
    {
        if(data instanceof Integer)
            subHit = ((Integer) data).intValue();
        this.data = data;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getData(MovingObjectPosition mop)
    {
        if(mop instanceof ExtendedMOP)
            return (T)((ExtendedMOP)mop).data;

        return (T)Integer.valueOf(mop.subHit);
    }

    @Override
    public int compareTo(ExtendedMOP o)
    {
        return dist == o.dist ? 0 : dist < o.dist ? -1 : 1;
    }
}

Extend MOP for RayTracer depth sorting.

Extend MOP for RayTracer depth sorting.


//@@author A0162266E
package guitests;

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

import org.junit.Test;

import werkbook.task.logic.commands.SaveCommand;

public class SaveCommandTest extends TaskListGuiTest {

    @Test
    public void save_invalidPath_failure() {
        commandBox.runCommand("save \"\" ");
        assertResultMessage(SaveCommand.MESSAGE_INVALID_PATH);
    }

    @Test
    public void save_nonExistentFolder_failure() {
        commandBox.runCommand("save src\\test\\data\\sandbox\\some_folder");
        assertResultMessage(SaveCommand.MESSAGE_FOLDER_NOT_EXIST);
    }

    @Test
    public void save_notDirectory_failure() {
        File newFile = new File("src\\test\\data\\sandbox\\newFile");
        try {
            newFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        commandBox.runCommand("save src\\test\\data\\sandbox\\newFile");
        assertResultMessage(SaveCommand.MESSAGE_NOT_A_DIRECTORY);
    }

    @Test
    public void save_validDirectory_success() {
        File newFolder = new File("src\\test\\data\\sandbox\\newFolder");
        newFolder.mkdir();
        commandBox.runCommand("save src\\test\\data\\sandbox\\newFolder");
        assertResultMessage(SaveCommand.MESSAGE_SUCCESS);
    }

}

//@@author A0162266E
package guitests;

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

import org.junit.Test;

import werkbook.task.logic.commands.SaveCommand;

public class SaveCommandTest extends TaskListGuiTest {

    @Test
    public void save_invalidPath_failure() {
        commandBox.runCommand("save \"\0\"");
        assertResultMessage(SaveCommand.MESSAGE_INVALID_PATH);
    }

    @Test
    public void save_nonExistentFolder_failure() {
        commandBox.runCommand("save src\\test\\data\\sandbox\\some_folder");
        assertResultMessage(SaveCommand.MESSAGE_FOLDER_NOT_EXIST);
    }

    @Test
    public void save_notDirectory_failure() {
        File newFile = new File("src\\test\\data\\sandbox\\newFile");
        try {
            newFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        commandBox.runCommand("save src\\test\\data\\sandbox\\newFile");
        assertResultMessage(SaveCommand.MESSAGE_NOT_A_DIRECTORY);
    }

    @Test
    public void save_validDirectory_success() {
        File newFolder = new File("src\\test\\data\\sandbox\\newFolder");
        newFolder.mkdir();
        commandBox.runCommand("save src\\test\\data\\sandbox\\newFolder");
        assertResultMessage(SaveCommand.MESSAGE_SUCCESS);
    }

}

Add null in invalid path test

Add null in invalid path test


package integration;

import hello.Application;
import org.fluentlenium.adapter.FluentTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.*;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import static org.assertj.core.api.Assertions.assertThat;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest("server.port:0")
public class GreetingTest extends FluentTest {
    @Value("${local.server.port}")
    private int port;

    private DesiredCapabilities capabilities = DesiredCapabilities.phantomjs();
    private WebDriver driver = new PhantomJSDriver(capabilities);

    @Override
    public WebDriver getDefaultDriver() {
        return driver;
    }

    @Test
    public void testGetIndex() {
        goTo("http://127.0.0.1:" + port + "/greeting?name=Sam");
        assertThat(pageSource()).contains("Hello, Sam!");

        goTo("http://127.0.0.1:" + port + "/greeting?name=Bob");
        assertThat(pageSource()).contains("Hello, Bob!");
    }
}

package integration;

import hello.Application;
import org.fluentlenium.adapter.FluentTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.*;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.assertj.core.api.Assertions.assertThat;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebIntegrationTest("server.port:0")
public class GreetingTest extends FluentTest {
    @Value("${local.server.port}")
    private int port;

    private DesiredCapabilities capabilities = DesiredCapabilities.phantomjs();
    private WebDriver driver = new PhantomJSDriver(capabilities);

    @Override
    public WebDriver getDefaultDriver() {
        return driver;
    }

    @Test
    public void testGetIndex() {
        goTo("http://127.0.0.1:" + port + "/greeting?name=Sam");
        assertThat(pageSource()).contains("Hello, Sam!");

        goTo("http://127.0.0.1:" + port + "/greeting?name=Bob");
        assertThat(pageSource()).contains("Hello, Bob!");
    }
}

Switch to web integration test

Switch to web integration test


// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.diagnostic;

import com.intellij.icons.AllIcons;
import com.intellij.openapi.wm.StatusBarWidget;
import com.intellij.ui.AnimatedIcon.Blinking;

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

import static com.intellij.util.ui.EmptyIcon.ICON_16;

class IdeErrorsIcon extends JLabel {
  private final boolean myEnableBlink;

  IdeErrorsIcon(boolean enableBlink) {
    myEnableBlink = enableBlink;
    setBorder(StatusBarWidget.WidgetBorder.INSTANCE);
  }

  void setState(MessagePool.State state) {
    Icon myUnreadIcon = !myEnableBlink ? AllIcons.Ide.FatalError : new Blinking(AllIcons.Ide.FatalError);
    if (state != null && state != MessagePool.State.NoErrors) {
      setIcon(state == MessagePool.State.ReadErrors ? AllIcons.Ide.FatalError_read : myUnreadIcon);
      setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
      setToolTipText(DiagnosticBundle.message("error.notification.tooltip"));
    }
    else {
      setIcon(ICON_16);
      setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
      setToolTipText(null);
    }
  }
}

// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.diagnostic;

import com.intellij.icons.AllIcons;
import com.intellij.openapi.wm.StatusBarWidget;
import com.intellij.ui.AnimatedIcon.Blinking;

import javax.swing.*;

import static com.intellij.util.ui.EmptyIcon.ICON_16;

class IdeErrorsIcon extends JLabel {
  private final boolean myEnableBlink;

  IdeErrorsIcon(boolean enableBlink) {
    myEnableBlink = enableBlink;
    setBorder(StatusBarWidget.WidgetBorder.INSTANCE);
  }

  void setState(MessagePool.State state) {
    Icon myUnreadIcon = !myEnableBlink ? AllIcons.Ide.FatalError : new Blinking(AllIcons.Ide.FatalError);
    if (state != null && state != MessagePool.State.NoErrors) {
      setIcon(state == MessagePool.State.ReadErrors ? AllIcons.Ide.FatalError_read : myUnreadIcon);
      setToolTipText(DiagnosticBundle.message("error.notification.tooltip"));
    }
    else {
      setIcon(ICON_16);
      setToolTipText(null);
    }
  }
}

Remove hand cursor from ErrorsLabel

Remove hand cursor from ErrorsLabel

there is changing background is used hover indication now

GitOrigin-RevId: 65ebd0b94c8d306b27d306020b10115637f1827e


package evercookie;

public interface EvercookieBackend {

	boolean initialize();

	void set(String name, String value);

	void get(String name);

	boolean contains(String name);

	void clear();

	void cleanup();

}

package evercookie;

import java.util.Properties;

public interface EvercookieBackend {

	boolean initialize();

	void save(Properties values);

	Properties load();

	void cleanup();

}

Change interface to only load/save a collection of properties.


package org.subethamail.smtp.server.io;

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

import javax.mail.util.SharedFileInputStream;

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

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

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

package org.subethamail.smtp.server.io;

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

import javax.mail.util.SharedFileInputStream;

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

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

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

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

git-svn-id: 22ec8cfea0672d04b2346d96717164b900bedbad@229 d4f6eda6-38e6-11de-8fef-1f5ae417a2df


package nl.myndocs.database.migrator.definition;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;

public class Constraint {
    public enum TYPE {
        INDEX, UNIQUE
    }

    private String constraintName;
    private Optional<TYPE> type;
    private Collection<String> columnNames = new ArrayList<>();

    private Constraint(Builder builder) {
        constraintName = builder.getConstraintName();
        type = builder.getType();
        columnNames = builder.getColumnNames();
    }

    public String getConstraintName() {
        return constraintName;
    }

    public Optional<TYPE> getType() {
        return type;
    }

    public Collection<String> getColumnNames() {
        return columnNames;
    }

    public static class Builder {
        private String constraintName;
        private Optional<TYPE> type;
        private Collection<String> columnNames = new ArrayList<>();

        public Builder(String constraintName) {
            this.constraintName = constraintName;
        }

        public Builder(String constraintName, TYPE type) {
            this.constraintName = constraintName;
            this.type = Optional.ofNullable(type);
        }

        public Builder columns(String... columnNames) {
            this.columnNames = Arrays.asList(columnNames);

            return this;
        }

        public String getConstraintName() {
            return constraintName;
        }

        public Optional<TYPE> getType() {
            return type;
        }

        public Collection<String> getColumnNames() {
            return columnNames;
        }
    }
}

package nl.myndocs.database.migrator.definition;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;

public class Constraint {
    public enum TYPE {
        INDEX, UNIQUE, FOREIGN_KEY
    }

    private String constraintName;
    private Optional<TYPE> type;
    private Collection<String> columnNames = new ArrayList<>();

    private Constraint(Builder builder) {
        constraintName = builder.getConstraintName();
        type = builder.getType();
        columnNames = builder.getColumnNames();
    }

    public String getConstraintName() {
        return constraintName;
    }

    public Optional<TYPE> getType() {
        return type;
    }

    public Collection<String> getColumnNames() {
        return columnNames;
    }

    public static class Builder {
        private String constraintName;
        private Optional<TYPE> type;
        private Collection<String> columnNames = new ArrayList<>();

        public Builder(String constraintName) {
            this.constraintName = constraintName;
        }

        public Builder(String constraintName, TYPE type) {
            this.constraintName = constraintName;
            this.type = Optional.ofNullable(type);
        }

        public Builder columns(String... columnNames) {
            this.columnNames = Arrays.asList(columnNames);

            return this;
        }

        public String getConstraintName() {
            return constraintName;
        }

        public Optional<TYPE> getType() {
            return type;
        }

        public Collection<String> getColumnNames() {
            return columnNames;
        }
    }
}

Prepare FOREIGN_KEY as ALTER TABLE

Prepare FOREIGN_KEY as ALTER TABLE


// TODO clean up

package imagej.legacy.patches;

public class FunctionsMethods {

	public static int InsideBatchDrawing = 0;

	public static void beforeBatchDraw() {
		InsideBatchDrawing++;
	}

	public static void afterBatchDraw() {
		InsideBatchDrawing--;
	}
}

Add reminder to clean up code later.

Add reminder to clean up code later.

This used to be revision r3211.


package seedu.taskmanager.commons.core;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

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

public class ConfigTest {
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void toString_defaultObject_stringReturned() {
        String defaultConfigAsString = "App title : Task Manager App\n" +
                "Current log level : INFO\n" +
                "Preference file Location : preferences.json\n" +
                "Local data file location : data/taskmanager.xml\n" +
                "TaskManager name : MyTaskManager";

        assertEquals(defaultConfigAsString, new Config().toString());
    }

    @Test
    public void equalsMethod() {
        Config defaultConfig = new Config();
        assertNotNull(defaultConfig);
        assertTrue(defaultConfig.equals(defaultConfig));
    }

}

package seedu.taskmanager.commons.core;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

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

public class ConfigTest {
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void toString_defaultObject_stringReturned() {
        String defaultConfigAsString = "App title : Funtasktic\n" +
                "Current log level : INFO\n" +
                "Preference file Location : preferences.json\n" +
                "Local data file location : data/taskmanager.xml\n" +
                "TaskManager name : MyTaskManager";

        assertEquals(defaultConfigAsString, new Config().toString());
    }

    @Test
    public void equalsMethod() {
        Config defaultConfig = new Config();
        assertNotNull(defaultConfig);
        assertTrue(defaultConfig.equals(defaultConfig));
    }

}

Fix JUnit test due to default config change


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

package com.googlesource.gerrit.plugins.reviewers;

import com.google.gerrit.common.ChangeListener;
import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.gerrit.server.config.FactoryModule;

public class Module extends FactoryModule {
  @Override
  protected void configure() {
    DynamicSet.bind(binder(), ChangeListener.class).to(
        ChangeEventListener.class);
    factory(DefaultReviewers.Factory.class);
  }
}

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

package com.googlesource.gerrit.plugins.reviewers;

import com.google.gerrit.common.ChangeListener;
import com.google.gerrit.extensions.annotations.Exports;
import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.gerrit.server.config.FactoryModule;
import com.google.gerrit.server.config.ProjectConfigEntry;

public class Module extends FactoryModule {
  @Override
  protected void configure() {
    DynamicSet.bind(binder(), ChangeListener.class).to(
        ChangeEventListener.class);
    factory(DefaultReviewers.Factory.class);
    bind(ProjectConfigEntry.class)
       .annotatedWith(Exports.named("reviewers"))
       .toInstance(
           new ProjectConfigEntry("Reviewers", null,
               ProjectConfigEntry.Type.ARRAY, null, false,
               "Users or groups can be provided as reviewers"));
  }
}

Allow configuration of reviewers on project info screen

Change-Id: Ib529ce8b2593daba58a2c8f737a932323b2f9220


package mnm.mods.util;

import java.util.Iterator;
import java.util.List;

import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.Launch;

public class TweakTools {

    /**
     * Returns whether LiteLoader is loaded into LaunchWrapper.
     *
     * @return True if it's loaded
     */
    public static boolean isLiteLoaderLoaded() {
        return isTweakLoaded("com.mumfrey.liteloader.launch.LiteLoaderTweaker");
    }

    /**
     * Returns whether FML is loaded into LaunchWrapper.
     *
     * @return True if it's loaded
     */
    public static boolean isFMLLoaded() {
        return isTweakLoaded("net.minecraftforge.fml.common.launcher.FMLTweaker");
    }

    /**
     * Gets if a given tweak is loaded into LaunchWrapper.
     *
     * @param name The fully qualified class name
     * @return True if it's loaded
     */
    public static boolean isTweakLoaded(String name) {
        boolean load = false;
        @SuppressWarnings("unchecked")
        List<ITweaker> tweakers = (List<ITweaker>) Launch.blackboard.get("Tweaks");

        // Iterate through the tweaks and check the class name
        Iterator<ITweaker> iter = tweakers.iterator();
        while (!load && iter.hasNext()) {
            ITweaker tweak = iter.next();
            String className = tweak.getClass().getName();
            load = className.equals(name);
        }
        return load;
    }
}

package mnm.mods.util;

import net.minecraftforge.fml.common.FMLCommonHandler;

import com.mumfrey.liteloader.core.LiteLoader;

public class TweakTools {

    /**
     * Returns whether LiteLoader is currently loaded.
     *
     * @return True if it's loaded
     */
    public static boolean isLiteLoaderLoaded() {
        boolean loaded = false;
        try {
            loaded = LiteLoader.getInstance() != null;
        } catch (Throwable t) {
        }
        return loaded;
    }

    /**
     * Returns whether FML is currently loaded.
     *
     * @return True if it's loaded
     */
    public static boolean isFMLLoaded() {
        boolean loaded = false;
        if (ForgeUtils.FML_INSTALLED) {
            loaded = FMLCommonHandler.instance() != null;
        }
        return loaded;
    }
}

Make the tweak tools actually useful. Fix always returning false because the Tweaks list is empty.


package aima.core.search.framework;

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;

/**
 * Factory class for queues. Changes made here will affect all queue based
 * search algorithms of this library.
 *
 * @author Ruediger Lunde
 *
 */
public class QueueFactory {

	/**
	 * Returns a {@link LinkedList}.
	 */
	public static <E> Queue<E> createFifoQueue() {
		return new LinkedList<E>();
	}

	/**
	 * Returns a Last-in-first-out (Lifo) view on a {@link LinkedList}.
	 */
	public static <E> Queue<E> createLifoQueue() {
		return Collections.asLifoQueue(new LinkedList<E>());
	}

	/**
	 * Returns a standard java {@link PriorityQueue}. Note that the smallest
	 * element comes first!
	 */
	public static <E> Queue<E> createPriorityQueue(Comparator<? super E> comparator) {
		return new PriorityQueue<E>(comparator);
	}
}

package aima.core.search.framework;

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;

/**
 * Factory class for queues. Changes made here will affect all queue based
 * search algorithms of this library.
 *
 * @author Ruediger Lunde
 *
 */
public class QueueFactory {

	/**
	 * Returns a {@link LinkedList}.
	 */
	public static <E> Queue<E> createFifoQueue() {
		return new LinkedList<E>();
	}

	/**
	 * Returns a Last-in-first-out (Lifo) view on a {@link LinkedList}.
	 */
	public static <E> Queue<E> createLifoQueue() {
		return Collections.asLifoQueue(new LinkedList<E>());
	}

	/**
	 * Returns a standard java {@link PriorityQueue}. Note that the smallest
	 * element comes first!
	 */
	public static <E> Queue<E> createPriorityQueue(Comparator<? super E> comparator) {
		return new PriorityQueue<E>(11, comparator);
	}
}

Modify PriorityQueue constructor call to be compliant with JDK 7.

Was using a JDK 8 only constructor.


package org.tigris.subversion.lib;

/**
 * ====================================================================
 * Copyright (c) 2000-2001 CollabNet.  All rights reserved.
 *
 * This software is licensed as described in the file COPYING, which
 * you should have received as part of this distribution.  The terms
 * are also available at http://subversion.tigris.org/license-1.html.
 * If newer versions of this license are posted there, you may use a
 * newer version instead, at your option.
 *
 * This software consists of voluntary contributions made by many
 * individuals.  For exact contribution history, see the revision
 * history and logs, available at http://subversion.tigris.org/.
 * ====================================================================
 *
 */

public class StatusKind
{
    public final static int NONE=1;
    public final static int NORMAL=2;
    public final static int ADDED=3;
    public final static int ABSENT=4;
    public final static int DELETED=5;
    public final static int REPLACED=6;
    public final static int MODIFIED=7;
    public final static int MERGED=8;
    public final static int CONFLICTED=9;

    public final int kind;

    public StatusKind(int kind)
	{
	    this.kind = kind;
	}
}

package org.tigris.subversion.lib;

/**
 * ====================================================================
 * Copyright (c) 2000-2001 CollabNet.  All rights reserved.
 *
 * This software is licensed as described in the file COPYING, which
 * you should have received as part of this distribution.  The terms
 * are also available at http://subversion.tigris.org/license-1.html.
 * If newer versions of this license are posted there, you may use a
 * newer version instead, at your option.
 *
 * This software consists of voluntary contributions made by many
 * individuals.  For exact contribution history, see the revision
 * history and logs, available at http://subversion.tigris.org/.
 * ====================================================================
 *
 */

public class StatusKind
{
    public final static int NONE=1;
    public final static int NORMAL=2;
    public final static int ADDED=3;
    public final static int ABSENT=4;
    public final static int DELETED=5;
    public final static int REPLACED=6;
    public final static int MODIFIED=7;
    public final static int MERGED=8;
    public final static int CONFLICTED=9;

    private int kind = NONE;

    public StatusKind(int kind)
	{
	    super();
	    this.kind = kind;
	}

    public StatusKind()
	{
	    this(NONE);
	}

    public void setKind(int _kind)
	{
	    kind = _kind;
	}

    public int getKind()
	{
	    return kind;
	}
}

Integrate the hashtable Unit testcases.

Integrate the hashtable Unit testcases.

* tests/AllTests.java (suite): added HashtableTests

git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@841027 13f79535-47bb-0310-9956-ffa450edef68


package es.softwareprocess.fillercreep;

public class AIMaximum implements AI {

    public FundamentalStuff evaluate(int playernumber, FillerCreep fillerCreep) {
        FundamentalStuff[] stuff = FillerCreep.getStuffArray();
        int maxscore = -1;
        int maxstuff = -1;
        for (int i = 0; i < stuff.length; i++) {
            int score = fillerCreep.testPlayerPlay(playernumber, stuff[i]);
            if (score > maxscore) {
                maxscore = score;
                maxstuff = i;
            }
        }
        return stuff[maxstuff];
    }

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

	}

}

package es.softwareprocess.fillercreep;

public class AIMaximum implements AI {

    public FundamentalStuff evaluate(int playernumber, FillerCreep fillerCreep) {
        FundamentalStuff[] stuff = FillerCreep.getStuffArray();
        int maxscore = -1;
        int maxstuff = -1;
        for (int i = 0; i < stuff.length; i++) {
            int score = fillerCreep.testPlayerPlay(playernumber, stuff[i]);
            if (score > maxscore) {
                maxscore = score;
                maxstuff = i;
            }
        }
        return stuff[maxstuff];
    }

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

	}

	public int iWantTwo() {
		return 2;
	}

	public int iWantZero() {
		return 0;
	}

}

Add the iWantTwo and iWantZero functions ?


package com.race604.react.view;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.react.uimanager.ViewManager;
import com.race604.react.view.swiperefresh.ReactSwipeRefreshLayoutManager;
import com.race604.react.view.webview.ReactWebViewManager;

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

/**
 * Created by Jing on 15/9/22.
 */
public class CustomReactPackage implements ReactPackage {

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

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

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        List<ViewManager> result = new ArrayList<>();
        result.add(new ReactWebViewManager());
        result.add(new ReactSwipeRefreshLayoutManager());

        return result;
    }
}

package com.race604.react.view;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.react.uimanager.ViewManager;
import com.race604.react.view.swiperefresh.ReactSwipeRefreshLayoutManager;
import com.race604.react.view.webview.ReactWebViewManager;

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

/**
 * Created by Jing on 15/9/22.
 */
public class CustomReactPackage implements ReactPackage {

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

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

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        List<ViewManager> result = new ArrayList<ViewManager>();
        result.add(new ReactWebViewManager());
        result.add(new ReactSwipeRefreshLayoutManager());

        return result;
    }
}

Fix failed when compile with java 1.6

Fix failed when compile with java 1.6


package qa.qcri.aidr.trainer.api.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import org.codehaus.jackson.annotate.JsonIgnoreProperties;

import java.io.Serializable;

/**
 * Created with IntelliJ IDEA.
 * User: jilucas
 * Date: 9/20/13
 * Time: 2:35 PM
 * To change this template use File | Settings | File Templates.
 */
@Entity
@Table(catalog = "aidr_predict",name = "account")
@JsonIgnoreProperties(ignoreUnknown=true)
public class Users implements Serializable {

    private static final long serialVersionUID = -5527566248002296042L;

    public Long getUserID() {
        return userID;
    }

    public void setUserID(Long userID) {
        this.userID = userID;
    }

    public String getName() {
        return name;
    }

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

    @Id
    @Column(name = "id")
    private Long userID;

    @Column (name = "name", nullable = false)
    private String name;

}

package qa.qcri.aidr.trainer.api.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import org.codehaus.jackson.annotate.JsonIgnoreProperties;

import java.io.Serializable;

/**
 * Created with IntelliJ IDEA.
 * User: jilucas
 * Date: 9/20/13
 * Time: 2:35 PM
 * To change this template use File | Settings | File Templates.
 */
@Entity
@Table(catalog = "aidr_predict",name = "account")
@JsonIgnoreProperties(ignoreUnknown=true)
public class Users implements Serializable {

    private static final long serialVersionUID = -5527566248002296042L;

    public Long getUserID() {
        return userID;
    }

    public void setUserID(Long userID) {
        this.userID = userID;
    }

    public String getName() {
        return name;
    }

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

    @Id
    @Column(name = "id")
    private Long userID;

    @Column (name = "user_name", nullable = false)
    private String name;

}

Change fieldName for user in AIDRTrainerAPI


package loc;

import loc.filter.Filter;
import loc.filter.FilterFactory;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

public class ConfigFileReader {
	public static Filter[] readFilters(Path filePath) throws IOException {
		List<Filter> filterList = new ArrayList<>();
		BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath.toFile()));
		String line;
		while ((line = bufferedReader.readLine()) != null) {
			line = line.trim();
			if (line.isEmpty()) continue;
			filterList.add(FilterFactory.create(line));
		}
		return filterList.toArray(new Filter[filterList.size()]);
	}
}

package loc;

import loc.filter.Filter;
import loc.filter.FilterFactory;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class ConfigFileReader {
	public static Filter[] readFilters(Path filePath) throws IOException {
		HashSet<Filter> filters = new HashSet<>();
		BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath.toFile()));
		String line;
		while ((line = bufferedReader.readLine()) != null) {
			line = line.trim();
			if (line.isEmpty()) continue;
			filters.add(FilterFactory.create(line));
		}
		return filters.toArray(new Filter[filters.size()]);
	}
}

Fix bug with duplicated filters in config Change ArrayList container to HashSet container


package com.google.sps.tests;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public final class AuthInfoTest {

  @Test
  public void example() {
    // placeholder test to show that tests are evaluated
    Assert.assertEquals(1 + 1, 2);
    Assert.assertEquals(2 * 2, 4);
    Assert.assertEquals(1337, 1500 - 163);
  }
}

package com.google.sps;

import com.google.sps.data.AuthInfo;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public final class AuthInfoTest {

  @Test
  public void testDefaultBuilderValues() {
    AuthInfo uninitializedAuthInfo = AuthInfo.builder().setIsLoggedIn(false).build();
    Assert.assertEquals("", uninitializedAuthInfo.email());
    Assert.assertEquals("", uninitializedAuthInfo.loginUrl());
    Assert.assertEquals("", uninitializedAuthInfo.logoutUrl());
  }

  @Test
  public void testBuilderLoggedInFields() {
    AuthInfo loggedInAuthInfo = AuthInfo.builder()
                                  .setIsLoggedIn(true)
                                  .setEmail("test@gmail.com")
                                  .setLogoutUrl("https://google.com")
                                  .build();
    Assert.assertEquals(true, loggedInAuthInfo.isLoggedIn());
    Assert.assertEquals("test@gmail.com", loggedInAuthInfo.email());
    Assert.assertEquals("https://google.com", loggedInAuthInfo.logoutUrl());
    Assert.assertEquals("", loggedInAuthInfo.loginUrl());
  }
}

Add tests for AuthInfo value class

Add tests for AuthInfo value class


package org.realityforge.arez.api2;

import javax.annotation.Nonnull;

public class Derivation
  extends Node
{
  /**
   * The stalest state of the associated observables that are also derivations.
   */
  @Nonnull
  private ObserverState _dependenciesState = ObserverState.NOT_TRACKING;
  /**
   * The observables that this derivation is derived from.
   * This corresponds to the list of observables that were observed whilst
   * tracking the last derivation. THis list should contain no duplicates.
   */
  private final ArrayList<Observable> _dependencies = new ArrayList<>();

  public Derivation( @Nonnull final ArezContext context,
                     @Nonnull final String name )
  {
    super( context, name );
  }

  @Override
  public void setState( @Nonnull final ObserverState state )
  {
    _dependenciesState = state;
    if ( state == ObserverState.STALE || state == ObserverState.POSSIBLY_STALE )
    {
      onBecomeStale();
    }
  }

  @Nonnull
  protected final ArrayList<Observable> getDependencies()
  {
    return _dependencies;
  }
}

package org.realityforge.arez.api2;

import javax.annotation.Nonnull;

public class Derivation
  extends Node
{
  /**
   * The stalest state of the associated observables that are also derivations.
   */
  @Nonnull
  private ObserverState _dependenciesState = ObserverState.NOT_TRACKING;
  /**
   * The observables that this derivation is derived from.
   * This corresponds to the list of observables that were observed whilst
   * tracking the last derivation. THis list should contain no duplicates.
   */
  private final ArrayList<Observable> _dependencies = new ArrayList<>();

  public Derivation( @Nonnull final ArezContext context,
                     @Nonnull final String name )
  {
    super( context, name );
  }

  @Override
  public void setState( @Nonnull final ObserverState state )
  {
    _dependenciesState = state;
    if ( state == ObserverState.STALE || state == ObserverState.POSSIBLY_STALE )
    {
      onBecomeStale();
    }
  }

  @Nonnull
  protected final ArrayList<Observable> getDependencies()
  {
    return _dependencies;
  }

  final void invariantDependenciesUnique()
  {

    Guards.invariant( () -> getDependencies().size() == new HashSet<>( getDependencies() ).size(),
                      () -> String.format(
                        "The set of dependencies in derivation named '%s' is not unique. Current list: '%s'.",
                        getName(),
                        getDependencies().stream().map( Node::getName ).collect( Collectors.toList() ).toString() ) );
  }
}

Add method that asserts invariants

Add method that asserts invariants


package com.todoist.mediaparser.mediaparser;

import com.todoist.mediaparser.util.MediaType;

import java.util.regex.Pattern;

public class ScreenrParser extends BaseOEmbedMediaParser {
	private static Pattern sMatchingPattern;

	ScreenrParser(String url) {
		super(url);
	}

	@Override
	public MediaType getContentMediaType() {
		return MediaType.VIDEO;
	}

	@Override
	protected Pattern getMatchingPattern() {
		if(sMatchingPattern == null)
			sMatchingPattern = Pattern.compile("https?://(?:www\\.)?screenr\\.com/\\w+/?", Pattern.CASE_INSENSITIVE);
		return sMatchingPattern;
	}

	@Override
	protected String getOEmbedUrlTemplate() {
		return "http://www.screenr.com/api/oembed.json?url=%s";
	}

	@Override
	protected String getOEmbedThumbnailUrlName() {
		return "thumbnail_url";
	}
}

package com.todoist.mediaparser.mediaparser;

import com.todoist.mediaparser.util.MediaType;

import java.util.regex.Pattern;

public class ScreenrParser extends BaseOEmbedMediaParser {
	private static Pattern sMatchingPattern;

	ScreenrParser(String url) {
		super(url);
	}

	@Override
	public MediaType getContentMediaType() {
		return MediaType.VIDEO;
	}

	@Override
	protected Pattern getMatchingPattern() {
		if(sMatchingPattern == null)
			sMatchingPattern = Pattern.compile("https?://(?:www\\.)?screenr\\.com/\\w+/?", Pattern.CASE_INSENSITIVE);
		return sMatchingPattern;
	}

	@Override
	protected String createThumbnailUrl(int smallestSide) {
		String thumbnailUrl = super.createThumbnailUrl(smallestSide);
		if(smallestSide > 110)
			return thumbnailUrl.replaceFirst("_thumb\\.jpg$", ".jpg");
		else
			return thumbnailUrl;
	}

	@Override
	protected String getOEmbedUrlTemplate() {
		return "http://www.screenr.com/api/oembed.json?url=%s";
	}

	@Override
	protected String getOEmbedThumbnailUrlName() {
		return "thumbnail_url";
	}
}

Support larger thumbnails on screenr.com


package vu.de.npolke.myexpenses.servlets;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import vu.de.npolke.myexpenses.backend.DatabaseConnection;
import vu.de.npolke.myexpenses.model.Category;

@WebServlet("/addcategory")
public class AddCategoryServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private final DatabaseConnection DB_CONNECT = new DatabaseConnection();

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");

		final String name = request.getParameter("name");

		Category category = new Category();
		category.setName(name);

		EntityManager dbConnection = DB_CONNECT.connect();
		dbConnection.persist(category);

		DB_CONNECT.commit();
		DB_CONNECT.close();

		response.sendRedirect("listexpenses");
	}
}

package vu.de.npolke.myexpenses.servlets;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import vu.de.npolke.myexpenses.backend.DatabaseConnection;
import vu.de.npolke.myexpenses.model.Category;

@WebServlet("/addcategory")
public class AddCategoryServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private final DatabaseConnection DB_CONNECT = new DatabaseConnection();

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");

		final String name = request.getParameter("name");

		Category category = new Category();
		category.setName(name);

		EntityManager dbConnection = DB_CONNECT.connect();
		dbConnection.persist(category);

		DB_CONNECT.commit();
		DB_CONNECT.close();

		response.sendRedirect("listcategories");
	}
}

Change navigation after add category to list categories


// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security.tls;

import java.util.Arrays;

/**
 * @author bjorncs
 */
public enum AuthorizationMode {
    DISABLE("disable"),
    LOG_ONLY("log-only"),
    ENFORCE("enforce");

    final String configValue;

    AuthorizationMode(String configValue) {
        this.configValue = configValue;
    }

    public String configValue() {
        return configValue;
    }

    static AuthorizationMode fromConfigValue(String configValue) {
        return Arrays.stream(values())
                .filter(v -> v.configValue.equals(configValue))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("Unknown value: " + configValue));
    }
}

// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security.tls;

import java.util.Arrays;

/**
 * @author bjorncs
 */
public enum AuthorizationMode {
    DISABLE("disable"),
    LOG_ONLY("log_only"),
    ENFORCE("enforce");

    final String configValue;

    AuthorizationMode(String configValue) {
        this.configValue = configValue;
    }

    public String configValue() {
        return configValue;
    }

    static AuthorizationMode fromConfigValue(String configValue) {
        return Arrays.stream(values())
                .filter(v -> v.configValue.equals(configValue))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("Unknown value: " + configValue));
    }
}

Change LOG_ONLY config value from 'log-only' to 'log_only'


package jp.ac.nii.prl.mape.autoscaling.analysis;

import org.mockito.Mockito;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import jp.ac.nii.prl.mape.autoscaling.analysis.service.DeploymentService;

@Configuration
public class TestContext {

	@Bean
	public DeploymentService deploymentService() {
		return Mockito.mock(DeploymentService.class);
	}
}

package jp.ac.nii.prl.mape.autoscaling.analysis;

import org.mockito.Mockito;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import jp.ac.nii.prl.mape.autoscaling.analysis.service.DeploymentService;
import jp.ac.nii.prl.mape.autoscaling.analysis.service.VirtualMachineService;

@Configuration
public class TestContext {

	@Bean
	public DeploymentService deploymentService() {
		return Mockito.mock(DeploymentService.class);
	}

	@Bean
	public VirtualMachineService virtualMachineService() {
		return Mockito.mock(VirtualMachineService.class);
	}
}

Add VirtualMachineController mock to testing context


package com.elmakers.mine.bukkit.magic.dao;

import org.bukkit.Material;

import com.elmakers.mine.bukkit.persisted.PersistClass;
import com.elmakers.mine.bukkit.persisted.PersistField;
import com.elmakers.mine.bukkit.persistence.dao.MaterialData;

@PersistClass(schema="magic", name="cost", contained=true)
public class CastingCost
{
    public void addItem(Material material, int count)
    {
        this.item = new MaterialData(material);
        this.count = count;
    }

    @PersistField
    public float getHealth()
    {
        return health;
    }

    public void setHealth(float health)
    {
        this.health = health;
    }

    @PersistField
    public MaterialData getItem()
    {
        return item;
    }

    public void setItem(MaterialData item)
    {
        this.item = item;
    }

    @PersistField
    public int getCount()
    {
        return count;
    }

    public void setCount(int count)
    {
        this.count = count;
    }

    protected float        health = 0;
    protected MaterialData item   = null;
    protected int          count  = 0;
}

package com.elmakers.mine.bukkit.magic.dao;

import org.bukkit.Material;

import com.elmakers.mine.bukkit.persisted.PersistClass;
import com.elmakers.mine.bukkit.persisted.PersistField;
import com.elmakers.mine.bukkit.persistence.dao.MaterialData;

@PersistClass(schema="magic", name="cost", contained=true)
public class CastingCost
{
    protected float        health = 0;
    protected float        mana   = 0;
    protected MaterialData item   = null;
    protected int          count  = 0;

    public void addItem(Material material, int count)
    {
        this.item = new MaterialData(material);
        this.count = count;
    }

    @PersistField
    public float getHealth()
    {
        return health;
    }

    public void setHealth(float health)
    {
        this.health = health;
    }

    @PersistField
    public MaterialData getItem()
    {
        return item;
    }

    public void setItem(MaterialData item)
    {
        this.item = item;
    }

    @PersistField
    public int getCount()
    {
        return count;
    }

    public void setCount(int count)
    {
        this.count = count;
    }

    @PersistField
    public float getMana()
    {
        return mana;
    }

    public void setMana(float mana)
    {
        this.mana = mana;
    }

}

Add mana to casting cost.

Add mana to casting cost.


package com.elmakers.mine.bukkit.api.maps;

import org.bukkit.inventory.ItemStack;

import java.util.List;

public interface MapController {
    List<URLMap> getAll();
    void loadMap(String world, short id, String url, String name, int x, int y, int width, int height, Integer priority);
    ItemStack getURLItem(String world, String url, String name, int x, int y, int width, int height, Integer priority);
    void forceReloadPlayerPortrait(String worldName, String playerName);
    ItemStack getPlayerPortrait(String worldName, String playerName, Integer priority, String photoName);
    ItemStack getMapItem(short id);
    boolean hasMap(short id);
    boolean remove(short id);
    void save();
    short getURLMapId(String world, String url, String name, int x, int y, int width, int height, Integer priority);
    short getURLMapId(String world, String url);
}

package com.elmakers.mine.bukkit.api.maps;

import org.bukkit.inventory.ItemStack;

import java.util.List;

public interface MapController {
    List<URLMap> getAll();
    URLMap getMap(short id);
    void loadMap(String world, short id, String url, String name, int x, int y, int width, int height, Integer priority);
    ItemStack getURLItem(String world, String url, String name, int x, int y, int width, int height, Integer priority);
    void forceReloadPlayerPortrait(String worldName, String playerName);
    ItemStack getPlayerPortrait(String worldName, String playerName, Integer priority, String photoName);
    ItemStack getMapItem(short id);
    boolean hasMap(short id);
    boolean remove(short id);
    void save();
    short getURLMapId(String world, String url, String name, int x, int y, int width, int height, Integer priority);
    short getURLMapId(String world, String url);
}

Add API method to fetch a URLMap by id

Add API method to fetch a URLMap by id


package com.boundary.sdk.event;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.daemon.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class EchoTask extends TimerTask {
    @Override
    public void run() {
        System.out.println(new Date() + " running ...");
    }
}

public class BoundaryEventDaemon extends EventApplication implements Daemon {

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

    private static Timer timer = null;

    public BoundaryEventDaemon() {

    }

    public static void main(String[] args) {
//        timer = new Timer();
//        timer.schedule(new EchoTask(), 0, 1000);
    }

    public void init(DaemonContext dc) throws DaemonInitException, Exception {
        System.out.println("initializing ...");
    }

    public void start() throws Exception {
        System.out.println("starting ...");
        boot();
    }

    public void stop() throws Exception {
        System.out.println("stopping ...");
        main.stop();

        if (timer != null) {
            timer.cancel();
        }
    }

    public void destroy() {
        System.out.println("done.");
    }
 }

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

import org.apache.commons.daemon.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BoundaryEventDaemon extends EventApplication implements Daemon {

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

    public BoundaryEventDaemon() {

    }

    public static void main(String[] args) {

    }

    public void init(DaemonContext dc) throws DaemonInitException, Exception {
        LOG.info("Initializing ...");
    }

    public void start() throws Exception {
    	LOG.info("Starting ...");
        boot();
    }

    public void stop() throws Exception {
    	LOG.info("Stopping ...");
        main.stop();
    }

    public void destroy() {
    	LOG.info("Destroy ...");
    }
 }

Clean up ; remove unused imports ; license header


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

package com.eatnumber1.util.concurrent;

import java.util.concurrent.Callable;
import org.jetbrains.annotations.NotNull;

/**
 * @author Russell Harmon
 * @since Jul 13, 2007
 */
public class ThreadUtils {
    private ThreadUtils() {}

    @NotNull
    public static <T> Callable<T> caughtCallable( @NotNull Callable<T> callable ) {
        return new ExceptionReportingCallable<T>(callable);
    }
}

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

package com.eatnumber1.util.concurrent;

import java.util.concurrent.Callable;
import org.jetbrains.annotations.NotNull;

/**
 * @author Russell Harmon
 * @since Jul 13, 2007
 */
public class ThreadUtils {
    private ThreadUtils() {}

    @NotNull
    public static <T> Callable<T> caughtCallable( @NotNull Callable<T> callable ) {
        return new ExceptionReportingCallable<T>(callable);
    }

    @NotNull
    public static <T> Runnable runnable( @NotNull Callable<T> callable ) {
        return new ThreadAdapter<T>(callable);
    }
}

Add runnable method to convert a callable into a runnable.


package nu.studer.teamcity.buildscan.internal;

import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class Util {

    private static final Pattern BUILD_SCAN_URL_PATTERN = Pattern.compile("https?://.*/s/(.*)");

    private Util() {
    }

    public static boolean isBuildScanUrl(String text) {
        return doGetBuildScanId(text).isPresent();
    }

    public static String getBuildScanId(String text) {
        //noinspection OptionalGetWithoutIsPresent
        return doGetBuildScanId(text).get();
    }

    private static Optional<String> doGetBuildScanId(String text) {
        Matcher matcher = BUILD_SCAN_URL_PATTERN.matcher(text);
        return matcher.matches() ? Optional.of(matcher.group(1)) : Optional.empty();
    }
}

package nu.studer.teamcity.buildscan.internal;

import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

final class Util {

    private static final Pattern BUILD_SCAN_URL_PATTERN = Pattern.compile("https?://.*/s/(.*)");

    static boolean isBuildScanUrl(String text) {
        return doGetBuildScanId(text).isPresent();
    }

    static String getBuildScanId(String text) {
        //noinspection OptionalGetWithoutIsPresent
        return doGetBuildScanId(text).get();
    }

    private static Optional<String> doGetBuildScanId(String text) {
        Matcher matcher = BUILD_SCAN_URL_PATTERN.matcher(text);
        return matcher.matches() ? Optional.of(matcher.group(1)) : Optional.empty();
    }

    private Util() {
    }

}

Reduce class and method visibility

Reduce class and method visibility


/*
 * This file is part of the DITA Open Toolkit project.
 *
 * Copyright 2011 Jarno Elovirta
 *
 * See the accompanying LICENSE file for applicable license.
 */
package org.dita.dost.platform;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

/**
 * List transtypes integration action.
 *
 * @since 1.5.4
 * @author Jarno Elovirta
 */
final class ListTranstypeAction extends ImportAction {

    /**
     * Get result.
     */
    @Override
    public void getResult(final ContentHandler buf) throws SAXException {
        final String separator = paramTable.getOrDefault("separator", "|");
        final List<String> v = valueSet.stream()
                .map(fileValue -> fileValue.value)
                .collect(Collectors.toList());
        Collections.sort(v);
        final StringBuilder retBuf = new StringBuilder();
        for (final Iterator<String> i = v.iterator(); i.hasNext();) {
            retBuf.append(i.next());
            if (i.hasNext()) {
                retBuf.append(separator);
            }
        }
        final char[] ret = retBuf.toString().toCharArray();
        buf.characters(ret, 0, ret.length);
    }

    @Override
    public String getResult() {
        throw new UnsupportedOperationException();
    }

}

/*
 * This file is part of the DITA Open Toolkit project.
 *
 * Copyright 2011 Jarno Elovirta
 *
 * See the accompanying LICENSE file for applicable license.
 */
package org.dita.dost.platform;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

/**
 * List transtypes integration action.
 *
 * @since 1.5.4
 * @author Jarno Elovirta
 */
final class ListTranstypeAction extends ImportAction {

    /**
     * Get result.
     */
    @Override
    public void getResult(final ContentHandler buf) throws SAXException {
        final String separator = paramTable.getOrDefault("separator", "|");
        final List<String> v = valueSet.stream()
                .map(fileValue -> fileValue.value)
                .distinct()
                .collect(Collectors.toList());
        Collections.sort(v);
        final StringBuilder retBuf = new StringBuilder();
        for (final Iterator<String> i = v.iterator(); i.hasNext();) {
            retBuf.append(i.next());
            if (i.hasNext()) {
                retBuf.append(separator);
            }
        }
        final char[] ret = retBuf.toString().toCharArray();
        buf.characters(ret, 0, ret.length);
    }

    @Override
    public String getResult() {
        throw new UnsupportedOperationException();
    }

}

Drop duplicates when listing transform types

Signed-off-by: Robert D Anderson <4907d442684b61876fae0471c4d2d08024a9ca72@us.ibm.com>


/*
 * Copyright 2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.types.requests.idol.actions.tags;

import lombok.Data;

import java.io.Serializable;

@SuppressWarnings({"WeakerAccess", "unused"})
@Data
public class TagName implements Serializable {
    private static final long serialVersionUID = -6221132711228529797L;
    private final String id;
    private final String name;

    public TagName(final String name, final String id) {
        this.name = name;
        this.id = id;
    }
}

/*
 * Copyright 2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.types.requests.idol.actions.tags;

import com.fasterxml.jackson.annotation.JsonCreator;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@SuppressWarnings({"WeakerAccess", "unused"})
@Getter
@NoArgsConstructor
@EqualsAndHashCode
public class TagName implements Serializable {
    private static final long serialVersionUID = -6221132711228529797L;
    private String id;
    private String name;

    @JsonCreator
    public TagName(final String path) {
        name = getFieldNameFromPath(path);
        id = adjustFieldPath(path, name);
    }

    private String adjustFieldPath(final String fieldPath, final String fieldName) {
        // Need an extra '/' to be able to query a field by its root path (since wildcards in Idol config file take the form */SOME_FIELD)
        // However, for the special autn_date field which does not have a path, adding such a '/' would break the query
        return fieldName.equals(fieldPath) || fieldPath.startsWith("/") ? fieldPath : '/' + fieldPath;
    }

    private String getFieldNameFromPath(final String value) {
        return value.contains("/") ? value.substring(value.lastIndexOf('/') + 1) : value;
    }
}

Undo change a3351c6 as the update to haven-search-components required to use it is currently on hold

[rev. matthew.gordon]


package com.team254.frc2013.commands;

import edu.wpi.first.wpilibj.Timer;

/**
 * Shoots a disc that is already loaded into the shooter.
 *
 * @author tom@team254.com (Tom Bottiglieri)
 * @author pat@team254.com (Patrick Fairbank)
 */
public class ShootCommand extends CommandBase {
  private Timer shooterTimer;

  public ShootCommand() {
    requires(shooter);
    shooterTimer = new Timer();
  }

  protected void initialize() {
    // Don't fire the piston if the shooter is not turned on.
    if (shooter.isOn()) {
      shooter.extend();
      shooterTimer.reset();
      shooterTimer.start();
    }
  }

  protected void execute() {
  }

  protected boolean isFinished() {
    return shooterTimer.get() > 0.2 || !shooter.isOn();
  }

  protected void end() {
    System.out.println("RPM of shot: " + shooter.getRpm());
    shooter.retract();
  }

  protected void interrupted() {
  }
}

package com.team254.frc2013.commands;

import edu.wpi.first.wpilibj.Timer;

/**
 * Shoots a disc that is already loaded into the shooter.
 *
 * @author tom@team254.com (Tom Bottiglieri)
 * @author pat@team254.com (Patrick Fairbank)
 */
public class ShootCommand extends CommandBase {
  private Timer shooterTimer;

  public ShootCommand() {
    requires(shooter);
    shooterTimer = new Timer();
  }

  protected void initialize() {
    // Don't fire the piston if the shooter is not turned on.
    if (shooter.isOn()) {
      shooter.extend();
      shooterTimer.reset();
      shooterTimer.start();
    }
    conveyor.setMotor(-.175);
    intake.setIntakePower(-.1);
  }

  protected void execute() {
  }

  protected boolean isFinished() {
    return shooterTimer.get() > 0.2 || !shooter.isOn();
  }

  protected void end() {
    System.out.println("RPM of shot: " + shooter.getRpm());
    shooter.retract();
  }

  protected void interrupted() {
  }
}

Make conveyor run backwards as disc is shooting to prevent jams


/**
 * Waffle (https://github.com/Waffle/waffle)
 *
 * Copyright (c) 2010-2016 Application Security, 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
 * https://www.eclipse.org/legal/epl-v10.html.
 *
 * Contributors: Application Security, Inc.
 */
package waffle.apache;

import org.junit.Assert;
import org.junit.Test;

/**
 * Windows Realm Tests.
 *
 * @author dblock[at]dblock[dot]org
 */
public class WindowsRealmTests {

    /**
     * Test properties.
     */
    @Test
    public void testProperties() {
        final WindowsRealm realm = new WindowsRealm();
        Assert.assertNull(realm.getPassword(null));
        Assert.assertNull(realm.getPrincipal(null));
        // To support tomcat 9.0.0.M13 and lower this will still work
        Assert.assertEquals("waffle.apache.WindowsRealm/1.0", realm.getName());
        // In tomcat 9.0.0.M15+, this is all that will now report
        Assert.assertEquals("WindowsRealm", WindowsRealm.class.getSimpleName());
    }
}

/**
 * Waffle (https://github.com/Waffle/waffle)
 *
 * Copyright (c) 2010-2017 Application Security, 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
 * https://www.eclipse.org/legal/epl-v10.html.
 *
 * Contributors: Application Security, Inc.
 */
package waffle.apache;

import org.junit.Assert;
import org.junit.Test;

/**
 * Windows Realm Tests.
 *
 * @author dblock[at]dblock[dot]org
 */
public class WindowsRealmTests {

    /**
     * Test properties.
     */
    @Test
    public void testProperties() {
        final WindowsRealm realm = new WindowsRealm();
        Assert.assertNull(realm.getPassword(null));
        Assert.assertNull(realm.getPrincipal(null));
        // To support tomcat 9.0.0.M13 and lower this will still work
        Assert.assertEquals("waffle.apache.WindowsRealm/1.0", realm.getName());
        // In tomcat 9.0.0.M15+, this is all that will now report
        Assert.assertEquals("WindowsRealm", realm.getClass().getSimpleName());
    }
}

[ci] Correct test to use the instantiated class instead


package com.kaviju.accesscontrol.authentication;

import java.util.Random;

public class RandomPasswordGenerator {
	static final String possibleChars = "23456789abcdefghjklmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ@#$%?&*()-+";
	static Random rnd = new Random();

	static public String newPassword(int len) {
		{
			StringBuilder password = new StringBuilder( len );
			for( int i = 0; i < len; i++ ) {
				int nextCharIndex = rnd.nextInt(possibleChars.length());
				password.append(possibleChars.charAt(nextCharIndex));
			}
			return password.toString();
		}
	}
}

package com.kaviju.accesscontrol.authentication;

import java.util.Random;

public class RandomPasswordGenerator {
	static final String possibleChars = "23456789abcdefghjklmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ@#$%?&*()-+";
	static final String possibleDigits = "0123456789";
	static Random rnd = new Random();

	static public String newPassword(int len) {
		{
			StringBuilder password = new StringBuilder( len );
			for( int i = 0; i < len; i++ ) {
				int nextCharIndex = rnd.nextInt(possibleChars.length());
				password.append(possibleChars.charAt(nextCharIndex));
			}
			return password.toString();
		}
	}

	static public String newDigitsPassword(int len) {
		{
			StringBuilder password = new StringBuilder( len );
			for( int i = 0; i < len; i++ ) {
				int nextCharIndex = rnd.nextInt(possibleDigits.length());
				password.append(possibleDigits.charAt(nextCharIndex));
			}
			return password.toString();
		}
	}
}

Add a digits only password generator.

Add a digits only password generator.