package fape.core.planning.search.strategies.plans;

import fape.core.planning.states.State;

import java.util.LinkedList;
import java.util.List;

/**
 * Used to use a sequence of PartialPlanComparator as one.
 *
 * The basic algorithm for comparing two partial plans is to apply the comparators in sequence until it results in an ordering
 * between the two plans. If no comparator is found, the plans are left unordered.
 */
public class SeqPlanComparator implements PartialPlanComparator {

    List<PartialPlanComparator> comparators;

    public SeqPlanComparator(List<PartialPlanComparator> comparators) {
        this.comparators = new LinkedList<>(comparators);
    }

    @Override
    public String shortName() {
        String ret = "";
        for(PartialPlanComparator comp : comparators) {
            ret += comp.shortName() + ",";
        }
        return ret.substring(0, ret.length()-1);
    }

    @Override
    public int compare(State state, State state2) {
        for(PartialPlanComparator comp : comparators) {
            int res = comp.compare(state, state2);
            if(res != 0) {
                return res;
            }
        }
        // no resolver could rank those flaws.
        return 0;
    }
}

package fape.core.planning.search.strategies.plans;

import fape.core.planning.states.State;

import java.util.LinkedList;
import java.util.List;

/**
 * Used to use a sequence of PartialPlanComparator as one.
 *
 * The basic algorithm for comparing two partial plans is to apply the comparators in sequence until it results in an ordering
 * between the two plans. If no comparator is found, the plans are left unordered.
 */
public class SeqPlanComparator implements PartialPlanComparator {

    List<PartialPlanComparator> comparators;

    public SeqPlanComparator(List<PartialPlanComparator> comparators) {
        this.comparators = new LinkedList<>(comparators);
    }

    @Override
    public String shortName() {
        String ret = "";
        for(PartialPlanComparator comp : comparators) {
            ret += comp.shortName() + ",";
        }
        return ret.substring(0, ret.length()-1);
    }

    @Override
    public int compare(State state, State state2) {
        for(PartialPlanComparator comp : comparators) {
            int res = comp.compare(state, state2);
            if(res != 0) {
                return res;
            }
        }

        // tie breaker: makespan
        int diffMakespan = state.getEarliestStartTime(state.pb.end()) - state2.getEarliestStartTime(state2.pb.end());
        if(diffMakespan != 0)
            return diffMakespan;

        // no ranking done, use mID to make deterministic
        return state.mID - state2.mID;
    }
}

Add tie breaker for plan comparators.

Add tie breaker for plan comparators.

First choose the one with shortest makespan.
If it still a tie, use the id of the state to make sure the output is deterministic.


package com.flipboard.bottomsheet.commons;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * An ImageView that keeps a 1:1 aspect ratio
 */
final class SquareImageView extends ImageView {
    public SquareImageView(Context context) {
        super(context);
    }

    public SquareImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SquareImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public SquareImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @SuppressWarnings("SuspiciousNameCombination")
    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec);
    }
}

package com.flipboard.bottomsheet.commons;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * An ImageView that keeps a 1:1 aspect ratio
 */
final class SquareImageView extends ImageView {
    public SquareImageView(Context context) {
        super(context);
    }

    public SquareImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SquareImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public SquareImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @SuppressWarnings("UnnecessaryLocalVariable")
    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int bothDimensionsSpec = widthMeasureSpec;
        super.onMeasure(bothDimensionsSpec, bothDimensionsSpec);
    }
}

Use more accurate name for clarity in measuring


package weatherhandler;

import java.util.Date;
import java.text.SimpleDateFormat;

public class Logger {
    final public static int ERROR = 0;
    final public static int WARN = 1;
    final public static int INFO = 2;
    final public static int DEBUG = 3;

    private static int level = Logger.DEBUG;
    private String name;

    public Logger(String name) {
        this.name = name;
    }

    private void log(String level, String[] text) {
        String time = new SimpleDateFormat("hh:mm:ss").format(new Date());
        System.out.println(
            "[" + level + " " + time + "] " +
            this.name + ": " + String.join(" ", text)
        );
    }

    public void debug(String... args) {
        if (Logger.level >= Logger.DEBUG) {
            this.log("DEBUG", args);
        }
    }

    public void info(String... args) {
        if (Logger.level >= Logger.INFO) {
            this.log("INFO", args);
        }
    }

    public void warn(String... args) {
        if (Logger.level >= Logger.WARN) {
            this.log("WARN", args);
        }
    }

    public void error(String... args) {
        this.log("ERROR", args);
    }
}

package weatherhandler;

import java.util.Date;
import java.text.SimpleDateFormat;

public class Logger {
    final public static int ERROR = 0;
    final public static int WARN = 1;
    final public static int INFO = 2;
    final public static int DEBUG = 3;

    private static int level = Logger.DEBUG;
    private String name;

    public Logger(String name) {
        this.name = name;
    }

    private void log(String level, String[] text) {
        String time = new SimpleDateFormat("hh:mm:ss").format(new Date());
        System.err.println(
            "[" + level + " " + time + "] " +
            this.name + ": " + String.join(" ", text)
        );
    }

    public void debug(String... args) {
        if (Logger.level >= Logger.DEBUG) {
            this.log("DEBUG", args);
        }
    }

    public void info(String... args) {
        if (Logger.level >= Logger.INFO) {
            this.log("INFO", args);
        }
    }

    public void warn(String... args) {
        if (Logger.level >= Logger.WARN) {
            this.log("WARN", args);
        }
    }

    public void error(String... args) {
        this.log("ERROR", args);
    }
}

Print logger output to stderr

:mailbox_with_mail: Print logger output to stderr


package com.github.neunkasulle.chronocommand.control;

import com.github.neunkasulle.chronocommand.model.Category;
import com.github.neunkasulle.chronocommand.model.CategoryDAO;
import com.github.neunkasulle.chronocommand.model.DAOHelper;
import org.hibernate.cfg.NotYetImplementedException;

/**
 * Created by Janze on 18.01.2016.
 * Controling startup and shutdown
 */
public class MainControl extends Control {

    private static MainControl ourInstance = new MainControl();

    private MainControl() {
        realm = new com.github.neunkasulle.chronocommand.security.Realm();
    }

    public static MainControl getInstance() {
        return ourInstance;
    }

    private void exceptionHandling() {
        throw new NotYetImplementedException();
    }

    public void startup() {
        DAOHelper.getInstance().startup();

        CategoryDAO.getInstance().saveCategory(new Category("Programming"));
        CategoryDAO.getInstance().saveCategory(new Category("Procrastination"));

        // TODO initiate anything that needs initiating
    }

    public void shutdown() {
        DAOHelper.getInstance().shutdown();

        // TODO initiate anything that needs initiating
    }
}

package com.github.neunkasulle.chronocommand.control;

import com.github.neunkasulle.chronocommand.model.Category;
import com.github.neunkasulle.chronocommand.model.CategoryDAO;
import com.github.neunkasulle.chronocommand.model.DAOHelper;
import com.github.neunkasulle.chronocommand.model.UserDAO;
import com.github.neunkasulle.chronocommand.model.User;
import org.hibernate.cfg.NotYetImplementedException;

/**
 * Created by Janze on 18.01.2016.
 * Controling startup and shutdown
 */
public class MainControl extends Control {

    private static MainControl ourInstance = new MainControl();

    private MainControl() {
        realm = new com.github.neunkasulle.chronocommand.security.Realm();
    }

    public static MainControl getInstance() {
        return ourInstance;
    }

    private void exceptionHandling() {
        throw new NotYetImplementedException();
    }

    public void startup() {
        DAOHelper.getInstance().startup();

        // TODO initiate anything that needs initiating

        // DEBUG fill database with data
        CategoryDAO.getInstance().saveCategory(new Category("Programming"));
        CategoryDAO.getInstance().saveCategory(new Category("Procrastination"));

        User tom = new User();
        tom.setEmail("tom@chronocommand.eu");
        tom.setPassword("cat");
        tom.setUsername("tom");
        UserDAO.getInstance().saveUser(tom);

        User matt = new User();
        matt.setEmail("matt@example.com");
        matt.setPassword("matt");
        matt.setUsername("matt");
        matt.setSupervisor(tom);
        UserDAO.getInstance().saveUser(matt);
    }

    public void shutdown() {
        DAOHelper.getInstance().shutdown();

        // TODO initiate anything that needs initiating
    }
}

Create users on startup for testing purposes


/*
Copyright 2011 Frederic Langlet
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 kanzi.entropy;

import kanzi.EntropyEncoder;
import kanzi.BitStream;
import kanzi.BitStreamException;

public abstract class AbstractEncoder implements EntropyEncoder
{
    @Override
    public abstract boolean encodeByte(byte val);

    @Override
    public abstract BitStream getBitStream();

    // Default implementation: fallback to encodeByte
    // Some implementations should be able to use an optimized algorithm
    @Override
    public int encode(byte[] array, int blkptr, int len)
    {
        if ((array == null) || (blkptr + len > array.length) || (blkptr < 0) || (len < 0))
           return -1;

        int end = blkptr + len;
        int i = blkptr;

        try
        {
           while (i < end)
           {
              if (this.encodeByte(array[i]) == false)
                 return i;

              i++;
           }
        }
        catch (BitStreamException e)
        {
           return i;
        }

        return len;
    }

    @Override
    public void dispose()
    {
    }

}

/*
Copyright 2011 Frederic Langlet
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 kanzi.entropy;

import kanzi.EntropyEncoder;
import kanzi.BitStream;
import kanzi.BitStreamException;

public abstract class AbstractEncoder implements EntropyEncoder
{
    @Override
    public abstract boolean encodeByte(byte val);

    @Override
    public abstract BitStream getBitStream();

    // Default implementation: fallback to encodeByte
    // Some implementations should be able to use an optimized algorithm
    @Override
    public int encode(byte[] array, int blkptr, int len)
    {
        if ((array == null) || (blkptr + len > array.length) || (blkptr < 0) || (len < 0))
           return -1;

        int end = blkptr + len;
        int i = blkptr;

        try
        {
           while (i < end)
           {
              if (this.encodeByte(array[i]) == false)
                 return i;

              i++;
           }
        }
        catch (BitStreamException e)
        {
           return i - blkptr;
        }

        return len;
    }

    @Override
    public void dispose()
    {
    }

}

Fix length calculation in the exception path


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

/**
 * Represents an HTTP method.
 *
 * @author David BRASSELY (brasseld at gmail.com)
 */
