package tars.testutil;

import tars.commons.exceptions.IllegalValueException;
import tars.model.Tars;
import tars.model.person.Person;
import tars.model.person.UniquePersonList;
import tars.model.tag.Tag;

/**
 * A utility class to help with building Addressbook objects.
 * Example usage: <br>
 *     {@code Tars ab = new TarsBuilder().withPerson("John", "Doe").withTag("Friend").build();}
 */
public class TarsBuilder {

    private Tars addressBook;

    public TarsBuilder(Tars addressBook){
        this.addressBook = addressBook;
    }

    public TarsBuilder withPerson(Person person) throws UniquePersonList.DuplicatePersonException {
        addressBook.addPerson(person);
        return this;
    }

    public TarsBuilder withTag(String tagName) throws IllegalValueException {
        addressBook.addTag(new Tag(tagName));
        return this;
    }

    public Tars build(){
        return addressBook;
    }
}

package tars.testutil;

import tars.commons.exceptions.IllegalValueException;
import tars.model.Tars;
import tars.model.person.Person;
import tars.model.person.UniquePersonList;
import tars.model.tag.Tag;

/**
 * A utility class to help with building Tars objects.
 * Example usage: <br>
 *     {@code Tars ab = new TarsBuilder().withPerson("John", "Doe").withTag("Friend").build();}
 */
public class TarsBuilder {

    private Tars addressBook;

    public TarsBuilder(Tars addressBook){
        this.addressBook = addressBook;
    }

    public TarsBuilder withPerson(Person person) throws UniquePersonList.DuplicatePersonException {
        addressBook.addPerson(person);
        return this;
    }

    public TarsBuilder withTag(String tagName) throws IllegalValueException {
        addressBook.addTag(new Tag(tagName));
        return this;
    }

    public Tars build(){
        return addressBook;
    }
}

Rename all containing 'Addressbook' to 'Tars'


package staticResources;

import java.io.File;

import utilities.FileUtility;

public class WebUIResources extends AbstractBootstrapResource {

	@Override
	protected boolean correctExtension(String name) {
		return true;
	}

	@Override
	protected File getExtractingDest() {
		return new File(FileUtility.joinPath("resources", "webui"));
	}

	@Override
	protected String getName() {
		return "WebUI";
	}

	@Override
	protected String getRelativeSourcePath() {
		return "staticContent/webui";
	}

	/**
	 * Returns the directory containing all web UI resources.
	 */
	public File getRoot() {
		return getExtractingDest();
	}

	/**
	 * Returns the directory containing all static resources.
	 */
	public File getStaticDir() {
		return new File(FileUtility.joinPath(getRoot().getAbsolutePath(), "static"));
	}

	/**
	 * Returns the directory containing all HTML templates.
	 */
	public File getTemplateDir() {
		return new File(FileUtility.joinPath(getRoot().getAbsolutePath(), "templates"));
	}
}

package staticResources;

import java.io.File;

import utilities.FileUtility;

public class WebUIResources extends AbstractBootstrapResource {

	@Override
	protected boolean correctExtension(String name) {
		return true;
	}

	@Override
	protected File getExtractingDest() {
		return new File(FileUtility.joinPath("resources", "webui", "templates"));
	}

	@Override
	protected String getName() {
		return "WebUI";
	}

	@Override
	protected String getRelativeSourcePath() {
		return "staticContent/webui/templates";
	}

	/**
	 * Returns the directory containing all web UI resources.
	 */
	public File getRoot() {
		return getExtractingDest();
	}

	/**
	 * Returns the directory containing all HTML templates.
	 */
	public File getTemplateDir() {
		return new File(FileUtility.joinPath(getRoot().getAbsolutePath()));
	}
}

Remove extraction of static resources from bootstrap resource.


/*******************************************************************************
 * This file is part of TERMINAL RECALL
 * Copyright (c) 2015 Chuck Ritola
 * Part of the jTRFP.org project
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl.html
 *
 * Contributors:
 *     chuck - initial API and implementation
 ******************************************************************************/

package org.jtrfp.trcl.core;

public interface Feature<T> {
 void apply(T target);
 void remove(T target);
}//end Feature

/*******************************************************************************
 * This file is part of TERMINAL RECALL
 * Copyright (c) 2015 Chuck Ritola
 * Part of the jTRFP.org project
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl.html
 *
 * Contributors:
 *     chuck - initial API and implementation
 ******************************************************************************/

package org.jtrfp.trcl.core;

public interface Feature<T> {
 void apply(T target);
}//end Feature

Remove .remove() in favor of finalize().


package seedu.tasklist.commons.util;

import static org.junit.Assert.assertEquals;

import java.io.File;

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

public class FileUtilTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void getPath() {

        // valid case
        assertEquals("folder" + File.separator + "sub-folder", FileUtil.getPath("folder/sub-folder"));

        // null parameter -> assertion failure
        thrown.expect(AssertionError.class);
        FileUtil.getPath(null);

        // no forwards slash -> assertion failure
        thrown.expect(AssertionError.class);
        FileUtil.getPath("folder");
    }

}

package seedu.tasklist.commons.util;

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

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

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

public class FileUtilTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void getPath() {

        // valid case
        assertEquals("folder" + File.separator + "sub-folder", FileUtil.getPath("folder/sub-folder"));

        // null parameter -> assertion failure
        thrown.expect(AssertionError.class);
        FileUtil.getPath(null);

        // no forwards slash -> assertion failure
        thrown.expect(AssertionError.class);
        FileUtil.getPath("folder");
    }
//@@author A0141993X
    @Test
    public void isFileExists_fileExists_returnsTrue() throws IOException {
        String filePath = "filePathExists.xml";
        File file = new File(filePath);
        FileUtil.createFile(file);
        assertTrue(FileUtil.isFileExists(file));
    }

    @Test
    public void isFileExists_fileDoesNotExist_returnsFalse() {
        String filePath = "fileDoesNotExist.xml";
        File file = new File (filePath);
        assertFalse(FileUtil.isFileExists(file));
    }

    @Test
    public void createDirs_validDirectory_successful() throws IOException {
        String dir = "Users/test/saveData";
        File dirFile = new File(dir);
        FileUtil.createDirs(dirFile);
    }

    @Test  (expected = IOException.class)
    public void createDirs_invalidDirectory_throwsException() throws IOException {
        String dir = "test< \0? save";
        File dirFile = new File(dir);
        FileUtil.createDirs(dirFile);
    }

}

Add test cases to improve code coverage

Add test cases to improve code coverage


package org.wikipedia.gallery;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.gson.annotations.SerializedName;

import org.apache.commons.lang3.StringUtils;

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

@SuppressWarnings("unused")
public class MediaListItem implements Serializable {
    @Nullable private String title;
    @SerializedName("section_id") private int sectionId;
    @Nullable private String type;
    @Nullable private TextInfo caption;
    private boolean showInGallery;
    @Nullable @SerializedName("srcset") private List<ImageSrcSet> srcSets;

    public MediaListItem() {
    }

    public MediaListItem(@NonNull String title) {
        this.title = title;
    }

    @NonNull
    public String getType() {
        return StringUtils.defaultString(type);
    }

    @Nullable
    public TextInfo getCaption() {
        return caption;
    }

    public boolean showInGallery() {
        return showInGallery;
    }

    @NonNull
    public String getTitle() {
        return StringUtils.defaultString(title);
    }

    @NonNull
    public List<ImageSrcSet> getSrcSets() {
        return srcSets != null ? srcSets : Collections.emptyList();
    }

    public class ImageSrcSet implements Serializable {
        @Nullable private String src;
        @Nullable private String scale;

        @Nullable
        public String getSrc() {
            return src;
        }

        @Nullable
        public String getScale() {
            return scale;
        }
    }
}

package org.wikipedia.gallery;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.gson.annotations.SerializedName;

import org.apache.commons.lang3.StringUtils;

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

@SuppressWarnings("unused")
public class MediaListItem implements Serializable {
    @Nullable private String title;
    @SerializedName("section_id") private int sectionId;
    @Nullable private String type;
    @Nullable private TextInfo caption;
    private boolean showInGallery;
    @Nullable @SerializedName("srcset") private List<ImageSrcSet> srcSets;

    public MediaListItem() {
    }

    public MediaListItem(@NonNull String title) {
        this.title = title;
    }

    @NonNull
    public String getType() {
        return StringUtils.defaultString(type);
    }

    @Nullable
    public TextInfo getCaption() {
        return caption;
    }

    public boolean showInGallery() {
        return showInGallery;
    }

    @NonNull
    public String getTitle() {
        return StringUtils.defaultString(title);
    }

    @NonNull
    public List<ImageSrcSet> getSrcSets() {
        return srcSets != null ? srcSets : Collections.emptyList();
    }

    public class ImageSrcSet implements Serializable {
        @Nullable private String src;
        @Nullable private String scale;

        @NonNull
        public String getSrc() {
            return StringUtils.defaultString(src);
        }

        @NonNull
        public String getScale() {
            return StringUtils.defaultString(scale);
        }
    }
}

Use StringUtils for the default string

Use StringUtils for the default string


package com.felipecsl.elifut.util;

import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.Toolbar;

public final class ColorUtils {
  private ColorUtils() {
  }

  @TargetApi(Build.VERSION_CODES.LOLLIPOP)
  public static void colorizeHeader(Activity activity, Toolbar toolbar, TabLayout tabs,
      int primaryColor, int secondaryColor) {
    toolbar.setBackgroundColor(primaryColor);
    tabs.setBackgroundColor(primaryColor);
    tabs.setSelectedTabIndicatorColor(secondaryColor);
    if (AndroidVersion.isAtLeastLollipop()) {
      activity.getWindow().setStatusBarColor(primaryColor);
    }
  }
}

package com.felipecsl.elifut.util;

import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.Toolbar;

public final class ColorUtils {
  private ColorUtils() {
  }

  @TargetApi(Build.VERSION_CODES.LOLLIPOP)
  public static void colorizeHeader(Activity activity, Toolbar toolbar, TabLayout tabs,
      int primaryColor, int secondaryColor) {
    toolbar.setBackgroundColor(primaryColor);
    tabs.setBackgroundColor(primaryColor);
    tabs.setSelectedTabIndicatorColor(secondaryColor);
    if (AndroidVersion.isAtLeastLollipop()) {
      activity.getWindow().setStatusBarColor(darken(primaryColor, 0.9f));
    }
  }

  /** Returns darker version of specified color */
  public static int darken(int color, float factor) {
    int a = Color.alpha(color);
    int r = Color.red(color);
    int g = Color.green(color);
    int b = Color.blue(color);

    return Color.argb(a,
        Math.max((int) (r * factor), 0),
        Math.max((int) (g * factor), 0),
        Math.max((int) (b * factor), 0));
  }
}

Use 10% darker color for system status bar tinting


package hu.elte.txtuml.validation.model;

import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.TypeDeclaration;

import hu.elte.txtuml.validation.common.AbstractValidationError;
import hu.elte.txtuml.validation.common.SourceInfo;

/**
 * Base class for all JtxtUML model validation errors.
 */
public abstract class ModelValidationError extends AbstractValidationError {

	public ModelValidationError(SourceInfo sourceInfo, ASTNode node) {
		super(sourceInfo, node);
		Class<?> c = ASTNode.nodeClassForType(node.getNodeType());
		if (c == MethodDeclaration.class || c == TypeDeclaration.class) {
			SimpleName name;
			if (c == MethodDeclaration.class) {
				name = ((MethodDeclaration) node).getName();
			} else {
				name = ((TypeDeclaration) node).getName();
			}
			this.sourceStart = name.getStartPosition();
			this.sourceEnd = name.getStartPosition() + name.getLength();
		}

	}

	@Override
	public String getMarkerType() {
		return JtxtUMLModelCompilationParticipant.JTXTUML_MODEL_MARKER_TYPE;
	}

	@Override
	public String toString() {
		return getType() + " (" + getMessage() + ")";
	}

}

package hu.elte.txtuml.validation.model;

import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.TypeDeclaration;

import hu.elte.txtuml.validation.common.AbstractValidationError;
import hu.elte.txtuml.validation.common.SourceInfo;

/**
 * Base class for all JtxtUML model validation errors.
 */
public abstract class ModelValidationError extends AbstractValidationError {

	public ModelValidationError(SourceInfo sourceInfo, ASTNode node) {
		super(sourceInfo, node);
		if (node instanceof MethodDeclaration || node instanceof TypeDeclaration) {
			SimpleName name;
			if (node instanceof MethodDeclaration) {
				name = ((MethodDeclaration) node).getName();
			} else {
				name = ((TypeDeclaration) node).getName();
			}
			this.sourceStart = name.getStartPosition();
			this.sourceEnd = name.getStartPosition() + name.getLength();
		}

	}

	@Override
	public String getMarkerType() {
		return JtxtUMLModelCompilationParticipant.JTXTUML_MODEL_MARKER_TYPE;
	}

	@Override
	public String toString() {
		return getType() + " (" + getMessage() + ")";
	}

}

Replace class equality test with instanceof


package net.tropicraft.core.client.entity.render.layer;

import com.mojang.blaze3d.platform.GlStateManager;
import net.minecraft.client.renderer.entity.IEntityRenderer;
import net.minecraft.client.renderer.entity.layers.HeldItemLayer;
import net.minecraft.client.renderer.entity.model.EntityModel;
import net.minecraft.client.renderer.entity.model.IHasArm;
import net.minecraft.entity.LivingEntity;
import net.minecraft.util.HandSide;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

@OnlyIn(Dist.CLIENT)
public class TropiSkellyHeldItemLayer<T extends LivingEntity, M extends EntityModel<T> & IHasArm> extends HeldItemLayer<T, M> {
    public TropiSkellyHeldItemLayer(IEntityRenderer<T, M> renderer) {
        super(renderer);
    }

    @Override
    protected void translateToHand(HandSide handSide) {
        GlStateManager.translatef(0.09375F, 0.1875F, 0.0F);
    }
}

package net.tropicraft.core.client.entity.render.layer;

import com.mojang.blaze3d.platform.GlStateManager;

import net.minecraft.client.renderer.entity.IEntityRenderer;
import net.minecraft.client.renderer.entity.layers.HeldItemLayer;
import net.minecraft.client.renderer.entity.model.EntityModel;
import net.minecraft.client.renderer.entity.model.IHasArm;
import net.minecraft.entity.LivingEntity;
import net.minecraft.util.HandSide;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

@OnlyIn(Dist.CLIENT)
public class TropiSkellyHeldItemLayer<T extends LivingEntity, M extends EntityModel<T> & IHasArm> extends HeldItemLayer<T, M> {
    public TropiSkellyHeldItemLayer(IEntityRenderer<T, M> renderer) {
        super(renderer);
    }

    @Override
    protected void translateToHand(HandSide handSide) {
        super.translateToHand(handSide);
        GlStateManager.translatef(0.09375F, 0.1875F, 0.0F);
    }
}

Fix tropiskellies using their spear inappropriately

Gross, tropiskellies. Gross.


package com.zelory.kace.adressbook.data.model;

import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.zelory.kace.adressbook.util.JsonParser;
import lombok.Getter;
import lombok.Setter;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@Getter
@Setter
public class AddressBook {
    private String name;
    private List<Person> persons;
    private String path;

    public AddressBook() {
        this("Untitled", new ArrayList<>());
    }

    public AddressBook(File file) throws IOException, JsonSyntaxException {
        StringBuilder data = new StringBuilder();
        Files.lines(Paths.get(file.getAbsolutePath()), StandardCharsets.UTF_8).forEach(data::append);
        name = file.getName();
        persons = JsonParser.getInstance().getParser().fromJson(data.toString(), new TypeToken<List<Person>>() {}.getType());
        path = file.getAbsolutePath();
    }

    public AddressBook(String name, List<Person> persons) {
        this.name = name;
        this.persons = persons;
    }
}

package com.zelory.kace.adressbook.data.model;

import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.zelory.kace.adressbook.util.JsonParser;
import lombok.Getter;
import lombok.Setter;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@Getter
@Setter
public class AddressBook {

    public static final int PERSON_ADDED = 1;
    public static final int PERSON_UPDATED = 2;

    private String name;
    private List<Person> persons;
    private String path;

    public AddressBook() {
        this("Untitled", new ArrayList<>());
    }

    public AddressBook(File file) throws IOException, JsonSyntaxException {
        StringBuilder data = new StringBuilder();
        Files.lines(Paths.get(file.getAbsolutePath()), StandardCharsets.UTF_8).forEach(data::append);
        name = file.getName();
        persons = JsonParser.getInstance().getParser().fromJson(data.toString(), new TypeToken<List<Person>>() {}.getType());
        path = file.getAbsolutePath();
    }

    public AddressBook(String name, List<Person> persons) {
        this.name = name;
        this.persons = persons;
    }

    public int addOrUpdatePerson(Person person) {
        int pos = persons.indexOf(person);
        if (pos > 0) {
            persons.set(pos, person);
            return PERSON_UPDATED;
        } else {
            persons.add(person);
            return PERSON_ADDED;
        }
    }
}

Add method for handling add or update person


package com.ezardlabs.dethsquare.prefabs;

import com.ezardlabs.dethsquare.GameObject;

public abstract class PrefabCreator {
	public abstract GameObject create();
}

package com.ezardlabs.dethsquare.prefabs;

import com.ezardlabs.dethsquare.GameObject;

public interface PrefabCreator {
	GameObject create();
}

Change from abstract class to interface

Change from abstract class to interface


package com.skelril.aurora.prayer.PrayerFX;

import com.sk89q.worldedit.blocks.BlockID;
import com.skelril.aurora.prayer.PrayerType;
import com.skelril.aurora.util.ChanceUtil;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

/**
 * Author: Turtle9598
 */
public class InventoryFX extends AbstractPrayer {

    int type, amount;

    public InventoryFX() {
        super();
        this.type = BlockID.DIRT;
        this.amount = 1;
    }

    public InventoryFX(int type, int amount) {
        super();
        this.type = type;
        this.amount = amount;
    }

    @Override
    public PrayerType getType() {

        return PrayerType.INVENTORY;
    }

    @Override
    public void add(Player player) {

        ItemStack held = player.getItemInHand().clone();
        ItemStack stack = new ItemStack(type, ChanceUtil.getRandom(amount));
        if (held != null && held.getTypeId() != BlockID.AIR && !held.isSimilar(stack)) {
            Item item = player.getWorld().dropItem(player.getLocation(), held);
            item.setPickupDelay(20 * 5);
        }
        player.setItemInHand(stack);
    }

    @Override
    public void clean(Player player) {

        // Nothing to do here
    }
}

package com.skelril.aurora.prayer.PrayerFX;

import com.sk89q.worldedit.blocks.BlockID;
import com.skelril.aurora.prayer.PrayerType;
import com.skelril.aurora.util.ChanceUtil;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

/**
 * Author: Turtle9598
 */
public class InventoryFX extends AbstractPrayer {

    private int type, amount;

    public InventoryFX() {
        super();
        this.type = BlockID.DIRT;
        this.amount = 1;
    }

    public InventoryFX(int type, int amount) {
        super();
        this.type = type;
        this.amount = amount;
    }

    @Override
    public PrayerType getType() {

        return PrayerType.INVENTORY;
    }

    @Override
    public void add(Player player) {

        ItemStack held = player.getItemInHand().clone();
        ItemStack stack = new ItemStack(type, ChanceUtil.getRandom(amount));
        if (held != null && held.getTypeId() != BlockID.AIR && !held.isSimilar(stack)) {
            Item item = player.getWorld().dropItem(player.getLocation(), held);
            item.setPickupDelay(20 * 5);
        }
        player.setItemInHand(stack);
    }

    @Override
    public void clean(Player player) {

        // Nothing to do here
    }
}

Fix bad habit caused by c++ programming

Fix bad habit caused by c++ programming


package com.chbi.rest;

import com.chbi.ApplicationConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * Handles the jenkins urls, appends the json api suffix and replaces url parts if necessary.
 */
@Service
public class UrlRewriter {

    public static final String API_JSON_URL_ENDING = "api/json";

    @Autowired
    private ApplicationConfiguration configuration;

    String prepareUrl(String baseUrl) {

        String preparedUrl = StringUtils.replace(baseUrl, configuration.getUrlSearchPattern(),
                configuration.getUrlReplacement());
        preparedUrl += API_JSON_URL_ENDING;

        return preparedUrl;
    }

    String getPreparedBaseUrl() {
        return prepareUrl(configuration.getBaseUrl());
    }
}