public enum HttpMethod {

  CONNECT, DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT, TRACE;
}

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

/**
 * Represents an HTTP method.
 *
 * @author David BRASSELY (david.brassely at graviteesource.com)
 * @author GraviteeSource Team
 */
public enum HttpMethod {

  CONNECT(1), DELETE(2), GET(3), HEAD(4), OPTIONS(5), PATCH(6), POST(7), PUT(8), TRACE(9);

  private int code;

  HttpMethod(int code) {
    this.code = code;
  }

  public int code() {
    return code;
  }

  public static HttpMethod get(int code) {
    for(HttpMethod method : HttpMethod.values()) {
      if (method.code == code) {
        return method;
      }
    }

    throw new IllegalArgumentException("Invalid HTTP method code");
  }
}

Add code to HTTP method

feat(http): Add code to HTTP method

Closes gravitee-io/issues#836


package info.u_team.u_team_core.util;

import static net.minecraft.client.renderer.model.ModelBakery.STATE_CONTAINER_OVERRIDES;

import java.util.*;

import com.google.common.collect.ImmutableMap;

import net.minecraft.block.*;
import net.minecraft.state.StateContainer;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.api.distmarker.*;

@OnlyIn(Dist.CLIENT)
public class ModelUtil {

	static {
		if (STATE_CONTAINER_OVERRIDES instanceof ImmutableMap) {
			final Map<ResourceLocation, StateContainer<Block, BlockState>> mutableMap = new HashMap<>();
			STATE_CONTAINER_OVERRIDES.forEach(mutableMap::put);
			STATE_CONTAINER_OVERRIDES = mutableMap;
		}
	}

	public static void addCustomStateContainer(ResourceLocation location, StateContainer<Block, BlockState> container) {
		STATE_CONTAINER_OVERRIDES.put(location, container);
	}

}

package info.u_team.u_team_core.util;

import static net.minecraft.client.renderer.model.ModelBakery.STATE_CONTAINER_OVERRIDES;

import java.util.*;

import com.google.common.collect.*;

import net.minecraft.block.*;
import net.minecraft.state.StateContainer;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.api.distmarker.*;

@OnlyIn(Dist.CLIENT)
public class ModelUtil {

	static {
		if (STATE_CONTAINER_OVERRIDES instanceof ImmutableMap) {
			final Map<ResourceLocation, StateContainer<Block, BlockState>> mutableMap = new HashMap<>();
			STATE_CONTAINER_OVERRIDES.forEach(mutableMap::put);
			STATE_CONTAINER_OVERRIDES = mutableMap;
		}
	}

	public static void addCustomStateContainer(ResourceLocation location, StateContainer<Block, BlockState> container) {
		STATE_CONTAINER_OVERRIDES.put(location, container);
	}

	public static class EmptyStateContainer extends StateContainer<Block, BlockState> {

		public EmptyStateContainer(Block block) {
			super(block, BlockState::new, new HashMap<>());
		}

		@Override
		public ImmutableList<BlockState> getValidStates() {
			return getOwner().getStateContainer().getValidStates();
		}

	}

}

Add empty state container class as utility


package info.u_team.u_team_test.container;

import info.u_team.u_team_core.container.UTileEntityContainer;
import info.u_team.u_team_test.init.TestContainers;
import info.u_team.u_team_test.tileentity.BasicFluidInventoryTileEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.network.PacketBuffer;

public class BasicFluidInventoryContainer extends UTileEntityContainer<BasicFluidInventoryTileEntity> {

	// Client
	public BasicFluidInventoryContainer(int id, PlayerInventory playerInventory, PacketBuffer buffer) {
		super(TestContainers.BASIC_FLUID_INVENTORY, id, playerInventory, buffer);
	}

	// Server
	public BasicFluidInventoryContainer(int id, PlayerInventory playerInventory, BasicFluidInventoryTileEntity tileEntity) {
		super(TestContainers.BASIC_FLUID_INVENTORY, id, playerInventory, tileEntity);
	}

	@Override
	protected void init(boolean server) {

	}

}

package info.u_team.u_team_test.container;

import info.u_team.u_team_core.container.UTileEntityContainer;
import info.u_team.u_team_test.init.TestContainers;
import info.u_team.u_team_test.tileentity.BasicFluidInventoryTileEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.network.PacketBuffer;

public class BasicFluidInventoryContainer extends UTileEntityContainer<BasicFluidInventoryTileEntity> {

	// Client
	public BasicFluidInventoryContainer(int id, PlayerInventory playerInventory, PacketBuffer buffer) {
		super(TestContainers.BASIC_FLUID_INVENTORY, id, playerInventory, buffer);
	}

	// Server
	public BasicFluidInventoryContainer(int id, PlayerInventory playerInventory, BasicFluidInventoryTileEntity tileEntity) {
		super(TestContainers.BASIC_FLUID_INVENTORY, id, playerInventory, tileEntity);
	}

	@Override
	protected void init(boolean server) {
		appendInventory(tileEntity.getItemSlots(), 2, 9, 8, 41);
		appendPlayerInventory(playerInventory, 8, 91);
	}

}

Add player inventory and basic fluid slots


/* $This file is distributed under the terms of the license in /doc/license.txt$ */

package edu.cornell.mannlib.vitro.webapp.controller;

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

import edu.cornell.mannlib.vitro.webapp.web.ContentType;

public class EntityControllerTest {

	@Test
	public void testAcceptHeader(){
		EntityController entityController = new EntityController();

		/* Check to see if vitro would send RDF/XML to tabulator */
		String tabulatorsAcceptHeader =
			"text/xml,application/xml,application/xhtml+xml,text/html;q=0.5,text/plain;q=0.5," +
			"image/png,*/*;q=0.1," +
			"application/rdf+xml;q=1.0,text/n3;q=0.4";
		ContentType result = entityController.checkForLinkedDataRequest("http://notUsedInThisTestCase.com/bogus",tabulatorsAcceptHeader);
		Assert.assertTrue( result != null );
		Assert.assertTrue( "application/rdf+xml".equals( result.toString()) );
	}
}

Add a "magic license comment"

Add a "magic license comment"


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

import junit.framework.TestCase;

public class TestRendererRegistry extends TestCase {

  private HtmlRenderer _default;

  private RendererRegistry _registry;

  public void setUp() {
    _default = new HtmlRenderer(null, null, null, null);
    _registry = new RendererRegistry(_default);
  }

  /**
   * Test that we can retrieve the default renderer.
   */
  public void testGetDefault() {
    assertNotNull(_registry.getDefaultRenderer());
    assertEquals(_default, _registry.getDefaultRenderer());
  }
}

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

import java.io.InputStream;

import net.hillsdon.reviki.wiki.MarkupRenderer;
import junit.framework.TestCase;

public class TestRendererRegistry extends TestCase {

  private HtmlRenderer _default;

  private RendererRegistry _registry;

  public void setUp() {
    _default = new HtmlRenderer(null, null, null, null);
    _registry = new RendererRegistry(_default);
  }

  /**
   * Test that we can retrieve the default renderer.
   */
  public void testGetDefault() {
    assertNotNull(_registry.getDefaultRenderer());
    assertEquals(_default, _registry.getDefaultRenderer());
  }

  /**
   * Test that we can insert and retrieve renderers.
   */
  public void testRetrieve() {
    MarkupRenderer<InputStream> renderer = new XSLFORenderer(null);
    String ctype = "xslfo";

    assertFalse(_registry.hasRenderer(ctype));
    _registry.addRenderer(ctype, renderer);
    assertTrue(_registry.hasRenderer(ctype));
    assertEquals(renderer, _registry.getRenderer(ctype));
  }

  /**
   * Test that null ctypes are correctly handled.
   */
  public void testNull() {
    assertFalse(_registry.hasRenderer(null));
    assertNull(_registry.getRenderer(null));
  }
}

Add extra tests for the renderer registry


import java.util.Hashtable;
import java.util.Random;

/**
 * A weight table is used to have keys that contain an ordered set of N strings corresponding to values that are string-
 * integer pairs.
 *
 * [a, b, c, d] -> [(foo, 12), (bar, 7)]
 * [b, c, d, foo] -> [(baz, 1)]
 * [b, c, d, bar] -> [(foobar, 1), (foobaz, 2)];
 * @author Alek Ratzloff
 *
 */
public class Weighttable extends Hashtable<String, Integer> {
	/**
	 * This is to kill the warnings
	 */
	private static final long serialVersionUID = 570882516693488244L;
	private Random random = new Random();

	public Weighttable() {
		super();
	}

	public String getRandomWord() {

		Object[] words = this.keySet().toArray();
		int range = 0;
		for(Object word : words) {
			int weight = this.get(word);
			range += weight;
		}

		int choice = random.nextInt(range);
		int sum = 0;
		for(Object word : words) {
			int weight = this.get(word);
			sum += weight;
			if(sum > choice)
				return (String)word;
		}

		return ".";
	}
}

import java.util.Hashtable;
import java.util.Random;

/**
 * A weight table is used to have keys that contain an ordered set of N strings corresponding to values that are string-
 * integer pairs.
 * @author Alek Ratzloff
 *
 */
public class Weighttable extends Hashtable<String, Integer> {
	/**
	 * This is to kill the warnings
	 */
	private static final long serialVersionUID = 570882516693488244L;
	private Random random = new Random();

	public Weighttable() {
		super();
	}

	public String getRandomWord() {

		Object[] words = this.keySet().toArray();
		int range = 0;
		for(Object word : words) {
			int weight = this.get(word);
			range += weight;
		}

		int choice = random.nextInt(range);
		int sum = 0;
		for(Object word : words) {
			int weight = this.get(word);
			sum += weight;
			if(sum > choice)
				return (String)word;
		}

		return ".";
	}
}