package com.chbi.rest;

import com.chbi.ApplicationConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * Handles the jenkins urls, appends the json api suffix and replaces url parts if necessary.
 */
@Service
public class UrlRewriter {

    private static final String API_JSON_URL_ENDING = "api/json";
    private static final String HTML_WHITESPACE = "%20";
    private static final String WHITESPACE = " ";

    @Autowired
    private ApplicationConfiguration configuration;

    String prepareUrl(String baseUrl) {

        String preparedUrl = StringUtils.replace(baseUrl, configuration.getUrlSearchPattern(),
                configuration.getUrlReplacement());
        preparedUrl = StringUtils.replace(preparedUrl, HTML_WHITESPACE, WHITESPACE);
        preparedUrl += API_JSON_URL_ENDING;

        return preparedUrl;
    }

    String getPreparedBaseUrl() {
        return prepareUrl(configuration.getBaseUrl());
    }
}

Fix urls with %20 instead of whitespaces


package info.u_team.u_team_test.init;

import info.u_team.u_team_core.soundevent.USoundEvent;
import info.u_team.u_team_core.util.registry.BaseRegistryUtil;
import info.u_team.u_team_test.TestMod;
import net.minecraft.util.SoundEvent;
import net.minecraftforge.event.RegistryEvent.Register;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;

@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD)
public class TestSounds {

	public static final SoundEvent BETTER_ENDERPEARL_USE = new USoundEvent("better_enderpearl_use");

	@SubscribeEvent
	public static void register(Register<SoundEvent> event) {
		BaseRegistryUtil.getAllRegistryEntriesAndApplyNames(TestMod.MODID, SoundEvent.class).forEach(event.getRegistry()::register);
	}

}

package info.u_team.u_team_test.init;

import info.u_team.u_team_core.soundevent.USoundEvent;
import info.u_team.u_team_test.TestMod;
import net.minecraft.util.SoundEvent;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
import net.minecraftforge.registries.*;

@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD)
public class TestSounds {

	public static final DeferredRegister<SoundEvent> SOUND_EVENTS = DeferredRegister.create(ForgeRegistries.SOUND_EVENTS, TestMod.MODID);

	public static final SoundEvent BETTER_ENDERPEARL_USE = new USoundEvent("better_enderpearl_use");

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

}

Add deferred register to test sounds

Add deferred register to test sounds


package kamkor.covariance;

import org.junit.Test;

public class CovariantArrayExample {

	// Scala solves this by making its Arrays invariant (nonvariant)
	@Test(expected = ArrayStoreException.class)
	public void covariantArraysLeadToRuntimeExceptions() {
		String[] c1 = { "abc" };
		Object[] c2 = c1;
		// OOPS! Line below throws a runtime exception: ArrayStoreException
		// Reason is, that c2 is actually an instance of String array, and
		// we try to update it with an Integer.
		c2[0] = 1;
	}

}

package kamkor.covariance;

import org.junit.Test;

public class CovariantArrayExample {

	// Scala solves this by making its Arrays invariant (nonvariant)
	@Test(expected = ArrayStoreException.class)
	public void covariantArraysLeadToRuntimeExceptions() {
		String[] strings = { "abc" };
		Object[] objects = strings;
		// OOPS! Line below throws a runtime exception: ArrayStoreException
		// Reason is, that objects is actually an instance of String array, and
		// we try to update it with an Integer.
		objects[0] = 1;
	}

}

Refactor Java covariant array example

Refactor Java covariant array example


import java.util.stream.IntStream;

/**
 * @author David Clutter
 */
public class Problem0001 {

    public static void main(final String[] args) {
        System.out.println(
                IntStream.range(1, 1000)
                        .filter(n -> n % 3 == 0 || n % 5 == 0)
                        .sum()
        );
    }
}

import java.util.stream.IntStream;

/**
 * If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these
 * multiples is 23.
 *
 * Find the sum of all the multiples of 3 or 5 below 1000.
 *
 * @author David Clutter
 */
public class Problem0001 {

    public static void main(final String[] args) {
        System.out.println(
                IntStream.range(1, 1000)
                        .filter(n -> n % 3 == 0 || n % 5 == 0)
                        .sum()
        );
    }
}

Add problem text to javadoc

Add problem text to javadoc


/**
 * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.util.time;

import org.testng.annotations.Test;
import org.threeten.bp.LocalDate;

import com.opengamma.util.test.AbstractFudgeBuilderTestCase;

/**
 * Test Fudge encoding.
 */
@Test(groups = "unit")
public class LocalDateRangeFudgeEncodingTest extends AbstractFudgeBuilderTestCase {

  public void test_inclusive() {
    LocalDateRange range = LocalDateRange.of(LocalDate.of(2010, 7, 1), LocalDate.of(2010, 8, 1), true);
    assertEncodeDecodeCycle(LocalDateRange.class, range);
  }

  public void test_exclusive() {
    LocalDateRange range = LocalDateRange.of(LocalDate.of(2010, 7, 1), LocalDate.of(2010, 8, 1), false);
    assertEncodeDecodeCycle(LocalDateRange.class, range);
  }

}

/**
 * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.util.time;

import org.testng.annotations.Test;
import org.threeten.bp.LocalDate;

import com.opengamma.util.test.AbstractFudgeBuilderTestCase;

/**
 * Test Fudge encoding.
 */
@Test(groups = "unit")
public class LocalDateRangeFudgeEncodingTest extends AbstractFudgeBuilderTestCase {

  public void test_inclusive() {
    LocalDateRange range = LocalDateRange.of(LocalDate.of(2010, 7, 1), LocalDate.of(2010, 8, 1), true);
    assertEncodeDecodeCycle(LocalDateRange.class, range);
  }

  public void test_exclusive() {
    LocalDateRange range = LocalDateRange.of(LocalDate.of(2010, 7, 1), LocalDate.of(2010, 8, 1), false);
    assertEncodeDecodeCycle(LocalDateRange.class, range);
  }

  public void test_all() {
    assertEncodeDecodeCycle(LocalDateRange.class, LocalDateRange.ALL);
  }

}

Add test for fudge serialization of LocalDate.ALL


package se.vidstige.jadb;

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

/**
 * Launches the ADB server
 */
public class AdbServerLauncher {
    private final String executable;
    private Subprocess subprocess;

    public AdbServerLauncher(Subprocess subprocess, Map<String, String> environment) {
        this.subprocess = subprocess;
        this.executable = findAdbExecutable(environment);
    }

    private static String findAdbExecutable(Map<String, String> environment) {
        String android_home = environment.get("ANDROID_HOME");
        if (android_home == null || android_home.equals("")) {
            return "adb";
        }
        return android_home + "/platform-tools/adb";
    }

    public void launch() throws IOException, InterruptedException {
        Process p = subprocess.execute(new String[]{executable, "start-server"});
        p.waitFor();
        int exitValue = p.exitValue();
        if (exitValue != 0) throw new IOException("adb exited with exit code: " + exitValue);
    }
}

package se.vidstige.jadb;

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

/**
 * Launches the ADB server
 */
public class AdbServerLauncher {
    private final String executable;
    private Subprocess subprocess;

    /**
     * Creates a new launcher loading ADB from the environment.
     *
     * @param subprocess the sub-process.
     * @param environment the environment to use to locate the ADB executable.
     */
    public AdbServerLauncher(Subprocess subprocess, Map<String, String> environment) {
        this(subprocess, findAdbExecutable(environment));
    }

    /**
     * Creates a new launcher with the specified ADB.
     *
     * @param subprocess the sub-process.
     * @param executable the location of the ADB executable.
     */
    public AdbServerLauncher(Subprocess subprocess, String executable) {
        this.subprocess = subprocess;
        this.executable = executable;
    }

    private static String findAdbExecutable(Map<String, String> environment) {
        String android_home = environment.get("ANDROID_HOME");
        if (android_home == null || android_home.equals("")) {
            return "adb";
        }
        return android_home + "/platform-tools/adb";
    }

    public void launch() throws IOException, InterruptedException {
        Process p = subprocess.execute(new String[]{executable, "start-server"});
        p.waitFor();
        int exitValue = p.exitValue();
        if (exitValue != 0) throw new IOException("adb exited with exit code: " + exitValue);
    }
}

Allow the location of the ADB binary to be specified.


package hex.schemas;

import hex.tree.drf.DRF;
import hex.tree.drf.DRFModel.DRFParameters;
import water.api.API;
import water.api.SupervisedModelParametersSchema;
import hex.schemas.SharedTreeV2;                        // Yes, this is needed.  Compiler bug.
import hex.schemas.SharedTreeV2.SharedTreeParametersV2; // Yes, this is needed.  Compiler bug.

public class DRFV2 extends SharedTreeV2<DRF,DRFV2,DRFV2.DRFParametersV2> {

  public static final class DRFParametersV2 extends SharedTreeParametersV2<DRFParameters, DRFParametersV2> {
    static public String[] own_fields = new String[] {
        "mtries",
        "sample_rate",
        "do_grpsplit",
        "build_tree_one_node"
    };

    // Input fields
    @API(help = "Columns to randomly select at each level, or -1 for sqrt(#cols)")
    public int mtries;

    @API(help = "Sample rate, from 0. to 1.0")
    public float sample_rate;

    @API(help = "Check non-contiguous group splits for categorical predictors")
    public boolean do_grpsplit;

    @API(help="Run on one node only; no network overhead but fewer cpus used.  Suitable for small datasets.")
    public boolean build_tree_one_node;
  }
}

package hex.schemas;

import hex.tree.drf.DRF;
import hex.tree.drf.DRFModel.DRFParameters;
import water.api.API;
import water.api.SupervisedModelParametersSchema;
import hex.schemas.SharedTreeV2;                        // Yes, this is needed.  Compiler bug.
import hex.schemas.SharedTreeV2.SharedTreeParametersV2; // Yes, this is needed.  Compiler bug.

public class DRFV2 extends SharedTreeV2<DRF,DRFV2,DRFV2.DRFParametersV2> {

  public static final class DRFParametersV2 extends SharedTreeParametersV2<DRFParameters, DRFParametersV2> {
    static public String[] own_fields = new String[] {
        "mtries",
        "sample_rate",
        "build_tree_one_node"
    };

    // Input fields
    @API(help = "Number of columns to randomly select at each level, or -1 for sqrt(#cols)")
    public int mtries;

    @API(help = "Sample rate, from 0. to 1.0")
    public float sample_rate;

    @API(help="Run on one node only; no network overhead but fewer cpus used.  Suitable for small datasets.")
    public boolean build_tree_one_node;
  }
}

PUBDEV-455: Fix DRFParametersV2, remove unused do_grpsplit argument.


package mil.nga.giat.geowave.core.store.query.aggregate;

import mil.nga.giat.geowave.core.index.Persistable;

public class CountAggregation<T> implements
		Aggregation<Persistable, CountResult, T>
{
	private CountResult countResult = new CountResult();

	public CountAggregation() {}

	@Override
	public String toString() {
		return countResult.toString();
	}

	@Override
	public void aggregate(
			final T entry ) {
		if (!countResult.isSet()) {
			countResult.count = 0;
		}
		countResult.count += 1;
	}

	@Override
	public Persistable getParameters() {
		return null;
	}

	@Override
	public CountResult getResult() {
		if (!countResult.isSet()) {
			return null;
		}
		return countResult;
	}

	@Override
	public void setParameters(
			final Persistable parameters ) {}

	@Override
	public void clearResult() {
		countResult.count = 0;
	}
}

package mil.nga.giat.geowave.core.store.query.aggregate;

import mil.nga.giat.geowave.core.index.Persistable;

public class CountAggregation<T> implements
		Aggregation<Persistable, CountResult, T>
{
	private long count = Long.MIN_VALUE;

	public CountAggregation() {}

	public boolean isSet() {
		return count != Long.MIN_VALUE;
	}

	@Override
	public String toString() {
		final StringBuffer buffer = new StringBuffer();
		buffer.append(
				"count[count=").append(
				count);
		buffer.append("]");
		return buffer.toString();
	}

	@Override
	public void aggregate(
			final T entry ) {
		if (!isSet()) {
			count = 0;
		}

		count += 1;
	}

	@Override
	public Persistable getParameters() {
		return null;
	}

	@Override
	public CountResult getResult() {
		if (!isSet()) {
			return null;
		}

		return new CountResult(count);
	}

	@Override
	public void setParameters(
			final Persistable parameters ) {}

	@Override
	public void clearResult() {
		count = 0;
	}
}

Return new CountResult on getResult, and use long instead of CountResult object internally


/*
 * Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
 * license agreements.  See the NOTICE file distributed with this work for
 * additional information regarding copyright ownership.  Crate licenses
 * this file to you under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.  You may
 * obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations
 * under the License.
 *
 * However, if you have executed another commercial license agreement
 * with Crate these terms will supersede the license and you may use the
 * software solely pursuant to the terms of the relevant commercial agreement.
 */

package io.crate.plugin;

import io.crate.action.sql.DDLStatementDispatcher;
import io.crate.metadata.FulltextAnalyzerResolver;
import io.crate.protocols.postgres.PostgresNetty;
import org.elasticsearch.common.inject.AbstractModule;

public class SQLModule extends AbstractModule {

    @Override
    protected void configure() {
        bind(DDLStatementDispatcher.class).asEagerSingleton();
        bind(FulltextAnalyzerResolver.class).asEagerSingleton();
        bind(PostgresNetty.class).asEagerSingleton();
    }
}

/*
 * Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
 * license agreements.  See the NOTICE file distributed with this work for
 * additional information regarding copyright ownership.  Crate licenses
 * this file to you under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.  You may
 * obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations
 * under the License.
 *
 * However, if you have executed another commercial license agreement
 * with Crate these terms will supersede the license and you may use the
 * software solely pursuant to the terms of the relevant commercial agreement.
 */

package io.crate.plugin;

import io.crate.action.sql.DDLStatementDispatcher;
import io.crate.action.sql.SQLOperations;
import io.crate.metadata.FulltextAnalyzerResolver;
import io.crate.protocols.postgres.PostgresNetty;
import org.elasticsearch.common.inject.AbstractModule;

public class SQLModule extends AbstractModule {

    @Override
    protected void configure() {
        bind(DDLStatementDispatcher.class).asEagerSingleton();
        bind(FulltextAnalyzerResolver.class).asEagerSingleton();
        bind(PostgresNetty.class).asEagerSingleton();
        bind(SQLOperations.class).asEagerSingleton();
    }
}

Change SQLOperations to be an eager singleton


// Copyright 2014, Kevin Ko <kevin@faveset.com>

package com.faveset.khttpserver;

import java.io.IOException;
import com.faveset.log.OutputStreamLog;

public class HttpServer {
    public static void main(String[] args) throws IOException {
        if (args.length < 1) {
            System.out.println("<port>");
            return;
        }

        int port = new Integer(args[0]);

        OutputStreamLog log = new OutputStreamLog(System.out);

        com.faveset.khttp.HttpServer server = new com.faveset.khttp.HttpServer();
        server.setLog(log);

        server.listenAndServe("127.0.0.1", port);

        log.close();
    }
}

// Copyright 2014, Kevin Ko <kevin@faveset.com>

package com.faveset.khttpserver;

import java.io.IOException;
import sun.misc.Signal;
import sun.misc.SignalHandler;

import com.faveset.log.OutputStreamLog;

public class HttpServer {
    public static void main(String[] args) throws IOException {
        if (args.length < 1) {
            System.out.println("<port>");
            return;
        }

        int port = new Integer(args[0]);

        OutputStreamLog log = new OutputStreamLog(System.out);

        final com.faveset.khttp.HttpServer server = new com.faveset.khttp.HttpServer();
        server.setLog(log);

        // Set up the signal handler.
        Signal.handle(new Signal("INT"), new SignalHandler() {
            @Override
            public void handle(Signal sig) {
                server.stop();
            }
        });
        server.listenAndServe("::", port);

        log.close();
    }
}

Test server maps to all interfaces. Add signal handler for cleaning up on SIGINT.


package com.balancedpayments;

import com.balancedpayments.core.Resource;
import com.balancedpayments.core.ResourceCollection;
import com.balancedpayments.core.ResourceField;
import com.balancedpayments.core.ResourceQuery;
import com.balancedpayments.errors.HTTPError;

import java.util.Map;

public class Callback extends Resource {

    public static final String resource_href = "/callbacks";

    @ResourceField(mutable=true)
    public String url;

    @ResourceField(mutable=true, required=false)
    public String method;

    @ResourceField(mutable=true, required=false)
    public String revision;

    public static class Collection extends ResourceCollection<Callback> {
        public Collection(String href) {
            super(Callback.class, href);
        }
    };

    public Callback() {
        super();
    }

    public Callback(String href) throws HTTPError {
        super(href);
    }

    public Callback(Map<String, Object> payload) throws HTTPError {
        super(payload);
    }

    public static ResourceQuery<Callback> query() {
        return new ResourceQuery<Callback>(Callback.class, resource_href);
    }

    @Override
    public void save() throws HTTPError {
        if (id == null && href == null) {
            href = resource_href;
        }
        super.save();
    }
}

package com.balancedpayments;

import com.balancedpayments.core.Resource;
import com.balancedpayments.core.ResourceCollection;
import com.balancedpayments.core.ResourceField;
import com.balancedpayments.core.ResourceQuery;
import com.balancedpayments.errors.HTTPError;

import java.util.Map;

public class Callback extends Resource {

    public static final String resource_href = "/callbacks";

    @ResourceField(mutable=true)
    public String url;

    @ResourceField(mutable=true, required=false)
    public String method;

    @ResourceField(required=false)
    public String revision;

    public static class Collection extends ResourceCollection<Callback> {
        public Collection(String href) {
            super(Callback.class, href);
        }
    };

    public Callback() {
        super();
    }

    public Callback(String href) throws HTTPError {
        super(href);
    }

    public Callback(Map<String, Object> payload) throws HTTPError {
        super(payload);
    }

    public static ResourceQuery<Callback> query() {
        return new ResourceQuery<Callback>(Callback.class, resource_href);
    }

    @Override
    public void save() throws HTTPError {
        if (id == null && href == null) {
            href = resource_href;
        }
        super.save();
    }
}

Remove mutability of callback revision

Remove mutability of callback revision


package com.github.sparkcaller.preprocessing;

import htsjdk.samtools.BAMIndexer;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import org.apache.spark.api.java.function.Function;

import java.io.File;

public class BamIndexer implements Function<File, File> {
    // Create an index (.bai) file for the given BAM file.
    public File call(File bamFile) throws Exception {
        final SamReader bamReader = SamReaderFactory.makeDefault()
                                              .enable(SamReaderFactory.Option.INCLUDE_SOURCE_IN_RECORDS)
                                              .open(bamFile);
        BAMIndexer.createIndex(bamReader, new File(bamFile.getPath() + ".bai"));

        return bamFile;
    }
}

package com.github.sparkcaller.preprocessing;

import htsjdk.samtools.BAMIndexer;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;

import java.io.File;

public class BamIndexer implements Function<File, File> {
    // Create an index (.bai) file for the given BAM file.
    public static void indexBam(File bamFile) throws Exception {
        final SamReader bamReader = SamReaderFactory.makeDefault()
                                              .enable(SamReaderFactory.Option.INCLUDE_SOURCE_IN_RECORDS)
                                              .open(bamFile);
        BAMIndexer.createIndex(bamReader, new File(bamFile.getPath() + ".bai"));
    }

    @Override
    public File call(File inputBAM) throws Exception {
        BamIndexer.indexBam(inputBAM);
        return inputBAM;
    }
}

[Genomics]: Make it easier to run the SAM indexer on a single file.


package at.ac.tuwien.inso.repository;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import java.util.List;

import at.ac.tuwien.inso.entity.Lecturer;

public interface LecturerRepository extends CrudRepository<Lecturer, Long> {

    @Query("select l from Lecturer l where ACCOUNT_ID = ?1")
    Lecturer findLecturerByAccountId(Long id);

    public List<Lecturer> findAll();

    public Lecturer findById(Long id);
}

package at.ac.tuwien.inso.repository;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import java.util.List;

import at.ac.tuwien.inso.entity.Lecturer;

public interface LecturerRepository extends CrudRepository<Lecturer, Long> {

    @Query("select l from Lecturer l where ACCOUNT_ID = ?1")
    Lecturer findLecturerByAccountId(Long id);

    public List<Lecturer> findAllByIdentificationNumberLikeIgnoreCaseOrNameLikeIgnoreCase(
            String identificationNumber,
            String name
    );