Update documentation in weighttable.java to remove the non-relevant stuff anymore


/**
 * This is the top-level package of the OpenXC library. It contains the
 * primary entry point for applications, the {@link com.openxc.VechicleManager}.
 */
package com.openxc;

/**
 * This is the top-level package of the OpenXC library. It contains the
 * primary entry point for applications, the {@link com.openxc.VehicleManager}.
 */
package com.openxc;

Fix typo in javadocs link.

Fix typo in javadocs link.


package org.pdxfinder.repositories;

import org.pdxfinder.dao.Patient;
import org.pdxfinder.dao.PatientSnapshot;
import org.springframework.data.neo4j.annotation.Query;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Set;

@Repository
public interface PatientSnapshotRepository extends Neo4jRepository<PatientSnapshot, Long> {

    Set<Patient> findByAge(String sex);

    Set<Patient> findByPatientSex(String sex);

    Patient findByPatientExternalId(String externalId);

    @Query("MATCH (ps:PatientSnapshot)--(p:Patient) WHERE p.externalId = {patientId} RETURN ps")
    Set<PatientSnapshot> findByPatient(@Param("patientId") String patientId);

    @Query("MATCH (mod:ModelCreation)-[ii:IMPLANTED_IN]-(s:Sample)-[sf:SAMPLED_FROM]-(ps:PatientSnapshot)-[pr:PATIENT]-(p:Patient)" +
            "WHERE mod.sourcePdxId = {modelId} " +
            "RETURN mod,ii,s,sf,ps, p, pr")
    PatientSnapshot findByModelId(@Param("modelId") String modelId);

}

package org.pdxfinder.repositories;

import org.pdxfinder.dao.Patient;
import org.pdxfinder.dao.PatientSnapshot;
import org.springframework.data.neo4j.annotation.Query;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Set;

@Repository
public interface PatientSnapshotRepository extends Neo4jRepository<PatientSnapshot, Long> {

    Set<Patient> findByAge(String sex);

    Set<Patient> findByPatientSex(String sex);

    Patient findByPatientExternalId(String externalId);

    @Query("MATCH (ps:PatientSnapshot)--(p:Patient) WHERE p.externalId = {patientId} RETURN ps")
    Set<PatientSnapshot> findByPatient(@Param("patientId") String patientId);

    @Query("MATCH (mod:ModelCreation)-[ii:IMPLANTED_IN]-(s:Sample)-[sf:SAMPLED_FROM]-(ps:PatientSnapshot)-[pr:PATIENT]-(p:Patient) \n" +
            "WHERE mod.sourcePdxId = {modelId}\n" +
            "WITH mod, ii, s, sf, ps, pr, p\n" +
            "OPTIONAL MATCH (s)-[ot:ORIGIN_TISSUE]-(t1:Tissue)\n" +
            "OPTIONAL MATCH (s)-[ss:SAMPLE_SITE]-(t2:Tissue)\n" +
            "\n" +
            "RETURN mod,ii,s,sf,ps, p, pr, t1, t2, ot, ss")
    PatientSnapshot findByModelId(@Param("modelId") String modelId);

}

Update query with additional nodes

Update query with additional nodes


package no.nordicsemi.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import org.droidparts.persist.sql.AbstractDBOpenHelper;

public class DBOpenHelper extends AbstractDBOpenHelper {

    private static final String DB_FILE = "Evere.sql";
    private static final int DB_VERSION = 1;

    public DBOpenHelper(Context ctx) {
        super(ctx, DB_FILE, DB_VERSION);
    }

    @Override
    protected void onCreateTables(SQLiteDatabase sqLiteDatabase) {
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        /* TODO: add migration */
        dropTables(db);
        onCreate(db);
    }
}

package no.nordicsemi.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import org.droidparts.persist.sql.AbstractDBOpenHelper;

import no.nordicsemi.models.LocationPuck;

public class DBOpenHelper extends AbstractDBOpenHelper {

    private static final String DB_FILE = "Evere.sql";
    private static final int DB_VERSION = 1;

    public DBOpenHelper(Context ctx) {
        super(ctx, DB_FILE, DB_VERSION);
    }

    @Override
    protected void onCreateTables(SQLiteDatabase sqLiteDatabase) {
        createTables(sqLiteDatabase, LocationPuck.class);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        /* TODO: add migration */
        dropTables(db);
        onCreate(db);
    }
}

Create database table for Location Pucks


package com.nigorojr.typebest;

import java.sql.SQLException;
import java.util.HashMap;

public class Tester {