    public Lecturer findById(Long id);
}

Replace findAll with complicated search operation


package com.github.aureliano.achmed.resources;

import com.github.aureliano.achmed.resources.properties.IResourceProperties;

public interface IResource {

	public abstract void apply(IResourceProperties properties);

	public abstract ResourceType type();
}

package com.github.aureliano.achmed.resources;

import com.github.aureliano.achmed.resources.properties.IResourceProperties;

public interface IResource {

	public abstract void apply(IResourceProperties properties);

	public abstract ResourceType type();

	public abstract IResourceProperties getProperties();
}

Add method to get properties from resource.


package i5.las2peer.persistency;

/**
 * The old XmlAble interface enforced an setStateFromXmlMethod.
 *
 * Due to several problems I decided to remove this method and leave the deserialization
 * in the hand of the programmer.
 *
 * If standard methods are to be used, the programmer of an XmlAble class should used one of
 * the following methods
 *
 *

 *
Use a factory called createFromXml ( String xml )

 * 		This is the preferred idea. An interface may not enforce static methods however...

 *
Use a Constructor with a single String parameter

 *
Use a base constructor in combination with setStateFromXml ( String )

 *  	This corresponds to the old XmlAble.

 *

 *
 * @author Holger Janßen
 *
 */
public interface XmlAble
{

	/**
	 * Returns a XML representation of this object.
	 *
	 * This method will be used by an object manager to get a persistency representation
	 * of this object.
	 *
	 *
	 * @return   a String
	 *
	 */
	public String toXmlString ();

}

package i5.las2peer.persistency;

/**
 * The old XmlAble interface enforced an setStateFromXmlMethod.
 *
 * Due to several problems I decided to remove this method and leave the deserialization
 * in the hand of the programmer.
 *
 * If standard methods are to be used, the programmer of an XmlAble class should used one of
 * the following methods
 *
 *

 *
Use a factory called createFromXml ( String xml )

 * 		This is the preferred idea. An interface may not enforce static methods however...

 *
Use a Constructor with a single String parameter

 *
Use a base constructor in combination with setStateFromXml ( String )

 *  	This corresponds to the old XmlAble.

 *

 *
 * @author Holger Janßen
 *
 */
public interface XmlAble
{

	/**
	 * Returns a XML representation of this object.
	 *
	 *
	 * @return   a String
	 *
	 */
	public String toXmlString ();

}

Comment was just not true anymore

Comment was just not true anymore
[ci skip]


package edu.stuy.starlorn.entities;

import edu.stuy.starlorn.upgrades.GunUpgrade;

import java.util.LinkedList;

public class Ship extends Entity {
    protected LinkedList<GunUpgrade> _gunupgrades;
    protected int _baseDamage, _baseShotSpeed, _health;
    protected double _baseAim;

    public Ship() {
        super();
        _gunupgrades = new LinkedList<GunUpgrade>();
        _baseDamage = 1;
        _baseShotSpeed = 1;
        _health = 10;
        _baseAim = Math.PI/2; //Aim up by default
    }

    public void addUpgrade(GunUpgrade upgrade) {
        _gunupgrades.add(upgrade);
    }

    /*
     * Create the shots based on the available GunUpgrades
     */
    public void shoot() {
        GunUpgrade topShot = _gunupgrades.get(0);
        int damage = _baseDamage;
        int shotSpeed = _baseShotSpeed;
        for (GunUpgrade up : _gunupgrades) {
            if (up.getNumShots() > topShot.getNumShots())
                topShot = up;
            damage = up.getDamage(damage);
            shotSpeed = up.getShotSpeed(shotSpeed);
        }
        // Create new shots, based on dem vars
        int numShots = topShot.getNumShots();
        for (int i = 0; i < numShots; i++) {
            Bullet b = new Bullet(_baseAim + topShot.getAimAngle(), damage, shotSpeed);
            b.setWorld(this.getWorld());
        }
    }
}

package edu.stuy.starlorn.entities;

import edu.stuy.starlorn.upgrades.GunUpgrade;

import java.util.LinkedList;

public class Ship extends Entity {
    protected LinkedList<GunUpgrade> _gunupgrades;
    protected int _baseDamage, _baseShotSpeed, _health;
    protected double _baseAim;

    public Ship() {
        super();
        _gunupgrades = new LinkedList<GunUpgrade>();
        _baseDamage = 1;
        _baseShotSpeed = 1;
        _health = 10;
        _baseAim = 0; //Aim up by default
    }

    public void addUpgrade(GunUpgrade upgrade) {
        _gunupgrades.add(upgrade);
    }

    /*
     * Create the shots based on the available GunUpgrades
     */
    public void shoot() {
        GunUpgrade topShot = _gunupgrades.get(0);
        int damage = _baseDamage;
        int shotSpeed = _baseShotSpeed;
        for (GunUpgrade up : _gunupgrades) {
            if (up.getNumShots() > topShot.getNumShots())
                topShot = up;
            damage = up.getDamage(damage);
            shotSpeed = up.getShotSpeed(shotSpeed);
        }
        // Create new shots, based on dem vars
        int numShots = topShot.getNumShots();
        for (int i = 0; i < numShots; i++) {
            Bullet b = new Bullet(_baseAim + topShot.getAimAngle(), damage, shotSpeed);
            b.setWorld(this.getWorld());
        }
    }
}

Change baseAim to 0, since we're using the Y axis


package ljfa.tntutils.gui;

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

import ljfa.tntutils.Config;
import ljfa.tntutils.Reference;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.common.config.ConfigCategory;
import net.minecraftforge.common.config.ConfigElement;
import cpw.mods.fml.client.config.DummyConfigElement;
import cpw.mods.fml.client.config.GuiConfig;
import cpw.mods.fml.client.config.IConfigElement;

public class TntuConfigGui extends GuiConfig {
    public TntuConfigGui(GuiScreen parent) {
        super(parent, getConfigElements(), Reference.MODID, false, false, "TNTUtils configuration");
    }

    /** Compiles a list of config elements */
    private static List<IConfigElement> getConfigElements() {
        List<IConfigElement> list = new ArrayList<IConfigElement>();

        //Add categories to config GUI
        list.add(new ConfigElement<ConfigCategory>(Config.conf.getCategory(Config.CATEGORY_GENERAL)));
        return list;
    }
}

package ljfa.tntutils.gui;

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

import ljfa.tntutils.Config;
import ljfa.tntutils.Reference;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.common.config.ConfigCategory;
import net.minecraftforge.common.config.ConfigElement;
import cpw.mods.fml.client.config.DummyConfigElement;
import cpw.mods.fml.client.config.GuiConfig;
import cpw.mods.fml.client.config.IConfigElement;

public class TntuConfigGui extends GuiConfig {
    public TntuConfigGui(GuiScreen parent) {
        super(parent, getConfigElements(), Reference.MODID, false, false, "TNTUtils configuration");
    }

    /** Compiles a list of config elements
     * Borrowed from EnderIO's implementation
     */
    private static List<IConfigElement> getConfigElements() {
        List<IConfigElement> list = new ArrayList<IConfigElement>();

        for(String name: Config.conf.getCategoryNames())
            list.add(new ConfigElement<ConfigCategory>(Config.conf.getCategory(name)));

        return list;
    }
}

Make Config GUIs easier to work with

Make Config GUIs easier to work with


package org.jboss.loom.utils.el;

import java.lang.reflect.Field;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 *  @author Ondrej Zizka, ozizka at redhat.com
 */
public class ELUtils {
    private static final Logger log = LoggerFactory.getLogger( ELUtils.class );

    public static void evaluateObjectMembersEL( Object obj, JuelCustomResolverEvaluator eval, EL.ResolvingStage stage ) {

        Class curClass = obj.getClass();
        while( curClass != null  &&  ! Object.class.equals( curClass ) ){
            for( Field fld : curClass.getDeclaredFields() ){
                //if( ! fld.getType().equals( String.class ))
                if( ! String.class.isAssignableFrom(  fld.getType() ) )
                    continue;
                final EL ann = fld.getAnnotation( EL.class );
                if( null == ann )
                    continue;
                if( stage != null  &&  ann.stage() != stage )
                    continue;

                try {
                    fld.setAccessible( true );
                    String orig = (String) fld.get( obj );
                    String res = eval.evaluateEL( orig );
                    fld.set( obj, res );
                } catch( IllegalArgumentException | IllegalAccessException ex ) {
                    throw new IllegalStateException("Failed resolving EL in " + obj + ": " + ex.getMessage(), ex);
                }
            }
            curClass = curClass.getSuperclass();
        }
    }

}// class

package org.jboss.loom.utils.el;

import java.lang.reflect.Field;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 *  @author Ondrej Zizka, ozizka at redhat.com
 */
public class ELUtils {
    private static final Logger log = LoggerFactory.getLogger( ELUtils.class );

    public static void evaluateObjectMembersEL( Object obj, JuelCustomResolverEvaluator eval, EL.ResolvingStage stage ) {

        Class curClass = obj.getClass();
        while( curClass != null  &&  ! Object.class.equals( curClass ) ){
            for( Field fld : curClass.getDeclaredFields() ){
                //if( ! fld.getType().equals( String.class ))
                if( ! String.class.isAssignableFrom(  fld.getType() ) )
                    continue;
                final EL ann = fld.getAnnotation( EL.class );
                if( null == ann )
                    continue;
                if( stage != null  &&  ann.stage() != stage )
                    continue;

                try {
                    fld.setAccessible( true );
                    String orig = (String) fld.get( obj );
                    if( orig == null || orig.trim().isEmpty() )
                        continue;
                    String res = eval.evaluateEL( orig );
                    fld.set( obj, res );
                } catch( IllegalArgumentException | IllegalAccessException ex ) {
                    throw new IllegalStateException("Failed resolving EL in " + obj + "." + fld.getName() + ": " + ex.getMessage(), ex);
                }
            }
            curClass = curClass.getSuperclass();
        }
    }

}// class

Fix NPE if property with @EL is null.

Fix NPE if property with @EL is null.


package org.talend.dataprep.exception;

import java.io.StringWriter;

import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class TDPExceptionController {

    private static HttpEntity<String> buildHttpEntity(TDPException e) {
        StringWriter writer = new StringWriter();
        e.writeTo(writer);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return new HttpEntity<>(writer.toString(), headers);
    }

    @ExceptionHandler(InternalException.class)
    public HttpEntity<String> handleInternalError(HttpServletResponse response, InternalException e) {
        HttpEntity<String> entity = buildHttpEntity(e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return entity;
    }

    @ExceptionHandler(UserException.class)
    public HttpEntity<String> handleUserError(HttpServletResponse response, UserException e) {
        HttpEntity<String> entity = buildHttpEntity(e);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return entity;
    }

}

package org.talend.dataprep.exception;

import java.io.StringWriter;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class TDPExceptionController {

    public static final Logger LOGGER = LoggerFactory.getLogger(TDPExceptionController.class);

    @ExceptionHandler(InternalException.class)
    public @ResponseBody String handleInternalError(HttpServletResponse response, InternalException e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        final StringWriter message = new StringWriter();
        e.writeTo(message);
        return message.toString();
    }

    @ExceptionHandler(UserException.class)
    public @ResponseBody String handleUserError(HttpServletResponse response, UserException e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        final StringWriter message = new StringWriter();
        e.writeTo(message);
        return message.toString();
    }

}

Use @ResponseBody to write exception message.


package fault.metrics;

import fault.Status;

/**
 * Created by timbrooks on 11/20/14.
 */
public interface ActionMetrics {
    int getFailuresForTimePeriod(int milliseconds);

    void reportActionResult(Status status);

    int getSuccessesForTimePeriod(int milliseconds);

    int getErrorsForTimePeriod(int milliseconds);

    int getTimeoutsForTimePeriod(int milliseconds);
}

package fault.metrics;

import fault.Status;

/**
 * Created by timbrooks on 11/20/14.
 */
public interface ActionMetrics {
    public void reportActionResult(Status status);

    public int getFailuresForTimePeriod(int milliseconds);

    public int getSuccessesForTimePeriod(int milliseconds);

    public int getErrorsForTimePeriod(int milliseconds);

    public int getTimeoutsForTimePeriod(int milliseconds);
}

Modify interface to have public methods

Modify interface to have public methods


package net.wequick.example.small.app.main;

import android.app.Application;
import android.util.Log;

/**
 * Created by Administrator on 2016/2/17.
 */
public class AppContext extends Application {

    public AppContext(){
        Log.d("main application","AppContext()");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println(this.getSharedPreferences("small.app-versions", 0).getAll());
        Log.d("main application","onCreate()");
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }
}

package net.wequick.example.small.app.main;

import android.app.Application;
import android.util.Log;

/**
 * Created by Administrator on 2016/2/17.
 */
public class AppContext extends Application {

    private static final String TAG = "Main Plugin";

    public AppContext() {
        Log.d(TAG, "AppContext()");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate()");

        // Test shared data
        Log.d(TAG, this.getSharedPreferences("small.app-versions", 0).getAll().toString());

        // Test resources
        String s = this.getString(R.string.action_settings);
        Log.d(TAG, s);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }
}

Add sample for using resources in plugin application


package com.michaldabski.utils;

import java.io.File;

import android.graphics.Bitmap;
import android.util.LruCache;

public class FilePreviewCache extends LruCache<File, Bitmap>
{
	public static final int DEFAULT_CACHE_SZE = 4*1024*1024;
	/**
	 * create new cache
	 * @param maxSize max size in bytes
	 */
	public FilePreviewCache(int maxSize) {
		super(maxSize);
		// TODO Auto-generated constructor stub
	}

	public FilePreviewCache()
	{
		this(DEFAULT_CACHE_SZE);
	}

	@Override
	protected int sizeOf(File key, Bitmap value)
	{
		return value.getByteCount();
	}

}

package com.michaldabski.utils;

import java.io.File;

import android.graphics.Bitmap;
import android.util.LruCache;

public class FilePreviewCache extends LruCache<File, Bitmap>
{
	public static final int DEFAULT_CACHE_SZE = 24*1024*1024;
	/**
	 * create new cache
	 * @param maxSize max size in bytes
	 */
	public FilePreviewCache(int maxSize) {
		super(maxSize);
		// TODO Auto-generated constructor stub
	}

	public FilePreviewCache()
	{
		this(DEFAULT_CACHE_SZE);
	}

	@Override
	protected int sizeOf(File key, Bitmap value)
	{
		return value.getByteCount();
	}

}

Increment allowed cache size to 24mb

Increment allowed cache size to 24mb


package org.twig.loader;

import org.twig.exception.LoaderException;

import java.util.HashMap;

/**
 * Used for unit tests only
 */
public class HashMapLoader implements Loader {
    HashMap<String, String> hashMap;

    /**
     * Default constructor
     */
    public HashMapLoader() {
        hashMap = new HashMap<>();
    }

    /**
     * Construct the loader with an existing hash map
     * @param hashMap The hashMap with templates
     */
    public HashMapLoader(HashMap<String, String> hashMap) {
        this.hashMap = hashMap;
    }

    @Override
    public String getSource(String name) throws LoaderException {
        if (hashMap.containsKey(name)) {
            return hashMap.get(name);
        }

        throw LoaderException.notDefined(name);
    }

    @Override
    public String getCacheKey(String name) throws LoaderException {
        if (!this.hashMap.containsKey(name)) {
            throw LoaderException.notDefined(name);
        }

        return this.hashMap.get(name);
    }

    /**
     * Get the hash map
     * @return The hashMap with templates
     */
    public HashMap<String, String> getHashMap() {
        return hashMap;
    }

    /**
     * Set the hashmap
     * @param hashMap The hashMap with templates
     */
    public void setHashMap(HashMap<String, String> hashMap) {
        this.hashMap = hashMap;
    }
}

package org.twig.loader;

import org.twig.exception.LoaderException;

import java.util.HashMap;
import java.util.Map;

/**
 * Used for unit tests only
 */
public class HashMapLoader implements Loader {
    Map<String, String> hashMap;

    /**
     * Default constructor
     */
    public HashMapLoader() {
        hashMap = new HashMap<>();
    }

    /**
     * Construct the loader with an existing hash map
     * @param hashMap The hashMap with templates
     */
    public HashMapLoader(Map<String, String> hashMap) {
        this.hashMap = hashMap;
    }

    @Override
    public String getSource(String name) throws LoaderException {
        if (hashMap.containsKey(name)) {
            return hashMap.get(name);
        }

        throw LoaderException.notDefined(name);
    }

    @Override
    public String getCacheKey(String name) throws LoaderException {
        if (!this.hashMap.containsKey(name)) {
            throw LoaderException.notDefined(name);
        }

        return this.hashMap.get(name);
    }

    /**
     * Get the hash map
     * @return The hashMap with templates
     */
    public Map<String, String> getHashMap() {
        return hashMap;
    }

    /**
     * Set the hashmap
     * @param hashMap The hashMap with templates
     */
    public void setHashMap(Map<String, String> hashMap) {
        this.hashMap = hashMap;
    }
}

Make hashmaploader use Map instead of hashmap


package seedu.ezdo.model.todo;

import seedu.ezdo.commons.exceptions.IllegalValueException;

/**
 * Represents the due date of a todo.
 */
public class DueDate {

    public static final String MESSAGE_DUEDATE_CONSTRAINTS =
            "Due dates should be in the format DD/MM/YYYY, and it should not be blank";

    public static final String DUEDATE_VALIDATION_REGEX = ".+";

    public final String value;

    /**
     * Validates given due date.
     *
     * @throws IllegalValueException if given due date string is invalid.
     */
    public DueDate(String dueDate) throws IllegalValueException {
        assert dueDate != null;
        if (!isValidDueDate(dueDate)) {
            throw new IllegalValueException(MESSAGE_DUEDATE_CONSTRAINTS);
        }
        this.value = dueDate;
    }

    /**
     * Returns true if a given string is a valid due date.
     */
    public static boolean isValidDueDate(String test) {
        return test.matches(DUEDATE_VALIDATION_REGEX);
    }

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

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

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

}

package seedu.ezdo.model.todo;

import seedu.ezdo.commons.exceptions.IllegalValueException;

/**
 * Represents the due date of a todo.
 */
public class DueDate {

    public static final String MESSAGE_DUEDATE_CONSTRAINTS =
            "Due dates should be in the format DD/MM/YYYY, and it should not be blank";

    public static final String DUEDATE_VALIDATION_REGEX = "([12][0-9]|3[01]|0?[1-9])/(0?[1-9]|1[012])/((?:19|20)\\d\\d)";

    public final String value;

    /**
     * Validates given due date.
     *
     * @throws IllegalValueException if given due date string is invalid.
     */
    public DueDate(String dueDate) throws IllegalValueException {
        assert dueDate != null;
        if (!isValidDueDate(dueDate)) {
            throw new IllegalValueException(MESSAGE_DUEDATE_CONSTRAINTS);
        }
        this.value = dueDate;
    }

    /**
     * Returns true if a given string is a valid due date.
     */
    public static boolean isValidDueDate(String test) {
        return test.matches(DUEDATE_VALIDATION_REGEX);
    }

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

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

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

}

Update regex to fit DD/MM/YYYY format

Update regex to fit DD/MM/YYYY format


package org.apache.maven.continuum.web.action;

import org.codehaus.plexus.xwork.action.PlexusActionSupport;
import org.apache.maven.continuum.Continuum;
import org.apache.maven.continuum.initialization.ContinuumInitializationException;
import com.opensymphony.xwork.Preparable;
/*
 * Copyright 2005 The Codehaus.
 *
 * 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.
 */

/**
 * ContinuumActionSupport:
 *
 * @author: Jesse McConnell <jesse@codehaus.org>
 * @version: $ID:$
 */
public class ContinuumActionSupport
    extends PlexusActionSupport
    implements Preparable
{

    /**
     * @plexus.requirement
     */
    protected Continuum continuum;

    public void prepare()
        throws Exception
    {
        getLogger().info("checking the continuum configuration");

        if ( !continuum.getConfiguration().isInitialized() )
        {
            throw new ContinuumInitializationException( "continuum not initialized" );
        }

    }

    public Continuum getContinuum()
    {
        return continuum;
    }

    public void setContinuum( Continuum continuum )
    {
        this.continuum = continuum;
    }
}

package org.apache.maven.continuum.web.action;

/*
 * Copyright 2005-2006 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.
 *
 */

import org.apache.maven.continuum.Continuum;
import org.codehaus.plexus.xwork.action.PlexusActionSupport;

import com.opensymphony.xwork.Preparable;

/**
 * ContinuumActionSupport
 *
 * @author Jesse McConnell <jesse@codehaus.org>
 * @version $Id$
 */
public abstract class ContinuumActionSupport
    extends PlexusActionSupport
    implements Preparable
{

    /**
     * @plexus.requirement
     */
    protected Continuum continuum;

    public void prepare()
        throws Exception
    {
    }

    public Continuum getContinuum()
    {
        return continuum;
    }

    public void setContinuum( Continuum continuum )
    {
        this.continuum = continuum;
    }
}

Remove continuum initialization from action, need another way to do it

git-svn-id: 1d22bf2b43db35b985fe5d7437c243537c14eeaa@432420 13f79535-47bb-0310-9956-ffa450edef68


package com.glasstunes;

import android.database.Cursor;
import android.net.Uri;

import com.glasstunes.cards.ActionCard;
import com.glasstunes.screenslide.CardFragment;

public class DetailActivity extends BaseContentCardActivity {

	@Override
	protected Uri getContentUri() {
		return Uri.withAppendedPath(getIntent().getData(), "/sections");
	}

	@Override
	protected CardFragment getCardFromCursor(Cursor cursor) {
		return ActionCard.newInstance(
				cursor.getString(cursor.getColumnIndex("display_name")),
				cursor.getString(cursor.getColumnIndex("intent_uri")));
	}

}

package com.glasstunes;

import android.database.Cursor;
import android.net.Uri;

import com.glasstunes.cards.ActionCard;
import com.glasstunes.screenslide.CardFragment;

public class DetailActivity extends BaseContentCardActivity {

	@Override
	protected Uri getContentUri() {
		return Uri.withAppendedPath(getIntent().getData(), "/actions");
	}

	@Override
	protected CardFragment getCardFromCursor(Cursor cursor) {
		return ActionCard.newInstance(
				cursor.getString(cursor.getColumnIndex("display_name")),
				cursor.getString(cursor.getColumnIndex("intent_uri")));
	}

}

Fix wrong path in detail activity

Fix wrong path in detail activity


package com.amee.service.item;

import com.amee.domain.IDataCategoryReference;
import com.amee.domain.data.DataCategory;
import com.amee.domain.item.BaseItemValue;
import com.amee.domain.item.data.DataItem;
import com.amee.domain.item.data.DataItemNumberValue;
import com.amee.domain.item.data.DataItemTextValue;

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

public interface DataItemServiceDAO extends ItemServiceDAO {

    public long getDataItemCount(IDataCategoryReference dataCategory);

    public List<DataItem> getDataItems(IDataCategoryReference dataCategory);

    public List<DataItem> getDataItems(Set<Long> dataItemIds);

    public DataItem getItemByUid(String uid);

    public Set<BaseItemValue> getDataItemValues(DataItem dataItem);

    public List<DataItemNumberValue> getDataItemNumberValues(DataItem dataItem);

    public List<DataItemTextValue> getDataItemTextValues(DataItem dataItem);

    public void persist(DataItem dataItem);

    public DataItem getDataItemByPath(IDataCategoryReference parent, String path);

    public Date getDataItemsModified(DataCategory dataCategory);

    public boolean isDataItemUniqueByPath(DataItem dataItem);
}

package com.amee.service.item;

import com.amee.domain.IDataCategoryReference;
import com.amee.domain.data.DataCategory;
import com.amee.domain.item.BaseItemValue;
import com.amee.domain.item.data.DataItem;
import com.amee.domain.item.data.DataItemNumberValue;
import com.amee.domain.item.data.DataItemTextValue;

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

public interface DataItemServiceDAO extends ItemServiceDAO {

    long getDataItemCount(IDataCategoryReference dataCategory);

    List<DataItem> getDataItems(IDataCategoryReference dataCategory);

    List<DataItem> getDataItems(Set<Long> dataItemIds);

    @Override
    DataItem getItemByUid(String uid);

    Set<BaseItemValue> getDataItemValues(DataItem dataItem);

    List<DataItemNumberValue> getDataItemNumberValues(DataItem dataItem);

    List<DataItemTextValue> getDataItemTextValues(DataItem dataItem);

    void persist(DataItem dataItem);

    DataItem getDataItemByPath(IDataCategoryReference parent, String path);

    Date getDataItemsModified(DataCategory dataCategory);

    boolean isDataItemUniqueByPath(DataItem dataItem);
}

Remove redundant access modifiers in interface.


package org.orekit.data;

/**
 * Holds a mutable static field since {@link DataContext} cannot.
 *
 * @author Evan Ward
 * @since 10.1
 */
class DefaultDataContextHolder {

    /** The default Orekit data context. */
    static LazyLoadedDataContext INSTANCE = new LazyLoadedDataContext();

    /** Private Constructor. */
    private DefaultDataContextHolder() {
    }

}

package org.orekit.data;

/**
 * Holds a mutable static field since {@link DataContext} cannot.
 *
 * @author Evan Ward
 * @since 10.1
 */
class DefaultDataContextHolder {

    /** The default Orekit data context. */
    static volatile LazyLoadedDataContext INSTANCE = new LazyLoadedDataContext();

    /** Private Constructor. */
    private DefaultDataContextHolder() {
    }

}

Make default data context volatile

Make default data context volatile

So that updates in one thread are seen by others.

Part of #607


package roycurtis.signshopexport.json;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;

/** Exclusions class for blacklisting objects and fields in Gson */
public class Exclusions implements ExclusionStrategy
{
    @Override
    public boolean shouldSkipField(FieldAttributes f)
    {
        String name = f.getName();

        return
            // Ignore dynamic CraftBukkit handle field
            name.equalsIgnoreCase("handle")
            // Ignore book page contents
            || name.equalsIgnoreCase("pages")
            // Ignore unsupported tags
            || name.equalsIgnoreCase("unhandledTags")
            // Ignore redundant data object
            || name.equalsIgnoreCase("data")
            // Ignore hide flags
            || name.equalsIgnoreCase("hideFlag")
            // Ignore skull profiles
            || name.equalsIgnoreCase("profile")
            // Ignore shield patterns
            || name.equalsIgnoreCase("blockEntityTag");
    }

    @Override
    public boolean shouldSkipClass(Class<?> clazz)
    {
        String name = clazz.getSimpleName();

        if ( name.equalsIgnoreCase("ItemStack") )
        if ( clazz.getTypeName().startsWith("net.minecraft.server") )
            return true;

        return name.equalsIgnoreCase("ChatComponentText");
    }
}

package roycurtis.signshopexport.json;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;

/** Exclusions class for blacklisting objects and fields in Gson */
public class Exclusions implements ExclusionStrategy
{
    @Override
    public boolean shouldSkipField(FieldAttributes f)
    {
        String name = f.getName();

        return
            // Ignore dynamic CraftBukkit handle field
            name.equalsIgnoreCase("handle")
            // Ignore book page contents
            || name.equalsIgnoreCase("pages")
            // Ignore unsupported tags
            || name.equalsIgnoreCase("unhandledTags")
            // Ignore redundant data object
            || name.equalsIgnoreCase("data")
            // Ignore hide flags
            || name.equalsIgnoreCase("hideFlag")
            // Ignore repair costs
            || name.equalsIgnoreCase("repairCost")
            // Ignore skull profiles
            || name.equalsIgnoreCase("profile")
            // Ignore shield patterns
            || name.equalsIgnoreCase("blockEntityTag");
    }

    @Override
    public boolean shouldSkipClass(Class<?> clazz)
    {
        String name = clazz.getSimpleName();

        if ( name.equalsIgnoreCase("ItemStack") )
        if ( clazz.getTypeName().startsWith("net.minecraft.server") )
            return true;

        return name.equalsIgnoreCase("ChatComponentText");
    }
}

Exclude noisy "repairCost" meta field

Exclude noisy "repairCost" meta field


/**
 * Created by Nathan_Zeplowitz on 4/14/15.
 */
interface Monster {
    public abstract void takeDamage(int amount);
    public abstract String name();
    public abstract int currentHitpoints();
}

/**
 * Created by Nathan_Zeplowitz on 4/14/15.
 */
interface Monster {
    void takeDamage(int amount);
    String name();
    int currentHitpoints();
}

Refactor Out Unnecessary Public Abstract Keywords


package de.otto.edison.togglz.configuration;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.togglz.console.TogglzConsoleServlet;

@Configuration
public class TogglzWebConfiguration {

    @Bean
    public ServletRegistrationBean togglzServlet(@Value("${management.context-path:/internal}") String prefix) {
        return new ServletRegistrationBean(new TogglzConsoleServlet(), prefix + "/togglz/*");
    }
}

package de.otto.edison.togglz.configuration;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.togglz.console.TogglzConsoleServlet;
import org.togglz.servlet.TogglzFilter;

@Configuration
public class TogglzWebConfiguration {

    @Bean
    public FilterRegistrationBean togglzFilter() {
        FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
        filterRegistration.setFilter(new TogglzFilter());
        filterRegistration.addUrlPatterns("/*");
        return filterRegistration;
    }

    @Bean
    public ServletRegistrationBean togglzServlet(@Value("${management.context-path:/internal}") String prefix) {
        return new ServletRegistrationBean(new TogglzConsoleServlet(), prefix + "/togglz/*");
    }
}

Revert "Make Togglz compatible to not embedded Tomcat"

This reverts commit fb8050f0dc814c82eb422d3bbfbb9ed606b4f75e.


package dk.kleistsvendsen;

import com.google.inject.Inject;

public class GameTimer implements IGameTimer {
    @Inject
    private ITicSource ticSource_;
    private long startTic_;

    public GameTimer() {
        startTic_ = ticSource_.tic();
    }

    @Override
    public long timeLeft() {
        return ticSource_.tic() -startTic_;
    }

    @Override
    public void pauseTimer() {

    }

    @Override
    public void startTimer() {
        ticSource_.tic();
    }

    @Override
    public void resetTimer() {

    }
}

package dk.kleistsvendsen;

import com.google.inject.Inject;

public class GameTimer implements IGameTimer {
    private ITicSource ticSource_;
    private long startTic_;

    @Inject
    public GameTimer(ITicSource ticSource) {
        ticSource_ = ticSource;
    }

    @Override
    public long timeLeft() {
        return ticSource_.tic() -startTic_;
    }

    @Override
    public void pauseTimer() {

    }

    @Override
    public void startTimer() {
        ticSource_.tic();
    }

    @Override
    public void resetTimer() {

    }
}

Use constructor injection instead of member injection


package org.osgi.test.cases.repository.junit;

import org.osgi.framework.Bundle;
import org.osgi.test.support.compatibility.DefaultTestBundleControl;

public class RepositoryTest extends DefaultTestBundleControl {
    public void testFoo() {
        for (Bundle b : getContext().getBundles()) {
            System.out.println("**** " + b.getSymbolicName());
        }
    }

    public void testBar() {
    }
}

package org.osgi.test.cases.repository.junit;

import java.util.Arrays;

import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.test.support.OSGiTestCase;

public class RepositoryTest extends OSGiTestCase {
    public void testFooXX() throws Exception {
        for (Bundle b : getContext().getBundles()) {
            System.err.println("@@@@ " + b.getSymbolicName());
        }

        for (ServiceReference<?> sr : getContext().getAllServiceReferences(null, null)) {
            System.err.println("**** " + Arrays.toString((String []) sr.getProperty(Constants.OBJECTCLASS)));
        }
    }

    public void testBar() {
    }
}

Test to output some basic info - bundles deploy ok.


package beaform.utilities;

public class SystemTime {

	private static final TimeSource defaultSrc = new TimeSource(){
		@Override
		public long getSystemTime() {
			return System.currentTimeMillis();
		}

	};

	private static TimeSource source;

	public static void reset() {
		source = null;
	}

	public static long getAsLong() {
		return getCurrentTimeSource().getSystemTime();
	}

	private static TimeSource getCurrentTimeSource() {
		return (source == null) ? defaultSrc : source;
	}

	public static void setTimeSource(TimeSource timeSource) {
		source = timeSource;
	}
}

package beaform.utilities;

public class SystemTime {

	private static final TimeSource defaultSrc = new TimeSource(){
		@Override
		public long getSystemTime() {
			return System.currentTimeMillis();
		}

	};

	private static volatile TimeSource source;

	public static void reset() {
		source = null;
	}

	public static long getAsLong() {
		return getCurrentTimeSource().getSystemTime();
	}

	private static TimeSource getCurrentTimeSource() {
		return (source == null) ? defaultSrc : source;
	}

	public static void setTimeSource(TimeSource timeSource) {
		source = timeSource;
	}
}

Make the non-default time source volatile to avoid some threading issues


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.opensim.view;

import java.io.File;
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;

/**
 *
 * @author Jingjing
 */
public class TestEnvironment {

    private static String modelPath = null;

    public static void initializePath() {
        ProtectionDomain pd = FileOpenOsimModelAction.class.getProtectionDomain();
        CodeSource cs = pd.getCodeSource();
        URL url = cs.getLocation();
        File f = new File(url.getFile());
        File targetFile = f.getParentFile().getParentFile().getParentFile().getParentFile().getParentFile().getParentFile();
        String ap = targetFile.getAbsolutePath() + "\\Models\\Arm26\\arm26.osim";
        modelPath = ap;

    }

    public static String getModelPath() {
        if (modelPath == null) {
            initializePath();
        }
        return modelPath;
    }
}

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.opensim.view;

import java.io.File;
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;

/**
 *
 * @author Jingjing
 */
public class TestEnvironment {

    private static String modelPath = null;

    public static void initializePath() {
        ProtectionDomain pd = FileOpenOsimModelAction.class.getProtectionDomain();
        CodeSource cs = pd.getCodeSource();
        URL url = cs.getLocation();
        File f = new File(url.getFile());
        File targetFile = f.getParentFile().getParentFile().getParentFile().getParentFile().getParentFile().getParentFile();
        String ap = targetFile.getAbsolutePath() + "\\opensim-models\\Models\\Arm26\\arm26.osim";
        modelPath = ap;

    }

    public static String getModelPath() {
        if (modelPath == null) {
            initializePath();
        }
        return modelPath;
    }
}

Use new path name to Models for test case


/*
 * Copyright 2016 Peter Kenji Yamanaka
 *
 * 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.pyamsoft.pydroid.tool;

import android.support.annotation.Nullable;
import timber.log.Timber;

public final class OffloaderHelper {

  private OffloaderHelper() {
    throw new RuntimeException("No instances");
  }

  public static void cancel(@Nullable ExecutedOffloader offloader) {
    if (offloader == null) {
      Timber.w("Offloader is NULL");
      return;
    }

    if (!offloader.isCancelled()) {
      offloader.cancel();
    }
  }
}

/*
 * Copyright 2016 Peter Kenji Yamanaka
 *
 * 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.pyamsoft.pydroid.tool;

import android.support.annotation.Nullable;
import timber.log.Timber;

public final class OffloaderHelper {

  private OffloaderHelper() {
    throw new RuntimeException("No instances");
  }

  public static void cancel(@Nullable ExecutedOffloader offloader) {
    if (offloader == null) {
      Timber.w("Offloader is NULL");
      return;
    }

    if (!offloader.isCancelled()) {
      offloader.cancel();
    }
  }

  public static void cancel(@Nullable ExecutedOffloader... offloaders) {
    if (offloaders == null) {
      Timber.w("Offloaders are NULL");
      return;
    }

    for (final ExecutedOffloader offloader : offloaders) {
      cancel(offloader);
    }
  }
}

Add offloader helper method for multiple


/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

package com.skelril.skree.service;

import com.skelril.nitro.Clause;

import java.util.Collection;

public interface ModifierService {
    void setExpiry(String modifier, long time);
    long expiryOf(String modifier);
    default long statusOf(String modifier) {
        return Math.max(expiryOf(modifier) - System.currentTimeMillis(), 0);
    }
    default boolean isActive(String modifier) {
        return statusOf(modifier) != 0;
    }

    Collection<Clause<String, Long>> getActiveModifiers();
}

/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

package com.skelril.skree.service;

import java.util.Map;

public interface ModifierService {
    void setExpiry(String modifier, long time);
    long expiryOf(String modifier);
    default long statusOf(String modifier) {
        return Math.max(expiryOf(modifier) - System.currentTimeMillis(), 0);
    }
    default boolean isActive(String modifier) {
        return statusOf(modifier) != 0;
    }

    Map<String, Long> getActiveModifiers();
}

Use a map for the collection of active modifiers


package heroku.template.service;

import heroku.template.model.Person;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class PersonServiceImpl implements PersonService {

    @PersistenceContext
    EntityManager em;

    @Transactional
    public void addPerson(Person person) {
    	em.persist(person);
    }

    @Transactional
    public List<Person> listPeople() {
    	CriteriaQuery<Person> c = em.getCriteriaBuilder().createQuery(Person.class);
        Root<Person> p = c.from(Person.class);
        return em.createQuery(c).getResultList();
    }

    @Transactional
    public void removePerson(Integer id) {
		Person person = (Person) em.find(Person.class, id);
		if (null != person) {
			em.remove(person);
		}
    }

}

package heroku.template.service;

import heroku.template.model.Person;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;
import java.util.List;

@Service
public class PersonServiceImpl implements PersonService {

    @PersistenceContext
    EntityManager em;

    @Transactional
    public void addPerson(Person person) {
    	em.persist(person);
    }

    @Transactional
    public List<Person> listPeople() {
    	CriteriaQuery<Person> c = em.getCriteriaBuilder().createQuery(Person.class);
        c.from(Person.class);
        return em.createQuery(c).getResultList();
    }

    @Transactional
    public void removePerson(Integer id) {
		Person person = em.find(Person.class, id);
		if (null != person) {
			em.remove(person);
		}
    }

}

Remove unnecessary assignment and cast

Remove unnecessary assignment and cast


package j8spec;

import static j8spec.J8Spec.var;
import static java.util.Objects.isNull;

class VarInitializer<T> implements UnsafeBlock {

    private final Var<T> variable;
    private final UnsafeFunction<T> function;
    private T value;

    VarInitializer(Var<T> variable, UnsafeFunction<T> function) {
        this.variable = variable;
        this.function = function;
    }

    @Override
    public void tryToExecute() throws Throwable {
        if (isNull(value)) {
            value = function.tryToGet();
        }
        var(variable, value);
    }
}

package j8spec;

import static j8spec.J8Spec.*;

class VarInitializer<T> implements UnsafeBlock {

    private final Var<T> variable;
    private final UnsafeFunction<T> function;
    private T value;

    VarInitializer(Var<T> variable, UnsafeFunction<T> function) {
        this.variable = variable;
        this.function = function;
    }

    @Override
    public void tryToExecute() throws Throwable {
        if (value == null) {
            value = function.tryToGet();
        }
        var(variable, value);
    }
}

Replace isNull with literal null

Replace isNull with literal null


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

package com.google.zxing.client.result;

import com.google.zxing.Result;

/**
 * Parses a "tel:" URI result, which specifies a phone number.
 *
 * @author Sean Owen
 */
final class TelResultParser extends ResultParser {

  private TelResultParser() {
  }

  public static TelParsedResult parse(Result result) {
    String rawText = result.getText();
    if (rawText == null || (!rawText.startsWith("tel:") && !rawText.startsWith("TEL:"))) {
      return null;
    }
    String telURI = rawText;
    // Drop tel, query portion
    int queryStart = rawText.indexOf('?', 4);
    if (queryStart < 0) {
      rawText = rawText.substring(4);
    } else {
      rawText = rawText.substring(4, queryStart);
    }
    return new TelParsedResult(rawText, telURI, null);
  }

}

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

package com.google.zxing.client.result;

import com.google.zxing.Result;

/**
 * Parses a "tel:" URI result, which specifies a phone number.
 *
 * @author Sean Owen
 */
final class TelResultParser extends ResultParser {

  private TelResultParser() {
  }

  public static TelParsedResult parse(Result result) {
    String rawText = result.getText();
    if (rawText == null || (!rawText.startsWith("tel:") && !rawText.startsWith("TEL:"))) {
      return null;
    }
    // Normalize "TEL:" to "tel:"
    String telURI = rawText.startsWith("TEL:") ? "tel:" + rawText.substring(4) : rawText;
    // Drop tel, query portion
    int queryStart = rawText.indexOf('?', 4);
    String number = queryStart < 0 ? rawText.substring(4) : rawText.substring(4, queryStart);
    return new TelParsedResult(number, telURI, null);
  }

}

Normalize TEL: to tel: to make sure it works with Android