    public static void main(String[] args) {
        // This is to test the behavior of the Database class
        try {
            Records rec = new Records();
            System.out.println("exist?\n" + rec.isTableExist());
            HashMap<String, String> pair = new HashMap<String, String>();
            pair.put("foo", "int");
            pair.put("hoge", "varchar(50)");
            if (!rec.isTableExist()) {
                rec.createTable(pair);
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

package com.nigorojr.typebest;

import java.sql.SQLException;
import java.util.HashMap;

public class Tester {

    public static void main(String[] args) {
        // This is to test the behavior of the Database class
        try {
            Records rec = new Records();
            System.out.println("exist?\n" + rec.isTableExist());
            HashMap<String, String> pair = new HashMap<String, String>();
            pair.put("foo", "int");
            pair.put("hoge", "varchar(50)");
            if (!rec.isTableExist()) {
                rec.createTable(pair);
            }
            System.out.println("finished creating...");
            HashMap<String, String> ins = new HashMap<String, String>();
            ins.put("foo", "50");
            ins.put("hoge", "'barbar'");
            rec.insert(ins);
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

Add test for checking whether insert method runs or not

Tester class for the insert method that was implemented in the Records class.
Whether or not the values were properly inserted has not been checked yet.
This test was done only to check if it can be ran without exceptions
happening.


package net.teamio.taam.content.common;

import net.minecraftforge.fluids.Fluid;

public class FluidDye extends Fluid {

	public FluidDye(String fluidName) {
		super(fluidName, null, null);//TODO: ResourceLocations
		setViscosity(400);
		setDensity(1300);
	}

}

package net.teamio.taam.content.common;

import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.Fluid;

public class FluidDye extends Fluid {

	public FluidDye(String fluidName) {
		super(fluidName, new ResourceLocation("taam", "dye"), new ResourceLocation("taam", "dye"));//TODO: ResourceLocations
		setViscosity(400);
		setDensity(1300);
	}

}

Fix a crash with fluid dyes

Fix a crash with fluid dyes


package com.mapzen.tangram;

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

/**
 * {@code TouchLabel} represents labels that can be selected on the scree
 */
public class TouchLabel {

    /**
     * Options for the type of TouchLabel
     */
    public enum LabelType {
        POINT,
        TEXT,
    }

    private List<LngLat> coordinates;
    private LabelType type;

    public TouchLabel(double[] coordinates, int type) {
        this.coordinates = new ArrayList<>();

        for (int i = 0; i < coordinates.length - 1; i += 2) {
            this.coordinates.add(new LngLat(coordinates[i], coordinates[i + 1]));
        }

        this.type = LabelType.values()[type];
    }

    public LabelType getType() {
        return this.type;
    }

    public List<LngLat> getCoordinates() {
        return this.coordinates;
    }
}

package com.mapzen.tangram;

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

/**
 * {@code TouchLabel} represents labels that can be selected on the screen
 */
public class TouchLabel {

    /**
     * Options for the type of TouchLabel
     */
    public enum LabelType {
        ICON,
        TEXT,
    }

    private List<LngLat> coordinates;
    private LabelType type;

    public TouchLabel(double[] coordinates, int type) {
        this.coordinates = new ArrayList<>();

        for (int i = 0; i < coordinates.length - 1; i += 2) {
            this.coordinates.add(new LngLat(coordinates[i], coordinates[i + 1]));
        }

        this.type = LabelType.values()[type];
    }

    public LabelType getType() {
        return this.type;
    }

    public List<LngLat> getCoordinates() {
        return this.coordinates;
    }
}

Use same defines as c++ interface in java code


public class Solution {

    public char findTheDifference(String s, String t) {

        char addedChar = 0;

        for (int i = 0; i < s.length(); ++i) {
            addedChar ^= s.charAt(i);
        }

        for (int i = 0; i < t.length(); ++i) {
            addedChar ^= t.charAt(i);
        }

        return addedChar;

    }

}

public class Solution {

    public char findTheDifference(String s, String t) {

        char addedChar = 0;

        for (int i = 0; i < s.length(); i++) {
            addedChar ^= s.charAt(i);
        }

        for (int i = 0; i < t.length(); i++) {
            addedChar ^= t.charAt(i);
        }

        return addedChar;

    }

}

Create : 389 Find the Difference

Create : 389 Find the Difference


package com.aayaffe.sailingracecoursemanager.communication;

import java.io.Serializable;

/**
 * Created by aayaffe on 30/09/2015.
 */
public enum ObjectTypes {
    WorkerBoat,
    FlagBuoy,
    TomatoBuoy,
    TriangleBuoy,
    StartLine,
    FinishLine,
    StartFinishLine,

    RaceManager,  //from here, the relevant ObjectTypes:
    Buoy,
    Gate,
    Satellite,
    ReferencePoint,
    Other
}

package com.aayaffe.sailingracecoursemanager.communication;

import java.io.Serializable;

/**
 * Created by aayaffe on 30/09/2015.
 */
public enum ObjectTypes {
    RaceManager(0),
    WorkerBoat(1),
    Buoy(2),
    FlagBuoy(3),
    TomatoBuoy(4),
    TriangleBuoy(5),
    StartLine(6),
    FinishLine(7),
    StartFinishLine(8),
    Gate(9),
    ReferencePoint(10),
    Other(11);

    private int value;

    ObjectTypes(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

Revert "Revert "Updated object types in Dev""

This reverts commit 640067d83b3bdb0c9547926fbecf69b08b227548.


package jp.wasabeef.recyclerview.internal;

import android.support.v4.view.ViewCompat;
import android.view.View;

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

public final class ViewHelper {

  public static void clear(View v) {
    ViewCompat.setAlpha(v, 1);
    ViewCompat.setScaleY(v, 1);
    ViewCompat.setScaleX(v, 1);
    ViewCompat.setTranslationY(v, 0);
    ViewCompat.setTranslationX(v, 0);
    ViewCompat.setRotation(v, 0);
    ViewCompat.setRotationY(v, 0);
    ViewCompat.setRotationX(v, 0);
    ViewCompat.setPivotY(v, v.getMeasuredHeight() / 2);
    ViewCompat.setPivotX(v, v.getMeasuredWidth() / 2);
    ViewCompat.animate(v).setInterpolator(null);
  }
}

package jp.wasabeef.recyclerview.internal;

import android.support.v4.view.ViewCompat;
import android.view.View;

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

public final class ViewHelper {

  public static void clear(View v) {
    ViewCompat.setAlpha(v, 1);
    ViewCompat.setScaleY(v, 1);
    ViewCompat.setScaleX(v, 1);
    ViewCompat.setTranslationY(v, 0);
    ViewCompat.setTranslationX(v, 0);
    ViewCompat.setRotation(v, 0);
    ViewCompat.setRotationY(v, 0);
    ViewCompat.setRotationX(v, 0);
    ViewCompat.setPivotY(v, v.getMeasuredHeight() / 2);
    ViewCompat.setPivotX(v, v.getMeasuredWidth() / 2);
    ViewCompat.animate(v)
            .setInterpolator(null)
            .setStartDelay(0);
  }
}

Fix setStartDelay() is not reset by clear()


package de.cdietze.ld37.core;

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

public class MathUtils {

  public static List<Integer> shuffledRange(int size, Random random) {
    ArrayList<Integer> list = new ArrayList<>(size);
    for (int i = 0; i < size; ++i) list.add(i);
    Collections.shuffle(list, random);
    return list;
  }
}

package de.cdietze.ld37.core;

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

public class MathUtils {

  public static List<Integer> shuffledRange(int size, Random random) {
    ArrayList<Integer> list = new ArrayList<>(size);
    for (int i = 0; i < size; ++i) list.add(i);
    shuffle(list, random);
    return list;
  }

  /** GWT does not emulate {@link java.util.Collections#shuffle(List, Random)} */
  public static void shuffle(List<?> list, Random random) {
    for (int index = 0; index < list.size(); index += 1) {
      Collections.swap(list, index, index + random.nextInt(list.size() - index));
    }
  }
}

Fix for GWT’s missing collections.shuffle


package edu.northwestern.bioinformatics.studycalendar.testing;

import junit.framework.TestCase;

import java.lang.reflect.Method;
import java.util.Set;
import java.util.HashSet;

import org.easymock.classextension.EasyMock;

/**
 * @author Rhett Sutphin
 */
public abstract class StudyCalendarTestCase extends TestCase {
    protected Set<Object> mocks = new HashSet<Object>();

    ////// MOCK REGISTRATION AND HANDLING

    protected <T> T registerMockFor(Class<T> forClass) {
        return registered(EasyMock.createMock(forClass));
    }

    protected <T> T registerMockFor(Class<T> forClass, Method[] methodsToMock) {
        return registered(EasyMock.createMock(forClass, methodsToMock));
    }

    protected void replayMocks() {
        for (Object mock : mocks) EasyMock.replay(mock);
    }

    protected void verifyMocks() {
        for (Object mock : mocks) EasyMock.verify(mock);
    }

    protected void resetMocks() {
        for (Object mock : mocks) EasyMock.reset(mock);
    }

    private <T> T registered(T mock) {
        mocks.add(mock);
        return mock;
    }
}

package edu.northwestern.bioinformatics.studycalendar.testing;

import edu.nwu.bioinformatics.commons.testing.CoreTestCase;

import junit.framework.TestCase;

import java.lang.reflect.Method;
import java.util.Set;
import java.util.HashSet;

import org.easymock.classextension.EasyMock;

/**
 * @author Rhett Sutphin
 */
public abstract class StudyCalendarTestCase extends CoreTestCase {
    protected Set<Object> mocks = new HashSet<Object>();

    ////// MOCK REGISTRATION AND HANDLING

    protected <T> T registerMockFor(Class<T> forClass) {
        return registered(EasyMock.createMock(forClass));
    }

    protected <T> T registerMockFor(Class<T> forClass, Method[] methodsToMock) {
        return registered(EasyMock.createMock(forClass, methodsToMock));
    }

    protected void replayMocks() {
        for (Object mock : mocks) EasyMock.replay(mock);
    }

    protected void verifyMocks() {
        for (Object mock : mocks) EasyMock.verify(mock);
    }

    protected void resetMocks() {
        for (Object mock : mocks) EasyMock.reset(mock);
    }

    private <T> T registered(T mock) {
        mocks.add(mock);
        return mock;
    }
}

Extend CoreTestCase for access to assertPositve/Negative, others

git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@136 0d517254-b314-0410-acde-c619094fa49f


package com.yahoo.vespa.hosted.node.admin.task.util.network;

/**
 * Strong type IPv4 and IPv6 with the respective iptables executable.
 *
 * @author smorgrav
 */
enum IPVersion {

    IPv6("ip6tables"),
    IPv4("iptables");

    IPVersion(String exec) {
        this.exec = exec;
    }

    private String exec;

    String exec() {
        return exec;
    }
}

package com.yahoo.vespa.hosted.node.admin.task.util.network;

/**
 * Strong type IPv4 and IPv6 with the respective iptables executable.
 *
 * @author smorgrav
 */
public enum IPVersion {

    IPv6("ip6tables"),
    IPv4("iptables");

    IPVersion(String exec) {
        this.exec = exec;
    }

    private String exec;

    String exec() {
        return exec;
    }
}

Make public to be able to use IPAddress class in other packages


package com.orhanobut.hawk;

import java.lang.reflect.Type;

/**
 * Intermediate layer that handles serialization/deserialization for the end result.
 * This is not the same as {@link Serializer}. This interface is only used to convert the intermediate value into String,
 * or vice-versa to be used for {@link Storage}
 *
 *
Use custom implementation if built-in implementation is not enough.

 *
 * @see GsonParser
 */
public interface Parser {

  /**
   * Deserialize the given text for the given type and returns it.
   *
   * @param content is the value that will be deserialized.
   * @param type is the object type which value will be converted to.
   * @param <T> is the expected type.
   * @return the expected type.
   * @throws Exception if the operation is not successful.
   */
  <T> T fromJson(String content, Type type) throws Exception;

  /**
   * Serialize the given object to String.
   *
   * @param body is the object that will be serialized.
   * @return the serialized text.
   */
  String toJson(Object body);

}

package com.orhanobut.hawk;

import java.lang.reflect.Type;

/**
 * Intermediate layer that handles serialization/deserialization for the end result.
 * This is not the same as {@link Serializer}. This interface is only used to convert the intermediate value
 * into String or vice-versa to be used for {@link Storage}
 *
 *
Use custom implementation if built-in implementation is not enough.

 *
 * @see GsonParser
 */
public interface Parser {

  /**
   * Deserialize the given text for the given type and returns it.
   *
   * @param content is the value that will be deserialized.
   * @param type is the object type which value will be converted to.
   * @param <T> is the expected type.
   * @return the expected type.
   * @throws Exception if the operation is not successful.
   */
  <T> T fromJson(String content, Type type) throws Exception;

  /**
   * Serialize the given object to String.
   *
   * @param body is the object that will be serialized.
   * @return the serialized text.
   */
  String toJson(Object body);

}

Fix checkstyle error that one line exceeds the width.


package starpunk;

import com.badlogic.gdx.Screen;

public class GameScreen
  implements Screen
{
  @Override
  public void render( final float delta )
  {
  }

  @Override
  public void resize( int width, int height )
  {
  }

  @Override
  public void show()
  {
  }

  @Override
  public void hide()
  {
  }

  @Override
  public void pause()
  {
  }

  @Override
  public void resume()
  {
  }

  @Override
  public void dispose()
  {
  }
}

package starpunk;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL10;

public class GameScreen
  implements Screen
{
  @Override
  public void render( final float delta )
  {
    Gdx.gl10.glClear( GL10.GL_COLOR_BUFFER_BIT );
  }

  @Override
  public void resize( int width, int height )
  {
  }

  @Override
  public void show()
  {
  }

  @Override
  public void hide()
  {
  }

  @Override
  public void pause()
  {
  }

  @Override
  public void resume()
  {
  }

  @Override
  public void dispose()
  {
  }
}

Clear the screen on render

Clear the screen on render


package com.example.e4.rcp.todo.events;

/**
 * @noimplement This interface is not intended to be implemented by clients.
 *
 * Only used for constant interfaces
 */

public interface MyEventConstants {

	// topic identifier for all todo topics
	String TOPIC_TODO= "TOPIC_TODOS";

	// this key can only used for event registration, you cannot
	// send out generic events
	String TOPIC_TODO_ALLTOPICS = "TOPIC_TODOS/*";

	String TOPIC_TODOS_CHANGED = "TOPIC_TODOS/CHANGED";

	String TOPIC_TODO_NEW = "TOPIC_TODOS/TODO/NEW";

	String TOPIC_TODO_DELETE = "TOPIC_TODOS/TODO/DELETED";

	String TOPIC_TODO_UPDATE = "TOPIC_TODOS/TODO/UPDATED";
}

package com.example.e4.rcp.todo.events;
/**
 *
 * @noimplement This interface is not intended to be implemented by clients.
 *
 * Only used for constant definition
 */

public interface MyEventConstants {

	// topic identifier for all todo topics
	String TOPIC_TODO = "TOPIC_TODOS";

	// this key can only be used for event registration, you cannot
	// send out generic events
	String TOPIC_TODO_ALLTOPICS = "TOPIC_TODOS/*";

	String TOPIC_TODOS_CHANGED = "TOPIC_TODOS/CHANGED";

	String TOPIC_TODO_NEW = "TOPIC_TODOS/TODO/NEW";

	String TOPIC_TODO_DELETE = "TOPIC_TODOS/TODO/DELETED";

	String TOPIC_TODO_UPDATE = "TOPIC_TODOS/TODO/UPDATED";
}

Tag added for all todo topics

Tag added for all todo topics


package controllers;

import java.util.ArrayList;

import com.feth.play.module.pa.PlayAuthenticate;
import com.feth.play.module.pa.user.AuthUser;

import models.User;

import play.Logger;
import play.mvc.Http.Context;
import play.mvc.Result;
import play.mvc.Security;

public class Secured extends Security.Authenticator {

	@Override
	public String getUsername(final Context ctx) {
        Logger.debug("Secured::getUsername " + ctx);
		final AuthUser u = PlayAuthenticate.getUser(ctx.session());

		if (u != null) {
            User the_user = User.findByAuthUserIdentity(u);
            if (the_user == null) {
                return null;
            }

            return u.getId();
        }

        return null;
	}

	@Override
	public Result onUnauthorized(final Context ctx) {
		return redirect(com.feth.play.module.pa.controllers.routes.Authenticate.logout());
	}
}

package controllers;

import java.util.ArrayList;

import com.feth.play.module.pa.PlayAuthenticate;
import com.feth.play.module.pa.user.AuthUser;

import models.User;

import play.Logger;
import play.mvc.Http.Context;
import play.mvc.Result;
import play.mvc.Security;

public class Secured extends Security.Authenticator {

	@Override
	public String getUsername(final Context ctx) {
        Logger.debug("Secured::getUsername " + ctx);
		final AuthUser u = PlayAuthenticate.getUser(ctx.session());

		if (u != null) {
            User the_user = User.findByAuthUserIdentity(u);
            if (the_user == null) {
                return null;
            }

            return u.getId();
        }

        PlayAuthenticate.storeOriginalUrl(ctx);

        return null;
	}

	@Override
	public Result onUnauthorized(final Context ctx) {
		return redirect(controllers.routes.Public.index());
	}
}

Store original URL before logging in so that user is properly redirected on login.


package panda.leatherworks.common.network.messagehandler;

import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;

public class DummyMessageHandler implements IMessageHandler<IMessage, IMessage> {
	@Override
	public IMessage onMessage(IMessage message, MessageContext ctx) {
		return null;
	}
}

package panda.leatherworks.common.network.messagehandler;

import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;

/**
 * This dummy handler will do nothing.
 *
 * Forge doesn't let us register messages without a handler. This is unfortunate because it makes
 * registering messages that should never be handled on a physical side inconvenient.
 * Use this message handler when registering client handled messages on a dedicated server.
 */
public class DummyMessageHandler implements IMessageHandler<IMessage, IMessage> {
	@Override
	public IMessage onMessage(IMessage message, MessageContext ctx) {
		return null;
	}
}

Add description to dummy message handler


package com.fasterxml.jackson.databind.deser;

import javax.measure.Measure;

import java.util.List;

import com.fasterxml.jackson.databind.BaseMapTest;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TestNoClassDefFoundDeserializer extends BaseMapTest {

    public static class Parent {
        public List<Child> child;
    }

    public static class Child {
        public Measure measure;
    }

    public void testClassIsMissing() throws ClassNotFoundException
    {
        boolean missing = false;
        try {
            Class.forName("javax.measure.Measure");
        } catch (ClassNotFoundException ex) {
            missing = true;
        }
        assertTrue("javax.measure.Measure is not in classpath", missing);
    }

    public void testDeserialize() throws Exception
    {
        ObjectMapper m = new ObjectMapper();
        Parent result = m.readValue(" { } ", Parent.class);
        assertNotNull(result);
    }

    public void testUseMissingClass() throws Exception
    {
        boolean missing = false;
        try {
            ObjectMapper m = new ObjectMapper();
            m.readValue(" { \"child\" : [{}] } ", Parent.class);
        } catch (NoClassDefFoundError ex) {
            missing = true;
        }
        assertTrue("cannot instantiate a missing class", missing);
    }

}

package com.fasterxml.jackson.databind.deser;

import javax.measure.Measure;

import java.util.List;

import com.fasterxml.jackson.databind.BaseMapTest;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TestNoClassDefFoundDeserializer extends BaseMapTest {

    public static class Parent {
        public List<Child> child;
    }

    public static class Child {
        public Measure measure;
    }

    public void testClassIsMissing()
    {
        boolean missing = false;
        try {
            Class.forName("javax.measure.Measure");
        } catch (ClassNotFoundException ex) {
            missing = true;
        }
        assertTrue("javax.measure.Measure is not in classpath", missing);
    }

    public void testDeserialize() throws Exception
    {
        ObjectMapper m = new ObjectMapper();
        Parent result = m.readValue(" { } ", Parent.class);
        assertNotNull(result);
    }

    public void testUseMissingClass() throws Exception
    {
        boolean missing = false;
        try {
            ObjectMapper m = new ObjectMapper();
            m.readValue(" { \"child\" : [{}] } ", Parent.class);
        } catch (NoClassDefFoundError ex) {
            missing = true;
        }
        assertTrue("cannot instantiate a missing class", missing);
    }

}

Remove unneeded exception signature from unit test.


package net.rdrei.android.wakimail;

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

import android.app.Application;

/**
 * Sets up settings that are required for the application to run.
 *
 * @author pascal
 */
@ReportsCrashes(
	formUri = "http://www.bugsense.com/api/acra?api_key=2b0a6e7c",
	formKey = "")
public class WAKiMailApplication extends Application {
	@Override
	public void onCreate() {
		// The following line triggers the initialization of ACRA
		ACRA.init(this);
		super.onCreate();
	}
}

package net.rdrei.android.wakimail;

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

import android.app.Application;
import android.os.StrictMode;

/**
 * Sets up settings that are required for the application to run.
 *
 * @author pascal
 */
@ReportsCrashes(formUri = "http://www.bugsense.com/api/acra?api_key=2b0a6e7c", formKey = "")
public class WAKiMailApplication extends Application {
	@Override
	public void onCreate() {
		super.onCreate();

		if (BuildConfig.DEBUG) {
			enableStrictMode();
		} else {
			// Only if DEBUG is disabled.
			ACRA.init(this);
		}
	}

	private void enableStrictMode() {
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
				.detectAll().penaltyLog().build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
				.detectLeakedSqlLiteObjects()
				// Only on 11+ if I'm not mistaken.
				.detectLeakedClosableObjects().penaltyLog().penaltyDeath()
				.build());
	}
}

Enable StrictMode in DEBUG env, disable ACRA there


package devopsdistilled.operp.client.items.controllers;

import devopsdistilled.operp.client.abstracts.SubTaskPaneController;
import devopsdistilled.operp.server.data.entity.items.Item;

public interface EditItemPaneController extends SubTaskPaneController {

	public void init(Item item);

	public Item save(Item item);

	public void validate(Item item);
}

package devopsdistilled.operp.client.items.controllers;

import devopsdistilled.operp.client.abstracts.SubTaskPaneController;
import devopsdistilled.operp.client.items.exceptions.ItemNameExistsException;
import devopsdistilled.operp.client.items.exceptions.NullFieldException;
import devopsdistilled.operp.client.items.exceptions.ProductBrandPairExistsException;
import devopsdistilled.operp.server.data.entity.items.Item;

public interface EditItemPaneController extends SubTaskPaneController {

	public void init(Item item);

	public Item save(Item item);

	public void validate(Item item) throws NullFieldException,
			ProductBrandPairExistsException, ItemNameExistsException;
}

Add throws clause to validate()

Add throws clause to validate()

OPEN - task 48: Create "Edit Item" functionality
http://github.com/DevOpsDistilled/OpERP/issues/issue/48


package annis.gui;

import com.github.mvysny.kaributesting.v8.MockVaadin;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeoutException;
import org.slf4j.LoggerFactory;

public class TestHelper {

  private static final org.slf4j.Logger log = LoggerFactory.getLogger(TestHelper.class);

  private TestHelper() {
    // Static helper class
  }

  public static void awaitCondition(int seconds, Callable<Boolean> conditionEvaluator,
      Callable<String> message)
      throws Exception {
    long startTime = System.currentTimeMillis();
    long maxExecutionTime = ((long) seconds) * 1000l;
    boolean condition = false;
    int attempt = 0;

    while (!condition && (System.currentTimeMillis() - startTime) < maxExecutionTime) {
      MockVaadin.INSTANCE.clientRoundtrip();

      log.debug("Evaluating await condition (attempt {})", attempt++);
      condition = conditionEvaluator.call();

      if (!condition) {
        // Wait until invoking the condition again
        log.debug("Waiting 10 ms before checking condition again");
        Thread.sleep(10); // NOSONAR The code should similar to the Karibu async example
      }
    }

    MockVaadin.INSTANCE.clientRoundtrip();

    if (!condition) {
      throw new TimeoutException(message.call());
    }
  }

  public static void awaitCondition(int seconds, Callable<Boolean> conditionEvaluator)
      throws Exception {
    awaitCondition(seconds, conditionEvaluator,
        () -> "Condition did not become true in " + seconds + " seconds.");
  }
}

package annis.gui;

import com.github.mvysny.kaributesting.v8.MockVaadin;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeoutException;
import org.slf4j.LoggerFactory;

public class TestHelper {

  private static final org.slf4j.Logger log = LoggerFactory.getLogger(TestHelper.class);

  private TestHelper() {
    // Static helper class
  }

  public static void awaitCondition(int seconds, Callable<Boolean> conditionEvaluator,
      Callable<String> message)
      throws Exception {
    long startTime = System.currentTimeMillis();
    long maxExecutionTime = ((long) seconds) * 1000l;
    boolean condition = false;
    int attempt = 0;

    while (!condition && (System.currentTimeMillis() - startTime) < maxExecutionTime) {
      MockVaadin.INSTANCE.clientRoundtrip();

      log.debug("Evaluating await condition (attempt {})", attempt++);
      condition = conditionEvaluator.call();

      if (!condition) {
        // Wait until invoking the condition again
        log.debug("Waiting 250 ms before checking condition again");
        Thread.sleep(250); // NOSONAR The code should similar to the Karibu async example
      }
    }

    MockVaadin.INSTANCE.clientRoundtrip();

    if (!condition) {
      throw new TimeoutException(message.call());
    }
  }

  public static void awaitCondition(int seconds, Callable<Boolean> conditionEvaluator)
      throws Exception {
    awaitCondition(seconds, conditionEvaluator,
        () -> "Condition did not become true in " + seconds + " seconds.");
  }
}

Increase sleep time to a more conservative level


package com.rehab.animation;

public interface Drawable {

	double getX ();

	double getY ();

	double getWidth();

	double getHeight();

	Sprite getSprite();

	void setSprite(Sprite s);

	int getZ();

	void onClick();

	boolean isVisible();

	float getRotation();

	void setRotation(float f);

}

package com.rehab.animation;

import javafx.scene.input.MouseEvent;

public interface Drawable {

	double getX ();

	double getY ();

	double getWidth();

	double getHeight();

	Sprite getSprite();

	void setSprite(Sprite s);

	int getZ();

	boolean isVisible();

	float getRotation();

	void setRotation(float f);

	boolean isFacingLeft();

	void onMousePress(MouseEvent event);

	void onMouseRelease(MouseEvent event);
}

Support for method to mirror

Support for method to mirror

Added isFacingLeft()


/*
	Article Parse
 */

import java.io.*;

public class ArticleParse {

    public static void main(String[] args) {

        System.out.println("Running Article Parse");

    }

}

/*
	Article Parse
 */

import java.io.*;

public class ArticleParse {

    public static void main(String[] args) {

    	if (args.length == 0) {
    		printUsageInterface();
    		System.exit(1);
    	}

        System.out.println("Running Article Parse... (prints PDFs encountered)");

    }

    private static void printUsageInterface() {
    	String message = "";
    	message += "+++ ArticleParse +++\n";
    	message += "\n";
    	message += "    PURPOSE: Given a list of locations (files or directories) reads each PDF document encountered.\n";
    	message += "    The content of the PDF is semantically parsed. For example the authors of the article can be selected and saved.\n";
    	message += "\n";
    	message += "    USAGE: ArticleParse <location_1> [ .. <location_n> ]\n";

    	System.err.print(message);
    }

}

feature: Print purpose and usage if called without arguments


package com.meta1203.ChessPlayer;

import java.util.List;

public class CalculateMovesThread extends Thread {
	private Turn originTurn;

	public CalculateMovesThread(Turn t) {
		originTurn = t;
	}

	@Override
	public void run() {
		List<Move> moves = originTurn.getBoard().getMoves(originTurn);
		for (Move x : moves) {
			Main.logger.info(x.toString());
			originTurn.addChild(originTurn.getBoard().executeMove(x));
		}
	}
}

package com.meta1203.ChessPlayer;

import java.util.List;

public class CalculateMovesThread implements Runnable {
	private Turn originTurn;

	public CalculateMovesThread(Turn t) {
		originTurn = t;
	}

	@Override
	public void run() {
		List<Move> moves = originTurn.getBoard().getMoves(originTurn);
		for (Move x : moves) {
			// I don't know enough about the thread safety of the Java logger, so I'm not taking any chances
			synchronized (Main.logger) {
				Main.logger.info(x.toString());
			}
			originTurn.addChild(originTurn.getBoard().executeMove(x));
		}
	}
}

Change from a Thread to a Runnable for use in an ExecutorService


package net.hillsdon.reviki.vc.impl;

import net.hillsdon.reviki.vc.AttachmentHistory;

import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.SVNWCUtil;

public class AttachmentListingDebug {

  public static void main(String[] args) throws Exception {
    DAVRepositoryFactory.setup();
    SVNRepository repository = SVNRepositoryFactory.create(SVNURL.parseURIDecoded("http://svn.dsl.local/svn/web/wiki/dsl"));
    repository.setAuthenticationManager(SVNWCUtil.createDefaultAuthenticationManager());
    RepositoryBasicSVNOperations operations = new RepositoryBasicSVNOperations(repository, null);
    SVNPageStore store = new SVNPageStore("wiki", new InMemoryDeletedRevisionTracker(), operations, null, null);
    for (AttachmentHistory attachment : store.attachments(new PageReferenceImpl("Printing"))) {
      System.err.println(attachment.getName());
    }
  }

}

package net.hillsdon.reviki.vc.impl;

import net.hillsdon.reviki.vc.AttachmentHistory;

import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.SVNWCUtil;

public class AttachmentListingDebug {

  public static void main(String[] args) throws Exception {
    DAVRepositoryFactory.setup();
    SVNRepository repository = SVNRepositoryFactory.create(SVNURL.parseURIDecoded("https://svn-dev-plaintext.int.corefiling.com/svn/web/wiki/dsl"));
    repository.setAuthenticationManager(SVNWCUtil.createDefaultAuthenticationManager());
    RepositoryBasicSVNOperations operations = new RepositoryBasicSVNOperations(repository, null);
    SVNPageStore store = new SVNPageStore("wiki", new InMemoryDeletedRevisionTracker(), operations, null, null);
    for (AttachmentHistory attachment : store.attachments(new PageReferenceImpl("Printing"))) {
      System.err.println(attachment.getName());
    }
  }

}

Use correct repository in debug thing

Use correct repository in debug thing


package valandur.webapi.json.serializers.events;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.spongepowered.api.event.cause.Cause;

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

public class CauseSerializer extends StdSerializer<Cause> {

    public CauseSerializer() {
        this(null);
    }

    public CauseSerializer(Class<Cause> t) {
        super(t);
    }

    @Override
    public void serialize(Cause value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeStartObject();

        for (Map.Entry<String, Object> entry : value.getNamedCauses().entrySet()) {
            if (entry.getValue().getClass().getName().startsWith("net.minecraft.server"))
                gen.writeStringField(entry.getKey(), entry.getValue().getClass().getName());
            else
                gen.writeObjectField(entry.getKey(), entry.getValue());
        }

        gen.writeEndObject();
    }
}

package valandur.webapi.json.serializers.events;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.spongepowered.api.event.cause.Cause;

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

public class CauseSerializer extends StdSerializer<Cause> {

    private static List<String> blockedCauseClasses;
    static {
        List<String> classes = new ArrayList<>();

        classes.add("net.minecraft.server");
        classes.add("valandur.webapi");

        blockedCauseClasses = classes;
    }

    public CauseSerializer() {
        this(null);
    }

    public CauseSerializer(Class<Cause> t) {
        super(t);
    }

    @Override
    public void serialize(Cause value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeStartObject();

        for (Map.Entry<String, Object> entry : value.getNamedCauses().entrySet()) {
            if (blockedCauseClasses.stream().anyMatch(c -> entry.getValue().getClass().getName().startsWith(c)))
                gen.writeStringField(entry.getKey(), entry.getValue().getClass().getName());
            else
                gen.writeObjectField(entry.getKey(), entry.getValue());
        }

        gen.writeEndObject();
    }
}

fix(hooks): Fix cmd hook not working for commands run via Web-API


package stream.flarebot.flarebot.util;

public class Pair<K, V> {

    private K key;
    private V value;

    public K getKey() {
        return this.key;
    }

    public void setKey(K key) {
        this.key = key;
    }

    public V getValue() {
        return this.value;
    }

    public void setValue(V value) {
        this.value = value;
    }

    public void setKeyValue(K key, V value) {
        this.key = key;
        this.value = value;
    }
}

package stream.flarebot.flarebot.util;

public class Pair<K, V> {

    private K key;
    private V value;

    public Pair(K key, V value) {
        this.key = key;
        this.value = value;
    }

    public Pair(){}

    public K getKey() {
        return this.key;
    }

    public void setKey(K key) {
        this.key = key;
    }

    public V getValue() {
        return this.value;
    }

    public void setValue(V value) {
        this.value = value;
    }

    public void setKeyValue(K key, V value) {
        this.key = key;
        this.value = value;
    }
}

Add a god damn constructor

Add a god damn constructor


package fi.aalto.trafficsense.regularroutes.backend.pipeline;

import fi.aalto.trafficsense.regularroutes.backend.parser.LocationData;
import timber.log.Timber;

import java.util.ArrayDeque;
import java.util.Deque;

public class DataQueue implements DataCollector.Listener {
    private final Deque<DataPoint> mDeque;

    private long mNextSequence;

    public DataQueue() {
        this.mDeque = new ArrayDeque<DataPoint>();
    }

    @Override
    public void onDataReady(LocationData locationData) {
        DataPoint dataPoint = new DataPoint(System.currentTimeMillis(), mNextSequence++, locationData);
        while (!this.mDeque.offer(dataPoint)) {
            DataPoint discarded = this.mDeque.pop();
            Timber.w("Queue full, discarding data point %s", discarded);
        }
        Timber.d("%s", this.mDeque);
    }

}

package fi.aalto.trafficsense.regularroutes.backend.pipeline;

import com.google.common.collect.EvictingQueue;
import fi.aalto.trafficsense.regularroutes.backend.parser.LocationData;
import timber.log.Timber;

import java.util.Queue;

public class DataQueue implements DataCollector.Listener {
    private static final int MAX_SIZE = 256;
    private final Queue<DataPoint> mDeque;

    private long mNextSequence;

    public DataQueue() {
        this.mDeque = EvictingQueue.create(MAX_SIZE);
    }

    @Override
    public void onDataReady(LocationData locationData) {
        DataPoint dataPoint = new DataPoint(System.currentTimeMillis(), mNextSequence++, locationData);
        this.mDeque.add(dataPoint);
        Timber.d("%s", this.mDeque);
    }

}

Use proper eviction for data queue

Use proper eviction for data queue


package chess;

public class MoveData {
	private int toRow;
	private int toCol;
	private boolean isACapture;

	public MoveData(int row, int col, boolean capture) {
		toRow = row;
		toCol = col;
		isACapture = capture;
	}

	public int getRow() {
		return toRow;
	}

	public int getCol() {
		return toCol;
	}
	public boolean checkCapture() {
		return isACapture;
	}
}

package chess;

import chess.pieces.Piece;

public class MoveData {
	private Piece startPiece;
	private int toRow;
	private int toCol;
	private int fromRow;
	private int fromCol;
	private boolean isACapture;

	public MoveData(Piece startPiece, int fromRow, int fromCol, int toRow, int toCol, boolean capture) {
		this.startPiece = startPiece;
		this.fromRow = fromRow;
		this.fromCol = fromCol;
		this.toRow = toRow;
		this.toCol = toCol;
		isACapture = capture;
	}

	public Piece getPiece() {
		return startPiece;
	}

	public int getStartRow() {
		return fromRow;
	}

	public int getStartCol() {
		return fromCol;
	}

	public int getEndRow() {
		return toRow;
	}

	public int getEndCol() {
		return toCol;
	}
	public boolean checkCapture() {
		return isACapture;
	}
}

Add from squares and calling piece data.


package ee.ria.DigiDoc.common;

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

public class FileUtil {

    /**
     * Check if file path is in cache directory
     *
     * @param file File to check
     * @return Boolean indicating if file is in the cache directory.
     */
    public static File getFileInDirectory(File file, File directory) throws IOException {
        if (file.getCanonicalPath().startsWith(directory.getCanonicalPath())) {
            return file;
        }

        throw new IOException("Invalid file path");
    }

    /**
     * Replace invalid string characters
     *
     * @param input Input to replace invalid characters
     * @param replacement Replacement to replace invalid characters with
     * @return String with valid characters
     */
    public static String sanitizeString(String input, char replacement) {
        String allowedCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_,.:/%;+=";

        StringBuilder sb = new StringBuilder(input.length());

        for (int offset = 0; offset < input.length(); offset++) {
            char c = input.charAt(offset);

            if (allowedCharacters.indexOf(c) == -1) {
                sb.append(replacement);
            }
            else {
                // Coverity does not want to see usages of the original string
                sb.append(allowedCharacters.charAt(allowedCharacters.indexOf(c)));
            }
        }

        return sb.toString();
    }
}

package ee.ria.DigiDoc.common;

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

public class FileUtil {

    /**
     * Check if file path is in cache directory
     *
     * @param file File to check
     * @return Boolean indicating if file is in the cache directory.
     */
    public static File getFileInDirectory(File file, File directory) throws IOException {
        if (file.getCanonicalPath().startsWith(directory.getCanonicalPath())) {
            return file;
        }

        throw new IOException("Invalid file path");
    }

    /**
     * Replace invalid string characters
     *
     * @param input Input to replace invalid characters
     * @param replacement Replacement to replace invalid characters with
     * @return String with valid characters
     */
    public static String sanitizeString(String input, char replacement) {
        String allowedCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_,.:/%;+=@?&";

        StringBuilder sb = new StringBuilder(input.length());

        for (int offset = 0; offset < input.length(); offset++) {
            char c = input.charAt(offset);

            if (allowedCharacters.indexOf(c) == -1) {
                sb.append(replacement);
            }
            else {
                // Coverity does not want to see usages of the original string
                sb.append(allowedCharacters.charAt(allowedCharacters.indexOf(c)));
            }
        }

        return sb.toString();
    }
}

Fix opening files from GMail

Fix opening files from GMail

* MOPPAND-751

Signed-off-by: ab8d0676af4d724c40f403280b143ae093b0e58d@nortal.com


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

package com.google.copybara.exception;

/**
 * An exception thrown by destinations when they detect that there is no change to submit. Usually
 * this means that the change was already applied.
 */
public class EmptyChangeException extends ValidationException {

  public EmptyChangeException(String message) {
    super(message);
  }

  public EmptyChangeException(Throwable cause, String message) {
    super(message, cause);
  }
}

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

package com.google.copybara.exception;

/**
 * An exception thrown by destinations when they detect that there is no change to submit. Usually
 * this means that the change was already applied.
 */
public class EmptyChangeException extends ValidationException {

  public EmptyChangeException(String message) {
    super(message);
  }

  public EmptyChangeException(Throwable cause, String message) {
    super(cause, message);
  }

  public EmptyChangeException(Throwable cause, String message, Object... args) {
    super(cause, message, args);
  }
}

Correct the argument order in EmptyChangeEx.super call

When refactoring exceptions, this one was overlooked, leading to a format string bug.

PiperOrigin-RevId: 189939495
Change-Id: I94172b07dbfcb23827efef78b858bab92eb9bd62


package com.io7m.jcanephora;

import java.io.IOException;

import javax.media.opengl.GLContext;

import junit.framework.Assert;

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

import com.io7m.jaux.Constraints.ConstraintError;

public class GLMetaJOGL30Test
{
  private GLContext context;

  @Before public void setUp()
    throws Exception
  {
    this.context = JOGL30.createOffscreenDisplay(640, 480);
  }

  @After public void tearDown()
    throws Exception
  {
    JOGL30.destroyDisplay(this.context);
  }

  @Test public void testMetaStrings()
    throws GLException,
      IOException,
      ConstraintError
  {
    final GLInterface gl = GLInterfaceJOGL30Util.getGL(this.context);

    final String vn = gl.metaGetVendor();
    final String vr = gl.metaGetVersion();
    final String r = gl.metaGetRenderer();

    Assert.assertNotNull(vn);
    Assert.assertNotNull(vr);
    Assert.assertNotNull(r);
  }
}

package com.io7m.jcanephora;

import java.io.IOException;

import javax.media.opengl.GLContext;

import junit.framework.Assert;

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

import com.io7m.jaux.Constraints.ConstraintError;

public class GLMetaJOGL30Test
{
  private GLContext context;

  @Before public void setUp()
    throws Exception
  {
    this.context = JOGL30.createOffscreenDisplay(640, 480);
  }

  @After public void tearDown()
    throws Exception
  {
    JOGL30.destroyDisplay(this.context);
  }

  @Test public void testMetaStrings()
    throws GLException,
      IOException,
      ConstraintError
  {
    final GLInterface gl = GLInterfaceJOGL30Util.getGL(this.context);

    final String vn = gl.metaGetVendor();
    final String vr = gl.metaGetVersion();
    final String r = gl.metaGetRenderer();

    Assert.assertNotNull(vn);
    Assert.assertNotNull(vr);
    Assert.assertNotNull(r);

    System.out.println("Vendor   : " + vn);
    System.out.println("Version  : " + vr);
    System.out.println("Renderer : " + r);
  }
}

Make test print meta strings

Make test print meta strings


package net.michaelsavich.notification;

import java.util.HashSet;

/**
 * An instance of NotificationCenter that dispatches {@link Notification notifications} to their {@link NotificationObserver observers} serially.
 * Note that an instance of this object is returned by the static method {@link NotificationCenter#primary()}. This class is exposed as public primarily because it
 * may be useful to subclass SynchronousNotificationCenter to implement custom bookkeeping. Furthermore, if for some reason you don't want to use
 * the singleton-like behavior of the static methods in NotificationCenter, you can instantiate this class directly and manage it yourself.
 */
public class SynchronousNotificationCenter extends NotificationCenter {

	/**
	 * {@inheritDoc}
	 *

	 * The implementation of this method provided by SynchronousNotificationCenter is
	 * synchronous, and will halt everything until all objects have finished responding.
	 * As such, avoid adding {@link NotificationObserver observers} with long-running callbacks to a SynchronousNotificationCenter.
	 *

	 *

	 * When calling this method, remember that no guarantee is made regarding the order in which  are notified.
	 *

	 */
	@Override
	public void post(Notification notification) {
		dispatchTable.getOrDefault(notification.getName(), new HashSet<>())
				.forEach(o -> o.receiveNotification(notification));
	}

}

package net.michaelsavich.notification;

import java.util.HashSet;

/**
 * An instance of NotificationCenter that dispatches {@link Notification notifications} to their {@link NotificationObserver observers} serially.
 * Note that an instance of this object is returned by the static method {@link NotificationCenter#primary()}. This class is exposed as public primarily because it
 * may be useful to subclass SynchronousNotificationCenter to implement custom bookkeeping. Furthermore, if for some reason you don't want to use
 * the singleton-like behavior of the static methods in NotificationCenter, you can instantiate this class directly and manage it yourself.
 */
public class SynchronousNotificationCenter extends NotificationCenter {

	/**
	 * {@inheritDoc}
	 *

	 * The implementation of this method provided by SynchronousNotificationCenter is
	 * synchronous, and will halt everything until all objects have finished responding.
	 * As such, avoid adding {@link NotificationObserver observers} with long-running callbacks to a SynchronousNotificationCenter.
	 *

	 *

	 * When calling this method, remember that no guarantee is made regarding the order in which  are notified.
	 *

	 */
	@Override
	public void post(Notification notification) {
			getObservers(notification.getName())
				.forEach(o -> o.receiveNotification(notification));
	}

}

Switch to using protected getter

Switch to using protected getter


package pete.metrics.adaptability;

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

public final class AdaptableElement {

	private final String name;

	private final List<String> adaptions;

	private String locatorExpression = "//*[local-name() = 'definitions']";

	public AdaptableElement(String name) {
		this.name = name;
		adaptions = new ArrayList<>();
	}

	public void addAdaption(String adaption) {
		adaptions.add(adaption);
	}

	public List<String> getAdaptions() {
		return Collections.unmodifiableList(adaptions);
	}

	public int getNumberOfAdaptions() {
		return adaptions.size();
	}

	public String getName() {
		return name;
	}

	public int getAdaptabilityScore() {
		return adaptions.size();
	}

	public String getLocatorExpression() {
		return locatorExpression;
	}

	public void setLocatorExpression(String locatorExpression) {
		this.locatorExpression += locatorExpression;
	}

}

package pete.metrics.adaptability;

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

public final class AdaptableElement {

	private final String name;

	private final List<String> adaptions;

	private String documentation;

	private String locatorExpression = "//*[local-name() = 'definitions']";

	public AdaptableElement(String name) {
		if (name == null) {
			throw new IllegalArgumentException("name must not be null");
		}

		this.name = name;
		adaptions = new ArrayList<>();
		documentation = "";
	}

	public void addAdaption(String adaption) {
		if (adaption != null) {
			adaptions.add(adaption);
		}
	}

	public List<String> getAdaptions() {
		return Collections.unmodifiableList(adaptions);
	}

	public int getNumberOfAdaptions() {
		return adaptions.size();
	}

	public String getName() {
		return name;
	}

	public int getAdaptabilityScore() {
		return adaptions.size();
	}

	public String getLocatorExpression() {
		return locatorExpression;
	}

	public void setLocatorExpression(String locatorExpression) {
		if (!(locatorExpression == null)) {
			this.locatorExpression += locatorExpression;
		}
	}

	public String getDocumentation() {
		return documentation;
	}

	public void setDocumentation(String documentation) {
		if (documentation == null) {
			this.documentation = "";
		} else {
			this.documentation = documentation;
		}
	}

}

Add documentation field and parameter validation


package test.com.github.tmurakami.dexopener;

import android.support.test.rule.ActivityTestRule;
import android.support.v4.app.FragmentActivity;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.willReturn;

public class MyFragmentTest {

    @Rule
    public final ActivityTestRule<FragmentActivity> rule = new ActivityTestRule<>(FragmentActivity.class);

    @Mock
    MyService service;

    @InjectMocks
    MyFragment target;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testOnCreate() {
        final Object o = new Object();
        willReturn(o).given(service).doIt();
        final FragmentActivity activity = rule.getActivity();
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                activity.getSupportFragmentManager().beginTransaction().add(target, null).commitNow();
                assertEquals(o, target.result);
            }
        });
    }

}

package test.com.github.tmurakami.dexopener;

import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import android.support.v4.app.FragmentActivity;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.willReturn;

public class MyFragmentTest {

    @Rule
    public final ActivityTestRule<FragmentActivity> rule = new ActivityTestRule<>(FragmentActivity.class, true, false);

    @Mock
    MyService service;

    @InjectMocks
    MyFragment target;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testOnCreate() {
        final Object o = new Object();
        willReturn(o).given(service).doIt();
        final FragmentActivity activity = rule.launchActivity(null);
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                activity.getSupportFragmentManager().beginTransaction().add(target, null).commitNow();
            }
        });
        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
        assertEquals(o, target.result);
    }

}

Fix to work on CI

Fix to work on CI


package bndtools.editor;

import org.bndtools.core.editors.BndResourceMarkerAnnotationModel;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.ui.editors.text.TextFileDocumentProvider;

public class BndSourceDocumentProvider extends TextFileDocumentProvider {
    @Override
    protected IAnnotationModel createAnnotationModel(IFile file) {
        return new BndResourceMarkerAnnotationModel(file);
    }
}

package bndtools.editor;

import org.bndtools.core.editors.BndResourceMarkerAnnotationModel;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.ui.editors.text.TextFileDocumentProvider;

public class BndSourceDocumentProvider extends TextFileDocumentProvider {
    @Override
    protected IAnnotationModel createAnnotationModel(IFile file) {
        return new BndResourceMarkerAnnotationModel(file);
    }

    @Override
    public String getDefaultEncoding() {
        return "UTF-8";
    }

}

Make sure we always save bnd files as UTF-8 and not accidentally inherit the local Eclipse platform encoding …

We need to force this since we should not depend on local Eclipse settings

Signed-off-by: Peter Kriens <016a769244db65ccbb64c8b271e9b7b28d4a3ce8@aqute.biz>


package edu.stuy.commands;

import edu.stuy.Robot;
import edu.wpi.first.wpilibj.command.Command;

/**
 * Rotates the Robot without PID values
 */

public class DrivetrainRotateNoPIDCommand extends Command {

    private double degrees;
    private double startAngle;

    public DrivetrainRotateNoPIDCommand(double _degrees) {
        requires(Robot.drivetrain);
        degrees = _degrees;
        startAngle = Robot.drivetrain.getGyroAngle();
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        Robot.drivetrain.arcadeDrive(0, degrees , false);
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
            return Math.abs(startAngle - Robot.drivetrain.getGyroAngle()) >= degrees;
    }

    // Called once after isFinished returns true
    protected void end() {
        Robot.drivetrain.stop();
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}

package edu.stuy.commands;

import edu.stuy.Robot;
import edu.wpi.first.wpilibj.command.Command;

/**
 * Rotates the Robot without PID values
 */

public class DrivetrainRotateNoPIDCommand extends Command {

    private double degrees;
    private double startAngle;

    public DrivetrainRotateNoPIDCommand(double _degrees) {
        requires(Robot.drivetrain);
        degrees = _degrees;
        startAngle = Robot.drivetrain.getGyroAngle();
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        if (degrees < 0) {
            Robot.drivetrain.tankDrive(-0.5, 0.5);
        } else if (degrees > 0) {
            Robot.drivetrain.tankDrive(0.5, -0.5);
        }
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
            return Math.abs(startAngle - Robot.drivetrain.getGyroAngle()) >= degrees;
    }

    // Called once after isFinished returns true
    protected void end() {
        Robot.drivetrain.stop();
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}

Change ArcadeDrive to TankDrive for speed control


package agaricus.mods.Jarmod2Coremod;

import cpw.mods.fml.relauncher.IFMLCallHook;

import java.io.File;
import java.util.Map;

public class Scanner implements IFMLCallHook {

    public File coremodLocation;

    /*
     * Gives the mod coremod data if it wants it.
     */
    @Override
    public void injectData(Map<String, Object> data) {
        if (data.containsKey("coremodLocation")) {
            coremodLocation = (File) data.get("coremodLocation");
        }
    }

    @Override
    public Void call() throws Exception {
        System.out.println("PRELOADING XXX");
        System.out.println("coremodLocation = "+coremodLocation);

        System.exit(0); // for testing
        return null;
    }
}

package agaricus.mods.Jarmod2Coremod;

import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.relauncher.IFMLCallHook;

import java.io.File;
import java.util.Map;
import java.util.logging.Level;

public class Scanner implements IFMLCallHook {

    public File coremodLocation;

    /*
     * Gives the mod coremod data if it wants it.
     */
    @Override
    public void injectData(Map<String, Object> data) {
        if (data.containsKey("coremodLocation")) {
            coremodLocation = (File) data.get("coremodLocation");
        }
    }

    @Override
    public Void call() throws Exception {
        FMLLog.log(Level.INFO, "Jarmod2Coremod loading...");
        //FMLLog.log(Level.INFO, "coremodLocation = "+coremodLocation);

        File root, jarmodsDir;

        if (coremodLocation != null) {
            root = coremodLocation.getParentFile(); // root/coremods/us.jar -> root/coremods
            if (root != null) {
                root = root.getParentFile(); // root
            }
        } else {
            root = new File(".").getCanonicalFile();
        }

        jarmodsDir = new File(root.getCanonicalPath() + System.getProperty("file.separator") + "jarmods");
        jarmodsDir.mkdirs();

        FMLLog.log(Level.INFO, "jarmod directory: " + jarmodsDir);

        System.exit(0); // for testing
        return null;
    }
}

Create and locate 'jarmods' directory if it doesn't exist


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

public final class EnvironmentDefaults
{
    public static final String DOCKER_IMAGES_VERSION = "32";
    public static final String HADOOP_BASE_IMAGE = "prestodev/hdp2.6-hive";
    public static final String HADOOP_IMAGES_VERSION = DOCKER_IMAGES_VERSION;
    public static final String TEMPTO_ENVIRONMENT_CONFIG = "/dev/null";

    private EnvironmentDefaults() {}
}

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

public final class EnvironmentDefaults
{
    public static final String DOCKER_IMAGES_VERSION = "33";
    public static final String HADOOP_BASE_IMAGE = "prestodev/hdp2.6-hive";
    public static final String HADOOP_IMAGES_VERSION = DOCKER_IMAGES_VERSION;
    public static final String TEMPTO_ENVIRONMENT_CONFIG = "/dev/null";

    private EnvironmentDefaults() {}
}

Update docker images to version 33

Update docker images to version 33


package sg.ncl.service.authentication.controllers;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import sg.ncl.service.authentication.AuthenticationService;

import javax.inject.Inject;

/**
 * @author Christopher Zhong
 */
@RestController
@RequestMapping(path = "/authentication", produces = MediaType.APPLICATION_JSON_VALUE)
public class AuthenticationController {

    private final AuthenticationService authenticationService;

    @Inject
    protected AuthenticationController(final AuthenticationService authenticationService) {
        this.authenticationService = authenticationService;
    }

    @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public String login(@RequestHeader("X-Username") String username, @RequestHeader("X-Password") String password) {
        return authenticationService.login(username, password);
    }

    @RequestMapping(method = RequestMethod.DELETE)
    public void logout() {
        authenticationService.logout();
    }

}

package sg.ncl.service.authentication.controllers;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import sg.ncl.common.exceptions.BadRequestException;
import sg.ncl.service.authentication.AuthenticationService;

import javax.inject.Inject;

/**
 * @author Christopher Zhong
 */
@RestController
@RequestMapping(path = "/authentication", produces = MediaType.APPLICATION_JSON_VALUE)
public class AuthenticationController {

    private final AuthenticationService authenticationService;

    @Inject
    protected AuthenticationController(final AuthenticationService authenticationService) {
        this.authenticationService = authenticationService;
    }

    @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public String login(@RequestHeader("X-Username") String username, @RequestHeader("X-Password") String password) {
        if (username.isEmpty() || password.isEmpty()) {
            throw new BadRequestException();
        }
        return authenticationService.login(username, password);
    }

    @RequestMapping(method = RequestMethod.DELETE)
    public void logout() {
        authenticationService.logout();
    }

}

Add error checking to username and password (DEV-99)