repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
ReunionDev/reunion | jreunion/src/main/java/org/reunionemu/jreunion/game/items/ItemPlaceHolder.java | 418 | package org.reunionemu.jreunion.game.items;
import org.reunionemu.jreunion.game.PlayerItem;
/**
* @author Aidamina
* @license http://reunion.googlecode.com/svn/trunk/license.txt
*/
public class ItemPlaceHolder extends PlayerItem{
public ItemPlaceHolder(int id) {
super(id);
loadFromReference(id);
}
@Override
public void loadFromReference(int id) {
super.loadFromReference(id);
}
} | gpl-3.0 |
hqnghi88/gamaClone | msi.gama.core/src/msi/gama/common/util/RandomUtils.java | 16064 | /*********************************************************************************************
*
* 'RandomUtils.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and simulation platform.
* (c) 2007-2016 UMI 209 UMMISCO IRD/UPMC & Partners
*
* Visit https://github.com/gama-platform/gama for license information and developers contact.
*
*
**********************************************************************************************/
package msi.gama.common.util;
import java.math.BigDecimal;
import java.security.SecureRandom;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import msi.gama.common.interfaces.IKeyword;
import msi.gama.common.preferences.GamaPreferences;
import msi.gama.util.random.CellularAutomatonRNG;
import msi.gama.util.random.GamaRNG;
import msi.gama.util.random.JavaRNG;
import msi.gama.util.random.MersenneTwisterRNG;
import msi.gaml.operators.Maths;
import msi.gaml.operators.fastmaths.FastMath;
@SuppressWarnings ({ "rawtypes", "unchecked" })
public class RandomUtils {
/** The seed. */
protected Double seed;
private static final SecureRandom SEED_SOURCE = new SecureRandom();
/** The generator name. */
private String generatorName;
/** The generator. */
private GamaRNG generator;
public static class State {
public State(final Double seed, final String generatorName, final int usage) {
this.seed = seed;
this.generatorName = generatorName;
this.usage = usage;
}
Double seed;
String generatorName;
int usage;
}
public RandomUtils(final State state) {
setState(state);
}
public RandomUtils(final Double seed, final String rng) {
setSeed(seed, false);
setGenerator(rng, true);
}
public RandomUtils(final String rng) {
this(GamaPreferences.External.CORE_SEED_DEFINED.getValue() ? GamaPreferences.External.CORE_SEED.getValue()
: (Double) null, rng);
}
public RandomUtils() {
this(GamaPreferences.External.CORE_RNG.getValue());
}
public State getState() {
return new State(seed, generatorName, generator.getUsage());
}
public void setState(final State state) {
setSeed(state.seed, false);
setGenerator(state.generatorName, true);
generator.setUsage(state.usage);
}
/**
* Inits the generator.
*/
private void initGenerator() {
if (generatorName.equals(IKeyword.CELLULAR)) {
generator = new CellularAutomatonRNG(this);
} else if (generatorName.equals(IKeyword.JAVA)) {
generator = new JavaRNG(this);
} else {
/* By default */
generator = new MersenneTwisterRNG(this);
}
}
public void setUsage(final Integer usage) {
generator.setUsage(usage);
}
public Integer getUsage() {
return generator.getUsage();
}
/**
* Creates a new Continuous Uniform Generator object.
*
* @param min
* the min
* @param max
* the max
*
* @return the continuous uniform generator
*/
public double createUniform(final double min, final double max) {
return next() * (max - min) + min;
}
/**
* Creates a new Gaussian Generator object.
*
* @param mean
* the mean
* @param stdv
* the stdv
*
* @return the gaussian generator
*/
public double createGaussian(final double mean, final double stdv) {
return generator.nextGaussian() * stdv + mean;
}
/**
* Creates a new Binomial Generator object.
*
* @param n
* the n
* @param p
* the p
*
* @return the binomial generator
*/
public int createBinomial(final int n, final double p) {
double value = p;
final StringBuilder bits = new StringBuilder(64);
double bitValue = 0.5d;
while (value > 0) {
if (value >= bitValue) {
bits.append('1');
value -= bitValue;
} else {
bits.append('0');
}
bitValue /= 2;
}
final BitString pBits = new BitString(bits.toString());
int trials = n;
int totalSuccesses = 0;
int pIndex = pBits.getLength() - 1;
while (trials > 0 && pIndex >= 0) {
final BitString bs = new BitString(trials, generator);
final int successes = bs.countSetBits();
trials -= successes;
if (pBits.getBit(pIndex)) {
totalSuccesses += successes;
}
--pIndex;
}
return totalSuccesses;
}
/**
* Creates a new Poisson Generator object.
*
* @param mean
* the mean
*
* @return the poisson generator
*/
public int createPoisson(final double mean) {
int x = 0;
double t = 0.0;
while (true) {
t -= Math.log(next()) / mean;
if (t > 1.0) {
break;
}
++x;
}
return x;
}
public static boolean USE_BITWISE = true;
private byte[] createSeed(final Double s, final int length) {
this.seed = s;
Double realSeed = seed;
if (realSeed < 0) {
realSeed *= -1;
}
if (realSeed < 1) {
realSeed *= Long.MAX_VALUE;
}
long l;
if (!USE_BITWISE)
l = realSeed.longValue();
else
l = Double.doubleToRawLongBits(realSeed);
final byte[] result = new byte[length];
switch (length) {
case 4:
for (int i1 = 0; i1 < 4; i1++) {
result[i1] = (byte) (l & 0xff);
l >>= 8;
}
break;
case 8:
for (int i = 0; i < 8; i++) {
result[i] = (byte) l;
l >>= 8;
}
break;
case 16:
for (int i = 0; i < 8; i++) {
result[i] = result[i + 8] = (byte) (l & 0xff);
l >>= 8;
}
}
return result;
}
public void dispose() {
seed = null;
generator = null;
}
public byte[] generateSeed(final int length) {
return createSeed(seed, length);
}
public void setSeed(final Double newSeed, final boolean init) {
seed = newSeed;
if (seed == null) {
seed = SEED_SOURCE.nextDouble();
}
if (init) {
initGenerator();
}
}
/**
* Sets the generator.
*
* @param newGen
* the new generator
*/
public void setGenerator(final String newGen, final boolean init) {
generatorName = newGen;
if (init) {
initGenerator();
}
}
public void shuffle2(final Collection list) {
final int size = list.size();
if (size < 2) { return; }
final Object[] a = list.toArray(new Object[size]);
list.clear();
for (int i = 0; i < size; i++) {
final int change = between(i, size - 1);
final Object helper = a[i];
a[i] = a[change];
a[change] = helper;
list.add(a[i]);
}
}
public List shuffle(final List list) {
for (int i = list.size(); i > 1; i--) {
final int i1 = i - 1;
final int j = between(0, i - 1);
final Object tmp = list.get(i1);
list.set(i1, list.get(j));
list.set(j, tmp);
}
return list;
}
public String shuffle(final String string) {
final char[] c = string.toCharArray();
shuffle(c);
return String.copyValueOf(c);
}
public <T> T[] shuffle(final T[] array) {
final T[] copy = array.clone();
for (int i = array.length; i > 1; i--) {
final int i1 = i - 1;
final int j = between(0, i - 1);
final T tmp = copy[i1];
copy[i1] = copy[j];
copy[j] = tmp;
}
return copy;
}
/**
* @return an uniformly distributed int random number in [from, to]
*/
public int between(final int min, final int max) {
return (int) (min + (long) ((1L + max - min) * next()));
}
public double between(final double min, final double max) {
// uniformly distributed double random number in [min, max]
return min + (max + Double.MIN_VALUE - min) * next();
}
/**
* @return an uniformly distributed int random number in [min, max] respecting the step
*/
public int between(final int min, final int max, final int step) {
final int nbSteps = (max - min) / step;
return min + between(0, nbSteps) * step;
}
public double between(final double min, final double max, final double step) {
// uniformly distributed double random number in [min, max] respecting
// the step
final double val = between(min, max);
final int nbStep = (int) ((val - min) / step);
final double valSup = FastMath.min(max, min + (nbStep + 1.0) * step);
final double valMin = min + nbStep * step;
final int precision = BigDecimal.valueOf(step).scale() + 5;
final double high = Maths.round(valSup, precision);
final double low = Maths.round(valMin, precision);
return val - low < high - val ? low : high;
}
public double next() {
return generator.nextDouble();
}
public int nextInt() {
return generator.nextInt();
}
/**
* @param matrix
* @return
*/
public double[] shuffle(final double[] array) {
for (int i = array.length; i > 1; i--) {
final int i1 = i - 1;
final int j = between(0, i - 1);
final double tmp = array[i1];
array[i1] = array[j];
array[j] = tmp;
}
return array;
}
public int[] shuffle(final int[] array) {
for (int i = array.length; i > 1; i--) {
final int i1 = i - 1;
final int j = between(0, i - 1);
final int tmp = array[i1];
array[i1] = array[j];
array[j] = tmp;
}
return array;
}
public char[] shuffle(final char[] array) {
for (int i = array.length; i > 1; i--) {
final int i1 = i - 1;
final int j = between(0, i - 1);
final char tmp = array[i1];
array[i1] = array[j];
array[j] = tmp;
}
return array;
}
/**
* @return
*/
public Double getSeed() {
return seed;
}
/**
* @return
*/
public String getRngName() {
return generatorName;
}
public static void testDrawRandomValues(final double min, final double max, final double step) {
System.out.println("Drawing 100 double between " + min + " and " + max + " step " + step);
final RandomUtils r = new RandomUtils(100.0, "mersenne");
for (int i = 0; i < 100; i++) {
final double val = r.between(min, max);
final int nbStep = (int) ((val - min) / step);
final double high = (int) (FastMath.min(max, min + (nbStep + 1.0) * step) * 1000000) / 1000000.0;
final double low = (int) ((min + nbStep * step) * 1000000) / 1000000.0;
System.out.print(val - low < high - val ? low : high);
System.out.print(" | ");
}
System.out.println();
}
public static void testDrawRandomValues(final int min, final int max, final int step) {
System.out.println("Drawing 100 int between " + min + " and " + max + " step " + step);
final RandomUtils r = new RandomUtils(100.0, "mersenne");
final int nbSteps = (max - min) / step;
for (int i = 0; i < 100; i++) {
final int val = min + r.between(0, nbSteps) * step;
System.out.print(val);
System.out.print(" | ");
}
System.out.println();
}
private class BitString {
private static final int WORD_LENGTH = 32;
private final int length;
/**
* Store the bits packed in an array of 32-bit ints. This field cannot be declared final because it must be
* cloneable.
*/
private final int[] data;
/**
* Creates a bit string of the specified length with all bits initially set to zero (off).
*
* @param length
* The number of bits.
*/
public BitString(final int length) {
if (length < 0) { throw new IllegalArgumentException("Length must be non-negative."); }
this.length = length;
this.data = new int[(length + WORD_LENGTH - 1) / WORD_LENGTH];
}
/**
* Creates a bit string of the specified length with each bit set randomly (the distribution of bits is uniform
* so long as the output from the provided RNG is also uniform). Using this constructor is more efficient than
* creating a bit string and then randomly setting each bit individually.
*
* @param length
* The number of bits.
* @param rng
* A source of randomness.
*/
public BitString(final int length, final Random rng) {
this(length);
// We can set bits 32 at a time rather than calling
// rng.nextBoolean()
// and setting each one individually.
for (int i = 0; i < data.length; i++) {
data[i] = rng.nextInt();
}
// If the last word is not fully utilised, zero any out-of-bounds
// bits.
// This is necessary because the countSetBits() methods will count
// out-of-bounds bits.
final int bitsUsed = length % WORD_LENGTH;
if (bitsUsed < WORD_LENGTH) {
final int unusedBits = WORD_LENGTH - bitsUsed;
final int mask = 0xFFFFFFFF >>> unusedBits;
data[data.length - 1] &= mask;
}
}
/**
* Initialises the bit string from a character string of 1s and 0s in big-endian order.
*
* @param value
* A character string of ones and zeros.
*/
public BitString(final String value) {
this(value.length());
for (int i = 0; i < value.length(); i++) {
if (value.charAt(i) == '1') {
setBit(value.length() - (i + 1), true);
} else if (value
.charAt(i) != '0') { throw new IllegalArgumentException("Illegal character at position " + i); }
}
}
/**
* @return The length of this bit string.
*/
public int getLength() {
return length;
}
/**
* Returns the bit at the specified index.
*
* @param index
* The index of the bit to look-up (0 is the least-significant bit).
* @return A boolean indicating whether the bit is set or not.
* @throws IndexOutOfBoundsException
* If the specified index is not a bit position in this bit string.
*/
public boolean getBit(final int index) {
assertValidIndex(index);
final int word = index / WORD_LENGTH;
final int offset = index % WORD_LENGTH;
return (data[word] & 1 << offset) != 0;
}
/**
* Sets the bit at the specified index.
*
* @param index
* The index of the bit to set (0 is the least-significant bit).
* @param set
* A boolean indicating whether the bit should be set or not.
* @throws IndexOutOfBoundsException
* If the specified index is not a bit position in this bit string.
*/
public void setBit(final int index, final boolean set) {
assertValidIndex(index);
final int word = index / WORD_LENGTH;
final int offset = index % WORD_LENGTH;
if (set) {
data[word] |= 1 << offset;
} else // Unset the bit.
{
data[word] &= ~(1 << offset);
}
}
/**
* Helper method to check whether a bit index is valid or not.
*
* @param index
* The index to check.
* @throws IndexOutOfBoundsException
* If the index is not valid.
*/
private void assertValidIndex(final int index) {
if (index >= length || index < 0) { throw new IndexOutOfBoundsException(
"Invalid index: " + index + " (length: " + length + ")"); }
}
/**
* @return The number of bits that are 1s rather than 0s.
*/
public int countSetBits() {
int count = 0;
for (int x : data) {
while (x != 0) {
x &= x - 1; // Unsets the least significant on bit.
++count; // Count how many times we have to unset a bit
// before x equals zero.
}
}
return count;
}
}
public GamaRNG getGenerator() {
return generator;
}
public static void main(final String[] args) {
USE_BITWISE = false;
RandomUtils r1 = new RandomUtils(1.0, "mersenne1");
RandomUtils r2 = new RandomUtils(1.0 * Math.pow(10, -50), "mersenne2");
RandomUtils r3 = new RandomUtils(1.1 * Math.pow(10, -50), "mersenne3");
for (int i = 0; i < 3; i++) {
System.out.println("r1 " + r1.nextInt() + " | r2 " + r2.nextInt() + " | r3 " + r3.nextInt());
}
USE_BITWISE = true;
r1 = new RandomUtils(1.0, "mersenne1");
r2 = new RandomUtils(1.0 * Math.pow(10, -50), "mersenne2");
r3 = new RandomUtils(1.1 * Math.pow(10, -50), "mersenne3");
for (int i = 0; i < 3; i++) {
System.out.println("r1 " + r1.nextInt() + " | r2 " + r2.nextInt() + " | r3 " + r3.nextInt());
}
}
}
| gpl-3.0 |
DavePearce/Pacman | pacman/ui/Board.java | 12679 | // This file is part of the Multi-player Pacman Game.
//
// Pacman is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 3 of the License,
// or (at your option) any later version.
//
// Pacman is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
// the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public
// License along with Pacman. If not, see <http://www.gnu.org/licenses/>
//
// Copyright 2010, David James Pearce.
package pacman.ui;
import java.util.*;
import java.io.*;
import pacman.game.Character;
import pacman.game.Disappear;
import pacman.game.Ghost;
import pacman.game.HomerGhost;
import pacman.game.MovingCharacter;
import pacman.game.Pacman;
import pacman.game.RandomGhost;
/**
* The board class represents the pacman game board. This class is used by the
* Character threads to move, and generally interact with each other.
*
* @author djp
*
*/
public class Board {
private final int width;
private final int height;
public static final int WAITING = 0;
public static final int READY = 1;
public static final int PLAYING = 2;
public static final int GAMEOVER = 3;
public static final int GAMEWON = 4;
private int state; // this is used to tell us what state we're in.
private int nPillsRemaining; // this is used to count the number of remaining pills
/**
* The following stores the locations in the grid of all walls. It is
* effectively implemented as a 2D grid of bits, where each bit represents a
* wall.
*/
private BitSet walls;
/**
* The following stores the locations in the grid of all pills. It is
* effectively implemented as a 2D grid of bits, where each bit represents a
* wall.
*/
private BitSet pills;
/**
* The following is a list of one dimension integer arrays, which are
* guaranteed to be of length 2. The first element gives the x-component of
* the portal, the second component gives the y-component.
*/
private final ArrayList<int[]> pacmanPortals = new ArrayList<int[]>();
private int nextPacPortal = 0; // identify the next portal to be used
/**
* The following is a list of one dimension integer arrays, which are
* guaranteed to be of length 2. The first element gives the x-component of
* the portal, the second component gives the y-component.
*/
private final ArrayList<int[]> ghostPortals = new ArrayList<int[]>();
private int nextGhostPortal = 0; // identify the next portal to be used
/**
* The following is a list of the characters in the game. This includes
* pacmen, ghosts and other misc things.
*/
private final ArrayList<Character> characters = new ArrayList<Character>();
public Board(int width, int height) {
this.width = width;
this.height = height;
this.walls = new BitSet();
this.pills = new BitSet();
}
/**
* Get the board width.
* @return
*/
public int width() {
return width;
}
/**
* Get the board height.
* @return
*/
public int height() {
return height;
}
/**
* The following constants determine the possible fixed-object types.
*/
public final static int NOUT = 0;
public final static int WALL = 1;
public boolean isPill(int x, int y) {
return pills.get(x + (y*width));
}
public void addPill(int x, int y) {
nPillsRemaining++;
pills.set(x + (y*width));
}
public void eatPill(int x, int y) {
nPillsRemaining--;
pills.clear(x + (y*width));
}
public boolean isWall(int x, int y) {
return walls.get(x + (y*width));
}
public void addWall(int x, int y) {
walls.set(x + (y*width));
}
/**
* The UID is a unique identifier for all characters in the game. This is
* required in order to synchronise the movements of different players
* across boards.
*/
private static int uid = 0;
/**
* Register a new pacman portal on the board. A pacman portal is a place
* where pacman will appear from.
*
* @param x
* @param y
*/
public synchronized void registerPacPortal(int x, int y) {
pacmanPortals.add(new int[]{x,y});
}
/**
* Register a new pacman into the game. The Pacman will be placed onto the
* next available portal.
*
* @return
*/
public synchronized int registerPacman() {
int[] portal = pacmanPortals.get(nextPacPortal);
nextPacPortal = (nextPacPortal + 1) % pacmanPortals.size();
Character r = new Pacman(portal[0] * 30, portal[1] * 30,
MovingCharacter.STOPPED, ++uid, 3, 0);
characters.add(r);
return uid;
}
/**
* A pre-registered pacman has died, but wants to come back to life.
* Therefore, allocate it the next available pacman portal.
*
* @return
*/
public int[] respawnPacman() {
int[] portal = pacmanPortals.get(nextPacPortal);
nextPacPortal = (nextPacPortal + 1) % pacmanPortals.size();
return portal;
}
/**
* Register a new ghost portal on the board. A ghost portal is a place
* where ghosts will appear from.
*
* @param x
* @param y
*/
public synchronized void registerGhostPortal(int x, int y) {
ghostPortals.add(new int[]{x,y});
}
/**
* Register a new ghost into the game. The ghost will be placed into the
* next available ghost portal.
*
* @param homer --- is this a homing ghost or not?
*/
public synchronized void registerGhost(boolean homer) {
int[] portal = ghostPortals.get(nextGhostPortal);
nextGhostPortal = (nextGhostPortal + 1) % ghostPortals.size();
Character r;
if(homer) {
r = new HomerGhost(portal[0]*30,portal[1]*30);
} else {
r = new RandomGhost(portal[0]*30,portal[1]*30);
}
characters.add(r);
}
public synchronized void removeCharacter(Character character) {
for(int i=0;i!=characters.size();++i) {
Character p = characters.get(i);
if(character == p) {
// NOTE: we can't call remove here, since this results in a
// concurrent modification exception, as this method will be
// called indirectly from the clockTick() method.
characters.set(i,null);
return;
}
}
}
public synchronized void disconnectPlayer(int uid) {
for(int i=0;i!=characters.size();++i) {
Character p = characters.get(i);
if (p instanceof Pacman && ((Pacman) p).uid() == uid) {
characters.set(i, new Disappear(p.realX(), p.realY(),0));
}
}
}
public synchronized Pacman player(int uid) {
for(Character p : characters) {
if (p instanceof Pacman && ((Pacman) p).uid() == uid) {
return (Pacman) p;
}
}
throw new IllegalArgumentException("Invalid Character UID");
}
/**
* Iterate the characters in the game
* @return
*/
public List<Character> characters() {
return characters;
}
/**
* Get current board state.
* @return
*/
public int state() {
return state;
}
/**
* Set the board state.
* @param state
*/
public void setState(int state) {
this.state = state;
}
public boolean canMoveUp(MovingCharacter p) {
int realX = p.realX();
int realY = p.realY();
realY -= p.speed();
int ny = realY / 30;
int nx = (realX+15)/30;
return !isWall(nx,ny);
}
public boolean canMoveDown(MovingCharacter p) {
int realX = p.realX();
int realY = p.realY();
realY += 5;
int ny = realY / 30;
if(realY % 30 != 0) { ny++; }
int nx = (realX+15)/30;
return !isWall(nx,ny);
}
public boolean canMoveLeft(MovingCharacter p) {
int realX = p.realX();
int realY = p.realY();
realX -= 5;
int nx = realX / 30;
int ny = (realY+15)/30;
return !isWall(nx,ny);
}
public boolean canMoveRight(MovingCharacter p) {
int realX = p.realX();
int realY = p.realY();
realX += 5;
int nx = realX / 30;
if(realX % 30 != 0) { nx++; }
int ny = (realY+15)/30;
return !isWall(nx,ny);
}
/**
* The clock tick is essentially a clock trigger, which allows the board to
* update the current state. The frequency with which this is called
* determines the rate at which the game state is updated.
*
* @return
*/
public synchronized void clockTick() {
if (state != PLAYING && state != GAMEOVER) {
return; // do nothing unless the game is active.
}
ArrayList<Character> ghosts = new ArrayList<Character>();
int nplayers = 0;
for(int i=0;i!=characters.size();++i) {
Character p = characters.get(i);
p.tick(this);
// reread p, since it might be gone now ...
p = characters.get(i);
if(p == null) {
// dead character encountered, remove it.
characters.remove(i--);
continue;
}
if (p instanceof Ghost) {
ghosts.add(p);
}
}
// Now, perform collision detection to see if any PACMEN have collided
// with ghosts.
for (int i = 0; i != characters.size(); ++i) {
Character c = characters.get(i);
int px = (c.realX() + 15) / 30;
int py = (c.realY() + 15) / 30;
if (c instanceof Pacman) {
Pacman p = (Pacman) c;
if(!p.isDead()) { nplayers++; }
if(p.isDead() || p.isDying()) { continue; }
for (Character g : ghosts) {
int gx = (g.realX() + 15) / 30;
int gy = (g.realY() + 15) / 30;
if (px == gx && py == gy) {
// pacman and ghost have collided ...
// So, replace pacman with disappearing character
p.markAsDying();
}
}
}
}
if (nplayers == 0) {
state = GAMEOVER;
} else if(nPillsRemaining == 0) {
state = GAMEWON;
}
}
/**
* The following method accepts a byte array representing the state of a
* pacman board; this state will be broadcast by a master connection, and is
* then used to overwrite the current state (since it should be more up to
* date).
*
* @param bytes
*/
public synchronized void fromByteArray(byte[] bytes) throws IOException {
ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
DataInputStream din = new DataInputStream(bin);
state = din.readByte();
// Second, update pills
int bitwidth = width%8 == 0 ? width : width+8;
int bitsize = (bitwidth/8)*height;
byte[] pillBytes = new byte[bitsize];
din.read(pillBytes);
pills = bitsFromByteArray(pillBytes);
nPillsRemaining = pills.cardinality();
// Third, update characters
int ncharacters = din.readInt();
characters.clear();
for(int i=0;i!=ncharacters;++i) {
characters.add(Character.fromInputStream(din));
}
}
/**
* The following method accepts a byte array representation of the board
* walls. This is broadcast by a master connection when the connection is
* established.
*
* @param bytes
*/
public synchronized void wallsFromByteArray(byte[] bytes) {
walls = bitsFromByteArray(bytes);
}
/**
* Read a bit set from a byte array.
*/
private static BitSet bitsFromByteArray(byte[] bytes) {
BitSet bits = new BitSet();
for (int i = 0; i < bytes.length * 8; i++) {
int offset = i >> 3;
if ((bytes[offset] & (1 << (i % 8))) > 0) {
bits.set(i);
}
}
return bits;
}
/**
* The following method converts the current state of the board into a byte
* array, such that it can be shipped across a connection to an awaiting
* client.
*
* @return
*/
public synchronized byte[] toByteArray() throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
dout.writeByte(state);
// First, write output locations of remaining pills
int bitwidth = width%8 == 0 ? width : width+8;
int bitsize = (bitwidth/8)*height;
byte[] pillBytes = new byte[bitsize];
bitsToByteArray(pills,pillBytes);
dout.write(pillBytes);
dout.writeInt(characters.size());
for(Character p : characters) {
p.toOutputStream(dout);
}
dout.flush();
// Finally, return!!
return bout.toByteArray();
}
/**
* The following method generates a byte array representation of the walls
* in the board. This is broadcast by a master connection when that
* connection is established.
*
* @return
*/
public synchronized byte[] wallsToByteArray() {
// First, write output locations of remaining pills
int bitwidth = width%8 == 0 ? width : width+8;
int bitsize = (bitwidth/8)*height;
byte[] wallBytes = new byte[bitsize];
bitsToByteArray(walls,wallBytes);
return wallBytes;
}
/**
* Create a byte array from a bit set
*/
private static byte[] bitsToByteArray(BitSet bits, byte[] bytes) {
for (int i=0; i<bits.length(); i++) {
int offset = i >> 3;
if (bits.get(i) && offset < bytes.length) {
bytes[offset] |= 1<<(i%8);
}
}
return bytes;
}
}
| gpl-3.0 |
ReunionDev/reunion | jreunion/src/main/java/org/reunionemu/jreunion/game/items/AssemblingPart.java | 413 | package org.reunionemu.jreunion.game.items;
import org.reunionemu.jreunion.game.items.etc.Etc;
/**
* @author Aidamina
* @license http://reunion.googlecode.com/svn/trunk/license.txt
*/
public class AssemblingPart extends Etc {
public AssemblingPart(int id) {
super(id);
loadFromReference(id);
}
@Override
public void loadFromReference(int id) {
super.loadFromReference(id);
}
} | gpl-3.0 |
cameronleger/neural-style-gui | src/main/java/com/cameronleger/neuralstylegui/helper/TextAreaLogHandler.java | 1044 | package com.cameronleger.neuralstylegui.helper;
import javafx.application.Platform;
import javafx.scene.control.TextArea;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.logging.LogRecord;
import java.util.logging.StreamHandler;
public class TextAreaLogHandler extends StreamHandler {
private TextArea textArea = null;
private final DateTimeFormatter formatter =
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.MEDIUM)
.withZone(ZoneId.systemDefault());
public TextAreaLogHandler(TextArea textArea) {
this.textArea = textArea;
}
@Override
public void publish(LogRecord record) {
super.publish(record);
if (textArea != null) {
Platform.runLater(() -> textArea.appendText(String.format(
"[%s] %s\n",
formatter.format(record.getInstant()),
record.getMessage()
)));
}
}
}
| gpl-3.0 |
j3l11234/swiftp | app/src/main/java/be/ppareit/swiftp/gui/MainActivity.java | 5618 | /*******************************************************************************
* Copyright (c) 2012-2013 Pieter Pareit.
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* <p>
* Contributors:
* Pieter Pareit - initial API and implementation
******************************************************************************/
package be.ppareit.swiftp.gui;
import android.Manifest;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import net.vrallev.android.cat.Cat;
import java.util.Arrays;
import be.ppareit.swiftp.App;
import be.ppareit.swiftp.BuildConfig;
import be.ppareit.swiftp.FsSettings;
import be.ppareit.swiftp.R;
/**
* This is the main activity for swiftp, it enables the user to start the server service
* and allows the users to change the settings.
*/
public class MainActivity extends AppCompatActivity {
final static int PERMISSIONS_REQUEST_CODE = 12;
@Override
public void onCreate(Bundle savedInstanceState) {
Cat.d("created");
setTheme(FsSettings.getTheme());
super.onCreate(savedInstanceState);
if (VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED ||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_CODE);
}
}
if (App.isFreeVersion() && App.isPaidVersionInstalled()) {
Cat.d("Running demo while paid is installed");
AlertDialog ad = new AlertDialog.Builder(this)
.setTitle(R.string.demo_while_paid_dialog_title)
.setMessage(R.string.demo_while_paid_dialog_message)
.setPositiveButton(getText(android.R.string.ok), (d, w) -> finish())
.create();
ad.show();
}
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new PreferenceFragment())
.commit();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode != PERMISSIONS_REQUEST_CODE) {
Cat.e("Unhandled request code");
return;
}
Cat.d("permissions: " + Arrays.toString(permissions));
Cat.d("grantResults: " + Arrays.toString(grantResults));
if (grantResults.length > 0) {
// Permissions not granted, close down
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, R.string.unable_to_proceed_no_permissions, Toast.LENGTH_LONG).show();
finish();
}
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_feedback) {
String to = "pieter.pareit@gmail.com";
String subject = "FTP Server feedback";
String message = "Device: " + Build.MODEL + "\n" +
"Android version: " + VERSION.RELEASE + "-" + VERSION.SDK_INT + "\n" +
"Application: " + BuildConfig.APPLICATION_ID + " (" + BuildConfig.FLAVOR + ")\n" +
"Application version: " + BuildConfig.VERSION_NAME + " - " + BuildConfig.VERSION_CODE + "\n" +
"Feedback: \n_";
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{to});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, message);
emailIntent.setType("message/rfc822");
try {
startActivity(emailIntent);
Toast.makeText(this, R.string.use_english, Toast.LENGTH_LONG).show();
} catch (ActivityNotFoundException exception) {
Toast.makeText(this, R.string.unable_to_start_mail_client, Toast.LENGTH_LONG).show();
}
} else if (item.getItemId() == R.id.action_about) {
startActivity(new Intent(this, AboutActivity.class));
}
return true;
}
}
| gpl-3.0 |
philreindl/Universal-G-Code-Sender | ugs-core/src/com/willwinder/universalgcodesender/pendantui/SystemStateBean.java | 4483 | package com.willwinder.universalgcodesender.pendantui;
import com.willwinder.universalgcodesender.model.UGSEvent.ControlState;
public class SystemStateBean {
private ControlState controlState = ControlState.COMM_DISCONNECTED;
private String fileName = "";
private String latestComment = "";
private String activeState = "";
private String workX = "0";
private String workY = "0";
private String workZ = "0";
private String machineX = "0";
private String machineY = "0";
private String machineZ = "0";
private String rowsInFile = "0";
private String sentRows = "0";
private String remainingRows = "0";
private String estimatedTimeRemaining = "--:--:--";
private String duration = "00:00:00";
private String sendButtonText = "Send";
private boolean sendButtonEnabled = false;
private String pauseResumeButtonText = "Pause";
private boolean pauseResumeButtonEnabled = false;
private String cancelButtonText = "Cancel";
private boolean cancelButtonEnabled = false;
public SystemStateBean() {
}
public ControlState getControlState() {
return controlState;
}
public void setControlState(ControlState controlState) {
this.controlState = controlState;
}
public String getActiveState() {
return activeState;
}
public void setActiveState(String activeState) {
this.activeState = activeState;
}
public String getWorkX() {
return workX;
}
public void setWorkX(String workX) {
this.workX = workX;
}
public String getWorkY() {
return workY;
}
public void setWorkY(String workY) {
this.workY = workY;
}
public String getWorkZ() {
return workZ;
}
public void setWorkZ(String workZ) {
this.workZ = workZ;
}
public String getMachineX() {
return machineX;
}
public void setMachineX(String machineX) {
this.machineX = machineX;
}
public String getMachineY() {
return machineY;
}
public void setMachineY(String machineY) {
this.machineY = machineY;
}
public String getMachineZ() {
return machineZ;
}
public void setMachineZ(String machineZ) {
this.machineZ = machineZ;
}
public String getRowsInFile() {
return rowsInFile;
}
public void setRowsInFile(String rowsInFile) {
this.rowsInFile = rowsInFile;
}
public String getSentRows() {
return sentRows;
}
public void setSentRows(String sentRows) {
this.sentRows = sentRows;
}
public String getRemainingRows() {
return remainingRows;
}
public void setRemainingRows(String remainingRows) {
this.remainingRows = remainingRows;
}
public String getEstimatedTimeRemaining() {
return estimatedTimeRemaining;
}
public void setEstimatedTimeRemaining(String estimatedTimeRemaining) {
this.estimatedTimeRemaining = estimatedTimeRemaining;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
String fileSeparator = System.getProperty("file.separator");
if(fileName.contains(fileSeparator)){
this.fileName = fileName.substring(fileName.lastIndexOf(fileSeparator)+1);
} else {
this.fileName = fileName;
}
}
public String getLatestComment() {
return latestComment;
}
public void setLatestComment(String lastComment) {
this.latestComment = lastComment;
}
public boolean isSendButtonEnabled() {
return sendButtonEnabled;
}
public void setSendButtonEnabled(boolean sendButtonEnabled) {
this.sendButtonEnabled = sendButtonEnabled;
}
public boolean isPauseResumeButtonEnabled() {
return pauseResumeButtonEnabled;
}
public void setPauseResumeButtonEnabled(boolean pauseResumeButtonEnabled) {
this.pauseResumeButtonEnabled = pauseResumeButtonEnabled;
}
public boolean isCancelButtonEnabled() {
return cancelButtonEnabled;
}
public void setCancelButtonEnabled(boolean cancelButtonEnabled) {
this.cancelButtonEnabled = cancelButtonEnabled;
}
public String getPauseResumeButtonText() {
return pauseResumeButtonText;
}
public void setPauseResumeButtonText(String pauseResumeButtonText) {
this.pauseResumeButtonText = pauseResumeButtonText;
}
public String getSendButtonText() {
return sendButtonText;
}
public void setSendButtonText(String sendButtonText) {
this.sendButtonText = sendButtonText;
}
public String getCancelButtonText() {
return cancelButtonText;
}
public void setCancelButtonText(String cancelButtonText) {
this.cancelButtonText = cancelButtonText;
}
}
| gpl-3.0 |
DesmondAssis/codebase | src/main/java/com/desmond/codebase/string/RegexUtil.java | 5119 | package com.desmond.codebase.string;
import com.desmond.codebase.number.NumberUtil;
import org.apache.commons.lang3.math.NumberUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.desmond.codebase.print.Print.printnb;
/**
* Created by Li.Xiaochuan on 15/10/28.
*/
public class RegexUtil {
public static int size = 0;
public static void main(String[] args) {
// find();
// testMatch();
testFfetch();
}
private static void testFfetch() {
fetch("type= \"push_marketing1\";");
fetch(" type= \"push_marketing2\";");
fetch(" type =\"push_marketing3\";");
fetch(" type = \"push_marketing4\" ;");
fetch(" type = \"push_marketing5\"; ");
}
public static String fetch(String str) {
String regex = "\\w*type\\s*=\\s*\\\"\\w*\\\"\\s*;";
String r = fetchType(regex, str);
if(StringUtils.isNotBlank(r)) {
size ++;
regex = "\\\"\\w*\\\"";
return fetchType(regex, r);
}
return null;
}
private static String fetchType(String regex, String str) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
String result = "";
while (m.find()) {
result = m.group();
}
return result;
}
private static void find() {
String reg = "<h3.*?>([^<]+)<\\/h3>";
String imgReg = "<img\\s+([^>]*?src\\s*=\\s*\"[^\"]+\".*?)>";
String imgStr = "test<br><img src=\"http://cdn.wanzhoumo.com/data/public/activity" +
"/2015/06/05_38/14334912339677.gif\" data-ratio=\"1.44\">泸沽湖位于川sort西南";
String tr = "testt<h3>行程安排</h3><image src/><br>sdfdf<br><h3>第 1 天。</h3><h3>第 2 天:早收费)。</h3>tt";
String tr1 = "<h3>行程安排</h3><image src/><h3>第 1 天。</h3><h3>第 2 天:早收费)。</h3>tt";
String tr2 = "<br>testt<h3>行程安排</h3><br>test<image src/><h3>第 1 天。</h3><h3>第 2 天:早收费)。</h3>";
List<SplitVO> splitVOList = splitFunc(imgStr, imgReg);
for(SplitVO vo : splitVOList) {
printnb(vo.isMatched() + "=" + vo.getContent());
}
}
private static void testMatch() {
String url1 = "inapp://nearby",
url2 = "inapp://dailylist",
url3 = "inapp://calendar",
url4 = "https://m.wanzhoumo.com/topic/519",
url5 = "https://m.wanzhoumo.com/disney/list";
System.out.println(match(url1, "inapp://nearby"));
System.out.println(match(url2, "inapp://dailylist"));
System.out.println(match(url3, "inapp://calendar"));
System.out.println(match(url4, "/topic/[0-9]+"));
System.out.println(match(url5, "/disney/list"));
System.out.println(fetchTopicId(url4, "/topic/[0-9]+"));
}
public static int fetchTopicId(String str, String regex) {
if(StringUtils.isNotBlank(str)) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
while (m.find()) {
String numStr = m.group();
if(StringUtils.isNotBlank(numStr)) {
String[] args = numStr.split("/");
if(args.length == 3) {
return NumberUtil.toInt(args[2]);
}
}
}
}
return 0;
}
public static boolean match(String str, String regex) {
if(StringUtils.isNotBlank(str)) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
return m.find();
}
return false;
}
/**
* 内容分割,模仿: preg_split($preg, $str, -1, PREG_SPLIT_DELIM_CAPTURE)
* --from http://php.net/manual/zh/function.preg-split.php
* @param str
* @param regex
* @return
*/
public static List<SplitVO> splitFunc(String str, String regex) {
List<SplitVO> splitVOList = new ArrayList<>();
if(StringUtils.isNotBlank(str)) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
int start = 0;
while(m.find()) {
String content = str.substring(start, m.start());
if(StringUtils.isNotBlank(content)) {
splitVOList.add(new SplitVO(false, content));
}
splitVOList.add(new SplitVO(true, m.group(1)));
start = m.end();
}
String content = str.substring(start);
if(StringUtils.isNotBlank(content)) {
splitVOList.add(new SplitVO(false, content));
}
}
return splitVOList;
}
/**
* 将html转化为指定格式。场景:将活动内容切分title/text/image
* @author Jason
* @param str
* @return
*/
public static String strToRichContent(String str) {
return null;
}
}
| gpl-3.0 |
ericrius1/SuperSumo | src/com/dozingcatsoftware/bouncy/Flock.java | 1389 |
package com.dozingcatsoftware.bouncy;
import java.util.ArrayList;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.box2d.Body;
public class Flock {
ArrayList<Ball> balls;
ArrayList<Body> ballBodies;
Camera cam;
Vector3 touchPoint;
Vector3 worldPoint;
public Flock (Camera cam) {
balls = new ArrayList<Ball>();
ballBodies = new ArrayList<Body>();
this.cam = cam;
touchPoint = new Vector3();
}
void addBall (Ball b) {
balls.add(b);
ballBodies.add(b.body);
}
void run (GLFieldRenderer renderer) {
for (Ball b : balls) {
// if (Gdx.input.isTouched()) {
worldPoint = screenToViewport(Gdx.input.getX(), Gdx.input.getY());
b.attract(Field.player.body.getPosition().x, Field.player.body.getPosition().y);
// }
b.run(balls, renderer);
checkBallsOutOfBounds();
}
}
void removeBalls () {
for (int i = 0; i < balls.size(); i++) {
Ball ball = balls.get(i);
if (ball.destroy) {
ballBodies.remove(ball.body);
balls.remove(ball);
Player.score++;
}
}
}
public Vector3 screenToViewport (float x, float y) {
cam.unproject(touchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0));
return touchPoint;
}
public void checkBallsOutOfBounds () {
for (Ball b : balls) {
if (b.OutOfBounds()) {
b.destroy = true;
}
}
}
}
| gpl-3.0 |
sergmain/aiai | apps/metaheuristic/src/main/java/ai/metaheuristic/ai/processor/ProcessorService.java | 13758 | /*
* Metaheuristic, Copyright (C) 2017-2021, Innovation platforms, LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package ai.metaheuristic.ai.processor;
import ai.metaheuristic.ai.Enums;
import ai.metaheuristic.ai.Globals;
import ai.metaheuristic.ai.commons.dispatcher_schedule.DispatcherSchedule;
import ai.metaheuristic.ai.exceptions.BreakFromLambdaException;
import ai.metaheuristic.ai.exceptions.VariableProviderException;
import ai.metaheuristic.ai.processor.actors.UploadVariableService;
import ai.metaheuristic.ai.processor.data.ProcessorData;
import ai.metaheuristic.ai.processor.env.EnvService;
import ai.metaheuristic.ai.processor.sourcing.git.GitSourcingService;
import ai.metaheuristic.ai.processor.tasks.UploadVariableTask;
import ai.metaheuristic.ai.processor.variable_providers.VariableProvider;
import ai.metaheuristic.ai.processor.variable_providers.VariableProviderFactory;
import ai.metaheuristic.ai.utils.asset.AssetFile;
import ai.metaheuristic.ai.utils.asset.AssetUtils;
import ai.metaheuristic.ai.yaml.communication.dispatcher.DispatcherCommParamsYaml;
import ai.metaheuristic.ai.yaml.communication.keep_alive.KeepAliveRequestParamYaml;
import ai.metaheuristic.ai.yaml.communication.keep_alive.KeepAliveResponseParamYaml;
import ai.metaheuristic.ai.yaml.communication.processor.ProcessorCommParamsYaml;
import ai.metaheuristic.ai.yaml.metadata.MetadataParamsYaml;
import ai.metaheuristic.ai.yaml.processor_task.ProcessorTask;
import ai.metaheuristic.api.data.task.TaskParamsYaml;
import ai.metaheuristic.commons.yaml.env.EnvParamsYaml;
import ai.metaheuristic.commons.yaml.task.TaskParamsYamlUtils;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.NotImplementedException;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Service
@Slf4j
@Profile("processor")
@RequiredArgsConstructor
public class ProcessorService {
private final Globals globals;
private final ProcessorTaskService processorTaskService;
private final UploadVariableService uploadResourceActor;
private final MetadataService metadataService;
private final DispatcherLookupExtendedService dispatcherLookupExtendedService;
private final EnvService envService;
private final VariableProviderFactory resourceProviderFactory;
private final GitSourcingService gitSourcingService;
private final CurrentExecState currentExecState;
// @Value("${logging.file.name:#{null}}")
@Value("#{ T(ai.metaheuristic.ai.utils.EnvProperty).toFile( environment.getProperty('logging.file.name' )) }")
public File logFile;
KeepAliveRequestParamYaml.ReportProcessor produceReportProcessorStatus(ProcessorData.ProcessorCodeAndIdAndDispatcherUrlRef ref, DispatcherSchedule schedule) {
// TODO 2019-06-22 why sessionCreatedOn is System.currentTimeMillis()?
// TODO 2019-08-29 why not? do we have to use a different type?
// TODO 2020-11-14 or it's about using TimeZoned value?
final File processorFile = new File(globals.processorDir, ref.processorCode);
KeepAliveRequestParamYaml.ReportProcessor status = new KeepAliveRequestParamYaml.ReportProcessor(
to(envService.getEnvParamsYaml(), envService.getTags(ref.processorCode)),
gitSourcingService.gitStatusInfo,
schedule.asString,
metadataService.getSessionId(ref.processorCode, ref.dispatcherUrl),
System.currentTimeMillis(),
"[unknown]", "[unknown]", null,
logFile!=null && logFile.exists(),
TaskParamsYamlUtils.BASE_YAML_UTILS.getDefault().getVersion(),
globals.os, processorFile.getAbsolutePath());
try {
InetAddress inetAddress = InetAddress.getLocalHost();
status.ip = inetAddress.getHostAddress();
status.host = inetAddress.getHostName();
} catch (UnknownHostException e) {
log.error("#749.010 Error", e);
status.addError(ExceptionUtils.getStackTrace(e));
}
return status;
}
private static KeepAliveRequestParamYaml.Env to(EnvParamsYaml envYaml, @Nullable String tags) {
KeepAliveRequestParamYaml.Env t = new KeepAliveRequestParamYaml.Env(tags);
t.mirrors.putAll(envYaml.mirrors);
t.envs.putAll(envYaml.envs);
envYaml.disk.stream().map(o->new KeepAliveRequestParamYaml.DiskStorage(o.code, o.path)).collect(Collectors.toCollection(() -> t.disk));
return t;
}
/**
* mark tasks as delivered.
* By delivering it means that result of exec was delivered to dispatcher
*
* @param ref ProcessorData.ProcessorCodeAndIdAndDispatcherUrlRef
* @param ids List<String> list if task ids
*/
public void markAsDelivered(ProcessorData.ProcessorCodeAndIdAndDispatcherUrlRef ref, List<Long> ids) {
for (Long id : ids) {
processorTaskService.setDelivered(ref, id);
}
}
public void assignTasks(ProcessorData.ProcessorCodeAndIdAndDispatcherUrlRef ref, DispatcherCommParamsYaml.AssignedTask task) {
synchronized (ProcessorSyncHolder.processorGlobalSync) {
currentExecState.registerDelta(ref.dispatcherUrl, List.of(new KeepAliveResponseParamYaml.ExecContextStatus.SimpleStatus(task.execContextId, task.state)));
processorTaskService.createTask(ref, task.taskId, task.execContextId, task.params);
}
}
public List<ProcessorCommParamsYaml.ResendTaskOutputResourceResult.SimpleStatus> getResendTaskOutputResourceResultStatus(
ProcessorData.ProcessorCodeAndIdAndDispatcherUrlRef ref, DispatcherCommParamsYaml.DispatcherResponse response) {
if (response.resendTaskOutputs==null || response.resendTaskOutputs.resends.isEmpty()) {
return List.of();
}
List<ProcessorCommParamsYaml.ResendTaskOutputResourceResult.SimpleStatus> statuses = new ArrayList<>();
for (DispatcherCommParamsYaml.ResendTaskOutput output : response.resendTaskOutputs.resends) {
Enums.ResendTaskOutputResourceStatus status = resendTaskOutputResources(ref, output.taskId, output.variableId);
statuses.add( new ProcessorCommParamsYaml.ResendTaskOutputResourceResult.SimpleStatus(output.taskId, output.variableId, status));
}
return statuses;
}
public Enums.ResendTaskOutputResourceStatus resendTaskOutputResources(ProcessorData.ProcessorCodeAndIdAndDispatcherUrlRef ref, Long taskId, Long variableId) {
ProcessorTask task = processorTaskService.findById(ref, taskId);
if (task==null) {
return Enums.ResendTaskOutputResourceStatus.TASK_NOT_FOUND;
}
final TaskParamsYaml taskParamYaml = TaskParamsYamlUtils.BASE_YAML_UTILS.to(task.getParams());
File taskDir = processorTaskService.prepareTaskDir(ref, taskId);
for (TaskParamsYaml.OutputVariable outputVariable : taskParamYaml.task.outputs) {
if (!outputVariable.id.equals(variableId)) {
continue;
}
Enums.ResendTaskOutputResourceStatus status;
switch (outputVariable.sourcing) {
case dispatcher:
status = scheduleSendingToDispatcher(ref, taskId, taskDir, outputVariable);
break;
case disk:
case git:
case inline:
default:
if (true) {
throw new NotImplementedException("need to set 'uploaded' in params for this variableId");
}
status = Enums.ResendTaskOutputResourceStatus.SEND_SCHEDULED;
break;
}
if (status!=Enums.ResendTaskOutputResourceStatus.SEND_SCHEDULED) {
return status;
}
}
return Enums.ResendTaskOutputResourceStatus.SEND_SCHEDULED;
}
private Enums.ResendTaskOutputResourceStatus scheduleSendingToDispatcher(ProcessorData.ProcessorCodeAndIdAndDispatcherUrlRef ref, Long taskId, File taskDir, TaskParamsYaml.OutputVariable outputVariable) {
final AssetFile assetFile = AssetUtils.prepareOutputAssetFile(taskDir, outputVariable.id.toString());
// is this variable prepared?
if (assetFile.isError || !assetFile.isContent) {
log.warn("#749.040 Variable wasn't found. Considering that this task is broken, {}", assetFile);
processorTaskService.markAsFinishedWithError(ref, taskId,
"#749.050 Variable #"+outputVariable.id+" wasn't found. Considering that this task is broken");
processorTaskService.setCompleted(ref, taskId);
return Enums.ResendTaskOutputResourceStatus.VARIABLE_NOT_FOUND;
}
final DispatcherLookupExtendedService.DispatcherLookupExtended dispatcher =
dispatcherLookupExtendedService.lookupExtendedMap.get(ref.dispatcherUrl);
UploadVariableTask uploadResourceTask = new UploadVariableTask(taskId, assetFile.file, outputVariable.id, ref, dispatcher.dispatcherLookup);
uploadResourceActor.add(uploadResourceTask);
return Enums.ResendTaskOutputResourceStatus.SEND_SCHEDULED;
}
@Data
public static class ResultOfChecking {
public boolean isAllLoaded = true;
public boolean isError = false;
}
public ProcessorService.ResultOfChecking checkForPreparingVariables(
ProcessorData.ProcessorCodeAndIdAndDispatcherUrlRef ref, ProcessorTask task, MetadataParamsYaml.ProcessorState processorState,
TaskParamsYaml taskParamYaml, DispatcherLookupExtendedService.DispatcherLookupExtended dispatcher, File taskDir) {
ProcessorService.ResultOfChecking result = new ProcessorService.ResultOfChecking();
if (!ref.dispatcherUrl.url.equals(task.dispatcherUrl)) {
throw new IllegalStateException("(!ref.dispatcherUrl.url.equals(task.dispatcherUrl))");
}
try {
taskParamYaml.task.inputs.forEach(input -> {
VariableProvider resourceProvider = resourceProviderFactory.getVariableProvider(input.sourcing);
if (task.empty.isEmpty(input.id.toString())) {
// variable was initialized and is empty so we don't need to download it again
return;
}
// the method prepareForDownloadingVariable() is creating a list dynamically. So don't cache the result
List<AssetFile> assetFiles = resourceProvider.prepareForDownloadingVariable(ref, taskDir, dispatcher, task, processorState, input);
for (AssetFile assetFile : assetFiles) {
// is this resource prepared?
if (assetFile.isError || !assetFile.isContent) {
result.isAllLoaded = false;
break;
}
}
});
}
catch (BreakFromLambdaException e) {
processorTaskService.markAsFinishedWithError(ref, task.taskId, e.getMessage());
result.isError = true;
return result;
}
catch (VariableProviderException e) {
log.error("#749.070 Error", e);
processorTaskService.markAsFinishedWithError(ref, task.taskId, e.toString());
result.isError = true;
return result;
}
if (result.isError) {
return result;
}
if (!result.isAllLoaded) {
if (task.assetsPrepared) {
processorTaskService.markAsAssetPrepared(ref, task.taskId, false);
}
result.isError = true;
return result;
}
result.isError = false;
return result;
}
public boolean checkOutputResourceFile(ProcessorData.ProcessorCodeAndIdAndDispatcherUrlRef ref, ProcessorTask task, TaskParamsYaml taskParamYaml, DispatcherLookupExtendedService.DispatcherLookupExtended dispatcher, File taskDir) {
for (TaskParamsYaml.OutputVariable outputVariable : taskParamYaml.task.outputs) {
try {
VariableProvider resourceProvider = resourceProviderFactory.getVariableProvider(outputVariable.sourcing);
//noinspection unused
File outputResourceFile = resourceProvider.getOutputVariableFromFile(ref, taskDir, dispatcher, task, outputVariable);
} catch (VariableProviderException e) {
final String msg = "#749.080 Error: " + e.toString();
log.error(msg, e);
processorTaskService.markAsFinishedWithError(ref, task.taskId, msg);
return false;
}
}
return true;
}
}
| gpl-3.0 |
odotopen/PixelDungeonLegend | src/com/watabou/pixeldungeon/items/weapon/missiles/FireArrow.java | 841 |
package com.watabou.pixeldungeon.items.weapon.missiles;
import com.watabou.pixeldungeon.actors.Char;
import com.watabou.pixeldungeon.actors.buffs.Buff;
import com.watabou.pixeldungeon.actors.buffs.Burning;
import com.watabou.pixeldungeon.sprites.ItemSpriteSheet;
public class FireArrow extends Arrow {
public FireArrow() {
this( 1 );
}
public FireArrow( int number ) {
super();
quantity(number);
baseMin = 1;
baseMax = 6;
baseDly = 0.75;
image = ItemSpriteSheet.ARROW_FIRE;
updateStatsForInfo();
}
@Override
public int price() {
return quantity() * 5;
}
@Override
public void proc( Char attacker, Char defender, int damage ) {
if(activateSpecial(attacker, defender, damage)) {
Buff.affect( defender, Burning.class ).reignite( defender );
}
super.proc( attacker, defender, damage );
}
}
| gpl-3.0 |
cubic-control/NeighborCraft | src/main/java/com/cubic_control/hnm/Entity/Model/ModelGrave.java | 2811 | // Date: 12/31/2016 5:25:06 PM
// Template version 1.1
// Java generated by Techne
// Keep in mind that you still need to fill in some blanks
// - ZeuX
package com.cubic_control.hnm.Entity.Model;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.entity.Entity;
public class ModelGrave extends ModelBase
{
//fields
ModelRenderer shape1;
ModelRenderer Shape2;
ModelRenderer Shape3;
ModelRenderer Shape4;
ModelRenderer Shape5;
ModelRenderer Shape6;
public ModelGrave()
{
textureWidth = 64;
textureHeight = 32;
shape1 = new ModelRenderer(this, 0, 0);
shape1.addBox(0F, 0F, 0F, 3, 31, 1);
shape1.setRotationPoint(-1.5F, -7F, -7F);
shape1.setTextureSize(64, 32);
shape1.mirror = true;
setRotation(shape1, 0F, 0F, 0F);
Shape2 = new ModelRenderer(this, 8, 0);
Shape2.addBox(0F, 0F, 0F, 14, 3, 1);
Shape2.setRotationPoint(-7F, -2F, -8F);
Shape2.setTextureSize(64, 32);
Shape2.mirror = true;
setRotation(Shape2, 0F, 0F, 0F);
Shape3 = new ModelRenderer(this, 38, 0);
Shape3.addBox(0F, 0F, 0F, 1, 5, 2);
Shape3.setRotationPoint(1.5F, -2.5F, -8.2F);
Shape3.setTextureSize(64, 32);
Shape3.mirror = true;
setRotation(Shape3, 0F, 0F, 0.7853982F);
Shape4 = new ModelRenderer(this, 44, 0);
Shape4.addBox(0F, 0F, 0F, 1, 5, 2);
Shape4.setRotationPoint(-2F, -2F, -8.1F);
Shape4.setTextureSize(64, 32);
Shape4.mirror = true;
setRotation(Shape4, 0F, 0F, -0.7853982F);
Shape5 = new ModelRenderer(this, 50, 0);
Shape5.addBox(0F, 0F, 0F, 1, 5, 1);
Shape5.setRotationPoint(1.5F, -2.5F, -6.9F);
Shape5.setTextureSize(64, 32);
Shape5.mirror = true;
setRotation(Shape5, 0F, 0F, 0.7853982F);
Shape6 = new ModelRenderer(this, 54, 0);
Shape6.addBox(0F, 0F, 0F, 1, 5, 1);
Shape6.setRotationPoint(-2F, -2F, -6.8F);
Shape6.setTextureSize(64, 32);
Shape6.mirror = true;
setRotation(Shape6, 0F, 0F, -0.7853982F);
}
public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5)
{
super.render(entity, f, f1, f2, f3, f4, f5);
setRotationAngles(f, f1, f2, f3, f4, f5, entity);
shape1.render(f5);
Shape2.render(f5);
Shape3.render(f5);
Shape4.render(f5);
Shape5.render(f5);
Shape6.render(f5);
}
private void setRotation(ModelRenderer model, float x, float y, float z)
{
model.rotateAngleX = x;
model.rotateAngleY = y;
model.rotateAngleZ = z;
}
public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity)
{
super.setRotationAngles(f, f1, f2, f3, f4, f5, entity);
}
}
| gpl-3.0 |
superklamer/Java | Eclipse-dev/GradingTest/src/TestCase.java | 150 | import static org.junit.Assert.*;
import org.junit.Test;
public class TestCase {
@Test
public void test() {
fail("Not yet implemented");
}
}
| gpl-3.0 |
bblauser/star-wars | StarWars/src/byui/cit260/starWars/view/GameMenuView.java | 8073 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package byui.cit260.starWars.view;
import byui.cit260.starWars.control.TargetControl;
import byui.cit260.starWars.model.EnemyFighter;
import byui.cit260.starWars.model.EvasiveManeuver;
import byui.cit260.starWars.model.Item;
import byui.cit260.starWars.model.Map;
import exceptions.TargetControlException;
import starwars.StarWars;
import exceptions.GameControlException;
import java.io.PrintWriter;
/**
*
* @author Edvaldo Melo
*/
public class GameMenuView extends View {
private String menu;
MainMenuView mainMenu = new MainMenuView();
public GameMenuView() {
super("\n"
+ "\n--------------------------------"
+ "\n| Game Menu |"
+ "\n--------------------------------"
+ "\nM - View Map"
// + "\nL - Attack Turbo Laser"
// + "\nF - Attack Tie Fighter"
// + "\nS - Attack Defletor Shield"
// + "\nE - Evasive Maneuver"
// + "\nT - Fire Torpedo"
+ "\nA - View Ammunition"
+ "\nV - View Strongest Enemy"
+ "\nW - View Weakest Enemy"
+ "\nR - View Remaining Enemies"
+ "\nH - View Average Health"
+ "\nP - Print Remaining Enemies"
+ "\nN - Select target"
+ "\nX - Exit"
+ "\n--------------------------------");
}
@Override
public boolean doAction(String value) {
value = value.toUpperCase(); //convert to upper
switch (value) {
case "M": // view map
this.viewMap();
break;
//case "L": // attack turbo laser
// this.attackTurboLaser();
// break;
//case "F": // attack tie fighter
// this.attackTieFighter();
// break;
//case "S": // attack deflector shield
// this.attackDeflectorShield();
// break;
//case "E": // evasive maneuver
// this.evasiveManeuver();
// break;
//case "T": // fire torpedo
// this.fireTorpedo();
// break;
case "A": // view ammunition
this.viewAmmuntion();
break;
case "V": // view strongest enemy
this.viewStrongestEnemy();
break;
case "W": // view weakest enemy
this.viewWeakEnemy();
break;
case "R": // view remaining ememy
this.viewRemainingEnemy();
break;
case "H": // view avearge health enemy
this.viewAvgEnemy();
break;
case "P": // print remaining enemies
this.remainingEnemiesp();
break;
case "N": // Select Target View
this.targetView();
break;
case "I": // Select Total
this.viewTotalPriceOfItem();
break;
default:
console.println("\n*** Invalid selection *** Try again");
}
return false;
}
private void viewMap() {
Map map = new Map();
map = StarWars.getCurrentGame().getMap();
map.displayMap(map);
// display the map view
MapView mapView = new MapView();
mapView.display();
}
private void viewAmmuntion() {
// Display the ammuntion
AmmunitionView ammoView = new AmmunitionView();
ammoView.display();
}
private void targetView() {
SelectTargetView targetView = new SelectTargetView();
targetView.display();
}
private void viewStrongestEnemy() {
TargetControl targetControl = new TargetControl();
EnemyFighter[] enemyFighterList = StarWars.getCurrentGame().getEnemyFighters();
try {
int strongestEnemy = targetControl.getMaxEnemyHealth(enemyFighterList);
console.println("\n The Strongest Enemy is: "
+ "\n Name:\t" + enemyFighterList[strongestEnemy].getTargetName()
+ "\n Location: \t(" + enemyFighterList[strongestEnemy].getTargetLocation().getRow() + ","
+ enemyFighterList[strongestEnemy].getTargetLocation().getColumn() + ")"
+ "\n Health: \t" + enemyFighterList[strongestEnemy].getTargetHealth());
} catch (TargetControlException me) {
ErrorView.display(this.getClass().getName(), me.getMessage());
}
}
/*gary moser*/
private void viewWeakEnemy() {
TargetControl targetControl = new TargetControl();
EnemyFighter[] enemyFighterList = StarWars.getCurrentGame().getEnemyFighters();
int weakEnemy = targetControl.getLowEnemyHealth(enemyFighterList);
if (weakEnemy >= 0) {
console.println("\n The weakest Enemy is: "
+ "\n Name:\t" + enemyFighterList[weakEnemy].getTargetName()
+ "\n Location: \t(" + enemyFighterList[weakEnemy].getTargetLocation().getRow() + ","
+ enemyFighterList[weakEnemy].getTargetLocation().getColumn() + ")"
+ "\n Health: \t" + enemyFighterList[weakEnemy].getTargetHealth()
);
} else {
console.println("\n No enemies exist");
}
}
/*gary moser*/
private void viewRemainingEnemy() {
TargetControl targetControl = new TargetControl();
EnemyFighter[] enemyFighterList = StarWars.getCurrentGame().getEnemyFighters();
int remainingEnemy = targetControl.getLengthEnemyHealth(enemyFighterList);
if (remainingEnemy > 0) {
console.println("\n" + remainingEnemy + " Enemies Remaining");
} else {
console.println("No Ememies Remain");
}
}
/*gary moser */
private void viewAvgEnemy() {
TargetControl targetControl = new TargetControl();
EnemyFighter[] enemyFighterList = StarWars.getCurrentGame().getEnemyFighters();
double avgEnemy = targetControl.getAvgEnemyHealth(enemyFighterList);
console.println("\n Average Enemy Health " + avgEnemy);
}
/*gary Moser */
private void remainingEnemiesp() {
console.println("\n\nEnter the file path for the file where the game is to be saved.");
String filePath = this.getInput();
try {
saveReport(filePath);
console.println("\nFile successfully saved to: " + filePath);
} catch (GameControlException ex) {
ErrorView.display("GameMenuView", ex.getMessage());
}
}
public void saveReport(String filePath) throws GameControlException {
EnemyFighter[] enemyFighterList = StarWars.getCurrentGame().getEnemyFighters();
try (PrintWriter out = new PrintWriter(filePath)) {
out.println("\n\n Remaining Enemies Report");
out.printf("%n%-20s%8s", "Target", "R,C");
out.printf("%n%-20s%8s", "---------------", "--------");
// for each inventory item
for (EnemyFighter enemyFighter : enemyFighterList) {
out.printf("%n%-20s%1d,%1d", enemyFighter.getTargetName(), enemyFighter.getTargetLocation().getRow(), enemyFighter.getTargetLocation().getColumn());
}
} catch (Exception e) {
throw new GameControlException(e.getMessage());
}
}
// By Edvaldo Melo
private void viewTotalPriceOfItem() {
TargetControl targetControl = new TargetControl();
Item[] ItemList;
ItemList = StarWars.getCurrentGame().getInventory();
double total = targetControl.getTotalPriceOfItem();
console.print("\n Total of Item " + total);
}
}
| gpl-3.0 |
vpechorin/kontempl | src/main/java/net/pechorina/kontempl/service/SiteService.java | 1549 | package net.pechorina.kontempl.service;
import net.pechorina.kontempl.data.Site;
import net.pechorina.kontempl.repos.SiteRepo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class SiteService {
static final Logger logger = LoggerFactory.getLogger(SiteService.class);
@Autowired
private SiteRepo siteRepo;
@Transactional
public List<Site> listAll() {
return siteRepo.findAll();
}
@Transactional
public Site findByName(String n) {
return siteRepo.findByName(n);
}
@Transactional
@Cacheable("siteCache")
public Site findByNameCached(String n) {
return siteRepo.findByName(n);
}
@Transactional
public Site findById(Integer id) {
return siteRepo.findOne(id);
}
@Transactional
@CacheEvict(value = {"siteCache"}, allEntries = true)
public Site save(Site s) {
return siteRepo.saveAndFlush(s);
}
@Transactional
@CacheEvict(value = {"siteCache"}, allEntries = true)
public void delete(Site s) {
siteRepo.delete(s);
}
@Transactional
@CacheEvict(value = {"siteCache"}, allEntries = true)
public void delete(Integer id) {
siteRepo.delete(id);
}
}
| gpl-3.0 |
limengbo/youyoulearning | src/com/lofter/youyoulearning/quxinyong/jsp/test/TopicDaoImplTest.java | 644 | package com.lofter.youyoulearning.quxinyong.jsp.test;
import java.util.List;
import com.lofter.youyoulearning.quxinyong.jsp.dao.TopicDao;
import com.lofter.youyoulearning.quxinyong.jsp.dao.impl.TopicDaoImpl;
import com.lofter.youyoulearning.quxinyong.jsp.entity.Topic;
public class TopicDaoImplTest {
public static void main(String[] args) {
TopicDao topicDao = new TopicDaoImpl();
List<Topic> listTopic = topicDao.findListTopic(1, 1);
System.out.println("===========主题列表===========");
for (int i = 0; i < listTopic.size(); i++) {
Topic topic = listTopic.get(i);
System.out.println(topic);
}
}
}
| gpl-3.0 |
ilarischeinin/chipster | src/main/java/fi/csc/microarray/client/visualisation/methods/gbrowser/util/SamBamUtils.java | 9687 | package fi.csc.microarray.client.visualisation.methods.gbrowser.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import net.sf.picard.io.IoUtil;
import net.sf.picard.sam.BuildBamIndex;
import net.sf.samtools.SAMFileHeader;
import net.sf.samtools.SAMFileReader;
import net.sf.samtools.SAMFileReader.ValidationStringency;
import net.sf.samtools.SAMFileWriter;
import net.sf.samtools.SAMFileWriterFactory;
import net.sf.samtools.SAMRecord;
import net.sf.samtools.SAMSequenceDictionary;
import net.sf.samtools.SAMSequenceRecord;
import net.sf.samtools.seekablestream.SeekableBufferedStream;
import net.sf.samtools.seekablestream.SeekableFileStream;
import net.sf.samtools.seekablestream.SeekableHTTPStream;
import net.sf.samtools.seekablestream.SeekableStream;
import org.broad.tribble.readers.TabixReader;
import fi.csc.microarray.util.IOUtils;
public class SamBamUtils {
public interface SamBamUtilStateListener {
public void stateChanged(SamBamUtilState newState);
}
public class SamBamUtilState {
private String state;
private double percentage;
public SamBamUtilState(String state, double percentage) {
this.state = state;
this.percentage = percentage;
}
public String getState() {
return this.state;
}
public double getPercentage() {
return this.percentage;
}
}
private SamBamUtilStateListener stateListener;
private ChromosomeNormaliser chromosomeNormaliser = new ChromosomeNormaliser() {
public String normaliseChromosome(String chromosomeName) {
// Leave prefix as it is
// Remove postfix, if present
String SEPARATOR = ".";
if (chromosomeName.contains(SEPARATOR)) {
chromosomeName = chromosomeName.substring(0, chromosomeName.indexOf(SEPARATOR));
}
return chromosomeName;
}
};
public SamBamUtils() {
}
public SamBamUtils(SamBamUtilStateListener stateListener) {
this.stateListener = stateListener;
}
private void updateState(String state, double percentage) {
if (this.stateListener != null) {
stateListener.stateChanged(new SamBamUtilState(state, percentage));
}
}
public static void convertElandToSortedBam(File elandFile, File bamFile) throws IOException {
BufferedReader in = null;
SAMFileWriter writer = null;
try {
in = new BufferedReader(new InputStreamReader(new FileInputStream(elandFile)));
SAMFileHeader header = new SAMFileHeader();
header.setSortOrder(SAMFileHeader.SortOrder.coordinate);
writer = new SAMFileWriterFactory().makeBAMWriter(header, false, bamFile);
for (String line = in.readLine(); line != null; line = in.readLine()) {
String[] fields = line.split("\t");
SAMRecord alignment = new SAMRecord(header);
alignment.setReadName(fields[0]);
alignment.setReadBases(fields[1].getBytes());
// String quality = fields[2];
alignment.setAlignmentStart(Integer.parseInt(fields[7]));
alignment.setReadNegativeStrandFlag("R".equals(fields[8]));
alignment.setReferenceName(fields[6]);
writer.addAlignment(alignment);
}
} finally {
IOUtils.closeIfPossible(in);
closeIfPossible(writer);
}
}
public static void sortSamBam(File samBamFile, File sortedBamFile) {
SAMFileReader.setDefaultValidationStringency(ValidationStringency.SILENT);
SAMFileReader reader = new SAMFileReader(IoUtil.openFileForReading(samBamFile));
SAMFileWriter writer = null;
try {
reader.getFileHeader().setSortOrder(SAMFileHeader.SortOrder.coordinate);
writer = new SAMFileWriterFactory().makeBAMWriter(reader.getFileHeader(), false, sortedBamFile);
Iterator<SAMRecord> iterator = reader.iterator();
while (iterator.hasNext()) {
writer.addAlignment(iterator.next());
}
} finally {
closeIfPossible(reader);
closeIfPossible(writer);
}
}
public void normaliseBam(File bamFile, File normalisedBamFile) {
// Read in a BAM file and its header
SAMFileReader.setDefaultValidationStringency(ValidationStringency.SILENT);
SAMFileReader reader = new SAMFileReader(IoUtil.openFileForReading(bamFile));
SAMFileWriter writer = null;
try {
SAMFileHeader normalisedHeader = reader.getFileHeader();
// Alter the chromosome names in header's SAMSequenceDictionary
SAMSequenceDictionary normalisedDictionary = new SAMSequenceDictionary();
for (SAMSequenceRecord sequenceRecord : normalisedHeader.getSequenceDictionary().getSequences()) {
// Normalise chromosome
String sequenceName = chromosomeNormaliser.normaliseChromosome(sequenceRecord.getSequenceName());
normalisedDictionary.addSequence(new SAMSequenceRecord(sequenceName, sequenceRecord.getSequenceLength()));
}
normalisedHeader.setSequenceDictionary(normalisedDictionary);
// Write new BAM file with normalised chromosome names
writer = new SAMFileWriterFactory().makeBAMWriter(normalisedHeader, true, normalisedBamFile);
for (final SAMRecord rec : reader) {
rec.setHeader(normalisedHeader);
writer.addAlignment(rec);
}
} finally {
closeIfPossible(reader);
closeIfPossible(writer);
}
}
public void indexBam(File bamFile, File baiFile) {
SAMFileReader.setDefaultValidationStringency(ValidationStringency.SILENT);
BuildBamIndex.createIndex(new SAMFileReader(IoUtil.openFileForReading(bamFile)), baiFile);
}
public void preprocessEland(File elandFile, File preprocessedBamFile, File baiFile) throws IOException {
File sortedTempBamFile = File.createTempFile("converted", "bam");
try {
// Convert & Sort
convertElandToSortedBam(elandFile, sortedTempBamFile);
// Normalise (input must be BAM)
normaliseBam(sortedTempBamFile, preprocessedBamFile);
sortedTempBamFile.delete();
// Index
indexBam(preprocessedBamFile, baiFile);
} finally {
sortedTempBamFile.delete();
}
}
public void preprocessSamBam(File samBamFile, File preprocessedBamFile, File baiFile) throws IOException {
// Sort
updateState("sorting", 0);
File sortedTempBamFile = File.createTempFile("sorted", "bam");
sortSamBam(samBamFile, sortedTempBamFile);
// Normalise (input must be BAM)
updateState("normalising", 33.3);
normaliseBam(sortedTempBamFile, preprocessedBamFile);
sortedTempBamFile.delete();
// Index
updateState("indexing", 66);
indexBam(preprocessedBamFile, baiFile);
updateState("done", 100);
}
public static List<String> readChromosomeNames(URL bam, URL index) throws FileNotFoundException, URISyntaxException {
SAMFileReader reader = getSAMReader(bam, index);
LinkedList<String> chromosomes = new LinkedList<String>();
for (SAMSequenceRecord record : reader.getFileHeader().getSequenceDictionary().getSequences()) {
chromosomes.add(record.getSequenceName());
}
closeIfPossible(reader);
return chromosomes;
}
public static SAMFileReader getSAMReader(URL bam, URL index) throws FileNotFoundException, URISyntaxException {
SAMFileReader reader = null;
SeekableStream bamStream = null;
SeekableStream indexStream = null;
try {
if ("file".equals(bam.getProtocol())) {
bamStream = new SeekableFileStream(new File(bam.toURI()));
} else {
bamStream = new SeekableHTTPStream(bam);
}
// Picard requires file to have a 'bam' extension, but our hashed url doesn't have it
SeekableBufferedStream bamBufferedStream = new SeekableBufferedStream(bamStream) {
@Override
public String getSource() {
return super.getSource() + "_fake-source.bam";
}
};
if ("file".equals(index.getProtocol())) {
indexStream = new SeekableFileStream(new File(index.toURI()));
} else {
indexStream = new SeekableHTTPStream(index);
}
SeekableBufferedStream indexBufferedStream = new SeekableBufferedStream(indexStream);
return new SAMFileReader(bamBufferedStream, indexBufferedStream, false);
} finally {
closeIfPossible(reader);
}
}
private static void closeIfPossible(SAMFileWriter writer) {
if (writer != null) {
try {
writer.close();
} catch (Exception e) {
// Ignore
}
}
}
public static void closeIfPossible(SAMFileReader reader) {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
// Ignore
}
}
}
public static void closeIfPossible(TabixReader reader) {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
// Ignore
}
}
}
public static boolean isSamBamExtension(String extension) {
if (extension == null) {
return false;
}
extension = extension.toLowerCase();
return "sam".equals(extension) || "bam".equals(extension);
}
public String printSamBam(InputStream samBamStream, int maxRecords) throws IOException {
SAMFileReader.setDefaultValidationStringency(ValidationStringency.SILENT);
SAMFileReader in = new SAMFileReader(samBamStream);
SAMFileHeader header = in.getFileHeader();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
SAMFileWriter out = new SAMFileWriterFactory().makeSAMWriter(header, true, buffer);
int i = 0;
try {
for (final SAMRecord rec : in) {
if (i > maxRecords) {
break;
}
out.addAlignment(rec);
i++;
}
} finally {
closeIfPossible(out);
}
if (i > maxRecords) {
buffer.write("SAM/BAM too long for viewing, truncated here!\n".getBytes());
}
return buffer.toString();
}
}
| gpl-3.0 |
openflexo-team/gina | flexographicutils/src/test/java/org/openflexo/swing/layout/TestMultiSplitPane.java | 7394 | /**
*
* Copyright (c) 2013-2014, Openflexo
* Copyright (c) 2012-2012, AgileBirds
*
* This file is part of Flexographicutils, a component of the software infrastructure
* developed at Openflexo.
*
*
* Openflexo is dual-licensed under the European Union Public License (EUPL, either
* version 1.1 of the License, or any later version ), which is available at
* https://joinup.ec.europa.eu/software/page/eupl/licence-eupl
* and the GNU General Public License (GPL, either version 3 of the License, or any
* later version), which is available at http://www.gnu.org/licenses/gpl.html .
*
* You can redistribute it and/or modify under the terms of either of these licenses
*
* If you choose to redistribute it and/or modify under the terms of the GNU GPL, you
* must include the following additional permission.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or
* combining it with software containing parts covered by the terms
* of EPL 1.0, the licensors of this Program grant you additional permission
* to convey the resulting work. *
*
* This software is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE.
*
* See http://www.openflexo.org/license.html for details.
*
*
* Please contact Openflexo (openflexo-contacts@openflexo.org)
* or visit www.openflexo.org if you need additional information.
*
*/
package org.openflexo.swing.layout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import org.openflexo.rm.ResourceLocator;
import org.openflexo.swing.layout.MultiSplitLayout.Leaf;
import org.openflexo.swing.layout.MultiSplitLayout.Node;
import org.openflexo.swing.layout.MultiSplitLayout.Split;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
public class TestMultiSplitPane {
public static final String LEFT = "left";
public static final String CENTER = "center";
public static final String RIGHT = "right";
public static final String TOP = "top";
public static final String MIDDLE = "middle";
public static final String BOTTOM = "bottom";
protected void initUI() {
MultiSplitLayoutFactory factory = new MultiSplitLayoutFactory.DefaultMultiSplitLayoutFactory();
Split<?> root = getDefaultLayout(factory);
final MultiSplitLayout layout = new MultiSplitLayout(factory);
layout.setLayoutByWeight(false);
layout.setFloatingDividers(false);
JXMultiSplitPane splitPane = new JXMultiSplitPane(layout);
splitPane.setDividerPainter(new KnobDividerPainter());
addButton(LEFT + TOP, splitPane);
addButton(CENTER + TOP, splitPane);
addButton(RIGHT + TOP, splitPane);
addButton(LEFT + BOTTOM, splitPane);
addButton(CENTER + BOTTOM, splitPane);
addButton(RIGHT + BOTTOM, splitPane);
System.out.println("root=" + root);
System.out.println("layout=" + layout);
MultiSplitLayout.printModel(root);
layout.setModel(root);
// restoreLayout(layout, root);
splitPane.setPreferredSize(layout.getModel().getBounds().getSize());
JFrame frame = new JFrame();
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
saveLayout(layout);
System.exit(0);
}
});
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
frame.add(splitPane);
frame.pack();
frame.setVisible(true);
}
protected Split<?> getDefaultLayout(MultiSplitLayoutFactory factory) {
Split root = factory.makeSplit();
root.setName("ROOT");
Split<?> left = getVerticalSplit(LEFT, 0.5, 0.5, factory);
left.setWeight(0);
left.setName(LEFT);
Split<?> center = getVerticalSplit(CENTER, 0.8, 0.2, factory);
center.setWeight(1.0);
center.setName(CENTER);
Split<?> right = getVerticalSplit(RIGHT, 0.5, 0.5, factory);
right.setWeight(0);
right.setName(RIGHT);
root.setChildren(left, factory.makeDivider(), center, factory.makeDivider(), right);
return root;
}
protected void addButton(final String buttonName, final JXMultiSplitPane splitPane) {
final JButton button = new JButton(buttonName);
splitPane.add(buttonName, button);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MultiSplitLayout layout = splitPane.getMultiSplitLayout();
restoreLayout(layout, getDefaultLayout(splitPane.getMultiSplitLayout().getFactory()));
splitPane.revalidate();
}
});
}
public Split<?> getVerticalSplit(String name, double topWeight, double bottomWeight, MultiSplitLayoutFactory factory) {
Split split = factory.makeSplit();
split.setRowLayout(false);
Leaf<?> top = factory.makeLeaf(name + TOP);
top.setWeight(topWeight);
Leaf<?> bottom = factory.makeLeaf(name + BOTTOM);
bottom.setWeight(bottomWeight);
split.setChildren(top, factory.makeDivider(), bottom);
return split;
}
protected void restoreLayout(MultiSplitLayout layout, Node defaultModel) {
Node<?> model = defaultModel;
try {
model = getGson().fromJson(new InputStreamReader(new FileInputStream(getLayoutFile()), "UTF-8"), Split.class);
} catch (JsonSyntaxException e) {
e.printStackTrace();
} catch (JsonIOException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
layout.setModel(model);
}
protected void saveLayout(MultiSplitLayout layout) {
Gson gson = getGson();
String json = gson.toJson(layout.getModel());
FileOutputStream fos = null;
try {
fos = new FileOutputStream(getLayoutFile());
fos.write(json.getBytes("UTF-8"));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
protected Gson getGson() {
GsonBuilder builder = new GsonBuilder().registerTypeAdapterFactory(new MultiSplitLayoutTypeAdapterFactory());
Gson gson = builder.create();
return gson;
}
protected File getLayoutFile() {
return ResourceLocator.retrieveResourceAsFile(ResourceLocator.locateResource("testlayout"));
}
public static void main(String[] args) {
/*BeanInfo info = Introspector.getBeanInfo(JTextField.class);
PropertyDescriptor[] propertyDescriptors = info.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; ++i) {
PropertyDescriptor pd = propertyDescriptors[i];
if (pd.getName().equals("text")) {
pd.setValue("transient", Boolean.TRUE);
}
}*/
SwingUtilities.invokeLater(() -> new TestMultiSplitPane().initUI());
}
}
| gpl-3.0 |
ablanco/dissim | behaviours/flood/AddWaterBehav.java | 3385 | // Flood and evacuation simulator using multi-agent technology
// Copyright (C) 2010 Alejandro Blanco and Manuel Gomar
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package behaviours.flood;
import jade.core.Agent;
import jade.core.behaviours.Behaviour;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import agents.EnvironmentAgent;
import agents.flood.WaterSourceAgent;
import util.HexagonalGrid;
import util.Point;
import util.flood.FloodHexagonalGrid;
import util.jcoord.LatLng;
/**
* {@link Behaviour} that receives water from {@link WaterSourceAgent} and adds
* it to a {@link HexagonalGrid}.
*
* @author Alejandro Blanco, Manuel Gomar
*
*/
@SuppressWarnings("serial")
public class AddWaterBehav extends CyclicBehaviour {
private FloodHexagonalGrid grid;
/**
* Grid coordinates of the {@link WaterSourceAgent}
*/
private Map<String, int[]> tiles = new Hashtable<String, int[]>();
/**
* {@link AddWaterBehav} constructor
*
* @param agt
* Usually a {@link EnvironmentAgent}
* @param grid
* {@link HexagonalGrid}
*/
public AddWaterBehav(Agent agt, FloodHexagonalGrid grid) {
super(agt);
this.grid = grid;
}
@Override
public void action() {
MessageTemplate mt = MessageTemplate.and(MessageTemplate
.MatchConversationId("add-water"), MessageTemplate
.MatchPerformative(ACLMessage.PROPOSE));
ACLMessage msg = myAgent.receive(mt);
if (msg != null) {
// Mensaje recibido, hay que procesarlo
String[] data = msg.getContent().split(" ");
double lat = Double.parseDouble(data[0]);
double lng = Double.parseDouble(data[1]);
short water = Short.parseShort(data[2]);
// Calcular posición
LatLng coord = new LatLng(lat, lng);
int[] gridCoord = tiles.get(coord.toString());
if (gridCoord == null) {
Point p = grid.coordToTile(coord);
gridCoord = new int[] { p.getCol(), p.getRow() };
tiles.put(coord.toString(), gridCoord);
}
int x = gridCoord[0];
int y = gridCoord[1];
// Máximo nivel que va a alcanzar el agua
short nivelMax = (short) (grid.getTerrainValue(x, y) + water);
Iterator<int[]> it = grid.getAdjacents(x, y).iterator();
short min = Short.MAX_VALUE;
// Buscamos la casilla adyacente más baja
while (it.hasNext()) {
int[] tile = it.next();
if (tile[2] < min)
min = (short) tile[2];
}
// Si las adyacentes tienen más agua no inundamos
if (min < nivelMax) {
grid.increaseValue(x, y, water);
} else {
if (water > grid.getWaterValue(x, y))
grid.setWaterValue(x, y, water);
}
} else {
block();
}
}
}
| gpl-3.0 |
danielbchapman/production-management | ProductionEJB/src/main/java/com/danielbchapman/production/entity/BudgetAdjustingEntry.java | 1876 | package com.danielbchapman.production.entity;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* An entry that ties to an initial budget entry and posts adjusting entries. This allows for a
* dynamic calculated field.
*
*/
@Entity
public class BudgetAdjustingEntry extends BaseEntity
{
private static final long serialVersionUID = 1L;
@ManyToOne(targetEntity = BudgetEntry.class, fetch = FetchType.EAGER, cascade = {
CascadeType.REFRESH, CascadeType.MERGE })
private BudgetEntry budgetEntry;
private Double amount = 0.00;
@Temporal(value = TemporalType.TIMESTAMP)
private Date date;
@Column(length = 200)
private String note = "";
private EntryType entryType;
public BudgetAdjustingEntry()
{
super();
}
public Double getAmount()
{
return amount;
}
public BudgetEntry getBudgetEntry()
{
return budgetEntry;
}
public Date getDate()
{
return date;
}
public EntryType getEntryType()
{
return entryType;
}
public String getNote()
{
return note;
}
/**
* @return <b>true</b> if this is confirms and <b>false</b> if not
*/
public boolean isConfirmed()
{
if(EntryType.CONFIRMED.equals(entryType))
return true;
return false;
}
public void setAmount(Double amount)
{
this.amount = amount;
}
public void setBudgetEntry(BudgetEntry budget)
{
this.budgetEntry = budget;
}
public void setDate(Date date)
{
this.date = date;
}
public void setEntryType(EntryType entryType)
{
this.entryType = entryType;
}
public void setNote(String note)
{
this.note = note;
}
}
| gpl-3.0 |
HxCKDMS/HxC-YouWillDieMod | src/main/java/YouWillDie/commands/CommandKillStats.java | 3059 | package YouWillDie.commands;
import YouWillDie.Config;
import YouWillDie.network.PacketHandler;
import YouWillDie.misc.EntityStatHelper;
import net.minecraft.command.ICommand;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import java.util.List;
public class CommandKillStats implements ICommand {
@Override
public int compareTo(Object arg0) {return 0;}
@Override
public String getCommandName() {return "creatureKnowledge";}
@Override
public String getCommandUsage(ICommandSender icommandsender) {return "commands.creatureKnowledge.usage";}
@Override
@SuppressWarnings("rawtypes")
public List getCommandAliases() {return null;}
@Override
public void processCommand(ICommandSender icommandsender, String[] astring) {
int page = astring.length > 0 ? Integer.parseInt(astring[0]) - 1 : 0, maxPage;
if(icommandsender instanceof EntityPlayer) {
EntityPlayer entityplayer = (EntityPlayer) icommandsender;
String message = "\u00A7c\u00A7oMob kill stats not enabled.";
if(Config.enableMobKillStats) {
message = "@Creature Knowledge:";
if(entityplayer.getEntityData().hasKey("KillStats")) {
NBTTagCompound killStats = entityplayer.getEntityData().getCompoundTag("KillStats");
String trackedMobs = killStats.hasKey("TrackedMobList") ? killStats.getString("TrackedMobList") : "";
if(trackedMobs != null && trackedMobs.length() > 0) {
String[] trackedMobList = trackedMobs.split(";");
maxPage = Math.max(0, (killStats.func_150296_c().size() - 1)/4);
if(page > maxPage) {page = maxPage;}
if(page < 0) {page = 0;}
message = "@Creature Knowledge (page " + (page + 1) + "/" + (maxPage + 1) + "):";
int count = 0, skip = 0;
for(String mob : trackedMobList) {
if(skip < page * 4) {skip++; continue;}
int kills = killStats.getInteger(mob);
int last = 0;
for(int i = 0; i < EntityStatHelper.killCount.length; i++) {
if(kills >= EntityStatHelper.killCount[i]) {last = i;
} else {break;}
}
message += "@\u00A7b " + EntityStatHelper.knowledge[last] + " " + mob.toLowerCase() + " slayer\u00A73 " + (last > 0 ? "+" + EntityStatHelper.damageBonusString[last] + "% damage bonus (" : "(") + kills + " kill(s)" + (last < EntityStatHelper.knowledge.length - 1 ? ", " + (EntityStatHelper.killCount[last + 1] - kills + " kill(s) to next rank)") : ")");
count++;
if(count >= 4) {break;}
}
}
} else {
message += "@ You've yet to learn anything.";
}
}
PacketHandler.SEND_MESSAGE.sendToPlayer(entityplayer, message);
}
}
@Override
public boolean canCommandSenderUseCommand(ICommandSender icommandsender) {return true;}
@Override
@SuppressWarnings("rawtypes")
public List addTabCompletionOptions(ICommandSender icommandsender, String[] astring) {return null;}
@Override
public boolean isUsernameIndex(String[] astring, int i) {return false;}
}
| gpl-3.0 |
danielhams/mad-java | 2COMMONPROJECTS/audio-services/src/uk/co/modularaudio/mads/base/controllertocv/ui/ControllerToCvLearnListener.java | 910 | /**
*
* Copyright (C) 2015 - Daniel Hams, Modular Audio Limited
* daniel.hams@gmail.com
*
* Mad is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Mad is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Mad. If not, see <http://www.gnu.org/licenses/>.
*
*/
package uk.co.modularaudio.mads.base.controllertocv.ui;
public interface ControllerToCvLearnListener
{
void receiveLearntController( int channel, int controller );
}
| gpl-3.0 |
geosolutions-it/geofence | src/services/core/model/src/test/java/it/geosolutions/geofence/core/model/Base64EncodersTest.java | 2015 | /*
* Copyright (C) 2014 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* GPLv3 + Classpath exception
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package it.geosolutions.geofence.core.model;
import java.util.Arrays;
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.codec.binary.Base64;
import org.junit.Assert;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
* Moving base64 de-coding from commons codec to DatatypeConverter.
* Making sure the results are the same, or we may lose some passwords in the db...
*
* @author ETj (etj at geo-solutions.it)
*/
public class Base64EncodersTest {
@Test
public void testEq() {
String msg1 = "this is the message to encode";
String output_codec = new String(Base64.encodeBase64(msg1.getBytes()));
String output_dconv = DatatypeConverter.printBase64Binary(msg1.getBytes());
System.out.println("apache commons: " + output_codec);
System.out.println("DatatypeConverter: " + output_dconv);
assertEquals(output_codec, output_dconv);
byte[] back_codec = Base64.decodeBase64(output_dconv);
byte[] back_dconv = DatatypeConverter.parseBase64Binary(output_dconv);
Assert.assertTrue( Arrays.equals(msg1.getBytes(), back_codec));
Assert.assertTrue( Arrays.equals(msg1.getBytes(), back_dconv));
}
}
| gpl-3.0 |
marvisan/HadesFIX | Model/src/test/java/net/hades/fix/message/impl/v40/NewsMsg40Test.java | 17496 | /*
* Copyright (c) 2006-2016 Marvisan Pty. Ltd. All rights reserved.
* Use is subject to license terms.
*/
/*
* NewsMsg40Test.java
*
* $Id: NewsMsg40Test.java,v 1.4 2010-03-21 10:18:18 vrotaru Exp $
*/
package net.hades.fix.message.impl.v40;
import net.hades.fix.message.impl.v40.data.NewsMsg40TestData;
import quickfix.DataDictionary;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import net.hades.fix.TestUtils;
import net.hades.fix.message.FIXMsg;
import net.hades.fix.message.MsgTest;
import net.hades.fix.message.NewsMsg;
import net.hades.fix.message.builder.FIXMsgBuilder;
import net.hades.fix.message.group.LinesOfTextGroup;
import net.hades.fix.message.type.BeginString;
import net.hades.fix.message.type.MsgType;
/**
* Test suite for FIX 4.0 NewsMsg class.
*
* @author <a href="mailto:support@marvisan.com">Support Team</a>
* @version $Revision: 1.4 $
* @created 02/03/2009, 7:38:11 PM
*/
public class NewsMsg40Test extends MsgTest {
private DataDictionary dictionary;
public NewsMsg40Test() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
TestUtils.enableValidation();
}
@After
public void tearDown() {
}
/**
* Test of encode method, of class NewsMsg for required fields only.
* @throws Exception
*/
@Test
public void a1_testEncodeReq() throws Exception {
System.out.println("-->testEncodeReq");
dictionary = getQF40DataDictionary();
NewsMsg msg = (NewsMsg) FIXMsgBuilder.build(MsgType.News.getValue(), BeginString.FIX_4_0);
TestUtils.populate40HeaderAll(msg);
msg.setNoLinesOfText(new Integer(2));
msg.getLinesOfTextGroups()[0].setText("line of text 1");
msg.getLinesOfTextGroups()[1].setText("line of text 2");
String encoded = new String(msg.encode(), DEFAULT_CHARACTER_SET);
System.out.println("encoded-->" + encoded);
quickfix.fix40.Message qfMsg = new quickfix.fix40.Message();
qfMsg.fromString(encoded, dictionary, true);
assertEquals(msg.getNoLinesOfText().intValue(), qfMsg.getInt(quickfix.field.LinesOfText.FIELD));
quickfix.fix40.News.LinesOfText grplot1 = new quickfix.fix40.News.LinesOfText();
qfMsg.getGroup(1, grplot1);
quickfix.field.Text flot1 = new quickfix.field.Text();
grplot1.get(flot1);
assertEquals(msg.getLinesOfTextGroups()[0].getText(), flot1.getValue());
quickfix.fix40.News.LinesOfText grplot2 = new quickfix.fix40.News.LinesOfText();
qfMsg.getGroup(2, grplot2);
quickfix.field.Text flot2 = new quickfix.field.Text();
grplot2.get(flot2);
assertEquals(msg.getLinesOfTextGroups()[1].getText(), flot2.getValue());
}
/**
* Test of encode method, of class IOIMsg all fields.
* @throws Exception
*/
@Test
public void a2_testEncodeAll() throws Exception {
System.out.println("-->testEncodeAll");
dictionary = getQF40DataDictionary();
NewsMsg msg = (NewsMsg) FIXMsgBuilder.build(MsgType.News.getValue(), BeginString.FIX_4_0);
NewsMsg40TestData.getInstance().populate(msg);
String encoded = new String(msg.encode(), DEFAULT_CHARACTER_SET);
System.out.println("encoded-->" + encoded);
quickfix.fix40.News qfMsg = new quickfix.fix40.News();
qfMsg.fromString(encoded, dictionary, true);
NewsMsg40TestData.getInstance().check(msg, qfMsg);
}
/**
* Test of decode method, of class NewsMsg only required.
* @throws Exception
*/
@Test
public void b1_testDecodeReq() throws Exception {
System.out.println("-->testDecodeReq");
dictionary = getQF40DataDictionary();
quickfix.fix40.News msg = new quickfix.fix40.News();
TestUtils.populateQuickFIX40HeaderAll(msg);
msg.setInt(quickfix.field.LinesOfText.FIELD, 2);
quickfix.fix40.News.LinesOfText grplot1 = new quickfix.fix40.News.LinesOfText();
grplot1.setString(quickfix.field.Text.FIELD, "TEXT 1");
msg.addGroup(grplot1);
quickfix.fix40.News.LinesOfText grplot2 = new quickfix.fix40.News.LinesOfText();
grplot2.setString(quickfix.field.Text.FIELD, "TEXT 2");
msg.addGroup(grplot2);
String strMsg = msg.toString();
System.out.println("qfix msg-->" + strMsg);
NewsMsg dmsg = (NewsMsg) FIXMsgBuilder.build(strMsg.getBytes(DEFAULT_CHARACTER_SET));
dmsg.decode();
assertEquals(msg.getInt(quickfix.field.LinesOfText.FIELD), dmsg.getNoLinesOfText().intValue());
assertEquals("TEXT 1", dmsg.getLinesOfTextGroups()[0].getText());
assertEquals("TEXT 2", dmsg.getLinesOfTextGroups()[1].getText());
}
/**
* Test of decode method, of class NewsMsg for FIX 4.0 all fields.
* @throws Exception
*/
@Test
public void b2_testDecodeAll() throws Exception {
System.out.println("-->testDecodeAll");
dictionary = getQF40DataDictionary();
quickfix.fix40.News msg = new quickfix.fix40.News();
NewsMsg40TestData.getInstance().populate(msg);
String strMsg = msg.toString();
System.out.println("qfix msg-->" + strMsg);
NewsMsg dmsg = (NewsMsg) FIXMsgBuilder.build(strMsg.getBytes(DEFAULT_CHARACTER_SET));
dmsg.decode();
NewsMsg40TestData.getInstance().check(msg, dmsg);
}
/**
* Test of encode method, of secured message.
* @throws Exception
*/
@Test
public void b3_testEncDecSecureAll() throws Exception {
System.out.println("-->testEncDecSecureAll");
setSecuredDataDES();
try {
NewsMsg msg = (NewsMsg) FIXMsgBuilder.build(MsgType.News.getValue(), BeginString.FIX_4_0);
NewsMsg40TestData.getInstance().populate(msg);
String encoded = new String(msg.encode(), DEFAULT_CHARACTER_SET);
System.out.println("encoded-->" + encoded);
NewsMsg dmsg = (NewsMsg) FIXMsgBuilder.build(encoded.getBytes(DEFAULT_CHARACTER_SET));
dmsg.decode();
NewsMsg40TestData.getInstance().check(msg, dmsg);
} finally {
unsetSecuredData();
}
}
/*
* Test of setNoLinesOfText method, of class NewsMsg40.
*/
@Test
public void testSetNoLinesOfText() throws Exception {
NewsMsg comp = (NewsMsg) FIXMsgBuilder.build(MsgType.News.getValue(), BeginString.FIX_4_0);
assertNull(comp.getLinesOfTextGroups());
comp.setNoLinesOfText(new Integer(3));
for (int i = 0; i < comp.getLinesOfTextGroups().length; i++) {
LinesOfTextGroup group = comp.getLinesOfTextGroups()[i];
group.setText("TEXT " + i);
}
assertEquals(3, comp.getLinesOfTextGroups().length);
int i = 0;
for (LinesOfTextGroup group : comp.getLinesOfTextGroups()) {
assertEquals("TEXT " + i, group.getText());
i++;
}
}
/*
* Test of addLinesOfTextGroup method, of class NewsMsg40.
*/
@Test
public void testAddLinesOfTextGroup() throws Exception {
NewsMsg comp = (NewsMsg) FIXMsgBuilder.build(MsgType.News.getValue(), BeginString.FIX_4_0);
assertNull(comp.getLinesOfTextGroups());
comp.setNoLinesOfText(new Integer(2));
assertEquals(2, comp.getLinesOfTextGroups().length);
for (int i = 0; i < comp.getLinesOfTextGroups().length; i++) {
LinesOfTextGroup group = comp.getLinesOfTextGroups()[i];
group.setText("TEXT " + i);
}
comp.addLinesOfTextGroup();
assertEquals(3, comp.getLinesOfTextGroups().length);
comp.getLinesOfTextGroups()[2].setText("TEXT 2");
int i = 0;
for (LinesOfTextGroup group : comp.getLinesOfTextGroups()) {
assertEquals("TEXT " + i, group.getText());
i++;
}
assertEquals(3, comp.getNoLinesOfText().intValue());
}
/*
* Test of deleteLinesOfTextGroup method, of class NewsMsg40.
*/
@Test
public void testDeleteLinesOfTextGroup() throws Exception {
NewsMsg comp = (NewsMsg) FIXMsgBuilder.build(MsgType.News.getValue(), BeginString.FIX_4_0);
assertNull(comp.getLinesOfTextGroups());
comp.setNoLinesOfText(new Integer(3));
for (int i = 0; i < comp.getLinesOfTextGroups().length; i++) {
LinesOfTextGroup group = comp.getLinesOfTextGroups()[i];
group.setText("TEXT " + i);
}
assertEquals(3, comp.getLinesOfTextGroups().length);
comp.deleteLinesOfTextGroup(1);
assertEquals(2, comp.getLinesOfTextGroups().length);
assertEquals(2, comp.getNoLinesOfText().intValue());
assertEquals("TEXT 2", comp.getLinesOfTextGroups()[1].getText());
}
/*
* Test of clearLinesOfTextGroups method, of class NewsMsg40.
*/
@Test
public void testClearLinesOfTextGroups() throws Exception {
NewsMsg comp = (NewsMsg) FIXMsgBuilder.build(MsgType.News.getValue(), BeginString.FIX_4_0);
assertNull(comp.getLinesOfTextGroups());
comp.setNoLinesOfText(new Integer(3));
for (int i = 0; i < comp.getLinesOfTextGroups().length; i++) {
LinesOfTextGroup group = comp.getLinesOfTextGroups()[i];
group.setText("TEXT " + i);
}
assertEquals(3, comp.getLinesOfTextGroups().length);
assertEquals(3, comp.getNoLinesOfText().intValue());
int i = 0;
for (LinesOfTextGroup group : comp.getLinesOfTextGroups()) {
assertEquals("TEXT " + i, group.getText());
i++;
}
comp.clearLinesOfTextGroups();
assertNull(comp.getNoLinesOfText());
assertNull(comp.getLinesOfTextGroups());
}
/**
* Test of encode getter method, of class NewsMsg 4.0 with unsupported tag.
*/
@Test
public void testGetUnsupportedMsgTag() {
System.out.println("-->testGetUnsupportedMsgTag");
NewsMsg msg = null;
try {
msg = (NewsMsg) FIXMsgBuilder.build(MsgType.News.getValue(), BeginString.FIX_4_0);
} catch (Exception ex) {
fail("Error building message");
}
try {
msg.getApplicationSequenceControl();
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.getNoRoutingIDs();
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.getRoutingIDGroups();
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.getNoRelatedSyms();
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.getInstruments();
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.getNoLegs();
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.getInstrumentLegs();
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.getNoUnderlyings();
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.getUnderlyingInstruments();
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
}
/**
* Test of encode setter method, of class NewsMsg 4.0 with unsupported tag.
*/
@Test
public void testSetUnsupportedMsgTag() {
System.out.println("-->testSetUnsupportedMsgTag");
NewsMsg msg = null;
try {
msg = (NewsMsg) FIXMsgBuilder.build(MsgType.News.getValue(), BeginString.FIX_4_0);
} catch (Exception ex) {
fail("Error building message");
}
try {
msg.setApplicationSequenceControl();
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.setNoRoutingIDs(new Integer(4));
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.addRoutingIDGroup();
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.deleteRoutingIDGroup(2);
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.clearRoutingIDGroups();
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.setNoRelatedSyms(new Integer(1));
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.addInstrument();
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.deleteInstrument(2);
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.clearInstruments();
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.setNoLegs(new Integer(1));
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.addInstrumentLeg();
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.deleteInstrumentLeg(2);
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.clearInstrumentLegs();
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.setNoUnderlyings(new Integer(3));
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.addUnderlyingInstrument();
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.deleteUnderlyingInstrument(3);
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
try {
msg.clearUnderlyingInstruments();
fail("Expect exception thrown.");
} catch (Exception ex) {
checkUnsupportedException(ex);
}
}
// NEGATIVE TEST CASES
/////////////////////////////////////////
/**
* Test of encode method, of class NewsMsg with missing NoLinesOfText data.
*/
@Test
public void testEncodeMissingNoLinesOfText() {
System.out.println("-->testEncodeMissingNoLinesOfText");
try {
NewsMsg msg = (NewsMsg) FIXMsgBuilder.build(MsgType.News.getValue(), BeginString.FIX_4_0);
TestUtils.populate40HeaderAll(msg);
msg.encode();
fail("Expect exception thrown.");
} catch (Exception ex) {
assertEquals( "Tag value(s) for [NoLinesOfText] is missing.", ex.getMessage());
}
}
/**
* Test of decode method, of class NewsMsg with missing NoLinesOfText data.
*/
@Test
public void testDecodeMissingReq() {
System.out.println("-->testDecodeMissingReq");
try {
dictionary = getQF40DataDictionary();
quickfix.fix40.News msg = new quickfix.fix40.News();
TestUtils.populateQuickFIX40HeaderAll(msg);
String strMsg = msg.toString();
System.out.println("qfix msg-->" + strMsg);
FIXMsg dmsg = FIXMsgBuilder.build(strMsg.getBytes(DEFAULT_CHARACTER_SET));
dmsg.decode();
fail("Expect exception thrown.");
} catch (Exception ex) {
assertEquals( "Tag value(s) for [NoLinesOfText] is missing.", ex.getMessage());
}
}
// UTILITY MESSAGES
/////////////////////////////////////////
private void checkUnsupportedException(Exception ex) {
assertEquals("This tag is not supported in [NewsMsg] message version [4.0].", ex.getMessage());
}
}
| gpl-3.0 |
MichielCM/jargon | jargon/src/main/java/jargon/model/folia/TermAnnotation.java | 4022 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.09.27 at 11:47:51 AM CEST
//
package jargon.model.folia;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="set" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
* <attribute name="annotator" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
* <attribute name="annotatortype" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
* <attribute name="datetime" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "term-annotation")
public class TermAnnotation {
@XmlAttribute(name = "set")
@XmlSchemaType(name = "anySimpleType")
protected String set;
@XmlAttribute(name = "annotator")
@XmlSchemaType(name = "anySimpleType")
protected String annotator;
@XmlAttribute(name = "annotatortype")
@XmlSchemaType(name = "anySimpleType")
protected String annotatortype;
@XmlAttribute(name = "datetime")
@XmlSchemaType(name = "anySimpleType")
protected String datetime;
/**
* Gets the value of the set property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSet() {
return set;
}
/**
* Sets the value of the set property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSet(String value) {
this.set = value;
}
/**
* Gets the value of the annotator property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAnnotator() {
return annotator;
}
/**
* Sets the value of the annotator property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAnnotator(String value) {
this.annotator = value;
}
/**
* Gets the value of the annotatortype property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAnnotatortype() {
return annotatortype;
}
/**
* Sets the value of the annotatortype property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAnnotatortype(String value) {
this.annotatortype = value;
}
/**
* Gets the value of the datetime property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDatetime() {
return datetime;
}
/**
* Sets the value of the datetime property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDatetime(String value) {
this.datetime = value;
}
}
| gpl-3.0 |
DavidVazGuijarro/simplerepost | app/src/main/java/ch/dbrgn/android/simplerepost/services/FileDownloadService.java | 5111 | /**
* SimpleRepost -- A simple Instagram reposting Android app.
* Copyright (C) 2014-2014 Danilo Bargen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**/
package ch.dbrgn.android.simplerepost.services;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import com.squareup.otto.Bus;
import com.squareup.otto.Subscribe;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.InputStream;
import ch.dbrgn.android.simplerepost.events.DownloadBitmapEvent;
import ch.dbrgn.android.simplerepost.events.DownloadErrorEvent;
import ch.dbrgn.android.simplerepost.events.DownloadedBitmapEvent;
import ch.dbrgn.android.simplerepost.models.ImageBitmap;
import ch.dbrgn.android.simplerepost.utils.AsyncTaskResult;
public class FileDownloadService implements Service {
private static final String LOG_TAG = FileDownloadService.class.getName();
private final Bus mBus;
public FileDownloadService(Bus bus) {
mBus = bus;
}
@Subscribe
public void onDownloadBitmap(DownloadBitmapEvent event) {
new DownloadBitmapTask().execute(event.getUrl());
}
/**
* Async task that downloads the bitmap in a background thread.
*/
private class DownloadBitmapTask extends AsyncTask<String, Void, AsyncTaskResult<ImageBitmap>> {
@Override
protected AsyncTaskResult<ImageBitmap> doInBackground(String... params) {
final String url = params[0];
return downloadBitmap(url);
}
@Override
protected void onPostExecute(AsyncTaskResult<ImageBitmap> result) {
if (result.hasError()) {
mBus.post(new DownloadErrorEvent(result.getError()));
} else {
final ImageBitmap imageBitmap = result.getResult();
mBus.post(new DownloadedBitmapEvent(imageBitmap));
}
}
/**
* Function that downloads the url and returns an AsyncTaskResult<ImageBitmap> instance.
*
* This code should be run in a background thread!
*/
private AsyncTaskResult<ImageBitmap> downloadBitmap(String url) {
final DefaultHttpClient client = new DefaultHttpClient();
Bitmap bitmap = null;
// Parse filename out of URL
final String[] parts = url.split("/");
final String filename = parts[parts.length - 1];
final HttpGet getRequest = new HttpGet(url);
try {
// Do the request
HttpResponse response = client.execute(getRequest);
// Check status code
final int statusCode = response.getStatusLine().getStatusCode();
// Handle error case
if (statusCode != HttpStatus.SC_OK) {
final String message = "Error " + statusCode + " while retrieving bitmap from " + url;
Log.w(LOG_TAG, message);
return new AsyncTaskResult<>(message);
}
// Get the data
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
// Get contents from the stream
inputStream = entity.getContent();
// Decode stream data back into image Bitmap that android understands
bitmap = BitmapFactory.decodeStream(inputStream);
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// TODO: We could provide a more explicit error message for IOException
getRequest.abort();
final String message = "Something went wrong while retrieving bitmap."; // TODO translate
Log.e(LOG_TAG, message, e);
return new AsyncTaskResult<>(message);
}
final ImageBitmap imageBitmap = new ImageBitmap(bitmap, filename);
return new AsyncTaskResult<>(imageBitmap);
}
}
}
| gpl-3.0 |
bd2kccd/tetradR | java/edu/cmu/tetrad/simulation/HsimEvalFromData.java | 11351 | package edu.cmu.tetrad.simulation;
import edu.cmu.tetrad.data.CovarianceMatrixOnTheFly;
import edu.cmu.tetrad.data.DataSet;
import edu.cmu.tetrad.data.ICovarianceMatrix;
import edu.cmu.tetrad.graph.Dag;
import edu.cmu.tetrad.graph.Graph;
import edu.cmu.tetrad.graph.GraphUtils;
import edu.cmu.tetrad.search.Fges;
import edu.cmu.tetrad.search.PatternToDag;
import edu.cmu.tetrad.search.SemBicScore;
import edu.cmu.tetrad.sem.SemEstimator;
import edu.cmu.tetrad.sem.SemIm;
import edu.cmu.tetrad.sem.SemPm;
import edu.cmu.tetrad.util.DataConvertUtils;
import edu.pitt.dbmi.data.reader.Delimiter;
import edu.pitt.dbmi.data.reader.tabular.ContinuousTabularDatasetFileReader;
import java.io.File;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
/**
* Created by ekummerfeld on 1/26/2017.
*/
public class HsimEvalFromData {
public static void main(String[] args) {
long timestart = System.nanoTime();
System.out.println("Beginning Evaluation");
String nl = System.lineSeparator();
String output = "Simulation edu.cmu.tetrad.study output comparing Fsim and Hsim on predicting graph discovery accuracy" + nl;
int iterations = 100;
int vars = 20;
int cases = 500;
int edgeratio = 3;
List<Integer> hsimRepeat = Arrays.asList(40);
List<Integer> fsimRepeat = Arrays.asList(40);
List<PRAOerrors>[] fsimErrsByPars = new ArrayList[fsimRepeat.size()];
int whichFrepeat = 0;
for (int frepeat : fsimRepeat) {
fsimErrsByPars[whichFrepeat] = new ArrayList<PRAOerrors>();
whichFrepeat++;
}
List<PRAOerrors>[][] hsimErrsByPars = new ArrayList[1][hsimRepeat.size()];
//System.out.println(resimSize.size()+" "+hsimRepeat.size());
int whichHrepeat;
whichHrepeat = 0;
for (int hrepeat : hsimRepeat) {
//System.out.println(whichrsize+" "+whichHrepeat);
hsimErrsByPars[0][whichHrepeat] = new ArrayList<PRAOerrors>();
whichHrepeat++;
}
//!(*%(@!*^!($%!^ START ITERATING HERE !#$%(*$#@!^(*!$*%(!$#
try {
for (int iterate = 0; iterate < iterations; iterate++) {
System.out.println("iteration " + iterate);
//@#$%@$%^@$^@$^@%$%@$#^ LOADING THE DATA AND GRAPH @$#%%*#^##*^$#@%$
DataSet data1;
Graph graph1 = GraphUtils.loadGraphTxt(new File("graph/graph.1.txt"));
Dag odag = new Dag(graph1);
Set<String> eVars = new HashSet<String>();
eVars.add("MULT");
Path dataFile = Paths.get("data/data.1.txt");
ContinuousTabularDatasetFileReader dataReader = new ContinuousTabularDatasetFileReader(dataFile, Delimiter.TAB);
data1 = (DataSet) DataConvertUtils.toDataModel(dataReader.readInData(eVars));
vars = data1.getNumColumns();
cases = data1.getNumRows();
edgeratio = 3;
//!#@^$@&%^!#$!&@^ CALCULATING TARGET ERRORS $%$#@^@!%!#^$!%$#%
ICovarianceMatrix newcov = new CovarianceMatrixOnTheFly(data1);
SemBicScore oscore = new SemBicScore(newcov);
Fges ofgs = new Fges(oscore);
ofgs.setVerbose(false);
ofgs.setNumPatternsToStore(0);
Graph oFGSGraph = ofgs.search();//***********This is the original FGS output on the data
PRAOerrors oErrors = new PRAOerrors(HsimUtils.errorEval(oFGSGraph, odag), "target errors");
//**then step 1: full resim. iterate through the combinations of estimator parameters (just repeat num)
for (whichFrepeat = 0; whichFrepeat < fsimRepeat.size(); whichFrepeat++) {
ArrayList<PRAOerrors> errorsList = new ArrayList<PRAOerrors>();
for (int r = 0; r < fsimRepeat.get(whichFrepeat); r++) {
PatternToDag pickdag = new PatternToDag(oFGSGraph);
Graph fgsDag = pickdag.patternToDagMeek();
Dag fgsdag2 = new Dag(fgsDag);
//then fit an IM to this dag and the data. GeneralizedSemEstimator seems to bug out
//GeneralizedSemPm simSemPm = new GeneralizedSemPm(fgsdag2);
//GeneralizedSemEstimator gsemEstimator = new GeneralizedSemEstimator();
//GeneralizedSemIm fittedIM = gsemEstimator.estimate(simSemPm, oData);
SemPm simSemPm = new SemPm(fgsdag2);
//BayesPm simBayesPm = new BayesPm(fgsdag2, bayesPm);
SemEstimator simSemEstimator = new SemEstimator(data1, simSemPm);
SemIm fittedIM = simSemEstimator.estimate();
DataSet simData = fittedIM.simulateData(data1.getNumRows(), false);
//after making the full resim data (simData), run FGS on that
ICovarianceMatrix simcov = new CovarianceMatrixOnTheFly(simData);
SemBicScore simscore = new SemBicScore(simcov);
Fges simfgs = new Fges(simscore);
simfgs.setVerbose(false);
simfgs.setNumPatternsToStore(0);
Graph simGraphOut = simfgs.search();
PRAOerrors simErrors = new PRAOerrors(HsimUtils.errorEval(simGraphOut, fgsdag2), "Fsim errors " + r);
errorsList.add(simErrors);
}
PRAOerrors avErrors = new PRAOerrors(errorsList, "Average errors for Fsim at repeat=" + fsimRepeat.get(whichFrepeat));
//if (verbosity>3) System.out.println(avErrors.allToString());
//****calculate the squared errors of prediction, store all these errors in a list
double FsimAR2 = (avErrors.getAdjRecall() - oErrors.getAdjRecall())
* (avErrors.getAdjRecall() - oErrors.getAdjRecall());
double FsimAP2 = (avErrors.getAdjPrecision() - oErrors.getAdjPrecision())
* (avErrors.getAdjPrecision() - oErrors.getAdjPrecision());
double FsimOR2 = (avErrors.getOrientRecall() - oErrors.getOrientRecall())
* (avErrors.getOrientRecall() - oErrors.getOrientRecall());
double FsimOP2 = (avErrors.getOrientPrecision() - oErrors.getOrientPrecision())
* (avErrors.getOrientPrecision() - oErrors.getOrientPrecision());
PRAOerrors Fsim2 = new PRAOerrors(new double[]{FsimAR2, FsimAP2, FsimOR2, FsimOP2},
"squared errors for Fsim at repeat=" + fsimRepeat.get(whichFrepeat));
//add the fsim squared errors to the appropriate list
fsimErrsByPars[whichFrepeat].add(Fsim2);
}
//**then step 2: hybrid sim. iterate through combos of params (repeat num, resimsize)
for (whichHrepeat = 0; whichHrepeat < hsimRepeat.size(); whichHrepeat++) {
HsimRepeatAC study = new HsimRepeatAC(data1);
PRAOerrors HsimErrors = new PRAOerrors(study.run(1, hsimRepeat.get(whichHrepeat)), "Hsim errors"
+ "at rsize=" + 1 + " repeat=" + hsimRepeat.get(whichHrepeat));
//****calculate the squared errors of prediction
double HsimAR2 = (HsimErrors.getAdjRecall() - oErrors.getAdjRecall())
* (HsimErrors.getAdjRecall() - oErrors.getAdjRecall());
double HsimAP2 = (HsimErrors.getAdjPrecision() - oErrors.getAdjPrecision())
* (HsimErrors.getAdjPrecision() - oErrors.getAdjPrecision());
double HsimOR2 = (HsimErrors.getOrientRecall() - oErrors.getOrientRecall())
* (HsimErrors.getOrientRecall() - oErrors.getOrientRecall());
double HsimOP2 = (HsimErrors.getOrientPrecision() - oErrors.getOrientPrecision())
* (HsimErrors.getOrientPrecision() - oErrors.getOrientPrecision());
PRAOerrors Hsim2 = new PRAOerrors(new double[]{HsimAR2, HsimAP2, HsimOR2, HsimOP2},
"squared errors for Hsim, rsize=" + 1 + " repeat=" + hsimRepeat.get(whichHrepeat));
hsimErrsByPars[0][whichHrepeat].add(Hsim2);
}
}
//Average the squared errors for each set of fsim/hsim params across all iterations
PRAOerrors[] fMSE = new PRAOerrors[fsimRepeat.size()];
PRAOerrors[][] hMSE = new PRAOerrors[1][hsimRepeat.size()];
String[][] latexTableArray = new String[1 * hsimRepeat.size() + fsimRepeat.size()][5];
for (int j = 0; j < fMSE.length; j++) {
fMSE[j] = new PRAOerrors(fsimErrsByPars[j], "MSE for Fsim at vars=" + vars + " edgeratio=" + edgeratio
+ " cases=" + cases + " frepeat=" + fsimRepeat.get(j) + " iterations=" + iterations);
//if(verbosity>0){System.out.println(fMSE[j].allToString());}
output = output + fMSE[j].allToString() + nl;
latexTableArray[j] = prelimToPRAOtable(fMSE[j]);
}
for (int j = 0; j < hMSE.length; j++) {
for (int k = 0; k < hMSE[j].length; k++) {
hMSE[j][k] = new PRAOerrors(hsimErrsByPars[j][k], "MSE for Hsim at vars=" + vars + " edgeratio=" + edgeratio
+ " cases=" + cases + " rsize=" + 1 + " repeat=" + hsimRepeat.get(k) + " iterations=" + iterations);
//if(verbosity>0){System.out.println(hMSE[j][k].allToString());}
output = output + hMSE[j][k].allToString() + nl;
latexTableArray[fsimRepeat.size() + j * hMSE[j].length + k] = prelimToPRAOtable(hMSE[j][k]);
}
}
//record all the params, the base error values, and the fsim/hsim mean squared errors
String latexTable = HsimUtils.makeLatexTable(latexTableArray);
PrintWriter writer = new PrintWriter("latexTable.txt", "UTF-8");
writer.println(latexTable);
writer.close();
PrintWriter writer2 = new PrintWriter("HvsF-SimulationEvaluation.txt", "UTF-8");
writer2.println(output);
writer2.close();
long timestop = System.nanoTime();
System.out.println("Evaluation Concluded. Duration: " + (timestop - timestart) / 1000000000 + "s");
} catch (Exception IOException) {
IOException.printStackTrace();
}
}
//******************Private Methods************************//
private static String[] prelimToPRAOtable(PRAOerrors input) {
String[] output = new String[5];
double[] values = input.toArray();
String[] vStrings = HsimUtils.formatErrorsArray(values, "%7.4e");
output[0] = input.getName();
for (int i = 1; i < output.length; i++) {
output[i] = vStrings[i - 1];
}
return output;
}
}
| gpl-3.0 |
s20121035/rk3288_android5.1_repo | packages/apps/Calendar/src/com/android/calendar/GoogleCalendarUriIntentFilter.java | 13462 | /*
**
** Copyright 2009, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** See the License for the specific language governing permissions and
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** limitations under the License.
*/
package com.android.calendar;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Attendees;
import android.provider.CalendarContract.Calendars;
import android.provider.CalendarContract.Events;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;
import com.android.calendarcommon2.DateException;
import com.android.calendarcommon2.Duration;
public class GoogleCalendarUriIntentFilter extends Activity {
private static final String TAG = "GoogleCalendarUriIntentFilter";
static final boolean debug = false;
private static final int EVENT_INDEX_ID = 0;
private static final int EVENT_INDEX_START = 1;
private static final int EVENT_INDEX_END = 2;
private static final int EVENT_INDEX_DURATION = 3;
private static final String[] EVENT_PROJECTION = new String[] {
Events._ID, // 0
Events.DTSTART, // 1
Events.DTEND, // 2
Events.DURATION, // 3
};
/**
* Extracts the ID and calendar email from the eid parameter of a URI.
*
* The URI contains an "eid" parameter, which is comprised of an ID, followed
* by a space, followed by the calendar email address. The domain is sometimes
* shortened. See the switch statement. This is Base64-encoded before being
* added to the URI.
*
* @param uri incoming request
* @return the decoded event ID and calendar email
*/
private String[] extractEidAndEmail(Uri uri) {
try {
String eidParam = uri.getQueryParameter("eid");
if (debug) Log.d(TAG, "eid=" + eidParam );
if (eidParam == null) {
return null;
}
byte[] decodedBytes = Base64.decode(eidParam, Base64.DEFAULT);
if (debug) Log.d(TAG, "decoded eid=" + new String(decodedBytes) );
for (int spacePosn = 0; spacePosn < decodedBytes.length; spacePosn++) {
if (decodedBytes[spacePosn] == ' ') {
int emailLen = decodedBytes.length - spacePosn - 1;
if (spacePosn == 0 || emailLen < 3) {
break;
}
String domain = null;
if (decodedBytes[decodedBytes.length - 2] == '@') {
// Drop the special one character domain
emailLen--;
switch(decodedBytes[decodedBytes.length - 1]) {
case 'm':
domain = "gmail.com";
break;
case 'g':
domain = "group.calendar.google.com";
break;
case 'h':
domain = "holiday.calendar.google.com";
break;
case 'i':
domain = "import.calendar.google.com";
break;
case 'v':
domain = "group.v.calendar.google.com";
break;
default:
Log.wtf(TAG, "Unexpected one letter domain: "
+ decodedBytes[decodedBytes.length - 1]);
// Add sql wild card char to handle new cases
// that we don't know about.
domain = "%";
break;
}
}
String eid = new String(decodedBytes, 0, spacePosn);
String email = new String(decodedBytes, spacePosn + 1, emailLen);
if (debug) Log.d(TAG, "eid= " + eid );
if (debug) Log.d(TAG, "email= " + email );
if (debug) Log.d(TAG, "domain=" + domain );
if (domain != null) {
email += domain;
}
return new String[] { eid, email };
}
}
} catch (RuntimeException e) {
Log.w(TAG, "Punting malformed URI " + uri);
}
return null;
}
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
Intent intent = getIntent();
if (intent != null) {
Uri uri = intent.getData();
if (uri != null) {
String[] eidParts = extractEidAndEmail(uri);
if (eidParts == null) {
Log.i(TAG, "Could not find event for uri: " +uri);
} else {
final String syncId = eidParts[0];
final String ownerAccount = eidParts[1];
if (debug) Log.d(TAG, "eidParts=" + syncId + "/" + ownerAccount);
final String selection = Events._SYNC_ID + " LIKE \"%" + syncId + "\" AND "
+ Calendars.OWNER_ACCOUNT + " LIKE \"" + ownerAccount + "\"";
if (debug) Log.d(TAG, "selection: " + selection);
Cursor eventCursor = getContentResolver().query(Events.CONTENT_URI,
EVENT_PROJECTION, selection, null,
Calendars.CALENDAR_ACCESS_LEVEL + " desc");
if (debug) Log.d(TAG, "Found: " + eventCursor.getCount());
if (eventCursor == null || eventCursor.getCount() == 0) {
Log.i(TAG, "NOTE: found no matches on event with id='" + syncId + "'");
return;
}
Log.i(TAG, "NOTE: found " + eventCursor.getCount()
+ " matches on event with id='" + syncId + "'");
// Don't print eidPart[1] as it contains the user's PII
try {
// Get info from Cursor
while (eventCursor.moveToNext()) {
int eventId = eventCursor.getInt(EVENT_INDEX_ID);
long startMillis = eventCursor.getLong(EVENT_INDEX_START);
long endMillis = eventCursor.getLong(EVENT_INDEX_END);
if (debug) Log.d(TAG, "_id: " + eventCursor.getLong(EVENT_INDEX_ID));
if (debug) Log.d(TAG, "startMillis: " + startMillis);
if (debug) Log.d(TAG, "endMillis: " + endMillis);
if (endMillis == 0) {
String duration = eventCursor.getString(EVENT_INDEX_DURATION);
if (debug) Log.d(TAG, "duration: " + duration);
if (TextUtils.isEmpty(duration)) {
continue;
}
try {
Duration d = new Duration();
d.parse(duration);
endMillis = startMillis + d.getMillis();
if (debug) Log.d(TAG, "startMillis! " + startMillis);
if (debug) Log.d(TAG, "endMillis! " + endMillis);
if (endMillis < startMillis) {
continue;
}
} catch (DateException e) {
if (debug) Log.d(TAG, "duration:" + e.toString());
continue;
}
}
// Pick up attendee status action from uri clicked
int attendeeStatus = Attendees.ATTENDEE_STATUS_NONE;
if ("RESPOND".equals(uri.getQueryParameter("action"))) {
try {
switch (Integer.parseInt(uri.getQueryParameter("rst"))) {
case 1: // Yes
attendeeStatus = Attendees.ATTENDEE_STATUS_ACCEPTED;
break;
case 2: // No
attendeeStatus = Attendees.ATTENDEE_STATUS_DECLINED;
break;
case 3: // Maybe
attendeeStatus = Attendees.ATTENDEE_STATUS_TENTATIVE;
break;
}
} catch (NumberFormatException e) {
// ignore this error as if the response code
// wasn't in the uri.
}
}
final Uri calendarUri = ContentUris.withAppendedId(
Events.CONTENT_URI, eventId);
intent = new Intent(Intent.ACTION_VIEW, calendarUri);
intent.setClass(this, EventInfoActivity.class);
intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startMillis);
intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endMillis);
if (attendeeStatus == Attendees.ATTENDEE_STATUS_NONE) {
startActivity(intent);
} else {
updateSelfAttendeeStatus(
eventId, ownerAccount, attendeeStatus, intent);
}
finish();
return;
}
} finally {
eventCursor.close();
}
}
}
// Can't handle the intent. Pass it on to the next Activity.
try {
startNextMatchingActivity(intent);
} catch (ActivityNotFoundException ex) {
// no browser installed? Just drop it.
}
}
finish();
}
private void updateSelfAttendeeStatus(
int eventId, String ownerAccount, final int status, final Intent intent) {
final ContentResolver cr = getContentResolver();
final AsyncQueryHandler queryHandler =
new AsyncQueryHandler(cr) {
@Override
protected void onUpdateComplete(int token, Object cookie, int result) {
if (result == 0) {
Log.w(TAG, "No rows updated - starting event viewer");
intent.putExtra(Attendees.ATTENDEE_STATUS, status);
startActivity(intent);
return;
}
final int toastId;
switch (status) {
case Attendees.ATTENDEE_STATUS_ACCEPTED:
toastId = R.string.rsvp_accepted;
break;
case Attendees.ATTENDEE_STATUS_DECLINED:
toastId = R.string.rsvp_declined;
break;
case Attendees.ATTENDEE_STATUS_TENTATIVE:
toastId = R.string.rsvp_tentative;
break;
default:
return;
}
Toast.makeText(GoogleCalendarUriIntentFilter.this,
toastId, Toast.LENGTH_LONG).show();
}
};
final ContentValues values = new ContentValues();
values.put(Attendees.ATTENDEE_STATUS, status);
queryHandler.startUpdate(0, null,
Attendees.CONTENT_URI,
values,
Attendees.ATTENDEE_EMAIL + "=? AND " + Attendees.EVENT_ID + "=?",
new String[]{ ownerAccount, String.valueOf(eventId) });
}
}
| gpl-3.0 |
SoapboxRaceWorld/soapbox-race-core | src/main/java/com/soapboxrace/jaxb/xmpp/XMPP_ResponseTypeRouteEntrantResult.java | 1271 | /*
* This file is part of the Soapbox Race World core source code.
* If you use any of this code for third-party purposes, please provide attribution.
* Copyright (c) 2020.
*/
package com.soapboxrace.jaxb.xmpp;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "XMPP_ResponseTypeRouteEntrantResult", propOrder = {"routeEntrantResult"})
@XmlRootElement(name = "response")
public class XMPP_ResponseTypeRouteEntrantResult {
@XmlElement(name = "RouteEntrantResult", required = true)
private XMPP_RouteEntrantResultType routeEntrantResult;
@XmlAttribute(name = "status")
private Integer status = 1;
@XmlAttribute(name = "ticket")
private Integer ticket = 0;
public XMPP_RouteEntrantResultType getRouteEntrantResult() {
return routeEntrantResult;
}
public void setRouteEntrantResult(XMPP_RouteEntrantResultType routeEntrantResult) {
this.routeEntrantResult = routeEntrantResult;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getTicket() {
return ticket;
}
public void setTicket(Integer ticket) {
this.ticket = ticket;
}
} | gpl-3.0 |
Robbie08/ParkSmart | app/src/main/java/com/example/robert/parksmart/dialog/BaseDialog.java | 1273 | package com.example.robert.parksmart.dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.os.Bundle;
import com.example.robert.parksmart.infrastructure.ParkSmartApplication;
import com.example.robert.parksmart.infrastructure.Utils;
import com.squareup.otto.Bus;
/**
* Created by ortiz on 9/25/2017.
*
* Base dialog that will be set as our model Dialog
*/
public class BaseDialog extends DialogFragment {
protected ParkSmartApplication application;
protected Bus bus;
protected String userEmail,userName;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
application = (ParkSmartApplication) getActivity().getApplication();
bus = application.getBus();
bus.register(this);
/* Allows us to get the userEmail and userName to all of our Dialog Fragments*/
userEmail = getActivity().getSharedPreferences(Utils.MY_PREFERENCE, Context.MODE_PRIVATE).getString(Utils.EMAIL,"");
userName = getActivity().getSharedPreferences(Utils.MY_PREFERENCE,Context.MODE_PRIVATE).getString(Utils.USERNAME,"");
}
@Override
public void onDestroy() {
super.onDestroy();
bus.unregister(this);
}
}
| gpl-3.0 |
Gameristic34/dark_heart | source/com/gameristic34/darkheart/modItems/ItemNames.java | 193 | package com.gameristic34.darkheart.modItems;
public class ItemNames {
public static String ITEM_PRIMAL_ESSENCE = "itemprimalessence";
public static String ITEMFOOD_GRULE = "itemfoodgrule";
} | gpl-3.0 |
otavanopisto/edelphi | edelphi/src/main/java/fi/internetix/edelphi/PrettyUrlFilter.java | 1041 | package fi.internetix.edelphi;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class PrettyUrlFilter implements Filter {
public void init(FilterConfig arg0) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
String ctxPath = ((HttpServletRequest) request).getContextPath();
String uri = ((HttpServletRequest) request).getRequestURI();
if (ctxPath.length() > 1) {
uri = uri.substring(ctxPath.length());
}
if (uri.startsWith("/_") || uri.equals("/robots.txt")) {
filterChain.doFilter(request, response);
}
else {
request.getRequestDispatcher("/_app" + uri).forward(request, response);
}
}
public void destroy() {
}
}
| gpl-3.0 |
derkaiserreich/structr | structr-core/src/main/java/org/structr/cron/CronService.java | 4426 | /**
* Copyright (C) 2010-2016 Structr GmbH
*
* This file is part of Structr <http://structr.org>.
*
* Structr is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Structr is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Structr. If not, see <http://www.gnu.org/licenses/>.
*/
package org.structr.cron;
import java.util.LinkedList;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.structr.api.service.Command;
import org.structr.api.service.RunnableService;
import org.structr.core.Services;
import org.structr.agent.Task;
import org.structr.api.service.StructrServices;
import org.structr.core.app.StructrApp;
/**
* A service that keeps track of registered tasks and runs
* them at their scheduled time.
*
*
*/
public class CronService extends Thread implements RunnableService {
private static final Logger logger = Logger.getLogger(CronService.class.getName());
public static final String TASKS = "CronService.tasks";
public static final String EXPRESSION_SUFFIX = ".cronExpression";
public static final TimeUnit GRANULARITY_UNIT = TimeUnit.SECONDS;
public static final long GRANULARITY = 1;
public static final int NUM_FIELDS = 6;
private LinkedList<CronEntry> cronEntries = new LinkedList<>();
private boolean doRun = false;
public CronService() {
super("CronService");
this.setDaemon(true);
}
@Override
public void run() {
final Services servicesInstance = Services.getInstance();
// wait for service layer to be initialized
while(!servicesInstance.isInitialized()) {
try { Thread.sleep(1000); } catch(InterruptedException iex) { }
}
// sleep 5 seconds more
try { Thread.sleep(5000); } catch(InterruptedException iex) { }
while(doRun) {
// sleep for some time
try { Thread.sleep(GRANULARITY_UNIT.toMillis(GRANULARITY)); } catch(InterruptedException iex) { }
for(CronEntry entry : cronEntries) {
if(entry.getDelayToNextExecutionInMillis() < GRANULARITY_UNIT.toMillis(GRANULARITY)) {
String taskClassName = entry.getName();
try {
Class taskClass = Class.forName(taskClassName);
Task task = (Task)taskClass.newInstance();
logger.log(Level.FINE, "Starting task {0}", taskClassName);
StructrApp.getInstance().processTasks(task);
} catch(Throwable t) {
logger.log(Level.WARNING, "Could not start task {0}: {1}", new Object[] { taskClassName, t.getMessage() } );
}
}
}
}
}
// ----- interface RunnableService -----
@Override
public void startService() throws Exception {
this.doRun = true;
this.start();
}
@Override
public void stopService() {
this.doRun = false;
}
@Override
public boolean runOnStartup() {
return true;
}
@Override
public boolean isRunning() {
return doRun;
}
@Override
public void injectArguments(Command command) {
}
@Override
public void initialize(final StructrServices services, final Properties config) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
final String taskList = config.getProperty(TASKS, "");
if (taskList != null) {
for(String task : taskList.split("[ \\t]+")) {
String expression = config.getProperty(task.concat(EXPRESSION_SUFFIX));
if(expression != null) {
CronEntry entry = CronEntry.parse(task, expression);
if(entry != null) {
logger.log(Level.INFO, "Adding cron entry {0} for {1}", new Object[]{ entry, task });
cronEntries.add(entry);
} else {
logger.log(Level.WARNING, "Unable to parse cron expression for taks {0}, ignoring.", task);
}
} else {
logger.log(Level.WARNING, "No cron expression for task {0}, ignoring.", task);
}
}
}
}
@Override
public void initialized() {}
@Override
public void shutdown() {
this.doRun = false;
}
@Override
public boolean isVital() {
return false;
}
}
| gpl-3.0 |
316181444/Hxms | src/main/java/net/sf/odinms/client/skills/弓手.java | 920 | package net.sf.odinms.client.skills;
public class 弓手 {
public static final int 精准弓 = 3100000;
public static final int 快速箭 = 3101002;
public static final int 强弓 = 3101003;
public static final int 无形箭 = 3101004;
public static final int 爆炸箭 = 3101005;
// 3
public static final int 贯穿箭 = 3110001;
public static final int 替身术 = 3111002;
public static final int 箭雨 = 3111004;
public static final int 银鹰召唤 = 3111005;
public static final int 箭扫射 = 3111006;
// 4
public static final int 冒险岛勇士 = 3121000;
public static final int 火眼晶晶 = 3121002;
public static final int 暴风箭雨 = 3121004;
public static final int 神箭手 = 3120005;
public static final int 火凤凰 = 3121006;
public static final int 缓速箭 = 3121007;
public static final int 集中精力 = 3121008;
public static final int 勇士的意志 = 3121009;
}
| gpl-3.0 |
coder7dc/Jpass | src/com/jjp/passwd/Passmang.java | 54 | package com.jjp.passwd;
public class Passmang {
}
| gpl-3.0 |
KHoW8Day/tastytungsten | src/processor/tastytungsten/ElementValuesKeyTransformer.java | 365 |
package tastytungsten ;
import javax . lang . model . element . Element ;
abstract class ElementValuesKeyTransformer implements Transformer < String , Element >
{
@ Override
public final String transform ( Element element )
{
Object simpleName = element . getSimpleName ( ) ;
String string = simpleName . toString ( ) ;
return string ;
}
}
| gpl-3.0 |
JDrost1818/plaster | src/main/java/github/jdrost1818/plaster/service/task/delete/ModelDelete.java | 433 | package github.jdrost1818.plaster.service.task.delete;
import github.jdrost1818.plaster.data.TemplateType;
import github.jdrost1818.plaster.service.task.PlasterTaskId;
public class ModelDelete extends DeleteTask {
public ModelDelete() {
super(
"Could not delete model",
PlasterTaskId.MODEL,
TemplateType.MODEL,
new ModelTestDelete()
);
}
}
| gpl-3.0 |
NYRDS/pixel-dungeon-remix | RemixedDungeon/src/main/java/com/watabou/pixeldungeon/actors/RespawnerActor.java | 1476 | package com.watabou.pixeldungeon.actors;
import com.nyrds.pixeldungeon.ai.MobAi;
import com.nyrds.pixeldungeon.ai.Wandering;
import com.watabou.pixeldungeon.Dungeon;
import com.watabou.pixeldungeon.Statistics;
import com.watabou.pixeldungeon.actors.hero.Hero;
import com.watabou.pixeldungeon.actors.mobs.Mob;
import com.watabou.pixeldungeon.levels.Level;
public class RespawnerActor extends Actor {
private static final float TIME_TO_RESPAWN = 50;
private final Level level;
public RespawnerActor(Level level) {
this.level = level;
}
@Override
protected boolean act() {
final Hero hero = Dungeon.hero;
if(hero.isAlive()) {
int hostileMobsCount = 0;
for (Mob mob : level.mobs) {
if (!mob.isPet()) {
hostileMobsCount++;
}
}
if (hostileMobsCount < level.nMobs()) {
Mob mob = level.createMob();
if (level.cellValid(mob.getPos())) {
mob.setState(MobAi.getStateByClass(Wandering.class));
level.spawnMob(mob);
if (Statistics.amuletObtained) {
mob.beckon(hero.getPos());
}
}
}
}
float time = Dungeon.nightMode || Statistics.amuletObtained ? TIME_TO_RESPAWN / 2
: TIME_TO_RESPAWN;
spend(time);
return true;
}
}
| gpl-3.0 |
interoberlin/lymbo | app/src/main/java/de/interoberlin/lymbo/util/ColorUtil.java | 1235 | package de.interoberlin.lymbo.util;
import android.content.Context;
import org.apache.commons.lang3.ArrayUtils;
import de.interoberlin.lymbo.R;
public class ColorUtil {
/**
* Returns a color from a given set of possibilities based on the string content
*
* @param c context
* @param value string value
* @param colorsDark array of dark colors
* @param colorsLight array of light colors
* @return generated color
*/
public static int getColorByString(Context c, String value, int[] colorsDark, int[] colorsLight) {
int[] colors = ArrayUtils.addAll(colorsDark, colorsLight);
return colors[Math.abs(value.hashCode()) % (colors.length)];
}
/**
* Returns a suitable text color for given set of possibilities
*
* @param value string value
* @param colorsDark array of dark colors
* @param colorsLight array of light colors
* @return suitable color
*/
public static int getTextColorByString(String value, int[] colorsDark, int[] colorsLight) {
return Math.abs(value.hashCode()) % (colorsDark.length + colorsLight.length) < colorsDark.length ? R.color.white : R.color.card_title_text;
}
}
| gpl-3.0 |
gama-platform/gama | msi.gama.core/src/msi/gama/kernel/batch/TabuSearch.java | 7956 | /*******************************************************************************************************
*
* msi.gama.kernel.batch.TabuSearch.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and
* simulation platform (v. 1.8.1)
*
* (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners
*
* Visit https://github.com/gama-platform/gama for license information and contacts.
*
********************************************************************************************************/
package msi.gama.kernel.batch;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import msi.gama.common.interfaces.IKeyword;
import msi.gama.kernel.experiment.BatchAgent;
import msi.gama.kernel.experiment.IExperimentPlan;
import msi.gama.kernel.experiment.IParameter;
import msi.gama.kernel.experiment.ParameterAdapter;
import msi.gama.kernel.experiment.ParametersSet;
import msi.gama.precompiler.GamlAnnotations.doc;
import msi.gama.precompiler.GamlAnnotations.example;
import msi.gama.precompiler.GamlAnnotations.facet;
import msi.gama.precompiler.GamlAnnotations.facets;
import msi.gama.precompiler.GamlAnnotations.inside;
import msi.gama.precompiler.GamlAnnotations.symbol;
import msi.gama.precompiler.GamlAnnotations.usage;
import msi.gama.precompiler.IConcept;
import msi.gama.precompiler.ISymbolKind;
import msi.gama.runtime.IScope;
import msi.gama.runtime.exceptions.GamaRuntimeException;
import msi.gaml.descriptions.IDescription;
import msi.gaml.expressions.IExpression;
import msi.gaml.operators.Cast;
import msi.gaml.types.IType;
@symbol (
name = IKeyword.TABU,
kind = ISymbolKind.BATCH_METHOD,
with_sequence = false,
concept = { IConcept.BATCH, IConcept.ALGORITHM })
@inside (
kinds = { ISymbolKind.EXPERIMENT })
@facets (
value = { @facet (
name = IKeyword.NAME,
type = IType.ID,
optional = false,
internal = true,
doc = @doc ("The name of the method. For internal use only")),
@facet (
name = TabuSearch.ITER_MAX,
type = IType.INT,
optional = true,
doc = @doc ("number of iterations")),
@facet (
name = TabuSearch.LIST_SIZE,
type = IType.INT,
optional = true,
doc = @doc ("size of the tabu list")),
@facet (
name = IKeyword.MAXIMIZE,
type = IType.FLOAT,
optional = true,
doc = @doc ("the value the algorithm tries to maximize")),
@facet (
name = IKeyword.MINIMIZE,
type = IType.FLOAT,
optional = true,
doc = @doc ("the value the algorithm tries to minimize")),
@facet (
name = IKeyword.AGGREGATION,
type = IType.LABEL,
optional = true,
values = { IKeyword.MIN, IKeyword.MAX },
doc = @doc ("the agregation method")) },
omissible = IKeyword.NAME)
@doc (
value = "This algorithm is an implementation of the Tabu Search algorithm. See the wikipedia article and [batch161 the batch dedicated page].",
usages = { @usage (
value = "As other batch methods, the basic syntax of the tabu statement uses `method tabu` instead of the expected `tabu name: id` : ",
examples = { @example (
value = "method tabu [facet: value];",
isExecutable = false) }),
@usage (
value = "For example: ",
examples = { @example (
value = "method tabu iter_max: 50 tabu_list_size: 5 maximize: food_gathered;",
isExecutable = false) }) })
public class TabuSearch extends LocalSearchAlgorithm {
protected static final String ITER_MAX = "iter_max";
protected static final String LIST_SIZE = "tabu_list_size";
int tabuListSize = 5;
StoppingCriterion stoppingCriterion = new StoppingCriterionMaxIt(50);
public TabuSearch(final IDescription species) {
super(species);
initParams();
}
@Override
public ParametersSet findBestSolution(final IScope scope) throws GamaRuntimeException {
initializeTestedSolutions();
final List<ParametersSet> tabuList = new ArrayList<>();
ParametersSet bestSolutionAlgo = this.solutionInit;
tabuList.add(bestSolutionAlgo);
final double currentFitness = currentExperiment.launchSimulationsWithSolution(bestSolutionAlgo);
testedSolutions.put(bestSolutionAlgo, currentFitness);
setBestSolution(new ParametersSet(bestSolutionAlgo));
setBestFitness(currentFitness);
int nbIt = 0;
double bestFitnessAlgo = currentFitness;
final Map<String, Object> endingCritParams = new Hashtable<>();
endingCritParams.put("Iteration", Integer.valueOf(nbIt));
while (!stoppingCriterion.stopSearchProcess(endingCritParams)) {
// scope.getGui().debug("TabuSearch.findBestSolution while stoppingCriterion " + endingCritParams);
final List<ParametersSet> neighbors = neighborhood.neighbor(scope, bestSolutionAlgo);
neighbors.removeAll(tabuList);
if (neighbors.isEmpty()) {
if (tabuList.isEmpty()) {
break;
}
neighbors.add(tabuList.get(scope.getRandom().between(0, tabuList.size() - 1)));
}
if (isMaximize()) {
bestFitnessAlgo = -Double.MAX_VALUE;
} else {
bestFitnessAlgo = Double.MAX_VALUE;
}
ParametersSet bestNeighbor = null;
for (final ParametersSet neighborSol : neighbors) {
// scope.getGui().debug("TabuSearch.findBestSolution for parametersSet " + neighborSol);
if (neighborSol == null) {
continue;
}
Double neighborFitness = testedSolutions.get(neighborSol);
if (neighborFitness == null || neighborFitness == Double.MAX_VALUE) {
neighborFitness = currentExperiment.launchSimulationsWithSolution(neighborSol);
nbIt++;
} else {
continue;
}
testedSolutions.put(neighborSol, neighborFitness);
// scope.getGui().debug("TabuSearch.findBestSolution neighborFitness = " + neighborFitness +
// " bestFitnessAlgo = " + bestFitnessAlgo + " bestFitness = " + getBestFitness() +
// " current fitness = " + currentFitness);
final boolean neighFitnessGreaterThanBest = neighborFitness > bestFitnessAlgo;
if (isMaximize() && neighFitnessGreaterThanBest || !isMaximize() && !neighFitnessGreaterThanBest) {
bestNeighbor = neighborSol;
bestFitnessAlgo = neighborFitness;
}
if (nbIt > iterMax) {
break;
}
}
if (bestNeighbor != null) {
bestSolutionAlgo = bestNeighbor;
tabuList.add(bestSolutionAlgo);
if (tabuList.size() > tabuListSize) {
tabuList.remove(0);
}
// currentFitness = bestFitnessAlgo;
} else {
break;
}
endingCritParams.put("Iteration", Integer.valueOf(nbIt));
}
// DEBUG.LOG("Best solution : " + currentSol + " fitness : "
// + currentFitness);
return getBestSolution();
}
int iterMax = 50;
//
// @Override
// public void initializeFor(final IScope scope, final BatchAgent agent) throws GamaRuntimeException {
// super.initializeFor(scope, agent);
//
// }
@Override
public void initParams(final IScope scope) {
final IExpression maxIt = getFacet(ITER_MAX);
if (maxIt != null) {
iterMax = Cast.asInt(scope, maxIt.value(scope));
stoppingCriterion = new StoppingCriterionMaxIt(iterMax);
}
final IExpression listsize = getFacet(LIST_SIZE);
if (listsize != null) {
tabuListSize = Cast.asInt(scope, listsize.value(scope));
}
}
@Override
public void addParametersTo(final List<IParameter.Batch> params, final BatchAgent agent) {
super.addParametersTo(params, agent);
params.add(new ParameterAdapter("Tabu list size", IExperimentPlan.BATCH_CATEGORY_NAME, IType.INT) {
@Override
public Object value() {
return tabuListSize;
}
});
params.add(
new ParameterAdapter("Maximum number of iterations", IExperimentPlan.BATCH_CATEGORY_NAME, IType.FLOAT) {
@Override
public Object value() {
return iterMax;
}
});
}
}
| gpl-3.0 |
ManuRodriguezSebastian/DAM | Procesos/EjerciciosClase/src/EjecutaPB03.java | 575 | import java.io.*;
import java.util.*;
public class EjecutaPB03 {
//Entrada y salida de comandos por medio de ficheros
/**
* @param args
*/
public static void main(String[] args) throws IOException {
ProcessBuilder pb=new ProcessBuilder("/bin/bash");
File f=new File("salida.txt");
File f_error=new File("error.txt");
File f_in=new File("entrada.txt");
try{
pb.redirectInput(f_in);
pb.redirectOutput(f);
pb.redirectError(f_error);
Process p=pb.start();
}catch(Exception ex){
System.out.println("Error");
ex.printStackTrace();
}
}
}
| gpl-3.0 |
JeppeLeth/robogrid | app/src/main/java/com/jleth/projects/robogrid/android/ui/activity/StartLocationActivity.java | 2881 | package com.jleth.projects.robogrid.android.ui.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.jleth.projects.robogrid.android.R;
import com.jleth.projects.robogrid.android.model.Location;
import com.jleth.projects.robogrid.android.model.Size;
/**
* Set start location and direction before beginning
*/
public class StartLocationActivity extends AppCompatActivity {
private static final String TAG = "StartLocationActivity";
private static final String ARGS_GRID_SIZE = "ARGS_GRID_SIZE";
private StartLocationPage mPage;
private Size mGridSize;
public static Intent newIntent(Context context, Size gridSize) {
Intent i = new Intent(context, StartLocationActivity.class);
i.putExtra(ARGS_GRID_SIZE, gridSize);
return i;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_location);
extractIntent();
initContent();
hide();
setupPageListener();
if (savedInstanceState == null) {
animateIntro();
}
}
private void extractIntent() {
mGridSize = getIntent().getParcelableExtra(ARGS_GRID_SIZE);
}
@Override
protected void onResume() {
super.onResume();
hide();
}
private void hide() {
// Hide UI first
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
mPage.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
private void initContent() {
mPage = (StartLocationPage) findViewById(R.id.mainContent);
mPage.setGridSize(mGridSize);
}
private void setupPageListener() {
mPage.setListener(new StartLocationPage.Listener() {
@Override
public void onLocationChosen(final Location location) {
mPage.animateDisappearContent(new Runnable() {
@Override
public void run() {
startActivity(MoveInteractionActivity.newIntent(mPage.getContext(), mGridSize, location));
finish();
overridePendingTransition(0, 0);
}
});
}
});
}
private void animateIntro() {
mPage.animateRevealContent(null);
}
}
| gpl-3.0 |
santanapablo1975/JavaTest | Dia1/src/UsuarioAdmin.java | 256 |
public class UsuarioAdmin {
public void Mostrar(Usuario modelo){
System.out.println("Nombre: " +modelo.getNombre());
System.out.println("Apellido: " +modelo.getApellido());
System.out.println("Edad: " +modelo.getEdad());
}
}
| gpl-3.0 |
liyi-david/ePMC | plugins/jani-model/src/main/java/epmc/jani/dd/DDComponent.java | 4382 | /****************************************************************************
ePMC - an extensible probabilistic model checker
Copyright (C) 2017
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
package epmc.jani.dd;
import java.io.Closeable;
import java.util.List;
import java.util.Set;
import epmc.dd.DD;
import epmc.dd.VariableDD;
import epmc.jani.model.component.Component;
/**
* DD-based symbolic representation of a {@link Component}.
* This class is responsible to build symbolic representations of
* <ul>
* <li>initial nodes,</li>
* <li>transitions resulting from automata and their composition,</li>
* <li>variables used (read and written) by the component</li>
* </ul>
* of the component, which result either directly (from automata) or indirectly
* (from composition).
*
* @author Ernst Moritz Hahn
*/
interface DDComponent extends Closeable {
/**
* Set the graph to which this DD component belongs.
* The parameter may not be {@code null}.
* The function must be called exactly once before calling {@link #build()}.
*
* @param graph graph to which this DD component belongs
*/
void setGraph(GraphDDJANI graph);
/**
* Set component which shall be represented by this DD component.
* The parameter may not be {@code null}.
* The function must be called exactly once before calling {@link #build()}.
* The function may only be called for a parameter which is of the correct
* class implementing the translation. Thus, this function as well as the
* preparing previous function calls should be performed by
* {@link PreparatorDDComponent} which contains an according translation
* table.
*
* @param component component to represent by this DD component
*/
void setComponent(Component component);
/**
* Build this DD component.
* Before calling this function, {@link #setGraph(GraphDDJANI)} and {@link
* #setComponent(Component)} must have been called. The function must be
* called exactly once.
*
*/
void build();
/**
* Obtain the DD transitions of this DD component.
* Before calling this function, {@link #build()} must have been called
* without throwing an exception.
*
* @return DD transitions of this DD component
*/
List<DDTransition> getTransitions();
/**
* Obtain initial nodes of this DD component.
* The initial nodes should assign the according values to the local
* variables of this DD component, but not the global ones.
* Before calling this function, {@link #build()} must have been called
* without throwing an exception.
*
* @return initial nodes of this DD component
*/
DD getInitialNodes();
/**
* Get the cube of present state variables of the component.
* This includes local variables as well as variables to encode states of
* automata. It does not include global variables.
*
* @return present state variables cube
*/
DD getPresCube();
/**
* Get the cube of next state variables of the component.
* This includes local variables as well as variables to encode states of
* automata. It does not include global variables.
*
* @return next state variables cube
*/
DD getNextCube();
/**
* Get the set of DD variables of the component.
* This includes the local variables of automata, as well as variables to
* encode variables in automata. It does not include global variables.
*
* @return variables of the component
*/
Set<VariableDD> getVariables();
@Override
void close();
}
| gpl-3.0 |
pgillet/Glue | glue-persistence/src/main/java/com/glue/persistence/index/SolrServerManager.java | 616 | package com.glue.persistence.index;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.impl.ConcurrentUpdateSolrServer;
public class SolrServerManager {
private static SolrServer solrServer;
public synchronized static SolrServer getSolrServer() {
if (solrServer == null) {
solrServer = createNewSolrServer();
}
return solrServer;
}
private static SolrServer createNewSolrServer() {
int queueSize = 1000;
int threadCount = 5;
// Thread-safe
return new ConcurrentUpdateSolrServer(SolrParams.getSolrServerUrl(),
queueSize,
threadCount);
}
}
| gpl-3.0 |
max-leuthaeuser/naoservice | javaClient/org.qualitune.naoservice.client/src/org/qualitune/naoservice/client/NaoJointInfos.java | 19318 | package org.qualitune.naoservice.client;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Class that contains infos of all Joints within the {@link Nao}.
*
* @author Claas Wilke
*/
public class NaoJointInfos {
/** Contains all identifiers necessary for a {@link NaoJointInfos} request. */
protected static List<Integer> identifiers;
/** The {@link NaoJointInfo} of every joint by its {@link NaoJointID}. */
protected Map<NaoJointID, NaoJointInfo> jointInfos = new HashMap<NaoJointID, NaoJointInfo>();
/**
* Creates new {@link NaoJointInfo}s for a given {@link Nao}.
*
* @param nao
* The {@link Nao}.
* @param requestInfos
* If <code>true</code> this {@link NaoJointID} will by itself
* connect to the {@link Nao} and requests its infos. Otherwhise
* they have to be set manually.
* @throws NaoUtilException
*/
public NaoJointInfos(NaoData nao, boolean requestInfos) throws NaoUtilException {
/* Create the infos. */
for (NaoJointID id : NaoJointID.values()) {
jointInfos.put(id, new NaoJointInfo(nao, id, false));
}
// end for.
if (requestInfos) {
if (identifiers == null)
initIdentifiers();
// no else.
/* Request all the info. */
Map<String, String> values = NaoUtil.getSensorValues(nao,
identifiers);
/* Set the info for all the NaoJointInfo objects. */
for (String key : values.keySet()) {
if (key.contains("HeadPitch"))
setNaoJointInfoValue(jointInfos.get(NaoJointID.HeadPitch),
key, values.get(key));
else if (key.contains("HeadYaw"))
setNaoJointInfoValue(jointInfos.get(NaoJointID.HeadYaw),
key, values.get(key));
else if (key.contains("LAnklePitch"))
setNaoJointInfoValue(
jointInfos.get(NaoJointID.LAnklePitch), key,
values.get(key));
else if (key.contains("LAnkleRoll"))
setNaoJointInfoValue(jointInfos.get(NaoJointID.LAnkleRoll),
key, values.get(key));
else if (key.contains("LElbowRoll"))
setNaoJointInfoValue(jointInfos.get(NaoJointID.LElbowRoll),
key, values.get(key));
else if (key.contains("LElbowYaw"))
setNaoJointInfoValue(jointInfos.get(NaoJointID.LElbowYaw),
key, values.get(key));
else if (key.contains("LHipPitch"))
setNaoJointInfoValue(jointInfos.get(NaoJointID.LHipPitch),
key, values.get(key));
else if (key.contains("LHipRoll"))
setNaoJointInfoValue(jointInfos.get(NaoJointID.LHipRoll),
key, values.get(key));
else if (key.contains("LHipYawPitch"))
setNaoJointInfoValue(
jointInfos.get(NaoJointID.LHipYawPitch), key,
values.get(key));
else if (key.contains("LKneePitch"))
setNaoJointInfoValue(jointInfos.get(NaoJointID.LKneePitch),
key, values.get(key));
else if (key.contains("LShoulderPitch"))
setNaoJointInfoValue(
jointInfos.get(NaoJointID.LShoulderPitch), key,
values.get(key));
else if (key.contains("LShoulderRoll"))
setNaoJointInfoValue(
jointInfos.get(NaoJointID.LShoulderRoll), key,
values.get(key));
else if (key.contains("RAnklePitch"))
setNaoJointInfoValue(
jointInfos.get(NaoJointID.RAnklePitch), key,
values.get(key));
else if (key.contains("RAnkleRoll"))
setNaoJointInfoValue(jointInfos.get(NaoJointID.RAnkleRoll),
key, values.get(key));
else if (key.contains("RElbowRoll"))
setNaoJointInfoValue(jointInfos.get(NaoJointID.RElbowRoll),
key, values.get(key));
else if (key.contains("RElbowYaw"))
setNaoJointInfoValue(jointInfos.get(NaoJointID.RElbowYaw),
key, values.get(key));
else if (key.contains("RHipPitch"))
setNaoJointInfoValue(jointInfos.get(NaoJointID.RHipPitch),
key, values.get(key));
else if (key.contains("RHipRoll"))
setNaoJointInfoValue(jointInfos.get(NaoJointID.RHipRoll),
key, values.get(key));
else if (key.contains("RKneePitch"))
setNaoJointInfoValue(jointInfos.get(NaoJointID.RKneePitch),
key, values.get(key));
else if (key.contains("RShoulderPitch"))
setNaoJointInfoValue(
jointInfos.get(NaoJointID.RShoulderPitch), key,
values.get(key));
else if (key.contains("RShoulderRoll"))
setNaoJointInfoValue(
jointInfos.get(NaoJointID.RShoulderRoll), key,
values.get(key));
else if (key.contains(NaoConstants.TIME_STAMP)) {
long timestamp = Math.round(Double.parseDouble(values
.get(key)) * 1000000000);
for (NaoJointID id : NaoJointID.values())
jointInfos.get(id).timeStamp = timestamp;
// end for.
} else
throw new NaoUtilException("Unknown sensor identifier: "
+ key);
}
}
// no else.
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuffer result = new StringBuffer();
result.append(NaoJointInfo.getLegend());
List<NaoJointID> keys = new ArrayList<NaoJointID>(jointInfos.keySet());
Collections.sort(keys);
for (NaoJointID id : keys) {
result.append(jointInfos.get(id) + "\n");
}
// end for.
return result.toString();
}
public String getIntendedJointPositions(boolean withLegend) {
StringBuffer resultLegend = new StringBuffer();
StringBuffer result = new StringBuffer();
for (NaoJointID id : NaoJointID.values()) {
resultLegend.append(id + " | ");
result.append(jointInfos.get(id).getPositionIntended() + " | ");
}
// end for.
if (withLegend)
return resultLegend.toString() + "\n" + result.toString();
else
return result.toString();
}
/**
* Returns the {@link NaoJointInfo} for a given {@link NaoJointID}.
*
* @param id
* The {@link NaoJointID}.
* @return The corresponding {@link NaoJointInfo}.
*/
public NaoJointInfo getJointInfo(NaoJointID id) {
if (id == null)
throw new IllegalArgumentException("Argument 'id' cannot be null.");
// no else.
return jointInfos.get(id);
}
/**
* Helper method to set a {@link NaoJointInfo} value for a given
* {@link NaoJointInfo} that is identified by its sensor name.
*
* @param info
* The {@link NaoJointInfo} for which the value shall be set.
* @param key
* The sensor name of the value.
* @param value
* The value as a String.
*/
protected void setNaoJointInfoValue(NaoJointInfo info, String key,
String value) {
if (key.contains("ElectricCurrent"))
info.current = Double.parseDouble(value);
else if (key.contains("Hardness"))
info.stiffness = Double.parseDouble(value);
else if (key.contains("Position/Actuator"))
info.positionIntended = Double.parseDouble(value);
else if (key.contains("Position/Sensor"))
info.position = Double.parseDouble(value);
else if (key.contains("Temperature"))
info.temperature = Double.parseDouble(value);
// no else.
}
/**
* Helper method to initialize the identifier list.
*/
protected void initIdentifiers() {
identifiers = new ArrayList<Integer>();
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_HEADYAW_ELECTRICCURRENT_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_HEADYAW_HARDNESS_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_HEADYAW_POSITION_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_HEADYAW_POSITION_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_HEADYAW_TEMPERATURE_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_HEADPITCH_ELECTRICCURRENT_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_HEADPITCH_HARDNESS_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_HEADPITCH_POSITION_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_HEADPITCH_POSITION_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_HEADPITCH_TEMPERATURE_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LSHOULDERPITCH_ELECTRICCURRENT_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LSHOULDERPITCH_HARDNESS_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LSHOULDERPITCH_POSITION_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LSHOULDERPITCH_POSITION_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LSHOULDERPITCH_TEMPERATURE_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LSHOULDERROLL_ELECTRICCURRENT_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LSHOULDERROLL_HARDNESS_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LSHOULDERROLL_POSITION_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LSHOULDERROLL_POSITION_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LSHOULDERROLL_TEMPERATURE_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LELBOWYAW_ELECTRICCURRENT_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LELBOWYAW_HARDNESS_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LELBOWYAW_POSITION_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LELBOWYAW_POSITION_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LELBOWYAW_TEMPERATURE_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LELBOWROLL_ELECTRICCURRENT_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LELBOWROLL_HARDNESS_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LELBOWROLL_POSITION_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LELBOWROLL_POSITION_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LELBOWROLL_TEMPERATURE_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LHIPYAWPITCH_ELECTRICCURRENT_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LHIPYAWPITCH_HARDNESS_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LHIPYAWPITCH_POSITION_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LHIPYAWPITCH_POSITION_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LHIPYAWPITCH_TEMPERATURE_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LHIPPITCH_ELECTRICCURRENT_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LHIPPITCH_HARDNESS_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LHIPPITCH_POSITION_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LHIPPITCH_POSITION_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LHIPPITCH_TEMPERATURE_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LHIPROLL_ELECTRICCURRENT_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LHIPROLL_HARDNESS_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LHIPROLL_POSITION_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LHIPROLL_POSITION_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LHIPROLL_TEMPERATURE_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LKNEEPITCH_ELECTRICCURRENT_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LKNEEPITCH_HARDNESS_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LKNEEPITCH_POSITION_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LKNEEPITCH_POSITION_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LKNEEPITCH_TEMPERATURE_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LANKLEPITCH_ELECTRICCURRENT_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LANKLEPITCH_HARDNESS_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LANKLEPITCH_POSITION_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LANKLEPITCH_POSITION_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LANKLEPITCH_TEMPERATURE_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LANKLEROLL_ELECTRICCURRENT_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LANKLEROLL_HARDNESS_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LANKLEROLL_POSITION_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LANKLEROLL_POSITION_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_LANKLEROLL_TEMPERATURE_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RSHOULDERPITCH_ELECTRICCURRENT_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RSHOULDERPITCH_HARDNESS_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RSHOULDERPITCH_POSITION_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RSHOULDERPITCH_POSITION_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RSHOULDERPITCH_TEMPERATURE_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RSHOULDERROLL_ELECTRICCURRENT_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RSHOULDERROLL_HARDNESS_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RSHOULDERROLL_POSITION_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RSHOULDERROLL_POSITION_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RSHOULDERROLL_TEMPERATURE_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RELBOWYAW_ELECTRICCURRENT_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RELBOWYAW_HARDNESS_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RELBOWYAW_POSITION_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RELBOWYAW_POSITION_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RELBOWYAW_TEMPERATURE_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RELBOWROLL_ELECTRICCURRENT_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RELBOWROLL_HARDNESS_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RELBOWROLL_POSITION_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RELBOWROLL_POSITION_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RELBOWROLL_TEMPERATURE_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RHIPPITCH_ELECTRICCURRENT_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RHIPPITCH_HARDNESS_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RHIPPITCH_POSITION_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RHIPPITCH_POSITION_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RHIPPITCH_TEMPERATURE_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RHIPROLL_ELECTRICCURRENT_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RHIPROLL_HARDNESS_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RHIPROLL_POSITION_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RHIPROLL_POSITION_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RHIPROLL_TEMPERATURE_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RKNEEPITCH_ELECTRICCURRENT_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RKNEEPITCH_HARDNESS_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RKNEEPITCH_POSITION_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RKNEEPITCH_POSITION_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RKNEEPITCH_TEMPERATURE_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RANKLEPITCH_ELECTRICCURRENT_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RANKLEPITCH_HARDNESS_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RANKLEPITCH_POSITION_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RANKLEPITCH_POSITION_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RANKLEPITCH_TEMPERATURE_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RANKLEROLL_ELECTRICCURRENT_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RANKLEROLL_HARDNESS_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RANKLEROLL_POSITION_ACTUATOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RANKLEROLL_POSITION_SENSOR_VALUE);
identifiers
.add(NaoConstants.SENSOR_ID_DEVICE_SUBDEVICELIST_RANKLEROLL_TEMPERATURE_SENSOR_VALUE);
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((jointInfos == null) ? 0 : jointInfos.hashCode());
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
NaoJointInfos other = (NaoJointInfos) obj;
if (jointInfos == null) {
if (other.jointInfos != null)
return false;
} else if (!jointInfos.equals(other.jointInfos))
return false;
return true;
}
}
| gpl-3.0 |
RBMarklogic/rdfcoder | jrefactory-2.9.19-full/src/net/sourceforge/jrefactory/io/CharStream.java | 8954 | package net.sourceforge.jrefactory.io;
import java.io.InputStreamReader;
/**
* Basic character stream. The javacc tool creates one of four different types
* of character streams. To be able to switch between different types, I've
* created this parent class. The parent class invokes the appropriate child
* class that was created by javacc. <P>
*
*
*@author Mike Atkinson
*@author <a href="mailto:JRefactory@ladyshot.demon.co.uk">Mike Atkinson</a>
*@version $Id$
*/
public abstract class CharStream {
/**
* Are there more characters available
*/
protected int available;
/**
* The buffer column
*/
protected int bufcolumn[];
/**
* The buffer
*/
protected char[] buffer;
/**
* The buffer line
*/
protected int bufline[];
/**
* The buffer location
*/
public int bufpos = -1;
/**
* The buffer size
*/
protected int bufsize;
/**
* The column index
*/
protected int column = 0;
/**
* Index into the buffer
*/
protected int inBuf = 0;
/**
* The input
*/
protected java.io.Reader inputStream;
/**
* The line index
*/
protected int line = 1;
/**
* The maximum next character index
*/
protected int maxNextCharInd = 0;
/**
* Was the previous character a CR?
*/
protected boolean prevCharIsCR = false;
/**
* Was the previous character a LF?
*/
protected boolean prevCharIsLF = false;
/**
* Index of the current token's starting point
*/
protected int tokenBegin;
/**
* Use the ascii character stream
*/
public final static int ASCII = 1;
/**
* Use the unicode character stream
*/
public final static int FULL_CHAR = 3;
/**
* Use the Java character stream
*/
public final static int JAVA_LIKE = 4;
/**
* Use the unicode character stream
*/
public final static int UNICODE = 2;
/**
* This field determines which type of character stream to use
*/
private static int charStreamType = -1;
/**
* Is this a parser
*/
public final static boolean staticFlag = false;
/**
* Description of the Method
*
*@return Description of the Returned Value
*/
public abstract String GetImage();
/**
* Description of the Method
*
*@param len Description of Parameter
*@return Description of the Returned Value
*/
public abstract char[] GetSuffix(int len);
/**
* Gets the BeginColumn attribute of the CharStream class
*
*@return The BeginColumn value
*/
public int getBeginColumn() {
return bufcolumn[tokenBegin];
}
/**
* Gets the BeginLine attribute of the CharStream class
*
*@return The BeginLine value
*/
public int getBeginLine(){
return bufline[tokenBegin];
}
/**
* Gets the Column attribute of the CharStream class
*
*@return The Column value
* @deprecated
* @see #getEndColumn
*/
public int getColumn() {
return bufcolumn[bufpos];
}
/**
* Gets the EndColumn attribute of the CharStream class
*
*@return The EndColumn value
*/
public int getEndColumn() {
return bufcolumn[bufpos];
}
/**
* Gets the EndLine attribute of the CharStream class
*
*@return The EndLine value
*/
public int getEndLine() {
return bufline[bufpos];
}
/**
* Gets the Line attribute of the CharStream class
*
*@return The Line value
* @deprecated
* @see #getEndLine
*/
public int getLine() {
return bufline[bufpos];
}
/**
* Description of the Method
*
*@return Description of the Returned Value
*@exception java.io.IOException Description of Exception
*/
public char BeginToken() throws java.io.IOException {
tokenBegin = -1;
char c = readChar();
tokenBegin = bufpos;
return c;
}
/**
* Description of the Method
*
*@param dstream Description of Parameter
*@param startline Description of Parameter
*@param startcolumn Description of Parameter
*@param buffersize Description of Parameter
*/
public abstract void ReInit(java.io.Reader dstream, int startline, int startcolumn, int buffersize);
/**
* Description of the Method
*
*@param dstream Description of Parameter
*@param startline Description of Parameter
*@param startcolumn Description of Parameter
*/
public void ReInit(java.io.Reader dstream, int startline, int startcolumn) {
ReInit(dstream, startline, startcolumn, 4096);
}
/**
* Description of the Method
*
*@param dstream Description of Parameter
*@param startline Description of Parameter
*@param startcolumn Description of Parameter
*@param buffersize Description of Parameter
*/
public void ReInit(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) {
ReInit(dstream, startline, startcolumn, buffersize);
}
/**
* Description of the Method
*
*@param dstream Description of Parameter
*@param startline Description of Parameter
*@param startcolumn Description of Parameter
*/
public void ReInit(java.io.InputStream dstream, int startline, int startcolumn) {
ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096);
}
/**
* Description of the Method
*
*@param newLine Description of Parameter
*@param newCol Description of Parameter
*/
public abstract void adjustBeginLineColumn(int newLine, int newCol);
/**
* Description of the Method
*
*@param amount Description of Parameter
*/
public abstract void backup(int amount);
/**
* Description of the Method
*
*@return Description of the Returned Value
*@exception java.io.IOException Description of Exception
*/
public abstract char readChar() throws java.io.IOException;
public static void setCharStreamType(int type) {
charStreamType = type;
}
/**
* Constructor for the CharStream object
*
*@param dstream Description of Parameter
*@param startline Description of Parameter
*@param startcolumn Description of Parameter
*@param buffersize Description of Parameter
*@return Description of the Returned Value
*/
public static CharStream make(java.io.Reader dstream, int startline,
int startcolumn, int buffersize) {
if (charStreamType == JAVA_LIKE) {
return new JavaCharStream(dstream, startline, startcolumn, buffersize);
} else if (charStreamType != UNICODE) {
return new ASCII_CharStream(dstream, startline, startcolumn, buffersize, charStreamType == FULL_CHAR);
} else {
return new SimpleCharStream(dstream, startline, startcolumn, buffersize);
}
}
/**
* Constructor for the CharStream object
*
*@param dstream Description of Parameter
*@param startline Description of Parameter
*@param startcolumn Description of Parameter
*@return Description of the Returned Value
*/
public static CharStream make(java.io.Reader dstream, int startline, int startcolumn) {
return make(dstream, startline, startcolumn, 4096);
}
/**
* Constructor for the CharStream object
*
*@param dstream Description of Parameter
*@param startline Description of Parameter
*@param startcolumn Description of Parameter
*@param buffersize Description of Parameter
*@return Description of the Returned Value
*/
public static CharStream make(java.io.InputStream dstream, int startline,
int startcolumn, int buffersize) {
return make(new InputStreamReader(dstream), startline, startcolumn, buffersize);
}
/**
* Constructor for the CharStream object
*
*@param dstream Description of Parameter
*@param startline Description of Parameter
*@param startcolumn Description of Parameter
*@return Description of the Returned Value
*/
public static CharStream make(java.io.InputStream dstream, int startline, int startcolumn) {
return make(new InputStreamReader(dstream), startline, startcolumn, 4096);
}
}
| gpl-3.0 |
hyperbox/vbox-4.2 | src/server/core/src/io/kamax/vbox4_2/factory/event/GuestPropertyChangeEventFactory.java | 1429 | /*
* Hyperbox - Virtual Infrastructure Manager
* Copyright (C) 2013-2015 Maxime Dor
*
* http://kamax.io/hbox/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package io.kamax.vbox4_2.factory.event;
import io.kamax.hbox.event._Event;
import io.kamax.vbox4_2.factory._PreciseEventFactory;
import org.virtualbox_4_2.IEvent;
import org.virtualbox_4_2.VBoxEventType;
public class GuestPropertyChangeEventFactory implements _PreciseEventFactory {
@Override
public VBoxEventType getType() {
return VBoxEventType.OnGuestPropertyChanged;
}
@Override
public IEvent getRaw(IEvent vbEvent) {
// TODO Auto-generated method stub
return null;
}
@Override
public _Event getEvent(IEvent vbEvent) {
// TODO Auto-generated method stub
return null;
}
}
| gpl-3.0 |
joansalasoler/aalina | src/main/java/com/joansala/engine/partner/package-info.java | 97 | /**
* Collaborative Monte-Carlo tree search algorithm.
*/
package com.joansala.engine.partner;
| gpl-3.0 |
zuonima/sql-utils | src/main/java/com/alibaba/druid/sql/dialect/sqlserver/ast/stmt/SQLServerInsertStatement.java | 2933 | /*
* Copyright 1999-2017 Alibaba Group Holding Ltd.
*
* 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.alibaba.druid.sql.dialect.sqlserver.ast.stmt;
import com.alibaba.druid.sql.JdbcConstants;
import com.alibaba.druid.sql.ast.statement.SQLInsertStatement;
import com.alibaba.druid.sql.dialect.sqlserver.ast.SQLServerObject;
import com.alibaba.druid.sql.dialect.sqlserver.ast.SQLServerOutput;
import com.alibaba.druid.sql.dialect.sqlserver.ast.SQLServerTop;
import com.alibaba.druid.sql.dialect.sqlserver.visitor.SQLServerASTVisitor;
import com.alibaba.druid.sql.visitor.SQLASTVisitor;
public class SQLServerInsertStatement extends SQLInsertStatement implements SQLServerObject {
private boolean defaultValues;
private SQLServerTop top;
private SQLServerOutput output;
public SQLServerInsertStatement() {
dbType = JdbcConstants.SQL_SERVER;
}
public void cloneTo(SQLServerInsertStatement x) {
super.cloneTo(x);
x.defaultValues = defaultValues;
if (top != null) {
x.setTop(top.clone());
}
if (output != null) {
x.setOutput(output.clone());
}
}
@Override
protected void accept0(SQLASTVisitor visitor) {
this.accept0((SQLServerASTVisitor) visitor);
}
@Override
public void accept0(SQLServerASTVisitor visitor) {
if (visitor.visit(this)) {
this.acceptChild(visitor, getTop());
this.acceptChild(visitor, getTableSource());
this.acceptChild(visitor, getColumns());
this.acceptChild(visitor, getOutput());
this.acceptChild(visitor, getValuesList());
this.acceptChild(visitor, getQuery());
}
visitor.endVisit(this);
}
public boolean isDefaultValues() {
return defaultValues;
}
public void setDefaultValues(boolean defaultValues) {
this.defaultValues = defaultValues;
}
public SQLServerOutput getOutput() {
return output;
}
public void setOutput(SQLServerOutput output) {
this.output = output;
}
public SQLServerTop getTop() {
return top;
}
public void setTop(SQLServerTop top) {
this.top = top;
}
public SQLServerInsertStatement clone() {
SQLServerInsertStatement x = new SQLServerInsertStatement();
cloneTo(x);
return x;
}
}
| gpl-3.0 |
Mariusz-v7/ClientServer | src/test/integration/pl/mrugames/nucleus/server/object_server/Worker.java | 1347 | package pl.mrugames.nucleus.server.object_server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.mrugames.nucleus.server.client.ClientController;
import pl.mrugames.nucleus.server.client.ClientWorker;
import pl.mrugames.nucleus.server.client.Comm;
import javax.annotation.Nullable;
class Worker implements ClientWorker<Frame, Frame> {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final Comm comm;
private final Runnable shutdownServer;
private final ClientController clientController;
Worker(Comm comm, Runnable shutdownServer, ClientController clientController) {
this.comm = comm;
this.shutdownServer = shutdownServer;
this.clientController = clientController;
}
@Override
public Frame onInit() {
logger.info("Client initialized");
return null;
}
@Override
public Frame onRequest(Frame request) {
logger.info("Frame received: {}", request);
if (request.getMessage().equals("shutdown")) {
logger.info("Initiating shutdown");
shutdownServer.run();
}
return new Frame("your message was: " + request.getMessage());
}
@Nullable
@Override
public Frame onShutdown() {
logger.info("Client shutdown");
return null;
}
}
| gpl-3.0 |
camilourd/Artificial-Life | ArtificialLife/src/eater_cells/types/Point.java | 238 | package eater_cells.types;
public class Point {
public int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public double dist(Point p) {
return Math.sqrt((x - p.x) * (x - p.x) + (y - p.y) * (y - p.y));
}
}
| gpl-3.0 |
protyposis/Studentenportal | Studentenportal/src/main/java/at/ac/uniklu/mobile/sportal/ui/FragmentPagerSupport.java | 1354 | /*
* Copyright (c) 2014 Mario Guggenberger <mario.guggenberger@aau.at>
*
* This file is part of AAU Studentenportal.
*
* AAU Studentenportal is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AAU Studentenportal is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with AAU Studentenportal. If not, see <http://www.gnu.org/licenses/>.
*/
package at.ac.uniklu.mobile.sportal.ui;
public interface FragmentPagerSupport {
/**
* Returns the index of the currently displayed item in the ViewPager.
*/
int getCurrentItemIndex();
/**
* Registers a fragment in a ViewPager for being refreshed on the
* next {@link #refreshFragments()} call. The fragment tag will be
* used to obtain the corresponding fragment from the FragmentManager.
*/
void registerFragmentForRefresh(FragmentRefreshable fragment);
/**
*
*/
void refreshFragments();
}
| gpl-3.0 |
Niky4000/UsefulUtils | projects/tutorials-master/tutorials-master/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/CustomItemRepositoryImpl.java | 800 | package com.baeldung.boot.daos.impl;
import javax.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.baeldung.boot.daos.CustomItemRepository;
import com.baeldung.boot.domain.Item;
@Repository
public class CustomItemRepositoryImpl implements CustomItemRepository {
@Autowired
private EntityManager entityManager;
@Override
public void deleteCustom(Item item) {
entityManager.remove(item);
}
@Override
public Item findItemById(Long id) {
return entityManager.find(Item.class, id);
}
@Override
public void findThenDelete(Long id) {
final Item item = entityManager.find(Item.class, id);
entityManager.remove(item);
}
}
| gpl-3.0 |
McNetic/peris | app/src/main/java/de/enlightened/peris/site/ListedTopics.java | 1475 | /**
* Copyright (C) 2017 Nicolai Ehemann
* <p>
* This file is part of Peris.
* <p>
* Peris is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* Peris is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with Peris. If not, see <http://www.gnu.org/licenses/>.
*/
package de.enlightened.peris.site;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import lombok.Builder;
import lombok.Getter;
@Getter
@Builder
public class ListedTopics implements Serializable {
private final String forumId;
private final String forumName;
private final int count;
private final int unreadAnnouncementCount;
private final int unreadStickyCount;
private final boolean postAllowed;
private final boolean subscriptionAllowed;
private final boolean subscribed;
private final List<Topic> topics = new ArrayList<Topic>();
public void addTopic(final Topic topic) {
this.topics.add(topic);
}
//TODO: get rid of this? is this really a TopicItem?
private final String id;
}
| gpl-3.0 |
Neembuu-Uploader/neembuu-uploader | modules/nu-mega-co-nz/src/utils/megasdk/MegaSdk.java | 14782 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package utils.megasdk;
import java.util.Random;
import neembuu.uploader.httpclient.NUHttpClient;
import neembuu.uploader.httpclient.httprequest.NUHttpPost;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import java.lang.Math;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
/**
*
* @author RD
*/
public class MegaSdk {
private final HttpClient httpclient = NUHttpClient.getHttpClient();
private HttpContext httpContext = new BasicHttpContext();
private HttpResponse httpResponse;
private NUHttpPost httpPost;
private CookieStore cookieStore;
private String responseString;
private String sid = "";
Random rand = new Random();
private int seq_no = rand.nextInt((0xFFFFFFFF - 0) + 1) + 0;
public String api_req(String request) {
}
public String[] array_merge (String[] first, String[] second) {
List<String> both = new ArrayList<String>(first.length + second.length);
Collections.addAll(both, first);
Collections.addAll(both, second);
return both.toArray(new String[both.size()]);
}
public String a32_to_str (int[] hex) {
// i think hex and other arrays could also be byte[]
//return call_user_func_array('pack', array_merge(array('N*'), $hex));
int[]r = new int[hex.length + 2];
r[0] = 'N'; r[1]='*';
System.arraycopy(hex, 0, r, 2, hex.length);
String ret = "";
for (int i = 0; i < r.length; i++) {
ret+=packN(r[i]);
}
return ret;
}
// from https://gist.github.com/enrobsop/8403667
static String packN(int value) {
byte[]bytes = ByteBuffer.allocate(4).putInt(value).array();
char[]cbytes = toPositiveByteArray(bytes);
return new String(cbytes);
}
static char[] toPositiveByteArray(byte[]bytes) {
char[]c = new char[bytes.length];
for (int i = 0; i < bytes.length; i++) {
byte it = bytes[i];
c[i] = it<0?((char)(256+it)):(char)it;
}
return c;
}
public int[] str_to_a32(String b) {
double str_len = (double) b.length();
double mult = 4.0;
double rounded_val = Math.ceil(str_len / mult);
int pad_length = ((int) rounded_val) * 4;
String pad_with = "\0";
// Add padding, we need a string with a length multiple of 4
b = str_pad(b, pad_length, pad_with);
return unpack(b.getBytes());
}
public String str_pad(String str, Integer length, String pad) { // str_pad("Hi", 10, 'R') //gives "HiRRRRRRRR"
return String.format("%" + (length - str.length()) + "s", "")
.replace(" ", String.valueOf(pad))
+
str;
}
public static int[] unpack ( byte[] bytes ) {
// first, wrap the input array in a ByteBuffer:
ByteBuffer byteBuf = ByteBuffer.wrap( bytes );
// then turn it into an IntBuffer, using big-endian ("Network") byte order:
byteBuf.order( ByteOrder.BIG_ENDIAN );
IntBuffer intBuf = byteBuf.asIntBuffer();
// finally, dump the contents of the IntBuffer into an array
int[] integers = new int[ intBuf.remaining() ];
intBuf.get( integers );
return integers;
}
public String stringhash (String s, String aeskey) {
int[] s32 = str_to_a32(s);
int[] h32 = {0, 0, 0, 0};
int i = 0;
for(i=0 ; i<s32.length; i++){
h32[i%4] ^= s32[i];
}
for (i=0; i<0x4000; i++) {
h32 = aes_cbc_encrypt_a32(h32, aeskey);
}
}
/*
------------------------------------------------------------
--------This is the PHP code that needs to be ported--------
------------------------------------------------------------
<?php
$sid = '';
$seqno = rand(0, 0xFFFFFFFF);
$master_key = '';
$rsa_priv_key = '';
function base64urldecode($data) {
$data .= substr('==', (2 - strlen($data) * 3) % 4);
$data = str_replace(array('-', '_', ','), array('+', '/', ''), $data);
return base64_decode($data);
}
function base64urlencode($data) {
return str_replace(array('+', '/', '='), array('-', '_', ''), base64_encode($data));
}
function a32_to_str($hex) {
return call_user_func_array('pack', array_merge(array('N*'), $hex));
}
function a32_to_base64($a) {
return base64urlencode(a32_to_str($a));
}
function str_to_a32($b) {
// Add padding, we need a string with a length multiple of 4
$b = str_pad($b, 4 * ceil(strlen($b) / 4), "\0");
return array_values(unpack('N*', $b));
}
function base64_to_a32($s) {
return str_to_a32(base64urldecode($s));
}
function aes_cbc_encrypt($data, $key) {
return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
}
function aes_cbc_decrypt($data, $key) {
return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
}
function aes_cbc_encrypt_a32($data, $key) {
return str_to_a32(aes_cbc_encrypt(a32_to_str($data), a32_to_str($key)));
}
function aes_cbc_decrypt_a32($data, $key) {
return str_to_a32(aes_cbc_decrypt(a32_to_str($data), a32_to_str($key)));
}
function aes_ctr_encrypt($data, $key, $iv) {
return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, 'ctr', $iv);
}
function aes_ctr_decrypt($data, $key, $iv) {
return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, 'ctr', $iv);
}
// BEGIN RSA-related stuff -- taken from PEAR Crypt_RSA package
// http://pear.php.net/package/Crypt_RSA
function bin2int($str) {
$result = 0;
$n = strlen($str);
do {
$result = bcadd(bcmul($result, 256), ord($str[--$n]));
} while ($n > 0);
return $result;
}
function int2bin($num) {
$result = '';
do {
$result .= chr(bcmod($num, 256));
$num = bcdiv($num, 256);
} while (bccomp($num, 0));
return $result;
}
function bitOr($num1, $num2, $start_pos) {
$start_byte = intval($start_pos / 8);
$start_bit = $start_pos % 8;
$tmp1 = int2bin($num1);
$num2 = bcmul($num2, 1 << $start_bit);
$tmp2 = int2bin($num2);
if ($start_byte < strlen($tmp1)) {
$tmp2 |= substr($tmp1, $start_byte);
$tmp1 = substr($tmp1, 0, $start_byte) . $tmp2;
} else {
$tmp1 = str_pad($tmp1, $start_byte, '\0') . $tmp2;
}
return bin2int($tmp1);
}
function bitLen($num) {
$tmp = int2bin($num);
$bit_len = strlen($tmp) * 8;
$tmp = ord($tmp[strlen($tmp) - 1]);
if (!$tmp) {
$bit_len -= 8;
} else {
while (!($tmp & 0x80)) {
$bit_len--;
$tmp <<= 1;
}
}
return $bit_len;
}
function rsa_decrypt($enc_data, $p, $q, $d) {
$enc_data = int2bin($enc_data);
$exp = $d;
$modulus = bcmul($p, $q);
$data_len = strlen($enc_data);
$chunk_len = bitLen($modulus) - 1;
$block_len = (int) ceil($chunk_len / 8);
$curr_pos = 0;
$bit_pos = 0;
$plain_data = 0;
while ($curr_pos < $data_len) {
$tmp = bin2int(substr($enc_data, $curr_pos, $block_len));
$tmp = bcpowmod($tmp, $exp, $modulus);
$plain_data = bitOr($plain_data, $tmp, $bit_pos);
$bit_pos += $chunk_len;
$curr_pos += $block_len;
}
return int2bin($plain_data);
}
// END RSA-related stuff
function stringhash($s, $aeskey) {
$s32 = str_to_a32($s);
$h32 = array(0, 0, 0, 0);
for ($i = 0; $i < count($s32); $i++) {
$h32[$i % 4] ^= $s32[$i];
}
for ($i = 0; $i < 0x4000; $i++) {
$h32 = aes_cbc_encrypt_a32($h32, $aeskey);
}
return a32_to_base64(array($h32[0], $h32[2]));
}
function prepare_key($a) {
$pkey = array(0x93C467E3, 0x7DB0C7A4, 0xD1BE3F81, 0x0152CB56);
for ($r = 0; $r < 0x10000; $r++) {
for ($j = 0; $j < count($a); $j += 4) {
$key = array(0, 0, 0, 0);
for ($i = 0; $i < 4; $i++) {
if ($i + $j < count($a)) {
$key[$i] = $a[$i + $j];
}
}
$pkey = aes_cbc_encrypt_a32($pkey, $key);
}
}
return $pkey;
}
function encrypt_key($a, $key) {
$x = array();
for ($i = 0; $i < count($a); $i += 4) {
$x = array_merge($x, aes_cbc_encrypt_a32(array_slice($a, $i, 4), $key));
}
return $x;
}
function decrypt_key($a, $key) {
$x = array();
for ($i = 0; $i < count($a); $i += 4) {
$x = array_merge($x, aes_cbc_decrypt_a32(array_slice($a, $i, 4), $key));
}
return $x;
}
function mpi2bc($s) {
$s = bin2hex(substr($s, 2));
$len = strlen($s);
$n = 0;
for ($i = 0; $i < $len; $i++) {
$n = bcadd($n, bcmul(hexdec($s[$i]), bcpow(16, $len - $i - 1)));
}
return $n;
}
function api_req($req) {
global $seqno, $sid;
$resp = post('https://g.api.mega.co.nz/cs?id=' . ($seqno++) . ($sid ? '&sid=' . $sid : ''), json_encode(array($req)));
$resp = json_decode($resp);
return $resp[0];
}
function post($url, $data) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$resp = curl_exec($ch);
curl_close($ch);
return $resp;
}
function login($email, $password) {
global $sid, $master_key, $rsa_priv_key;
$password_aes = prepare_key(str_to_a32($password));
$uh = stringhash(strtolower($email), $password_aes);
$res = api_req(array('a' => 'us', 'user' => $email, 'uh' => $uh));
$enc_master_key = base64_to_a32($res->k);
$master_key = decrypt_key($enc_master_key, $password_aes);
if (!empty($res->csid)) {
$enc_rsa_priv_key = base64_to_a32($res->privk);
$rsa_priv_key = decrypt_key($enc_rsa_priv_key, $master_key);
$privk = a32_to_str($rsa_priv_key);
$rsa_priv_key = array(0, 0, 0, 0);
for ($i = 0; $i < 4; $i++) {
$l = ((ord($privk[0]) * 256 + ord($privk[1]) + 7) / 8) + 2;
$rsa_priv_key[$i] = mpi2bc(substr($privk, 0, $l));
$privk = substr($privk, $l);
}
$enc_sid = mpi2bc(base64urldecode($res->csid));
$sid = rsa_decrypt($enc_sid, $rsa_priv_key[0], $rsa_priv_key[1], $rsa_priv_key[2]);
$sid = base64urlencode(substr(strrev($sid), 0, 43));
}
}
function enc_attr($attr, $key) {
$attr = 'MEGA' . json_encode($attr);
return aes_cbc_encrypt($attr, a32_to_str($key));
}
function dec_attr($attr, $key) {
$attr = trim(aes_cbc_decrypt($attr, a32_to_str($key)));
if (substr($attr, 0, 6) != 'MEGA{"') {
return false;
}
return json_decode(substr($attr, 4));
}
function get_chunks($size) {
$chunks = array();
$p = $pp = 0;
for ($i = 1; $i <= 8 && $p < $size - $i * 0x20000; $i++) {
$chunks[$p] = $i * 0x20000;
$pp = $p;
$p += $chunks[$p];
}
while ($p < $size) {
$chunks[$p] = 0x100000;
$pp = $p;
$p += $chunks[$p];
}
$chunks[$pp] = ($size - $pp);
if (!$chunks[$pp]) {
unset($chunks[$pp]);
}
return $chunks;
}
function cbc_mac($data, $k, $n) {
$padding_size = (strlen($data) % 16) == 0 ? 0 : 16 - strlen($data) % 16;
$data .= str_repeat("\0", $padding_size);
$chunks = get_chunks(strlen($data));
$file_mac = array(0, 0, 0, 0);
foreach ($chunks as $pos => $size) {
$chunk_mac = array($n[0], $n[1], $n[0], $n[1]);
for ($i = $pos; $i < $pos + $size; $i += 16) {
$block = str_to_a32(substr($data, $i, 16));
$chunk_mac = array($chunk_mac[0] ^ $block[0], $chunk_mac[1] ^ $block[1], $chunk_mac[2] ^ $block[2], $chunk_mac[3] ^ $block[3]);
$chunk_mac = aes_cbc_encrypt_a32($chunk_mac, $k);
}
$file_mac = array($file_mac[0] ^ $chunk_mac[0], $file_mac[1] ^ $chunk_mac[1], $file_mac[2] ^ $chunk_mac[2], $file_mac[3] ^ $chunk_mac[3]);
$file_mac = aes_cbc_encrypt_a32($file_mac, $k);
}
return $file_mac;
}
function uploadfile($filename) {
global $master_key, $root_id;
$data = file_get_contents($filename);
$size = strlen($data);
$ul_url = api_req(array('a' => 'u', 's' => $size));
$ul_url = $ul_url->p;
$ul_key = array(0, 1, 2, 3, 4, 5);
for ($i = 0; $i < 6; $i++) {
$ul_key[$i] = rand(0, 0xFFFFFFFF);
}
$data_crypted = aes_ctr_encrypt($data, a32_to_str(array_slice($ul_key, 0, 4)), a32_to_str(array($ul_key[4], $ul_key[5], 0, 0)));
$completion_handle = post($ul_url, $data_crypted);
$data_mac = cbc_mac($data, array_slice($ul_key, 0, 4), array_slice($ul_key, 4, 2));
$meta_mac = array($data_mac[0] ^ $data_mac[1], $data_mac[2] ^ $data_mac[3]);
$attributes = array('n' => basename($filename));
$enc_attributes = enc_attr($attributes, array_slice($ul_key, 0, 4));
$key = array($ul_key[0] ^ $ul_key[4], $ul_key[1] ^ $ul_key[5], $ul_key[2] ^ $meta_mac[0], $ul_key[3] ^ $meta_mac[1], $ul_key[4], $ul_key[5], $meta_mac[0], $meta_mac[1]);
return api_req(array('a' => 'p', 't' => $root_id, 'n' => array(array('h' => $completion_handle, 't' => 0, 'a' => base64urlencode($enc_attributes), 'k' => a32_to_base64(encrypt_key($key, $master_key))))));
}
function downloadfile($file, $attributes, $k, $iv, $meta_mac) {
$dl_url = api_req(array('a' => 'g', 'g' => 1, 'n' => $file->h));
$data_enc = file_get_contents($dl_url->g);
$data = aes_ctr_decrypt($data_enc, a32_to_str($k), a32_to_str($iv));
file_put_contents($attributes->n, $data);
$file_mac = cbc_mac($data, $k, $iv);
if (array($file_mac[0] ^ $file_mac[1], $file_mac[2] ^ $file_mac[3]) != $meta_mac) {
echo "MAC mismatch";
}
}
function getfiles() {
global $master_key, $root_id, $inbox_id, $trashbin_id;
$files = api_req(array('a' => 'f', 'c' => 1));
foreach ($files->f as $file) {
if ($file->t == 0 || $file->t == 1) {
$key = substr($file->k, strpos($file->k, ':') + 1);
$key = decrypt_key(base64_to_a32($key), $master_key);
if ($file->t == 0) {
$k = array($key[0] ^ $key[4], $key[1] ^ $key[5], $key[2] ^ $key[6], $key[3] ^ $key[7]);
$iv = array_merge(array_slice($key, 4, 2), array(0, 0));
$meta_mac = array_slice($key, 6, 2);
} else {
$k = $key;
}
$attributes = base64urldecode($file->a);
$attributes = dec_attr($attributes, $k);
if ($file->h == 'gldU3Tab') {
downloadfile($file, $attributes, $k, $iv, $meta_mac);
}
} else if ($file->t == 2) {
$root_id = $file->k;
} else if ($file->t == 3) {
$inbox_id = $file->k;
} else if ($file->t == 4) {
$trashbin_id = $file->k;
}
}
}
?>
*/
}
| gpl-3.0 |
beldenge/Zenith | zenith-inference/src/main/java/com/ciphertool/zenith/inference/dao/CipherDao.java | 3611 | /*
* Copyright 2017-2020 George Belden
*
* This file is part of Zenith.
*
* Zenith is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* Zenith is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* Zenith. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ciphertool.zenith.inference.dao;
import com.ciphertool.zenith.inference.entities.Cipher;
import com.ciphertool.zenith.inference.entities.CipherJson;
import com.ciphertool.zenith.inference.entities.config.ApplicationConfiguration;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
@Component
public class CipherDao {
private static Logger log = LoggerFactory.getLogger(CipherDao.class);
private static final String CIPHERS_DIRECTORY = "ciphers";
private static final String JSON_EXTENSION = ".json";
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
@Autowired
private ApplicationConfiguration applicationConfiguration;
public Cipher findByCipherName(String name) {
if (name == null || name.isEmpty()) {
log.warn("Attempted to find cipher with null or empty name. Returning null.");
return null;
}
return findAll().stream()
.filter(cipher -> name.equalsIgnoreCase(cipher.getName()))
.findAny()
.orElse(null);
}
public List<Cipher> findAll() {
List<Cipher> ciphers = new ArrayList<>();
for (CipherJson cipherJson : applicationConfiguration.getCiphers()){
Cipher nextCipher = new Cipher(cipherJson);
if (containsCipher(ciphers, nextCipher)) {
throw new IllegalArgumentException("Cipher with name " + nextCipher.getName() + " already imported. Cannot import duplicate ciphers.");
}
ciphers.add(nextCipher);
}
return ciphers;
}
public void writeToFile(Cipher cipher) throws IOException {
// Write the file to the current working directory
String outputFilename = Paths.get(CIPHERS_DIRECTORY).toAbsolutePath().toString() + File.separator + cipher.getName() + JSON_EXTENSION;
if (!Files.exists(Paths.get(CIPHERS_DIRECTORY))) {
Files.createDirectory(Paths.get(CIPHERS_DIRECTORY));
}
try {
OBJECT_MAPPER.writeValue(new File(outputFilename), new CipherJson(cipher));
} catch (IOException e) {
throw new IllegalStateException("Unable to write Cipher with name=" + cipher.getName() + " to file=" + outputFilename + ".");
}
}
private boolean containsCipher(List<Cipher> ciphers, Cipher newCipher) {
return ciphers.stream().anyMatch(cipher -> cipher.getName().equals(newCipher.getName()));
}
}
| gpl-3.0 |
openmainframeproject/ade | ade-ext/src/main/java/org/openmainframe/ade/ext/os/parser/LinuxSyslog3164ParserFreeForm.java | 2688 | /*
Copyright IBM Corp. 2015, 2016
This file is part of Anomaly Detection Engine for Linux Logs (ADE).
ADE is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ADE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with ADE. If not, see <http://www.gnu.org/licenses/>.
*/
package org.openmainframe.ade.ext.os.parser;
import java.util.regex.Pattern;
import org.openmainframe.ade.exceptions.AdeException;
import org.openmainframe.ade.ext.os.LinuxAdeExtProperties;
/**
* An RFC3164 syslog parser that accepts everything after the header as
* message text.
*/
public class LinuxSyslog3164ParserFreeForm extends LinuxSyslog3164ParserBase {
/**
* Pattern object for matching against the base header regex and everything else after it.
*/
private static final Pattern pattern = Pattern.compile(RFC3164_HEADER + "(.*)$");
/**
* Add another capturing group, MSG which contains the message text, to the base number of captured groups.
*/
private static final int MSG_GROUP = RFC3164_HEADER_GROUPS + 1;
/**
* Default constructor to call its parent constructor.
* @throws AdeException
*/
public LinuxSyslog3164ParserFreeForm() throws AdeException {
super();
}
/**
* Explicit-value constructor for getting the properties file and passing it to the parent explicit value
* constructor.
* @param linuxAdeExtProperties Contains property and configuration information from the start of AdeExt main class.
* @throws AdeException
*/
public LinuxSyslog3164ParserFreeForm(LinuxAdeExtProperties linuxAdeExtProperties) throws AdeException {
super(linuxAdeExtProperties);
}
/**
* Parses the line by calling the super class's parseLine with the positions of the captured groups.
* Note: The MSG_GROUP captures everything pass the header as message text.
* @param line A line from the Linux syslog file.
* @return true if the line was parsed successfully.
*/
@Override
public final boolean parseLine(String line) {
return parseLine(pattern, RFC3164_HEADER_TIMESTAMP_GROUP,
RFC3164_HEADER_HOSTNAME_GROUP, 0, 0,
MSG_GROUP, line);
}
}
| gpl-3.0 |
ProgDan/maratona | URI/URI_2540 Impeachment do Líder.java | 716 | /*
+--------------------+
| Daniel Arndt Alves |
| URI 2540 |
+--------------------+
*/
import java.util.Locale;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
sc.useLocale(Locale.ENGLISH);
Locale.setDefault(new Locale("en", "US"));
while(sc.hasNext()) {
int total = sc.nextInt();
double contavotos=0;
for (int i=0 ; i<total ; i++)
if (sc.nextInt()==1)
contavotos++;
double doisterços = total*0.6666666666666667;
if(contavotos>=doisterços)
System.out.println("impeachment");
else
System.out.println("acusacao arquivada");
}
sc.close();
}
}
| gpl-3.0 |
smee/elateXam | taskmodel/taskmodel-core-view/src/main/java/de/thorstenberger/taskmodel/view/NavigationNodeFormatter.java | 3271 | /*
Copyright (C) 2006 Thorsten Berger
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/**
*
*/
package de.thorstenberger.taskmodel.view;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import de.thorstenberger.taskmodel.complex.complextaskhandling.Page;
import de.thorstenberger.taskmodel.view.tree.DataNode;
import de.thorstenberger.taskmodel.view.tree.DataNodeFormatter;
/**
* @author Thorsten Berger
*
*/
public class NavigationNodeFormatter implements DataNodeFormatter {
String path;
HttpServletRequest request;
HttpServletResponse response;
long taskId;
public NavigationNodeFormatter( long taskId, String path, HttpServletRequest request, HttpServletResponse response ){
this.taskId = taskId;
this.path = path;
this.request = request;
this.response = response;
}
/* (non-Javadoc)
* @see de.thorstenberger.taskmodel.view.tree.DataNodeFormatter#format(de.thorstenberger.taskmodel.view.tree.DataNode)
*/
public String format(DataNode node) {
if( node instanceof PageNode ){
PageNode pn = (PageNode)node;
String url = response.encodeURL( path + "?id=" + taskId + "&todo=continue&page=" + pn.getPageNumber() );
return "<a class=\"node\" href=javascript:leave(\"" + url + "\")>" +
"Seite " + pn.getPageNumber() + "</a>" +
( pn.isCurrentlyActivePage() ? "<img src=\"" + request.getContextPath() + "/pics/sparkle001bu.gif\"> " : "" );
}else
return node.getName();
}
/* (non-Javadoc)
* @see de.thorstenberger.taskmodel.view.tree.DataNodeFormatter#isLocked(de.thorstenberger.taskmodel.view.tree.DataNode)
*/
public boolean isLocked(DataNode node) {
return false;
}
/* (non-Javadoc)
* @see de.thorstenberger.taskmodel.view.tree.DataNodeFormatter#isVisible(de.thorstenberger.taskmodel.view.tree.DataNode)
*/
public boolean isVisible(DataNode node) {
return true;
}
/* (non-Javadoc)
* @see de.thorstenberger.taskmodel.view.tree.DataNodeFormatter#getFolderIcon(de.thorstenberger.taskmodel.view.tree.DataNode)
*/
public String getFolderIcon(DataNode node) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see de.thorstenberger.taskmodel.view.tree.DataNodeFormatter#getLeafIcon(de.thorstenberger.taskmodel.view.tree.DataNode)
*/
public String getLeafIcon(DataNode node) {
if( node instanceof PageNode ){
PageNode pn = (PageNode)node;
switch( pn.getProcessStatus() ){
case Page.NOT_PROCESSED : return "page.gif";
case Page.PARTLY_PROCESSED : return "partlyProcessed.gif";
case Page.COMPLETELY_PROCESSED : return "processed.gif";
}
}
return null;
}
}
| gpl-3.0 |
c0c0n3/spring-doh | src/test/java/util/ExceptionsThrowTest.java | 1252 | package util;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static util.Exceptions.throwAsIfUnchecked;
import java.io.IOException;
import org.junit.Test;
public class ExceptionsThrowTest {
private void throwChecked() {
try {
throw new IOException();
} catch (Exception e) {
throwAsIfUnchecked(e);
}
}
private void throwUnchecked() {
try {
throw new NullPointerException();
} catch (Exception e) {
throwAsIfUnchecked(e);
}
}
@Test
public void checkedExceptionBubblesUpAsIs() {
try {
throwChecked();
} catch (Exception e) {
assertTrue(e instanceof IOException);
StackTraceElement throwSite = e.getStackTrace()[0];
assertThat(throwSite.getMethodName(), is("throwChecked"));
}
}
@Test
public void uncheckedExceptionBubblesUpAsIs() {
try {
throwUnchecked();
} catch (NullPointerException e) {
StackTraceElement throwSite = e.getStackTrace()[0];
assertThat(throwSite.getMethodName(), is("throwUnchecked"));
}
}
}
| gpl-3.0 |
Devexperts/aprof | selftest/src/main/java/com/devexperts/aprof/selftest/TrackingIntfTest.java | 2330 | package com.devexperts.aprof.selftest;
/*-
* #%L
* Aprof Integration tests (selftest)
* %%
* Copyright (C) 2002 - 2017 Devexperts, LLC
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
import com.devexperts.aprof.AProfSizeUtil;
import com.devexperts.aprof.Configuration;
class TrackingIntfTest implements TestCase {
private static final int COUNT = 100000;
private static float[] temp; // prevent elimination
public String name() {
return "trackingIntf";
}
public String verifyConfiguration(Configuration config) {
return null;
}
public String[] getCheckedClasses() {
return new String[] { "float[]" };
}
public String getExpectedStatistics(Configuration config) {
long objSize = AProfSizeUtil.getObjectSize(new float[1]);
return TestUtil.fmt(
"float[]: {size} bytes in {count} objects (avg size {objSize} bytes)\n" +
"\t{impl}.allocateResult: {size} bytes in {count} objects (avg size {objSize} bytes)\n" +
"\t\t{impl}.trackedMethod: {size} bytes in {count} objects (avg size {objSize} bytes)\n" +
"\t\t\t{class}.invokeTrackedViaIntf: {size} bytes in {count} objects (avg size {objSize} bytes)\n",
"class=" + getClass().getName(),
"impl=" + TrackingIntfTrackedImpl.class.getName(),
"size=" + TestUtil.fmt(objSize * COUNT),
"count=" + TestUtil.fmt(COUNT),
"objSize=" + objSize);
}
public void doTest() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
TrackingIntf impl = new TrackingIntfTrackedImpl();
for (int i = 0; i < COUNT; i++)
invokeTrackedViaIntf(impl);
}
private void invokeTrackedViaIntf(TrackingIntf impl) {
temp = impl.trackedMethod(); // interface call to tracked implementation
}
}
| gpl-3.0 |
jlopezjuy/ClothesHipster | anelapi/src/main/java/ar/com/anelsoftware/clothes/domain/enumeration/Estado.java | 165 | package ar.com.anelsoftware.clothes.domain.enumeration;
/**
* The Estado enumeration.
*/
public enum Estado {
ENCARGADO,CORTADO,PROBADO,ENTREGADO,CANCELADO
}
| gpl-3.0 |
GUMGA/frameworkbackend | gumga-application/src/main/java/io/gumga/application/GumgaHqlEntry.java | 1114 | package io.gumga.application;
import java.util.Objects;
public class GumgaHqlEntry {
public final GumgaFieldStereotype type;
public final String operator;
public GumgaHqlEntry(GumgaFieldStereotype type, String operator) {
this.type = type;
this.operator = operator;
}
@Override
public int hashCode() {
int hash = 7;
hash = 59 * hash + Objects.hashCode(this.type);
hash = 59 * hash + Objects.hashCode(this.operator);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final GumgaHqlEntry other = (GumgaHqlEntry) obj;
if (!Objects.equals(this.type, other.type)) {
return false;
}
if (!Objects.equals(this.operator, other.operator)) {
return false;
}
return true;
}
@Override
public String toString() {
return "HqlEntry{" + "type=" + type + ", operator=" + operator + '}';
}
}
| gpl-3.0 |
glycoinfo/eurocarbdb | application/GlycoWorkbench/src/org/eurocarbdb/application/glycoworkbench/plugin/GAGDictionary.java | 4021 | /*
* EuroCarbDB, a framework for carbohydrate bioinformatics
*
* Copyright (c) 2006-2009, Eurocarb project, or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
* A copy of this license accompanies this distribution in the file LICENSE.txt.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* Last commit: $Rev: 1210 $ by $Author: glycoslave $ on $Date:: 2009-06-12 #$
*/
/**
@author Alessio Ceroni (a.ceroni@imperial.ac.uk)
*/
package org.eurocarbdb.application.glycoworkbench.plugin;
import org.eurocarbdb.application.glycoworkbench.*;
import org.eurocarbdb.application.glycanbuilder.*;
import java.util.*;
import java.io.*;
public class GAGDictionary implements Generator {
protected TreeMap<String,GAGType> dictionary = new TreeMap<String,GAGType>();
protected GAGOptions static_options = null;
public GAGDictionary(String filename) {
loadDictionary(filename);
}
public Collection<String> getFamilies() {
return dictionary.keySet();
}
public Collection<GAGType> getTypes() {
return dictionary.values();
}
public GAGType getType(String family) {
return dictionary.get(family);
}
public GAGType getType(String family, GAGOptions options) {
GAGType ret = dictionary.get(family);
if( ret==null )
return null;
if( options.ALLOW_UNLIKELY_ACETYLATION )
ret = ret.allowUnlikelyAcetylation();
ret = ret.applyModifications(options.MODIFICATIONS);
return ret;
}
public void setOptions(GAGOptions opt) {
static_options = opt;
}
public Vector<Glycan> getMotifs() {
return getMotifs(static_options);
}
public Vector<Glycan> getMotifs(GAGOptions options) {
Vector<Glycan> ret = new Vector<Glycan>();
for( int i=0; i<options.GAG_FAMILIES.length; i++ ) {
GAGType gt = getType(options.GAG_FAMILIES[i],options);
ret.add(gt.getMotifStructure(options));
}
return ret;
}
public void generate(int motif_ind, GeneratorListener listener) {
GAGType gt = getType(static_options.GAG_FAMILIES[motif_ind],static_options);
gt.generateStructures(listener,static_options);
}
public FragmentDocument generateStructures() {
return generateStructures(static_options);
}
public FragmentDocument generateStructures(GAGOptions options) {
FragmentDocument ret = new FragmentDocument();
for( int i=0; i<options.GAG_FAMILIES.length; i++ ) {
GAGType gt = getType(options.GAG_FAMILIES[i],options);
FragmentCollection fc = gt.generateStructures(options);
ret.addFragments(gt.getMotifStructure(options),fc);
}
return ret;
}
private void loadDictionary(String filename) {
// clear dict
dictionary.clear();
try {
// open file
java.net.URL file_url = GAGDictionary.class.getResource(filename);
if( file_url==null )
throw new FileNotFoundException(filename);
BufferedReader is = new BufferedReader(new InputStreamReader(file_url.openStream()));
// read dictionary
String line;
while( (line=is.readLine())!=null ) {
line = TextUtils.trim(line);
if( line.length()>0 && !line.startsWith("%") ) {
GAGType type = new GAGType(line);
dictionary.put(type.getFamily(),type);
}
}
}
catch(Exception e) {
LogUtils.report(e);
}
}
}
| gpl-3.0 |
jdupl/StrangeLove | AnalyticsJava/src/analytics/constants/Keys.java | 1016 | package analytics.constants;
public class Keys {
public static final String GPUS_STATUS = "gpus_status",
GPU_ID = "device_id", // string
TEMPERATURE = "temperature", // float
GPU_VOLTAGE = "device_voltage", // float
GPU_CLOCK = "engine_clock", // int
MEM_CLOCK = "memory_clock", // int
FAN_RPM = "fan_rpm", // int
HW_ERRORS = "hardware_errors", // int
REJECTED = "shares_rejected", // int
ACCEPTED = "shares_accepted", // int
CURRENT_HASH_RATE = "hashrate", // int (hashrate in kh/s)
INTENSITY = "intensity", // int
TIME_SINCE_LAST_WORK = "time_since_last_work", // int (seconds)
TIME_SINCE_LAST_VALID_WORK = "time_since_last_valid_work", // int
SERVER_STATUS = "server_status", // array of the following section
UPTIME = "uptime", // int (seconds)
LOAD_AVG = "load_avg", // array of float (unix timing format)
// General
TIMESTAMP = "timestamp", // int current ms of the server
SERVER_ID = "server_id", // String
REQUEST_STATUS = "r_status"; // int
}
| gpl-3.0 |
SOFTPOWER1991/AndroidPlayGround | Example/itemchooseexample/src/main/java/com/rayootech/www/itemchooseexample/SingleChooseActivity.java | 2511 | package com.rayootech.www.itemchooseexample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import com.rayootech.www.itemchooseexample.bean.Person;
import org.geek.commonlib.utils.L;
import org.geek.commonlib.utils.UIUtils;
import org.greenrobot.eventbus.EventBus;
/**
* File Description : 单选
*
* @author : zhanggeng
* @version : v1.0
* **************修订历史*************
* @email : zhanggengdyx@gmail.com
* @date : 2016/11/17 19:16
*/
public class SingleChooseActivity extends AppCompatActivity {
Button button;
ListView listView;
SingleListAdapter singleListAdapter;
// SingleChooseItemViewAdapter singleChooseItemViewAdapter;
private int selectPosition = -1;//用于记录用户选择的变量
Person person;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single);
button = (Button) findViewById(R.id.btn_sure);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EventBus.getDefault().post(person);
UIUtils.closeActivity(SingleChooseActivity.this);
}
});
listView = (ListView) findViewById(R.id.lv_single);
listView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
singleListAdapter = new SingleListAdapter(this, MockList.mockPersonList());
listView.setAdapter(singleListAdapter);
// singleChooseItemViewAdapter = new SingleChooseItemViewAdapter(this , MockList.mockPersonList());
//
// listView.setAdapter(singleChooseItemViewAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
selectPosition = i;
singleListAdapter.setSelectPosition(selectPosition);
singleListAdapter.notifyDataSetChanged();
L.et("item", "position==" + i + "===" + (singleListAdapter.getItem(i)).getName());
person = singleListAdapter.getItem(i);
// person = singleChooseItemViewAdapter.getItem(i);
}
});
}
}
| gpl-3.0 |
wildex999/stjerncraft_mcpc | src/minecraft/net/minecraftforge/common/ForgeChunkManager.java | 39918 | package net.minecraftforge.common;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.BiMap;
import com.google.common.collect.ForwardingSet;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Multiset;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import com.google.common.collect.TreeMultiset;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.ChunkCoordIntPair;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.MathHelper;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.ForgeChunkManager.Ticket;
import net.minecraftforge.event.Event;
/**
* Manages chunkloading for mods.
*
* The basic principle is a ticket based system.
* 1. Mods register a callback {@link #setForcedChunkLoadingCallback(Object, LoadingCallback)}
* 2. Mods ask for a ticket {@link #requestTicket(Object, World, Type)} and then hold on to that ticket.
* 3. Mods request chunks to stay loaded {@link #forceChunk(Ticket, ChunkCoordIntPair)} or remove chunks from force loading {@link #unforceChunk(Ticket, ChunkCoordIntPair)}.
* 4. When a world unloads, the tickets associated with that world are saved by the chunk manager.
* 5. When a world loads, saved tickets are offered to the mods associated with the tickets. The {@link Ticket#getModData()} that is set by the mod should be used to re-register
* chunks to stay loaded (and maybe take other actions).
*
* The chunkloading is configurable at runtime. The file "config/forgeChunkLoading.cfg" contains both default configuration for chunkloading, and a sample individual mod
* specific override section.
*
* @author cpw
*
*/
public class ForgeChunkManager
{
private static int defaultMaxCount;
private static int defaultMaxChunks;
private static boolean overridesEnabled;
private static Map<World, Multimap<String, Ticket>> tickets = new MapMaker().weakKeys().makeMap();
private static Map<String, Integer> ticketConstraints = Maps.newHashMap();
private static Map<String, Integer> chunkConstraints = Maps.newHashMap();
private static SetMultimap<String, Ticket> playerTickets = HashMultimap.create();
private static Map<String, LoadingCallback> callbacks = Maps.newHashMap();
private static Map<World, ImmutableSetMultimap<ChunkCoordIntPair,Ticket>> forcedChunks = new MapMaker().weakKeys().makeMap();
private static BiMap<UUID,Ticket> pendingEntities = HashBiMap.create();
private static Map<World,Cache<Long, Chunk>> dormantChunkCache = new MapMaker().weakKeys().makeMap();
private static File cfgFile;
private static Configuration config;
private static int playerTicketLength;
private static int dormantChunkCacheSize;
private static Set<String> warnedMods = Sets.newHashSet();
/**
* All mods requiring chunkloading need to implement this to handle the
* re-registration of chunk tickets at world loading time
*
* @author cpw
*
*/
public interface LoadingCallback
{
/**
* Called back when tickets are loaded from the world to allow the
* mod to re-register the chunks associated with those tickets. The list supplied
* here is truncated to length prior to use. Tickets unwanted by the
* mod must be disposed of manually unless the mod is an OrderedLoadingCallback instance
* in which case, they will have been disposed of by the earlier callback.
*
* @param tickets The tickets to re-register. The list is immutable and cannot be manipulated directly. Copy it first.
* @param world the world
*/
public void ticketsLoaded(List<Ticket> tickets, World world);
}
/**
* This is a special LoadingCallback that can be implemented as well as the
* LoadingCallback to provide access to additional behaviour.
* Specifically, this callback will fire prior to Forge dropping excess
* tickets. Tickets in the returned list are presumed ordered and excess will
* be truncated from the returned list.
* This allows the mod to control not only if they actually <em>want</em> a ticket but
* also their preferred ticket ordering.
*
* @author cpw
*
*/
public interface OrderedLoadingCallback extends LoadingCallback
{
/**
* Called back when tickets are loaded from the world to allow the
* mod to decide if it wants the ticket still, and prioritise overflow
* based on the ticket count.
* WARNING: You cannot force chunks in this callback, it is strictly for allowing the mod
* to be more selective in which tickets it wishes to preserve in an overflow situation
*
* @param tickets The tickets that you will want to select from. The list is immutable and cannot be manipulated directly. Copy it first.
* @param world The world
* @param maxTicketCount The maximum number of tickets that will be allowed.
* @return A list of the tickets this mod wishes to continue using. This list will be truncated
* to "maxTicketCount" size after the call returns and then offered to the other callback
* method
*/
public List<Ticket> ticketsLoaded(List<Ticket> tickets, World world, int maxTicketCount);
}
public interface PlayerOrderedLoadingCallback extends LoadingCallback
{
/**
* Called back when tickets are loaded from the world to allow the
* mod to decide if it wants the ticket still.
* This is for player bound tickets rather than mod bound tickets. It is here so mods can
* decide they want to dump all player tickets
*
* WARNING: You cannot force chunks in this callback, it is strictly for allowing the mod
* to be more selective in which tickets it wishes to preserve
*
* @param tickets The tickets that you will want to select from. The list is immutable and cannot be manipulated directly. Copy it first.
* @param world The world
* @return A list of the tickets this mod wishes to use. This list will subsequently be offered
* to the main callback for action
*/
public ListMultimap<String, Ticket> playerTicketsLoaded(ListMultimap<String, Ticket> tickets, World world);
}
public enum Type
{
/**
* For non-entity registrations
*/
NORMAL,
/**
* For entity registrations
*/
ENTITY
}
public static class Ticket
{
private String modId;
private Type ticketType;
private LinkedHashSet<ChunkCoordIntPair> requestedChunks;
private NBTTagCompound modData;
public final World world;
private int maxDepth;
private String entityClazz;
private int entityChunkX;
private int entityChunkZ;
private Entity entity;
private String player;
Ticket(String modId, Type type, World world)
{
this.modId = modId;
this.ticketType = type;
this.world = world;
this.maxDepth = getMaxChunkDepthFor(modId);
this.requestedChunks = Sets.newLinkedHashSet();
}
Ticket(String modId, Type type, World world, String player)
{
this(modId, type, world);
if (player != null)
{
this.player = player;
}
else
{
FMLLog.log(Level.SEVERE, "Attempt to create a player ticket without a valid player");
throw new RuntimeException();
}
}
/**
* The chunk list depth can be manipulated up to the maximal grant allowed for the mod. This value is configurable. Once the maximum is reached,
* the least recently forced chunk, by original registration time, is removed from the forced chunk list.
*
* @param depth The new depth to set
*/
public void setChunkListDepth(int depth)
{
if (depth > getMaxChunkDepthFor(modId) || (depth <= 0 && getMaxChunkDepthFor(modId) > 0))
{
FMLLog.warning("The mod %s tried to modify the chunk ticket depth to: %d, its allowed maximum is: %d", modId, depth, getMaxChunkDepthFor(modId));
}
else
{
this.maxDepth = depth;
}
}
/**
* Gets the current max depth for this ticket.
* Should be the same as getMaxChunkListDepth()
* unless setChunkListDepth has been called.
*
* @return Current max depth
*/
public int getChunkListDepth()
{
return maxDepth;
}
/**
* Get the maximum chunk depth size
*
* @return The maximum chunk depth size
*/
public int getMaxChunkListDepth()
{
return getMaxChunkDepthFor(modId);
}
/**
* Bind the entity to the ticket for {@link Type#ENTITY} type tickets. Other types will throw a runtime exception.
*
* @param entity The entity to bind
*/
public void bindEntity(Entity entity)
{
if (ticketType!=Type.ENTITY)
{
throw new RuntimeException("Cannot bind an entity to a non-entity ticket");
}
this.entity = entity;
}
/**
* Retrieve the {@link NBTTagCompound} that stores mod specific data for the chunk ticket.
* Example data to store would be a TileEntity or Block location. This is persisted with the ticket and
* provided to the {@link LoadingCallback} for the mod. It is recommended to use this to recover
* useful state information for the forced chunks.
*
* @return The custom compound tag for mods to store additional chunkloading data
*/
public NBTTagCompound getModData()
{
if (this.modData == null)
{
this.modData = new NBTTagCompound();
}
return modData;
}
/**
* Get the entity associated with this {@link Type#ENTITY} type ticket
* @return the entity
*/
public Entity getEntity()
{
return entity;
}
/**
* Is this a player associated ticket rather than a mod associated ticket?
*/
public boolean isPlayerTicket()
{
return player != null;
}
/**
* Get the player associated with this ticket
*/
public String getPlayerName()
{
return player;
}
/**
* Get the associated mod id
*/
public String getModId()
{
return modId;
}
/**
* Gets the ticket type
*/
public Type getType()
{
return ticketType;
}
/**
* Gets a list of requested chunks for this ticket.
*/
public ImmutableSet getChunkList()
{
return ImmutableSet.copyOf(requestedChunks);
}
}
public static class ForceChunkEvent extends Event {
public final Ticket ticket;
public final ChunkCoordIntPair location;
public ForceChunkEvent(Ticket ticket, ChunkCoordIntPair location)
{
this.ticket = ticket;
this.location = location;
}
}
public static class UnforceChunkEvent extends Event {
public final Ticket ticket;
public final ChunkCoordIntPair location;
public UnforceChunkEvent(Ticket ticket, ChunkCoordIntPair location)
{
this.ticket = ticket;
this.location = location;
}
}
/**
* Allows dynamically loading world mods to test if there are chunk tickets in the world
* Mods that add dynamically generated worlds (like Mystcraft) should call this method
* to determine if the world should be loaded during server starting.
*
* @param chunkDir The chunk directory to test: should be equivalent to {@link WorldServer#getChunkSaveLocation()}
* @return if there are tickets outstanding for this world or not
*/
public static boolean savedWorldHasForcedChunkTickets(File chunkDir)
{
File chunkLoaderData = new File(chunkDir, "forcedchunks.dat");
if (chunkLoaderData.exists() && chunkLoaderData.isFile())
{
;
try
{
NBTTagCompound forcedChunkData = CompressedStreamTools.read(chunkLoaderData);
return forcedChunkData.getTagList("TicketList").tagCount() > 0;
}
catch (IOException e)
{
}
}
return false;
}
static void loadWorld(World world)
{
ArrayListMultimap<String, Ticket> newTickets = ArrayListMultimap.<String, Ticket>create();
tickets.put(world, newTickets);
forcedChunks.put(world, ImmutableSetMultimap.<ChunkCoordIntPair,Ticket>of());
if (!(world instanceof WorldServer))
{
return;
}
dormantChunkCache.put(world, CacheBuilder.newBuilder().maximumSize(dormantChunkCacheSize).<Long, Chunk>build());
WorldServer worldServer = (WorldServer) world;
File chunkDir = worldServer.getChunkSaveLocation();
File chunkLoaderData = new File(chunkDir, "forcedchunks.dat");
if (chunkLoaderData.exists() && chunkLoaderData.isFile())
{
ArrayListMultimap<String, Ticket> loadedTickets = ArrayListMultimap.<String, Ticket>create();
Map<String,ListMultimap<String,Ticket>> playerLoadedTickets = Maps.newHashMap();
NBTTagCompound forcedChunkData;
try
{
forcedChunkData = CompressedStreamTools.read(chunkLoaderData);
}
catch (IOException e)
{
FMLLog.log(Level.WARNING, e, "Unable to read forced chunk data at %s - it will be ignored", chunkLoaderData.getAbsolutePath());
return;
}
NBTTagList ticketList = forcedChunkData.getTagList("TicketList");
for (int i = 0; i < ticketList.tagCount(); i++)
{
NBTTagCompound ticketHolder = (NBTTagCompound) ticketList.tagAt(i);
String modId = ticketHolder.getString("Owner");
boolean isPlayer = "Forge".equals(modId);
if (!isPlayer && !Loader.isModLoaded(modId))
{
FMLLog.warning("Found chunkloading data for mod %s which is currently not available or active - it will be removed from the world save", modId);
continue;
}
if (!isPlayer && !callbacks.containsKey(modId))
{
FMLLog.warning("The mod %s has registered persistent chunkloading data but doesn't seem to want to be called back with it - it will be removed from the world save", modId);
continue;
}
NBTTagList tickets = ticketHolder.getTagList("Tickets");
for (int j = 0; j < tickets.tagCount(); j++)
{
NBTTagCompound ticket = (NBTTagCompound) tickets.tagAt(j);
modId = ticket.hasKey("ModId") ? ticket.getString("ModId") : modId;
Type type = Type.values()[ticket.getByte("Type")];
byte ticketChunkDepth = ticket.getByte("ChunkListDepth");
Ticket tick = new Ticket(modId, type, world);
if (ticket.hasKey("ModData"))
{
tick.modData = ticket.getCompoundTag("ModData");
}
if (ticket.hasKey("Player"))
{
tick.player = ticket.getString("Player");
if (!playerLoadedTickets.containsKey(tick.modId))
{
playerLoadedTickets.put(modId, ArrayListMultimap.<String,Ticket>create());
}
playerLoadedTickets.get(tick.modId).put(tick.player, tick);
}
else
{
loadedTickets.put(modId, tick);
}
if (type == Type.ENTITY)
{
tick.entityChunkX = ticket.getInteger("chunkX");
tick.entityChunkZ = ticket.getInteger("chunkZ");
UUID uuid = new UUID(ticket.getLong("PersistentIDMSB"), ticket.getLong("PersistentIDLSB"));
// add the ticket to the "pending entity" list
pendingEntities.put(uuid, tick);
}
}
}
for (Ticket tick : ImmutableSet.copyOf(pendingEntities.values()))
{
if (tick.ticketType == Type.ENTITY && tick.entity == null)
{
// force the world to load the entity's chunk
// the load will come back through the loadEntity method and attach the entity
// to the ticket
world.getChunkFromChunkCoords(tick.entityChunkX, tick.entityChunkZ);
}
}
for (Ticket tick : ImmutableSet.copyOf(pendingEntities.values()))
{
if (tick.ticketType == Type.ENTITY && tick.entity == null)
{
FMLLog.warning("Failed to load persistent chunkloading entity %s from store.", pendingEntities.inverse().get(tick));
loadedTickets.remove(tick.modId, tick);
}
}
pendingEntities.clear();
// send callbacks
for (String modId : loadedTickets.keySet())
{
LoadingCallback loadingCallback = callbacks.get(modId);
if (loadingCallback == null)
{
continue;
}
int maxTicketLength = getMaxTicketLengthFor(modId);
List<Ticket> tickets = loadedTickets.get(modId);
if (loadingCallback instanceof OrderedLoadingCallback)
{
OrderedLoadingCallback orderedLoadingCallback = (OrderedLoadingCallback) loadingCallback;
tickets = orderedLoadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world, maxTicketLength);
}
if (tickets.size() > maxTicketLength)
{
FMLLog.warning("The mod %s has too many open chunkloading tickets %d. Excess will be dropped", modId, tickets.size());
tickets.subList(maxTicketLength, tickets.size()).clear();
}
ForgeChunkManager.tickets.get(world).putAll(modId, tickets);
loadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world);
}
for (String modId : playerLoadedTickets.keySet())
{
LoadingCallback loadingCallback = callbacks.get(modId);
if (loadingCallback == null)
{
continue;
}
ListMultimap<String,Ticket> tickets = playerLoadedTickets.get(modId);
if (loadingCallback instanceof PlayerOrderedLoadingCallback)
{
PlayerOrderedLoadingCallback orderedLoadingCallback = (PlayerOrderedLoadingCallback) loadingCallback;
tickets = orderedLoadingCallback.playerTicketsLoaded(ImmutableListMultimap.copyOf(tickets), world);
playerTickets.putAll(tickets);
}
ForgeChunkManager.tickets.get(world).putAll("Forge", tickets.values());
loadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets.values()), world);
}
}
}
static void unloadWorld(World world)
{
// World save fires before this event so the chunk loading info will be done
if (!(world instanceof WorldServer))
{
return;
}
forcedChunks.remove(world);
dormantChunkCache.remove(world);
// integrated server is shutting down
if (!MinecraftServer.getServer().isServerRunning())
{
playerTickets.clear();
tickets.clear();
}
}
/**
* Set a chunkloading callback for the supplied mod object
*
* @param mod The mod instance registering the callback
* @param callback The code to call back when forced chunks are loaded
*/
public static void setForcedChunkLoadingCallback(Object mod, LoadingCallback callback)
{
ModContainer container = getContainer(mod);
if (container == null)
{
FMLLog.warning("Unable to register a callback for an unknown mod %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod));
return;
}
callbacks.put(container.getModId(), callback);
}
/**
* Discover the available tickets for the mod in the world
*
* @param mod The mod that will own the tickets
* @param world The world
* @return The count of tickets left for the mod in the supplied world
*/
public static int ticketCountAvailableFor(Object mod, World world)
{
ModContainer container = getContainer(mod);
if (container!=null)
{
String modId = container.getModId();
int allowedCount = getMaxTicketLengthFor(modId);
return allowedCount - tickets.get(world).get(modId).size();
}
else
{
return 0;
}
}
private static ModContainer getContainer(Object mod)
{
ModContainer container = Loader.instance().getModObjectList().inverse().get(mod);
return container;
}
public static int getMaxTicketLengthFor(String modId)
{
int allowedCount = ticketConstraints.containsKey(modId) && overridesEnabled ? ticketConstraints.get(modId) : defaultMaxCount;
return allowedCount;
}
public static int getMaxChunkDepthFor(String modId)
{
int allowedCount = chunkConstraints.containsKey(modId) && overridesEnabled ? chunkConstraints.get(modId) : defaultMaxChunks;
return allowedCount;
}
public static int ticketCountAvailableFor(String username)
{
return playerTicketLength - playerTickets.get(username).size();
}
public static Ticket requestPlayerTicket(Object mod, String player, World world, Type type)
{
ModContainer mc = getContainer(mod);
if (mc == null)
{
FMLLog.log(Level.SEVERE, "Failed to locate the container for mod instance %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod));
return null;
}
if (playerTickets.get(player).size()>playerTicketLength)
{
FMLLog.warning("Unable to assign further chunkloading tickets to player %s (on behalf of mod %s)", player, mc.getModId());
return null;
}
Ticket ticket = new Ticket(mc.getModId(),type,world,player);
playerTickets.put(player, ticket);
tickets.get(world).put("Forge", ticket);
return ticket;
}
/**
* Request a chunkloading ticket of the appropriate type for the supplied mod
*
* @param mod The mod requesting a ticket
* @param world The world in which it is requesting the ticket
* @param type The type of ticket
* @return A ticket with which to register chunks for loading, or null if no further tickets are available
*/
public static Ticket requestTicket(Object mod, World world, Type type)
{
ModContainer container = getContainer(mod);
if (container == null)
{
FMLLog.log(Level.SEVERE, "Failed to locate the container for mod instance %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod));
return null;
}
String modId = container.getModId();
if (!callbacks.containsKey(modId))
{
FMLLog.severe("The mod %s has attempted to request a ticket without a listener in place", modId);
throw new RuntimeException("Invalid ticket request");
}
int allowedCount = ticketConstraints.containsKey(modId) ? ticketConstraints.get(modId) : defaultMaxCount;
if (tickets.get(world).get(modId).size() >= allowedCount)
{
if (!warnedMods.contains(modId))
{
FMLLog.info("The mod %s has attempted to allocate a chunkloading ticket beyond it's currently allocated maximum : %d", modId, allowedCount);
warnedMods.add(modId);
}
return null;
}
Ticket ticket = new Ticket(modId, type, world);
tickets.get(world).put(modId, ticket);
return ticket;
}
/**
* Release the ticket back to the system. This will also unforce any chunks held by the ticket so that they can be unloaded and/or stop ticking.
*
* @param ticket The ticket to release
*/
public static void releaseTicket(Ticket ticket)
{
if (ticket == null)
{
return;
}
if (ticket.isPlayerTicket() ? !playerTickets.containsValue(ticket) : !tickets.get(ticket.world).containsEntry(ticket.modId, ticket))
{
return;
}
if (ticket.requestedChunks!=null)
{
for (ChunkCoordIntPair chunk : ImmutableSet.copyOf(ticket.requestedChunks))
{
unforceChunk(ticket, chunk);
}
}
if (ticket.isPlayerTicket())
{
playerTickets.remove(ticket.player, ticket);
tickets.get(ticket.world).remove("Forge",ticket);
}
else
{
tickets.get(ticket.world).remove(ticket.modId, ticket);
}
}
/**
* Force the supplied chunk coordinate to be loaded by the supplied ticket. If the ticket's {@link Ticket#maxDepth} is exceeded, the least
* recently registered chunk is unforced and may be unloaded.
* It is safe to force the chunk several times for a ticket, it will not generate duplication or change the ordering.
*
* @param ticket The ticket registering the chunk
* @param chunk The chunk to force
*/
public static void forceChunk(Ticket ticket, ChunkCoordIntPair chunk)
{
if (ticket == null || chunk == null)
{
return;
}
if (ticket.ticketType == Type.ENTITY && ticket.entity == null)
{
throw new RuntimeException("Attempted to use an entity ticket to force a chunk, without an entity");
}
if (ticket.isPlayerTicket() ? !playerTickets.containsValue(ticket) : !tickets.get(ticket.world).containsEntry(ticket.modId, ticket))
{
FMLLog.severe("The mod %s attempted to force load a chunk with an invalid ticket. This is not permitted.", ticket.modId);
return;
}
ticket.requestedChunks.add(chunk);
MinecraftForge.EVENT_BUS.post(new ForceChunkEvent(ticket, chunk));
ImmutableSetMultimap<ChunkCoordIntPair, Ticket> newMap = ImmutableSetMultimap.<ChunkCoordIntPair,Ticket>builder().putAll(forcedChunks.get(ticket.world)).put(chunk, ticket).build();
forcedChunks.put(ticket.world, newMap);
if (ticket.maxDepth > 0 && ticket.requestedChunks.size() > ticket.maxDepth)
{
ChunkCoordIntPair removed = ticket.requestedChunks.iterator().next();
unforceChunk(ticket,removed);
}
}
/**
* Reorganize the internal chunk list so that the chunk supplied is at the *end* of the list
* This helps if you wish to guarantee a certain "automatic unload ordering" for the chunks
* in the ticket list
*
* @param ticket The ticket holding the chunk list
* @param chunk The chunk you wish to push to the end (so that it would be unloaded last)
*/
public static void reorderChunk(Ticket ticket, ChunkCoordIntPair chunk)
{
if (ticket == null || chunk == null || !ticket.requestedChunks.contains(chunk))
{
return;
}
ticket.requestedChunks.remove(chunk);
ticket.requestedChunks.add(chunk);
}
/**
* Unforce the supplied chunk, allowing it to be unloaded and stop ticking.
*
* @param ticket The ticket holding the chunk
* @param chunk The chunk to unforce
*/
public static void unforceChunk(Ticket ticket, ChunkCoordIntPair chunk)
{
if (ticket == null || chunk == null)
{
return;
}
ticket.requestedChunks.remove(chunk);
MinecraftForge.EVENT_BUS.post(new UnforceChunkEvent(ticket, chunk));
LinkedHashMultimap<ChunkCoordIntPair, Ticket> copy = LinkedHashMultimap.create(forcedChunks.get(ticket.world));
copy.remove(chunk, ticket);
ImmutableSetMultimap<ChunkCoordIntPair, Ticket> newMap = ImmutableSetMultimap.copyOf(copy);
forcedChunks.put(ticket.world,newMap);
}
static void loadConfiguration()
{
for (String mod : config.getCategoryNames())
{
if (mod.equals("Forge") || mod.equals("defaults"))
{
continue;
}
Property modTC = config.get(mod, "maximumTicketCount", 200);
Property modCPT = config.get(mod, "maximumChunksPerTicket", 25);
ticketConstraints.put(mod, modTC.getInt(200));
chunkConstraints.put(mod, modCPT.getInt(25));
}
if (config.hasChanged())
{
config.save();
}
}
/**
* The list of persistent chunks in the world. This set is immutable.
* @param world
* @return the list of persistent chunks in the world
*/
public static ImmutableSetMultimap<ChunkCoordIntPair, Ticket> getPersistentChunksFor(World world)
{
return forcedChunks.containsKey(world) ? forcedChunks.get(world) : ImmutableSetMultimap.<ChunkCoordIntPair,Ticket>of();
}
static void saveWorld(World world)
{
// only persist persistent worlds
if (!(world instanceof WorldServer)) { return; }
WorldServer worldServer = (WorldServer) world;
File chunkDir = worldServer.getChunkSaveLocation();
File chunkLoaderData = new File(chunkDir, "forcedchunks.dat");
NBTTagCompound forcedChunkData = new NBTTagCompound();
NBTTagList ticketList = new NBTTagList();
forcedChunkData.setTag("TicketList", ticketList);
Multimap<String, Ticket> ticketSet = tickets.get(worldServer);
for (String modId : ticketSet.keySet())
{
NBTTagCompound ticketHolder = new NBTTagCompound();
ticketList.appendTag(ticketHolder);
ticketHolder.setString("Owner", modId);
NBTTagList tickets = new NBTTagList();
ticketHolder.setTag("Tickets", tickets);
for (Ticket tick : ticketSet.get(modId))
{
NBTTagCompound ticket = new NBTTagCompound();
ticket.setByte("Type", (byte) tick.ticketType.ordinal());
ticket.setByte("ChunkListDepth", (byte) tick.maxDepth);
if (tick.isPlayerTicket())
{
ticket.setString("ModId", tick.modId);
ticket.setString("Player", tick.player);
}
if (tick.modData != null)
{
ticket.setCompoundTag("ModData", tick.modData);
}
if (tick.ticketType == Type.ENTITY && tick.entity != null && tick.entity.addEntityID(new NBTTagCompound()))
{
ticket.setInteger("chunkX", MathHelper.floor_double(tick.entity.chunkCoordX));
ticket.setInteger("chunkZ", MathHelper.floor_double(tick.entity.chunkCoordZ));
ticket.setLong("PersistentIDMSB", tick.entity.getPersistentID().getMostSignificantBits());
ticket.setLong("PersistentIDLSB", tick.entity.getPersistentID().getLeastSignificantBits());
tickets.appendTag(ticket);
}
else if (tick.ticketType != Type.ENTITY)
{
tickets.appendTag(ticket);
}
}
}
try
{
CompressedStreamTools.write(forcedChunkData, chunkLoaderData);
}
catch (IOException e)
{
FMLLog.log(Level.WARNING, e, "Unable to write forced chunk data to %s - chunkloading won't work", chunkLoaderData.getAbsolutePath());
return;
}
}
static void loadEntity(Entity entity)
{
UUID id = entity.getPersistentID();
Ticket tick = pendingEntities.get(id);
if (tick != null)
{
tick.bindEntity(entity);
pendingEntities.remove(id);
}
}
public static void putDormantChunk(long coords, Chunk chunk)
{
Cache<Long, Chunk> cache = dormantChunkCache.get(chunk.worldObj);
if (cache != null)
{
cache.put(coords, chunk);
}
}
public static Chunk fetchDormantChunk(long coords, World world)
{
Cache<Long, Chunk> cache = dormantChunkCache.get(world);
if (cache == null)
{
return null;
}
Chunk chunk = cache.getIfPresent(coords);
if (chunk != null)
{
for (List<Entity> eList : chunk.entityLists)
{
for (Entity e: eList)
{
e.resetEntityId();
}
}
}
return chunk;
}
static void captureConfig(File configDir)
{
cfgFile = new File(configDir,"forgeChunkLoading.cfg");
config = new Configuration(cfgFile, true);
try
{
config.load();
}
catch (Exception e)
{
File dest = new File(cfgFile.getParentFile(),"forgeChunkLoading.cfg.bak");
if (dest.exists())
{
dest.delete();
}
cfgFile.renameTo(dest);
FMLLog.log(Level.SEVERE, e, "A critical error occured reading the forgeChunkLoading.cfg file, defaults will be used - the invalid file is backed up at forgeChunkLoading.cfg.bak");
}
config.addCustomCategoryComment("defaults", "Default configuration for forge chunk loading control");
Property maxTicketCount = config.get("defaults", "maximumTicketCount", 200);
maxTicketCount.comment = "The default maximum ticket count for a mod which does not have an override\n" +
"in this file. This is the number of chunk loading requests a mod is allowed to make.";
defaultMaxCount = maxTicketCount.getInt(200);
Property maxChunks = config.get("defaults", "maximumChunksPerTicket", 25);
maxChunks.comment = "The default maximum number of chunks a mod can force, per ticket, \n" +
"for a mod without an override. This is the maximum number of chunks a single ticket can force.";
defaultMaxChunks = maxChunks.getInt(25);
Property playerTicketCount = config.get("defaults", "playerTicketCount", 500);
playerTicketCount.comment = "The number of tickets a player can be assigned instead of a mod. This is shared across all mods and it is up to the mods to use it.";
playerTicketLength = playerTicketCount.getInt(500);
Property dormantChunkCacheSizeProperty = config.get("defaults", "dormantChunkCacheSize", 0);
dormantChunkCacheSizeProperty.comment = "Unloaded chunks can first be kept in a dormant cache for quicker\n" +
"loading times. Specify the size (in chunks) of that cache here";
dormantChunkCacheSize = dormantChunkCacheSizeProperty.getInt(0);
FMLLog.info("Configured a dormant chunk cache size of %d", dormantChunkCacheSizeProperty.getInt(0));
Property modOverridesEnabled = config.get("defaults", "enabled", true);
modOverridesEnabled.comment = "Are mod overrides enabled?";
overridesEnabled = modOverridesEnabled.getBoolean(true);
config.addCustomCategoryComment("Forge", "Sample mod specific control section.\n" +
"Copy this section and rename the with the modid for the mod you wish to override.\n" +
"A value of zero in either entry effectively disables any chunkloading capabilities\n" +
"for that mod");
Property sampleTC = config.get("Forge", "maximumTicketCount", 200);
sampleTC.comment = "Maximum ticket count for the mod. Zero disables chunkloading capabilities.";
sampleTC = config.get("Forge", "maximumChunksPerTicket", 25);
sampleTC.comment = "Maximum chunks per ticket for the mod.";
for (String mod : config.getCategoryNames())
{
if (mod.equals("Forge") || mod.equals("defaults"))
{
continue;
}
Property modTC = config.get(mod, "maximumTicketCount", 200);
Property modCPT = config.get(mod, "maximumChunksPerTicket", 25);
}
}
public static ConfigCategory getConfigFor(Object mod)
{
ModContainer container = getContainer(mod);
if (container != null)
{
return config.getCategory(container.getModId());
}
return null;
}
public static void addConfigProperty(Object mod, String propertyName, String value, Property.Type type)
{
ModContainer container = getContainer(mod);
if (container != null)
{
ConfigCategory cat = config.getCategory(container.getModId());
cat.put(propertyName, new Property(propertyName, value, type));
}
}
}
| gpl-3.0 |
NEMESIS13cz/Evercraft | java/evercraft/NEMESIS13cz/Entity/EntityRedstoneArrow.java | 25926 | package evercraft.NEMESIS13cz.Entity;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.IProjectile;
import net.minecraft.entity.monster.EntityEnderman;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.play.server.S2BPacketChangeGameState;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EntityDamageSourceIndirect;
import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import evercraft.NEMESIS13cz.Main.Evercraft_Items;
public class EntityRedstoneArrow extends Entity implements IProjectile
{
private int field_145791_d = -1;
private int field_145792_e = -1;
private int field_145789_f = -1;
private Block field_145790_g;
private int inData;
private boolean inGround;
/**
* 1 if the player can pick up the arrow
*/
public int canBePickedUp;
/**
* Seems to be some sort of timer for animating an arrow.
*/
public int arrowShake;
/**
* The owner of this arrow.
*/
public Entity shootingEntity;
private int ticksInGround;
private int ticksInAir;
private double damage = 4.2D;
/**
* The amount of knockback an arrow applies when it hits a mob.
*/
private int knockbackStrength;
public EntityRedstoneArrow(World par1World)
{
super(par1World);
this.renderDistanceWeight = 10.0D;
this.setSize(0.5F, 0.5F);
}
public EntityRedstoneArrow(World par1World, double par2, double par4, double par6)
{
super(par1World);
this.renderDistanceWeight = 10.0D;
this.setSize(0.5F, 0.5F);
this.setPosition(par2, par4, par6);
this.yOffset = 0.0F;
}
public EntityRedstoneArrow(World par1World, EntityLivingBase par2EntityLivingBase, EntityLivingBase par3EntityLivingBase, float par4, float par5)
{
super(par1World);
this.renderDistanceWeight = 10.0D;
this.shootingEntity = par2EntityLivingBase;
if (par2EntityLivingBase instanceof EntityPlayer)
{
this.canBePickedUp = 1;
}
this.posY = par2EntityLivingBase.posY + (double)par2EntityLivingBase.getEyeHeight() - 0.10000000149011612D;
double d0 = par3EntityLivingBase.posX - par2EntityLivingBase.posX;
double d1 = par3EntityLivingBase.boundingBox.minY + (double)(par3EntityLivingBase.height / 3.0F) - this.posY;
double d2 = par3EntityLivingBase.posZ - par2EntityLivingBase.posZ;
double d3 = (double)MathHelper.sqrt_double(d0 * d0 + d2 * d2);
if (d3 >= 1.0E-7D)
{
float f2 = (float)(Math.atan2(d2, d0) * 180.0D / Math.PI) - 90.0F;
float f3 = (float)(-(Math.atan2(d1, d3) * 180.0D / Math.PI));
double d4 = d0 / d3;
double d5 = d2 / d3;
this.setLocationAndAngles(par2EntityLivingBase.posX + d4, this.posY, par2EntityLivingBase.posZ + d5, f2, f3);
this.yOffset = 0.0F;
float f4 = (float)d3 * 0.2F;
this.setThrowableHeading(d0, d1 + (double)f4, d2, par4, par5);
}
}
public EntityRedstoneArrow(World par1World, EntityLivingBase par2EntityLivingBase, float par3)
{
super(par1World);
this.renderDistanceWeight = 10.0D;
this.shootingEntity = par2EntityLivingBase;
if (par2EntityLivingBase instanceof EntityPlayer)
{
this.canBePickedUp = 1;
}
this.setSize(0.5F, 0.5F);
this.setLocationAndAngles(par2EntityLivingBase.posX, par2EntityLivingBase.posY + (double)par2EntityLivingBase.getEyeHeight(), par2EntityLivingBase.posZ, par2EntityLivingBase.rotationYaw, par2EntityLivingBase.rotationPitch);
this.posX -= (double)(MathHelper.cos(this.rotationYaw / 180.0F * (float)Math.PI) * 0.16F);
this.posY -= 0.10000000149011612D;
this.posZ -= (double)(MathHelper.sin(this.rotationYaw / 180.0F * (float)Math.PI) * 0.16F);
this.setPosition(this.posX, this.posY, this.posZ);
this.yOffset = 0.0F;
this.motionX = (double)(-MathHelper.sin(this.rotationYaw / 180.0F * (float)Math.PI) * MathHelper.cos(this.rotationPitch / 180.0F * (float)Math.PI));
this.motionZ = (double)(MathHelper.cos(this.rotationYaw / 180.0F * (float)Math.PI) * MathHelper.cos(this.rotationPitch / 180.0F * (float)Math.PI));
this.motionY = (double)(-MathHelper.sin(this.rotationPitch / 180.0F * (float)Math.PI));
this.setThrowableHeading(this.motionX, this.motionY, this.motionZ, par3 * 1.5F, 1.0F);
}
protected void entityInit()
{
this.dataWatcher.addObject(16, Byte.valueOf((byte)0));
}
/**
* Similar to setArrowHeading, it's point the throwable entity to a x, y, z direction.
*/
public void setThrowableHeading(double par1, double par3, double par5, float par7, float par8)
{
float f2 = MathHelper.sqrt_double(par1 * par1 + par3 * par3 + par5 * par5);
par1 /= (double)f2;
par3 /= (double)f2;
par5 /= (double)f2;
par1 += this.rand.nextGaussian() * (double)(this.rand.nextBoolean() ? -1 : 1) * 0.007499999832361937D * (double)par8;
par3 += this.rand.nextGaussian() * (double)(this.rand.nextBoolean() ? -1 : 1) * 0.007499999832361937D * (double)par8;
par5 += this.rand.nextGaussian() * (double)(this.rand.nextBoolean() ? -1 : 1) * 0.007499999832361937D * (double)par8;
par1 *= (double)par7;
par3 *= (double)par7;
par5 *= (double)par7;
this.motionX = par1;
this.motionY = par3;
this.motionZ = par5;
float f3 = MathHelper.sqrt_double(par1 * par1 + par5 * par5);
this.prevRotationYaw = this.rotationYaw = (float)(Math.atan2(par1, par5) * 180.0D / Math.PI);
this.prevRotationPitch = this.rotationPitch = (float)(Math.atan2(par3, (double)f3) * 180.0D / Math.PI);
this.ticksInGround = 0;
}
/**
* Sets the position and rotation. Only difference from the other one is no bounding on the rotation. Args: posX,
* posY, posZ, yaw, pitch
*/
@SideOnly(Side.CLIENT)
public void setPositionAndRotation2(double par1, double par3, double par5, float par7, float par8, int par9)
{
this.setPosition(par1, par3, par5);
this.setRotation(par7, par8);
}
public static DamageSource causeArrowDamage(EntityRedstoneArrow par0EntityArrow, Entity par1Entity)
{
return (new EntityDamageSourceIndirect("arrow", par0EntityArrow, par1Entity)).setProjectile();
}
/**
* Sets the velocity to the args. Args: x, y, z
*/
@SideOnly(Side.CLIENT)
public void setVelocity(double par1, double par3, double par5)
{
this.motionX = par1;
this.motionY = par3;
this.motionZ = par5;
if (this.prevRotationPitch == 0.0F && this.prevRotationYaw == 0.0F)
{
float f = MathHelper.sqrt_double(par1 * par1 + par5 * par5);
this.prevRotationYaw = this.rotationYaw = (float)(Math.atan2(par1, par5) * 180.0D / Math.PI);
this.prevRotationPitch = this.rotationPitch = (float)(Math.atan2(par3, (double)f) * 180.0D / Math.PI);
this.prevRotationPitch = this.rotationPitch;
this.prevRotationYaw = this.rotationYaw;
this.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotationYaw, this.rotationPitch);
this.ticksInGround = 0;
}
}
/**
* Called to update the entity's position/logic.
*/
public void onUpdate()
{
super.onUpdate();
if (this.prevRotationPitch == 0.0F && this.prevRotationYaw == 0.0F)
{
float f = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ);
this.prevRotationYaw = this.rotationYaw = (float)(Math.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI);
this.prevRotationPitch = this.rotationPitch = (float)(Math.atan2(this.motionY, (double)f) * 180.0D / Math.PI);
}
Block block = this.worldObj.getBlock(this.field_145791_d, this.field_145792_e, this.field_145789_f);
if (block.getMaterial() != Material.air)
{
block.setBlockBoundsBasedOnState(this.worldObj, this.field_145791_d, this.field_145792_e, this.field_145789_f);
AxisAlignedBB axisalignedbb = block.getCollisionBoundingBoxFromPool(this.worldObj, this.field_145791_d, this.field_145792_e, this.field_145789_f);
if (axisalignedbb != null && axisalignedbb.isVecInside(Vec3.createVectorHelper(this.posX, this.posY, this.posZ)))
{
this.inGround = true;
}
}
if (this.arrowShake > 0)
{
--this.arrowShake;
}
if (this.inGround)
{
int j = this.worldObj.getBlockMetadata(this.field_145791_d, this.field_145792_e, this.field_145789_f);
if (block == this.field_145790_g && j == this.inData)
{
++this.ticksInGround;
if (this.ticksInGround == 1200)
{
this.setDead();
}
}
else
{
this.inGround = false;
this.motionX *= (double)(this.rand.nextFloat() * 0.2F);
this.motionY *= (double)(this.rand.nextFloat() * 0.2F);
this.motionZ *= (double)(this.rand.nextFloat() * 0.2F);
this.ticksInGround = 0;
this.ticksInAir = 0;
}
}
else
{
++this.ticksInAir;
Vec3 vec31 = Vec3.createVectorHelper(this.posX, this.posY, this.posZ);
Vec3 vec3 = Vec3.createVectorHelper(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ);
MovingObjectPosition movingobjectposition = this.worldObj.func_147447_a(vec31, vec3, false, true, false);
vec31 = Vec3.createVectorHelper(this.posX, this.posY, this.posZ);
vec3 = Vec3.createVectorHelper(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ);
if (movingobjectposition != null)
{
vec3 = Vec3.createVectorHelper(movingobjectposition.hitVec.xCoord, movingobjectposition.hitVec.yCoord, movingobjectposition.hitVec.zCoord);
}
Entity entity = null;
List list = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.boundingBox.addCoord(this.motionX, this.motionY, this.motionZ).expand(1.0D, 1.0D, 1.0D));
double d0 = 0.0D;
int i;
float f1;
for (i = 0; i < list.size(); ++i)
{
Entity entity1 = (Entity)list.get(i);
if (entity1.canBeCollidedWith() && (entity1 != this.shootingEntity || this.ticksInAir >= 5))
{
f1 = 0.3F;
AxisAlignedBB axisalignedbb1 = entity1.boundingBox.expand((double)f1, (double)f1, (double)f1);
MovingObjectPosition movingobjectposition1 = axisalignedbb1.calculateIntercept(vec31, vec3);
if (movingobjectposition1 != null)
{
double d1 = vec31.distanceTo(movingobjectposition1.hitVec);
if (d1 < d0 || d0 == 0.0D)
{
entity = entity1;
d0 = d1;
}
}
}
}
if (entity != null)
{
movingobjectposition = new MovingObjectPosition(entity);
}
if (movingobjectposition != null && movingobjectposition.entityHit != null && movingobjectposition.entityHit instanceof EntityPlayer)
{
EntityPlayer entityplayer = (EntityPlayer)movingobjectposition.entityHit;
if (entityplayer.capabilities.disableDamage || this.shootingEntity instanceof EntityPlayer && !((EntityPlayer)this.shootingEntity).canAttackPlayer(entityplayer))
{
movingobjectposition = null;
}
}
float f2;
float f4;
if (movingobjectposition != null)
{
if (movingobjectposition.entityHit != null)
{
f2 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionY * this.motionY + this.motionZ * this.motionZ);
int k = MathHelper.ceiling_double_int((double)f2 * this.damage);
if (this.getIsCritical())
{
k += this.rand.nextInt(k / 2 + 2);
}
DamageSource damagesource = null;
if (this.shootingEntity == null)
{
damagesource = this.causeArrowDamage(this, this);
}
else
{
damagesource = this.causeArrowDamage(this, this.shootingEntity);
}
if (this.isBurning() && !(movingobjectposition.entityHit instanceof EntityEnderman))
{
movingobjectposition.entityHit.setFire(5);
}
if (movingobjectposition.entityHit.attackEntityFrom(damagesource, (float)k))
{
if (movingobjectposition.entityHit instanceof EntityLivingBase)
{
EntityLivingBase entitylivingbase = (EntityLivingBase)movingobjectposition.entityHit;
if (!this.worldObj.isRemote)
{
entitylivingbase.setArrowCountInEntity(entitylivingbase.getArrowCountInEntity() + 1);
}
if (this.knockbackStrength > 0)
{
f4 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ);
if (f4 > 0.0F)
{
movingobjectposition.entityHit.addVelocity(this.motionX * (double)this.knockbackStrength * 0.6000000238418579D / (double)f4, 0.1D, this.motionZ * (double)this.knockbackStrength * 0.6000000238418579D / (double)f4);
}
}
if (this.shootingEntity != null && this.shootingEntity instanceof EntityLivingBase)
{
EnchantmentHelper.func_151384_a(entitylivingbase, this.shootingEntity);
EnchantmentHelper.func_151385_b((EntityLivingBase)this.shootingEntity, entitylivingbase);
}
if (this.shootingEntity != null && movingobjectposition.entityHit != this.shootingEntity && movingobjectposition.entityHit instanceof EntityPlayer && this.shootingEntity instanceof EntityPlayerMP)
{
((EntityPlayerMP)this.shootingEntity).playerNetServerHandler.sendPacket(new S2BPacketChangeGameState(6, 0.0F));
}
}
this.playSound("random.bowhit", 1.0F, 1.2F / (this.rand.nextFloat() * 0.2F + 0.9F));
if (!(movingobjectposition.entityHit instanceof EntityEnderman))
{
this.setDead();
}
}
else
{
this.motionX *= -0.10000000149011612D;
this.motionY *= -0.10000000149011612D;
this.motionZ *= -0.10000000149011612D;
this.rotationYaw += 180.0F;
this.prevRotationYaw += 180.0F;
this.ticksInAir = 0;
}
}
else
{
this.field_145791_d = movingobjectposition.blockX;
this.field_145792_e = movingobjectposition.blockY;
this.field_145789_f = movingobjectposition.blockZ;
this.field_145790_g = block;
this.inData = this.worldObj.getBlockMetadata(this.field_145791_d, this.field_145792_e, this.field_145789_f);
this.motionX = (double)((float)(movingobjectposition.hitVec.xCoord - this.posX));
this.motionY = (double)((float)(movingobjectposition.hitVec.yCoord - this.posY));
this.motionZ = (double)((float)(movingobjectposition.hitVec.zCoord - this.posZ));
f2 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionY * this.motionY + this.motionZ * this.motionZ);
this.posX -= this.motionX / (double)f2 * 0.05000000074505806D;
this.posY -= this.motionY / (double)f2 * 0.05000000074505806D;
this.posZ -= this.motionZ / (double)f2 * 0.05000000074505806D;
this.playSound("random.bowhit", 1.0F, 1.2F / (this.rand.nextFloat() * 0.2F + 0.9F));
this.inGround = true;
this.arrowShake = 7;
this.setIsCritical(false);
if (this.field_145790_g.getMaterial() != Material.air)
{
this.field_145790_g.onEntityCollidedWithBlock(this.worldObj, this.field_145791_d, this.field_145792_e, this.field_145789_f, this);
}
}
}
if (this.getIsCritical())
{
for (i = 0; i < 4; ++i)
{
this.worldObj.spawnParticle("crit", this.posX + this.motionX * (double)i / 4.0D, this.posY + this.motionY * (double)i / 4.0D, this.posZ + this.motionZ * (double)i / 4.0D, -this.motionX, -this.motionY + 0.2D, -this.motionZ);
}
}
this.posX += this.motionX;
this.posY += this.motionY;
this.posZ += this.motionZ;
f2 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ);
this.rotationYaw = (float)(Math.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI);
for (this.rotationPitch = (float)(Math.atan2(this.motionY, (double)f2) * 180.0D / Math.PI); this.rotationPitch - this.prevRotationPitch < -180.0F; this.prevRotationPitch -= 360.0F)
{
;
}
while (this.rotationPitch - this.prevRotationPitch >= 180.0F)
{
this.prevRotationPitch += 360.0F;
}
while (this.rotationYaw - this.prevRotationYaw < -180.0F)
{
this.prevRotationYaw -= 360.0F;
}
while (this.rotationYaw - this.prevRotationYaw >= 180.0F)
{
this.prevRotationYaw += 360.0F;
}
this.rotationPitch = this.prevRotationPitch + (this.rotationPitch - this.prevRotationPitch) * 0.2F;
this.rotationYaw = this.prevRotationYaw + (this.rotationYaw - this.prevRotationYaw) * 0.2F;
float f3 = 0.99F;
f1 = 0.05F;
if (this.isInWater())
{
for (int l = 0; l < 4; ++l)
{
f4 = 0.25F;
this.worldObj.spawnParticle("bubble", this.posX - this.motionX * (double)f4, this.posY - this.motionY * (double)f4, this.posZ - this.motionZ * (double)f4, this.motionX, this.motionY, this.motionZ);
}
f3 = 0.8F;
}
if (this.isWet())
{
this.extinguish();
}
this.motionX *= (double)f3;
this.motionY *= (double)f3;
this.motionZ *= (double)f3;
this.motionY -= (double)f1;
this.setPosition(this.posX, this.posY, this.posZ);
this.func_145775_I();
}
}
/**
* (abstract) Protected helper method to write subclass entity data to NBT.
*/
public void writeEntityToNBT(NBTTagCompound par1NBTTagCompound)
{
par1NBTTagCompound.setShort("xTile", (short)this.field_145791_d);
par1NBTTagCompound.setShort("yTile", (short)this.field_145792_e);
par1NBTTagCompound.setShort("zTile", (short)this.field_145789_f);
par1NBTTagCompound.setShort("life", (short)this.ticksInGround);
par1NBTTagCompound.setByte("inTile", (byte)Block.getIdFromBlock(this.field_145790_g));
par1NBTTagCompound.setByte("inData", (byte)this.inData);
par1NBTTagCompound.setByte("shake", (byte)this.arrowShake);
par1NBTTagCompound.setByte("inGround", (byte)(this.inGround ? 1 : 0));
par1NBTTagCompound.setByte("pickup", (byte)this.canBePickedUp);
par1NBTTagCompound.setDouble("damage", this.damage);
}
/**
* (abstract) Protected helper method to read subclass entity data from NBT.
*/
public void readEntityFromNBT(NBTTagCompound par1NBTTagCompound)
{
this.field_145791_d = par1NBTTagCompound.getShort("xTile");
this.field_145792_e = par1NBTTagCompound.getShort("yTile");
this.field_145789_f = par1NBTTagCompound.getShort("zTile");
this.ticksInGround = par1NBTTagCompound.getShort("life");
this.field_145790_g = Block.getBlockById(par1NBTTagCompound.getByte("inTile") & 255);
this.inData = par1NBTTagCompound.getByte("inData") & 255;
this.arrowShake = par1NBTTagCompound.getByte("shake") & 255;
this.inGround = par1NBTTagCompound.getByte("inGround") == 1;
if (par1NBTTagCompound.hasKey("damage", 99))
{
this.damage = par1NBTTagCompound.getDouble("damage");
}
if (par1NBTTagCompound.hasKey("pickup", 99))
{
this.canBePickedUp = par1NBTTagCompound.getByte("pickup");
}
else if (par1NBTTagCompound.hasKey("player", 99))
{
this.canBePickedUp = par1NBTTagCompound.getBoolean("player") ? 1 : 0;
}
}
/**
* Called by a player entity when they collide with an entity
*/
public void onCollideWithPlayer(EntityPlayer par1EntityPlayer)
{
if (!this.worldObj.isRemote && this.inGround && this.arrowShake <= 0)
{
boolean flag = this.canBePickedUp == 1 || this.canBePickedUp == 2 && par1EntityPlayer.capabilities.isCreativeMode;
if (this.canBePickedUp == 1 && !par1EntityPlayer.inventory.addItemStackToInventory(new ItemStack(Evercraft_Items.redstonearrow, 1)))
{
flag = false;
}
if (flag)
{
this.playSound("random.pop", 0.2F, ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.7F + 1.0F) * 2.0F);
par1EntityPlayer.onItemPickup(this, 1);
this.setDead();
}
}
}
/**
* returns if this entity triggers Block.onEntityWalking on the blocks they walk on. used for spiders and wolves to
* prevent them from trampling crops
*/
protected boolean canTriggerWalking()
{
return false;
}
@SideOnly(Side.CLIENT)
public float getShadowSize()
{
return 0.0F;
}
public void setDamage(double par1)
{
this.damage = par1;
}
public double getDamage()
{
return this.damage;
}
/**
* Sets the amount of knockback the arrow applies when it hits a mob.
*/
public void setKnockbackStrength(int par1)
{
this.knockbackStrength = par1;
}
/**
* If returns false, the item will not inflict any damage against entities.
*/
public boolean canAttackWithItem()
{
return false;
}
/**
* Whether the arrow has a stream of critical hit particles flying behind it.
*/
public void setIsCritical(boolean par1)
{
byte b0 = this.dataWatcher.getWatchableObjectByte(16);
if (par1)
{
this.dataWatcher.updateObject(16, Byte.valueOf((byte)(b0 | 1)));
}
else
{
this.dataWatcher.updateObject(16, Byte.valueOf((byte)(b0 & -2)));
}
}
/**
* Whether the arrow has a stream of critical hit particles flying behind it.
*/
public boolean getIsCritical()
{
byte b0 = this.dataWatcher.getWatchableObjectByte(16);
return (b0 & 1) != 0;
}
} | gpl-3.0 |
thelineva/tilitin | src/kirjanpito/ui/AboutDialog.java | 2144 | package kirjanpito.ui;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import kirjanpito.ui.resources.Resources;
/**
* Tietoja ohjelmasta -ikkuna.
*
* @author Tommi Helineva
*/
public class AboutDialog extends JDialog {
private static final long serialVersionUID = 1L;
public AboutDialog(Frame owner) {
super(owner, "Tietoja ohjelmasta " +
Kirjanpito.APP_NAME, true);
}
/**
* Luo ikkunan komponentit.
*/
public void create() {
setLayout(new GridBagLayout());
setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
GridBagConstraints c = new GridBagConstraints();
ImageIcon icon = new ImageIcon(Resources.load("tilitin-48x48.png"));
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(15, 10, 5, 10);
c.weightx = 1.0;
c.weighty = 0.5;
add(new JLabel(icon), c);
JLabel label;
label = new JLabel("<html><big><b>" +
Kirjanpito.APP_NAME + " " + Kirjanpito.APP_VERSION +
"</b></big></html>");
c.gridy = 1;
c.insets = new Insets(5, 40, 5, 40);
c.weighty = 0.0;
add(label, c);
label = new JLabel("Kirjanpito-ohjelma");
c.gridy = 2;
c.insets = new Insets(5, 10, 5, 10);
add(label, c);
label = new JLabel(
"<html><small>© 2009–2013 Tommi Helineva</small></html>");
c.gridy = 3;
add(label, c);
JButton closeButton = new JButton("Sulje",
new ImageIcon(Resources.load("close-22x22.png")));
closeButton.setMnemonic('S');
closeButton.setPreferredSize(new Dimension(100, 35));
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
c.anchor = GridBagConstraints.LAST_LINE_END;
c.gridy = 4;
c.insets = new Insets(10, 10, 10, 10);
c.weighty = 0.5;
add(closeButton, c);
getRootPane().setDefaultButton(closeButton);
pack();
setLocationRelativeTo(getOwner());
}
}
| gpl-3.0 |
oitsjustjose/Geolosys | src/main/java/com/oitsjustjose/geolosys/common/config/CompatConfig.java | 1315 | package com.oitsjustjose.geolosys.common.config;
import net.minecraftforge.common.ForgeConfigSpec;
public class CompatConfig {
public static final String CATEGORY_COMPAT = "compat";
public static ForgeConfigSpec.BooleanValue ENABLE_OSMIUM;
public static ForgeConfigSpec.BooleanValue ENABLE_OSMIUM_EXCLUSIVELY;
public static ForgeConfigSpec.BooleanValue ENABLE_YELLORIUM;
public static ForgeConfigSpec.BooleanValue ENABLE_SULFUR;
public static void init(ForgeConfigSpec.Builder COMMON_BUILDER) {
COMMON_BUILDER.comment("Mod-Compat Settings").push(CATEGORY_COMPAT);
ENABLE_OSMIUM = COMMON_BUILDER.comment("This will make it so that Platinum will drop Platinum AND Osmium")
.define("enableOsmium", true);
ENABLE_OSMIUM_EXCLUSIVELY = COMMON_BUILDER.comment("This will make it so that Platinum will ONLY drop Osmium")
.define("enableOsmiumExclusively", true);
ENABLE_YELLORIUM = COMMON_BUILDER.comment("This will make it so that Autunite will drop Uranium AND Yellorium")
.define("enableYellorium", true);
ENABLE_SULFUR = COMMON_BUILDER.comment("This will make is so that Coal has a rare chance of dropping sulfur")
.define("enableSulfur", true);
COMMON_BUILDER.pop();
}
}
| gpl-3.0 |
lgdfiuba/futbolapp-android | app/src/main/java/ar/com/futbolapp/flows/NavigationFlow.java | 761 | package ar.com.futbolapp.flows;
import ar.com.futbolapp.R;
import ar.com.futbolapp.ui.activity.BenchActivity;
import ar.com.futbolapp.ui.fragment.DashboardFragment;
import flowengine.Flow;
import flowengine.annotations.flow.FlowSteps;
import flowengine.annotations.flow.Sequence;
import flowengine.annotations.flow.StepContainer;
import flowengine.annotations.flow.methods.Jump;
import flowengine.annotations.flow.parameters.Argument;
/**
* Created by Ignacio on 28/02/2016.
*/
@FlowSteps(
sequences = {
@Sequence(id = "main", steps = {DashboardFragment.class})
})
@StepContainer(R.id.container)
public interface NavigationFlow extends Flow {
@Jump(BenchActivity.class)
void jumpToBench(@Argument("id") Long id);
}
| gpl-3.0 |
shafr/ProgrammingTableGame | src/main/java/shafr/programmingtablegame/QrCodeGenerator.java | 416 | package shafr.programmingtablegame;
import net.glxn.qrgen.core.image.ImageType;
import net.glxn.qrgen.javase.QRCode;
/**
* Created by saikek on 04-Apr-17.
*/
public class QrCodeGenerator {
public static byte[] getQrCode(String text){
return QRCode.from(text)
.withSize(250, 250)
.to(ImageType.JPG)
.withCharset("UTF-8").stream().toByteArray();
}
}
| gpl-3.0 |
duniter/duniter4j | duniter4j-core-shared/src/main/java/org/duniter/core/util/jackson/JsonSerializerConverterAdapter.java | 2901 | package org.duniter.core.util.jackson;
/*
* #%L
* Duniter4j :: Core Client API
* %%
* Copyright (C) 2014 - 2017 EIS
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.extern.slf4j.Slf4j;
import org.duniter.core.exception.TechnicalException;
import org.duniter.core.util.converter.Converter;
import org.duniter.core.util.json.JsonSyntaxException;
import java.io.IOException;
/**
* Convert an object into a string
*/
@Slf4j
public class JsonSerializerConverterAdapter<T> extends JsonSerializer<T> {
private final Converter<T, String> converter;
private final boolean failIfInvalid;
public JsonSerializerConverterAdapter(Class<? extends Converter<T, String>> converterClass) {
this(converterClass, true);
}
public JsonSerializerConverterAdapter(
Class<? extends Converter<T, String>> converterClass,
boolean failIfInvalid) {
try {
converter = converterClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new TechnicalException(e);
}
this.failIfInvalid = failIfInvalid;
}
public JsonSerializerConverterAdapter(
Converter<T, String> converter) {
this(converter, true);
}
public JsonSerializerConverterAdapter(
Converter<T, String> converter,
boolean failIfInvalid) {
this.converter = converter;
this.failIfInvalid = failIfInvalid;
}
@Override
public void serialize(T head, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) {
try {
jsonGenerator.writeString(converter.convert(head));
}
// Unable to serialize
catch(IOException e) {
// Fail
if (failIfInvalid) {
throw new JsonSyntaxException(e);
}
// Or continue
if (log.isDebugEnabled()) {
log.warn(e.getMessage(), e); // link the exception
}
else {
log.warn(e.getMessage());
}
}
}
} | gpl-3.0 |
filipemb/siesp | app/br/com/core/jdbc/dao/curso/AvaliacaoDiscenteTable.java | 3445 | /*******************************************************************************
* This file is part of Educatio.
*
* Educatio is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Educatio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Educatio. If not, see <http://www.gnu.org/licenses/>.
*
* Authors:
* Filipe Marinho de Brito - filipe.marinho.brito@gmail.com
* Rodrigo de Souza Ataides - rodrigoataides@gmail.com
*******************************************************************************/
package br.com.core.jdbc.dao.curso;
import org.springframework.data.domain.Persistable;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.util.Date;
import java.math.BigDecimal;
/**
* This class is generated by Spring Data Jdbc code generator.
*
* @author Spring Data Jdbc Code Generator
*/
public class AvaliacaoDiscenteTable implements Persistable<Long>
{
private static final long serialVersionUID = 1L;
private Long id;
private Integer version;
private Date dataAvaliacao;
private Long disciplina;
private String nome;
private String descricao;
private BigDecimal valorAvaliacao;
private Long atividadeTurma;
private transient boolean persisted;
public AvaliacaoDiscenteTable ()
{
}
public Long getId ()
{
return this.id;
}
public boolean isNew ()
{
return this.id == null;
}
public void setId(Long id)
{
this.id = id;
}
public void setVersion (Integer version)
{
this.version = version;
}
public Integer getVersion ()
{
return this.version;
}
public void setDataAvaliacao (Date dataAvaliacao)
{
this.dataAvaliacao = dataAvaliacao;
}
public Date getDataAvaliacao ()
{
return this.dataAvaliacao;
}
public void setDisciplina (Long disciplina)
{
this.disciplina = disciplina;
}
public Long getDisciplina ()
{
return this.disciplina;
}
public void setNome (String nome)
{
this.nome = nome;
}
public String getNome ()
{
return this.nome;
}
public void setDescricao (String descricao)
{
this.descricao = descricao;
}
public String getDescricao ()
{
return this.descricao;
}
public void setValorAvaliacao (BigDecimal valorAvaliacao)
{
this.valorAvaliacao = valorAvaliacao;
}
public BigDecimal getValorAvaliacao ()
{
return this.valorAvaliacao;
}
public void setAtividadeTurma (Long atividadeTurma)
{
this.atividadeTurma = atividadeTurma;
}
public Long getAtividadeTurma ()
{
return this.atividadeTurma;
}
public void setPersisted (Boolean persisted)
{
this.persisted = persisted;
}
public Boolean getPersisted ()
{
return this.persisted;
}
@Override
public String toString ()
{
return ToStringBuilder.reflectionToString (this);
}
/* START Do not remove/edit this line. CodeGenerator will preserve any code between start and end tags.*/
/* END Do not remove/edit this line. CodeGenerator will preserve any between start and end tags.*/
} | gpl-3.0 |
Bvink/Sirocco | src/org/tornado/scripts/tornadoitemmagician/variants/tornadofletcher/enums/LimbCrossbow.java | 634 | package org.tornado.scripts.tornadoitemmagician.variants.tornadofletcher.enums;
public enum LimbCrossbow { //DONE
CROSSBOW_LIMB(0, 0),
BRONZE_LIMBS(9420, 9440),
BLURITE_LIMBS(9422, 9442),
IRON_LIMBS(9423, 9444),
STEEL_LIMBS(9425, 9446),
MITHRIL_LIMBS(9427, 9448),
ADAMANT_LIMBS(9429, 9450),
RUNE_LIMBS(9431, 9442),
DRAGON_LIMBS(25481, 25483);
private int idOne, idTwo;
LimbCrossbow(final int idOne, int idTwo) {
this.idOne = idOne;
this.idTwo = idTwo;
}
public int getOne() {
return idOne;
}
public int getTwo() {
return idTwo;
}
}
| gpl-3.0 |
ursfassler/rizzly | src/ast/data/expression/binop/Shl.java | 972 | /**
* This file is part of Rizzly.
*
* Rizzly is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Rizzly is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Rizzly. If not, see <http://www.gnu.org/licenses/>.
*/
package ast.data.expression.binop;
import ast.data.expression.Expression;
/**
*
* @author urs
*/
public class Shl extends ArithmeticOp {
public Shl(Expression left, Expression right) {
super(left, right);
}
@Override
public String getOpName() {
return "shl";
}
}
| gpl-3.0 |
mtomis/lemonjuice | src/com/codegremlins/lemonjuice/Main.java | 3456 | /*
* lemonjuice - Java Template Engine.
* Copyright (C) 2009-2012 Manuel Tomis manuel@codegremlins.com
*
* This library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
package com.codegremlins.lemonjuice;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;
public final class Main {
private TemplateContext context = new TemplateContext();
private Settings settings = new Settings();
public static void main(String[] args) {
new Main().run(new ArrayList<String>(Arrays.asList(args)));
}
private void run(List<String> args) {
settings.parse(args);
runFiles(args);
}
private void runFiles(List<String> files) {
for (String name : files) {
File file = new File(name);
if (!file.exists()) {
System.err.println("WARNING: File `" + name + "' does not exist.");
} else if (file.isDirectory()) {
System.err.println("WARNING: File `" + name + "' is a directory.");
} else {
try {
runTemplate(file);
} catch (IOException ex) {
ex.printStackTrace();
System.err.print("ERROR: Cannot process `" + name + "':");
System.err.println(ex.getMessage());
} catch (TemplateException ex) {
System.err.print("ERROR:");
System.err.println(ex.getMessage());
}
}
}
}
private void runTemplate(File file) throws IOException {
Template template = new Template(file.getAbsolutePath(), new FileInputStream(file));
String name = file.getAbsolutePath();
int index = name.lastIndexOf('/');
if (index != -1) {
template.setLocation(name.substring(0, index + 1));
}
Writer out = new OutputStreamWriter(System.out);
if (template != null) {
template.print(out, context);
}
out.flush();
}
private static class Settings {
public boolean outputJavascript = false;
public void parse(List<String> args) {
for (ListIterator<String> i = args.listIterator(); i.hasNext();) {
String item = i.next().trim();
if (item.startsWith("-")) {
if ("-js".equals(item) || "-javascript".equals(item)) {
outputJavascript = true;
}
} else {
continue;
}
i.remove();
}
}
}
} | gpl-3.0 |
cismet/verdis | src/main/java/de/cismet/verdis/AppModeListener.java | 1177 | /***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
/*
* Copyright (C) 2010 thorsten
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.cismet.verdis;
/**
* DOCUMENT ME!
*
* @author thorsten
* @version $Revision$, $Date$
*/
public interface AppModeListener {
//~ Methods ----------------------------------------------------------------
/**
* DOCUMENT ME!
*/
void appModeChanged();
}
| gpl-3.0 |
xfl03/ShakeShakePlus | src/idv/xfl03/shakeshakeplus/ExceptionHandler.java | 1219 | package idv.xfl03.shakeshakeplus;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import net.axdt.aek.file.RWKit;
public class ExceptionHandler {
public final static String ERROR_LOG_PATH="ERROR_LOG/ERROR_LOG-"+new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date())+".txt";
public static boolean CONSOLE_OUT=false;
public static final File ERROR_LOG_FILE=new File(ERROR_LOG_PATH);
public final static File ERROR_LOG_FOLDER=new File("ERROR_LOG");
public static void log(String Msg){
checkFile();
String finalLog=Version.NAME+" "+Version.VERSION+"\n"+Msg;
if(CONSOLE_OUT)
System.out.println(finalLog);
RWKit.writeLine2(ERROR_LOG_PATH, finalLog);
}
public static void log(Exception e){
//System.out.println(ERROR_LOG_PATH);
checkFile();
String finalLog=Version.NAME+" "+Version.VERSION+"\n"+e.getMessage();
if(CONSOLE_OUT)
System.out.println(finalLog);
RWKit.writeLine2(ERROR_LOG_PATH, finalLog);
}
private static void checkFile(){
if(!ERROR_LOG_FILE.exists())
try {
ERROR_LOG_FOLDER.mkdirs();
ERROR_LOG_FILE.createNewFile();
} catch (IOException e) {
//log(e);
e.printStackTrace();
}
}
}
| gpl-3.0 |
StrangeSkies/uk.co.strangeskies.modabi | uk.co.strangeskies.modabi.core.api/src/uk/co/strangeskies/modabi/processing/BindingBlocker.java | 5794 | /*
* Copyright (C) 2016 Elias N Vasylenko <eliasvasylenko@gmail.com>
*
* This file is part of uk.co.strangeskies.modabi.core.api.
*
* uk.co.strangeskies.modabi.core.api is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* uk.co.strangeskies.modabi.core.api is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with uk.co.strangeskies.modabi.core.api. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.strangeskies.modabi.processing;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import java.util.function.Function;
import uk.co.strangeskies.modabi.QualifiedName;
import uk.co.strangeskies.modabi.io.BufferingDataTarget;
import uk.co.strangeskies.modabi.io.DataItem;
import uk.co.strangeskies.modabi.io.DataSource;
import uk.co.strangeskies.modabi.io.Primitive;
/**
* {@link BindingBlock}s are intended to signal that a binding thread is waiting
* for resources or dependencies to be made available by some external process.
* Blocks should not be made if the resource is already available, even if
* released immediately.
* <p>
* This class contains methods to create blocks over {@link Function}s from, and
* {@link Consumer}s of {@link BindingBlock}. The block is created, then the
* given function or consumer should fetch the resource, or wait for it to be
* available.
* <p>
* Any {@link BindingBlock} which is currently blocking will prevent completion
* of the owning {@link BindingFuture} until the given runnable process
* completes, or until invocation of {@link BindingBlock#complete()}. The
* process will be completed on the invoking thread, so invocation returns only
* after the supplier completes execution and the block is lifted.
* <p>
* Unless otherwise specified to be internal, blocks may be satisfied by
* external processes, so if a block is still in place when binding otherwise
* completes, with no internal processing threads remaining unblocked, then the
* binding will simply wait until the dependency becomes available.
* <p>
* The thread which the given blocking process is invoked on will always
* terminate after invocation, and after releasing the block.
*
* @author Elias N Vasylenko
*
*/
public interface BindingBlocker extends BindingBlocks {
/**
* Create a block on a resource which can be uniquely identified by the given
* namespace, and the {@link DataSource} form of the id.
* <p>
* The invoking thread does not immediately wait on the block, and so the
* invocation returns immediately.
*
* @param namespace
* The namespace of the pending dependency
* @param id
* The type of the id of the pending dependency
* @param id
* The value of the id of the pending dependency
* @param internal
* Whether the block should only allow internal resolution, as
* opposed to possible satisfaction via external sources
* @return
*/
default <T> BindingBlock block(QualifiedName namespace, Primitive<T> idType, T id, boolean internal) {
return block(namespace, DataItem.forDataOfType(idType, id), internal);
}
/**
* Create a block on a resource which can be uniquely identified by the given
* namespace, and the {@link DataSource} form of the id.
* <p>
* The invoking thread does not immediately wait on the block, and so the
* invocation returns immediately.
*
* @param namespace
* The namespace of the pending dependency
* @param id
* The data of the id of the pending dependency
* @param internal
* Whether the block should only allow internal resolution, as
* opposed to possible satisfaction via external sources
* @return
*/
default BindingBlock block(QualifiedName namespace, DataItem<?> id, boolean internal) {
return block(namespace, new BufferingDataTarget().put(id).buffer(), internal);
}
/**
* Create a block on a resource which can be uniquely identified by the given
* namespace and id.
* <p>
* The invoking thread does not immediately wait on the block, and so the
* invocation returns immediately.
*
* @param namespace
* The namespace of the pending dependency
* @param id
* The id of the pending dependency
* @param internal
* Whether the block should only allow internal resolution, as
* opposed to possible satisfaction via external sources
* @return
*/
BindingBlock block(QualifiedName namespace, DataSource id, boolean internal);
public Set<Thread> getParticipatingThreads();
/**
* Register a thread as a participant in the binding/unbinding process. This
* helps the processor determine whether there is unblocked activity, or
* otherwise detect a deadlock or unsatisfied dependency.
*
* @param processingThread
* The thread participating in processing
*/
void addParticipatingThread(Thread processingThread);
/**
* Register the current thread as a participant in the binding/unbinding
* process. This helps the processor determine whether there is unblocked
* activity, or otherwise detect a deadlock or unsatisfied dependency.
*/
default void addParticipatingThread() {
addParticipatingThread(Thread.currentThread());
}
public void complete() throws InterruptedException, ExecutionException;
}
| gpl-3.0 |
gigabit101/OpenLootBags | src/main/java/gigabit101/openlootbags/compat/jei/LootbagsRecipeWrapper.java | 1687 | package gigabit101.openlootbags.compat.jei;
import com.google.common.collect.ImmutableList;
import gigabit101.openlootbags.OpenLootBags;
import gigabit101.openlootbags.api.LootMap;
import mezz.jei.api.recipe.IRecipeWrapper;
import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidStack;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
/**
* Created by Gigabit101 on 10/08/2016.
*/
public class LootbagsRecipeWrapper implements IRecipeWrapper
{
private final List inputs;
private final ItemStack outputs;
public LootbagsRecipeWrapper(LootMap map)
{
ImmutableList.Builder builder = ImmutableList.builder();
builder.add(new ItemStack(OpenLootBags.lootbag));
inputs = builder.build();
outputs = map.getStack();
}
@Override
public List getInputs() {
return inputs;
}
@Override
public List getOutputs() {
return ImmutableList.of(outputs);
}
@Override
public List<FluidStack> getFluidInputs() {
return ImmutableList.of();
}
@Override
public List<FluidStack> getFluidOutputs() {
return ImmutableList.of();
}
@Override
public void drawInfo(@Nonnull Minecraft minecraft, int i, int i1, int i2, int i3) {}
@Override
public void drawAnimations(@Nonnull Minecraft minecraft, int i, int i1) {}
@Nullable
@Override
public List<String> getTooltipStrings(int i, int i1) {
return null;
}
@Override
public boolean handleClick(@Nonnull Minecraft minecraft, int i, int i1, int i2) {
return false;
}
}
| gpl-3.0 |
daftano/dl-learner | components-core/src/main/java/org/dllearner/algorithms/ParCEL/split/ParCELDoubleSplitterV1.java | 11306 | package org.dllearner.algorithms.ParCEL.split;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.dllearner.algorithms.ParCEL.ParCELOntologyUtil;
import org.dllearner.core.AbstractReasonerComponent;
import org.dllearner.core.ComponentAnn;
import org.dllearner.core.ComponentInitException;
import org.dllearner.core.KnowledgeSource;
import org.dllearner.core.owl.DatatypeProperty;
import org.dllearner.core.owl.Individual;
import org.dllearner.kb.OWLFile;
import org.dllearner.utilities.owl.OWLAPIConverter;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLDataFactory;
import org.semanticweb.owlapi.model.OWLDataPropertyExpression;
import org.semanticweb.owlapi.model.OWLIndividual;
import org.semanticweb.owlapi.model.OWLLiteral;
import org.semanticweb.owlapi.model.OWLObjectPropertyExpression;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
/**
* This class implements a splitting strategy for datatype property In this strategy, the splitted
* value will be generate in a manner such that there exist no range which contains both positive
* and negative examples to avoid the learn get stuck in its specialisation
*
* @author An C. Tran
*
*/
@ComponentAnn(name = "ParCEL double splitter v1", shortName = "parcelSplitterV1", version = 0.08)
public class ParCELDoubleSplitterV1 implements ParCELDoubleSplitterAbstract {
private AbstractReasonerComponent reasoner = null;
private Set<Individual> positiveExamples = null;
private Set<Individual> negativeExamples = null;
private KnowledgeSource knowledgeSource = null;
private OWLOntology ontology = null;
Set<OWLDataPropertyExpression> doubleDatatypeProperties;
public ParCELDoubleSplitterV1() {
}
/**
* ============================================================================================
* Create a Splitter given a reasoner, positive and negative examples
*
* @param reasoner
* @param positiveExamples
* @param negativeExamples
*/
public ParCELDoubleSplitterV1(AbstractReasonerComponent reasoner,
Set<Individual> positiveExamples, Set<Individual> negativeExamples) {
this.reasoner = reasoner;
this.positiveExamples = positiveExamples;
this.negativeExamples = negativeExamples;
}
/**
* ============================================================================================
* Initialise the Splitter
*
* @throws ComponentInitException
* @throws OWLOntologyCreationException
*/
public void init() throws ComponentInitException {
if (this.reasoner == null)
throw new ComponentInitException("There is no reasoner for initialising the Splitter");
if (this.positiveExamples == null)
throw new ComponentInitException(
"There is no positive examples for initialising the Splitter");
if (this.negativeExamples == null)
throw new ComponentInitException(
"There is no negative examples for initialising the Splitter");
// get knowledge source (OWL file to built abox dependency graph
this.knowledgeSource = reasoner.getSources().iterator().next();
String ontologyPath = ((OWLFile) knowledgeSource).getBaseDir()
+ ((OWLFile) knowledgeSource).getFileName();
try {
ontology = ParCELOntologyUtil.loadOntology(ontologyPath);
} catch (OWLOntologyCreationException e) {
e.printStackTrace();
}
if (!(knowledgeSource instanceof OWLFile))
throw new RuntimeException("Only OWLFile is supported");
// get a list of double data type properties for filtering out other properties
this.doubleDatatypeProperties = new HashSet<OWLDataPropertyExpression>();
for (DatatypeProperty dp : reasoner.getDoubleDatatypeProperties())
this.doubleDatatypeProperties.add(OWLAPIConverter.getOWLAPIDataProperty(dp));
}
/**
* ============================================================================================
* Compute splits for all data properties in the ontology
*
* @return a map of datatype properties and their splitting values
*/
public Map<DatatypeProperty, List<Double>> computeSplits() {
// -------------------------------------------------
// generate relations for positive examples
// -------------------------------------------------
Map<DatatypeProperty, ValuesSet> relations = new HashMap<DatatypeProperty, ValuesSet>();
OWLDataFactory factory = ontology.getOWLOntologyManager().getOWLDataFactory();
for (Individual ind : positiveExamples) {
Map<DatatypeProperty, ValuesSet> individualRelations = getInstanceValueRelation(
factory.getOWLNamedIndividual(IRI.create(ind.getURI())), true, null);
for (DatatypeProperty pro : individualRelations.keySet()) {
if (relations.keySet().contains(pro))
relations.get(pro).addAll(individualRelations.get(pro));
else
relations.put(pro, individualRelations.get(pro));
}
}
// generate relation for negative examples
for (Individual ind : negativeExamples) {
Map<DatatypeProperty, ValuesSet> individualRelations = getInstanceValueRelation(
factory.getOWLNamedIndividual(IRI.create(ind.getURI())), false, null);
for (DatatypeProperty pro : individualRelations.keySet()) {
if (relations.keySet().contains(pro))
relations.get(pro).addAll(individualRelations.get(pro));
else
relations.put(pro, individualRelations.get(pro));
}
}
// -------------------------------------------------
// calculate the splits for each data property
// -------------------------------------------------
Map<DatatypeProperty, List<Double>> splits = new TreeMap<DatatypeProperty, List<Double>>();
// - - - . + + + + + . = . = . = . + . = . = . - . = . - - -
for (DatatypeProperty dp : relations.keySet()) {
if (relations.get(dp).size() > 0) {
List<Double> values = new ArrayList<Double>();
ValuesSet propertyValues = relations.get(dp);
int priorType = propertyValues.first().getType();
double priorValue = propertyValues.first().getValue();
Iterator<ValueCount> iterator = propertyValues.iterator();
while (iterator.hasNext()) {
ValueCount currentValueCount = iterator.next();
int currentType = currentValueCount.getType();
double currentValue = currentValueCount.getValue();
// check if a new value should be generated: when the type changes or the
// current value belongs to both pos. and neg.
if ((currentType == 3) || (currentType != priorType))
values.add((priorValue + currentValue) / 2.0);
// update the prior type and value after process the current element
priorType = currentValueCount.getType();
priorValue = currentValueCount.getValue();
}
// add processed property into the result set (splits)
splits.put(dp, values);
}
}
return splits;
}
/**
* ============================================================================================
* Find the related values of an individual
*
* @param individual
* The individual need to be seek for the related values
* @param positiveExample
* True if the given individual is a positive example and false otherwise
* @param visitedIndividuals
* Set of individuals that had been visited when finding the related values for the
* given individual
*
* @return A map from data property to its related values that had been discovered from the
* given individual
*/
private Map<DatatypeProperty, ValuesSet> getInstanceValueRelation(OWLIndividual individual,
boolean positiveExample, Set<OWLIndividual> visitedIndividuals) {
if (visitedIndividuals == null)
visitedIndividuals = new HashSet<OWLIndividual>();
// if the individual visited
if (visitedIndividuals.contains(individual))
return null;
else
visitedIndividuals.add(individual);
Map<DatatypeProperty, ValuesSet> relations = new HashMap<DatatypeProperty, ValuesSet>();
// get all data property values of the given individual
Map<OWLDataPropertyExpression, Set<OWLLiteral>> dataPropertyValues = individual
.getDataPropertyValues(this.ontology);
// get all object properties value of the given individual
Map<OWLObjectPropertyExpression, Set<OWLIndividual>> objectPropertyValues = individual
.getObjectPropertyValues(this.ontology);
// ---------------------------------------
// process data properties
// NOTE: filter the double data property
// ---------------------------------------
for (OWLDataPropertyExpression dp : dataPropertyValues.keySet()) {
if (this.doubleDatatypeProperties.contains(dp)) {
// process values of each data property: create a ValueCount object and add it into
// the result
ValuesSet values = new ValuesSet();
for (OWLLiteral lit : dataPropertyValues.get(dp)) {
ValueCount newValue = new ValueCount(Double.parseDouble(lit.getLiteral()),
positiveExample); // (value, pos)
values.add(newValue);
}
// if the data property exist, update its values
if (relations.keySet().contains(dp))
relations.get(new DatatypeProperty(dp.asOWLDataProperty().getIRI().toString()))
.addAll(values);
// otherwise, create a new map <data property - values and add it into the return
// value
else
relations.put(new DatatypeProperty(dp.asOWLDataProperty().getIRI().toString()),
values);
}
}
// process each object property: call this method recursively
for (OWLObjectPropertyExpression op : objectPropertyValues.keySet()) {
for (OWLIndividual ind : objectPropertyValues.get(op)) {
Map<DatatypeProperty, ValuesSet> subRelations = getInstanceValueRelation(ind,
positiveExample, visitedIndividuals);
// sub-relation == null if the ind had been visited
if (subRelations != null) {
for (DatatypeProperty dp : subRelations.keySet()) {
// if the data property exist, update its values
if (relations.keySet().contains(dp))
relations.get(dp).addAll(subRelations.get(dp));
// otherwise, create a new map <data property - values and add it into the
// return value
else
relations.put(dp, subRelations.get(dp));
}
}
}
}
return relations;
}
//-----------------------------
// getters and setters
//-----------------------------
public AbstractReasonerComponent getReasoner() {
return reasoner;
}
public void setReasoner(AbstractReasonerComponent reasoner) {
this.reasoner = reasoner;
}
public Set<Individual> getPositiveExamples() {
return positiveExamples;
}
public void setPositiveExamples(Set<Individual> positiveExamples) {
this.positiveExamples = positiveExamples;
}
public Set<Individual> getNegativeExamples() {
return negativeExamples;
}
public void setNegativeExamples(Set<Individual> negativeExamples) {
this.negativeExamples = negativeExamples;
}
}
| gpl-3.0 |
alexeykuptsov/JDI | Java/JDI/jdi-uitest-web/src/main/java/com/epam/jdi/uitests/web/selenium/elements/base/SelectElement.java | 1468 | package com.epam.jdi.uitests.web.selenium.elements.base;
/*
* Copyright 2004-2016 EPAM Systems
*
* This file is part of JDI project.
*
* JDI is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JDI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JDI. If not, see <http://www.gnu.org/licenses/>.
*/
import com.epam.jdi.uitests.core.interfaces.base.ISelect;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
/**
* Created by Roman_Iovlev on 7/9/2015.
*/
public class SelectElement extends ClickableText implements ISelect {
public SelectElement() {
}
public SelectElement(By byLocator) {
super(byLocator);
}
public SelectElement(WebElement webElement) {
super(webElement);
}
protected boolean isSelectedAction() {
return getWebElement().isSelected();
}
public void select() {
click();
}
public boolean isSelected() {
return actions.isSelected(this::isSelectedAction);
}
} | gpl-3.0 |
larryTheCoder/ASkyBlock-Nukkit | src/main/java/com/larryTheCoder/command/chat/MessageSubCommand.java | 2951 | /*
* Adapted from the Wizardry License
*
* Copyright (c) 2016-2018 larryTheCoder and contributors
*
* Permission is hereby granted to any persons and/or organizations
* using this software to copy, modify, merge, publish, and distribute it.
* Said persons and/or organizations are not allowed to use the software or
* any derivatives of the work for commercial use or any other means to generate
* income, nor are they allowed to claim this software as their own.
*
* The persons and/or organizations are also disallowed from sub-licensing
* and/or trademarking this software without explicit permission from larryTheCoder.
*
* Any persons and/or organizations using this software must disclose their
* source code and have it publicly available, include this license,
* provide sufficient credit to the original authors of the project (IE: larryTheCoder),
* as well as provide a link to the original project.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR
* PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.larryTheCoder.command.chat;
import cn.nukkit.Player;
import cn.nukkit.Server;
import cn.nukkit.command.CommandSender;
import com.larryTheCoder.ASkyBlock;
import com.larryTheCoder.command.SubCommand;
import java.util.List;
/**
* The default command of messages
*
* @author larryTheCoder
*/
public class MessageSubCommand extends SubCommand {
public MessageSubCommand(ASkyBlock plugin) {
super(plugin);
}
@Override
public boolean canUse(CommandSender sender) {
return sender.hasPermission("is.command.message") && sender.isPlayer();
}
@Override
public String getUsage() {
return "";
}
@Override
public String getName() {
return "messages";
}
@Override
public String getDescription() {
return "Get new messages while you offline";
}
@Override
public String[] getAliases() {
return new String[]{"msg"};
}
@Override
public boolean execute(CommandSender sender, String[] args) {
Player p = Server.getInstance().getPlayer(sender.getName());
List<String> list = getPlugin().getMessages().getMessages(p.getName());
if (!list.isEmpty()) {
p.sendMessage(getPlugin().getLocale(p).newsHeadline);
list.forEach((alist) -> p.sendMessage("- §e" + alist));
getPlugin().getMessages().clearMessages(p.getName());
} else {
p.sendMessage(getPrefix() + getPlugin().getLocale(p).newsEmpty);
}
return true;
}
}
| gpl-3.0 |
bonisamber/bookreader | Application/src/main/java/org/ebookdroid/ui/viewer/views/SearchControls.java | 2063 | package org.ebookdroid.ui.viewer.views;
import net.bonisamber.bookreader.R;
import org.ebookdroid.ui.viewer.ViewerActivity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import org.emdev.ui.actions.ActionEx;
import org.emdev.ui.actions.params.Constant;
import org.emdev.ui.actions.params.EditableValue;
public class SearchControls extends LinearLayout {
private EditText m_edit;
private ImageButton m_prevButton;
private ImageButton m_nextButton;
public SearchControls(final ViewerActivity parent) {
super(parent);
setVisibility(View.GONE);
setOrientation(LinearLayout.VERTICAL);
LayoutInflater.from(parent).inflate(R.layout.seach_controls, this, true);
m_prevButton = (ImageButton) findViewById(R.id.search_controls_prev);
m_nextButton = (ImageButton) findViewById(R.id.search_controls_next);
m_edit = (EditText) findViewById(R.id.search_controls_edit);
ActionEx forwardSearch = parent.getController().getOrCreateAction(R.id.actions_doSearch);
ActionEx backwardSearch = parent.getController().getOrCreateAction(R.id.actions_doSearchBack);
forwardSearch.addParameter(new EditableValue("input", m_edit)).addParameter(new Constant("forward", "true"));
backwardSearch.addParameter(new EditableValue("input", m_edit)).addParameter(new Constant("forward", "false"));
m_prevButton.setOnClickListener(backwardSearch);
m_nextButton.setOnClickListener(forwardSearch);
m_edit.setOnEditorActionListener(forwardSearch);
}
public void setVisibility(int visibility) {
super.setVisibility(visibility);
if (visibility == VISIBLE) {
m_edit.requestFocus();
}
}
@Override
public boolean onTouchEvent(final MotionEvent event) {
return false;
}
public int getActualHeight() {
return m_edit.getHeight();
}
}
| gpl-3.0 |
ehaikyu/DataAnalysisWin | src/com/xn/alex/data/ui/Logo.java | 2566 | package com.xn.alex.data.ui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JWindow;
import javax.swing.SwingWorker;
@SuppressWarnings("serial")
public class Logo extends JWindow implements MouseListener {
private JPanel panelMain = new JPanel();
private FlowLayout layout = new FlowLayout();
public Logo(String file) {
super();
layout.setHgap(3);
layout.setVgap(3);
getContentPane().setLayout(layout);
getContentPane().setBackground(java.awt.Color.gray);
getContentPane().add(panelMain);
SplashImage JLabel1 = new SplashImage();
ImageIcon image = new ImageIcon(file);
JLabel1.setIcon(image);
panelMain.setLayout(new BoxLayout(panelMain, BoxLayout.Y_AXIS));
panelMain.setSize(image.getIconWidth(), image.getIconHeight());
panelMain.setBackground(java.awt.Color.white);
panelMain.add(JLabel1);
addMouseListener(this);
pack();
Toolkit tk = Toolkit.getDefaultToolkit();
int xc = (int)(tk.getScreenSize().getWidth()/2 - getSize().getWidth()/2);
int yc = (int)(tk.getScreenSize().getHeight()/2 - getSize().getHeight()/2);
setLocation(new Point(xc, yc));
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}
@SuppressWarnings("serial")
class SplashImage extends JLabel {
static String srelease = "1.0";
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
Graphics2D g2 = (Graphics2D)g;
Dimension dsize = getSize();
FontMetrics fm = getFontMetrics(getFont());
g2.drawString(srelease, (float)dsize.width/2-fm.stringWidth(srelease)/2, (float)dsize.height * 3/4 + 30 + (fm.getMaxDescent()*2+3)*2+3);
g2.setColor(Color.white);
}
}
| gpl-3.0 |
guiguilechat/EveOnline | model/esi/JCESI/src/generated/java/fr/guiguilechat/jcelechat/model/jcesi/compiler/compiled/structures/get_corporations_corporation_id_starbases_starbase_id_offline.java | 851 | package fr.guiguilechat.jcelechat.model.jcesi.compiler.compiled.structures;
import com.fasterxml.jackson.annotation.JsonProperty;
public enum get_corporations_corporation_id_starbases_starbase_id_offline {
@JsonProperty("alliance_member")
alliance_member("alliance_member"),
@JsonProperty("config_starbase_equipment_role")
config_starbase_equipment_role("config_starbase_equipment_role"),
@JsonProperty("corporation_member")
corporation_member("corporation_member"),
@JsonProperty("starbase_fuel_technician_role")
starbase_fuel_technician_role("starbase_fuel_technician_role");
public final String toString;
get_corporations_corporation_id_starbases_starbase_id_offline(String toString) {
this.toString = toString;
}
@Override
public String toString() {
return toString;
}
}
| gpl-3.0 |
hydren/freepac | src/states/StateSpec.java | 607 | package states;
import org.newdawn.slick.state.BasicGameState;
public enum StateSpec
{
MENU_STATE(1, MenuState.class),
PLAY_STAGE_STATE(2, PlayStageState.class),
STAGE_CLEAR_STATE(3, StageClearState.class),
GAME_WON_STATE(4, GameWonState.class),
GAME_OVER_STATE(5, GameOverState.class),
OPTIONS_MENU_STATE(6, OptionsMenuState.class),
LOADING_STATE(7, LoadingState.class),
STAGE_SELECT_STATE(8, StageSelectState.class);
public int id;
public Class<? extends BasicGameState> clazz;
private StateSpec(int id, Class<? extends BasicGameState> clazz)
{
this.id = id; this.clazz = clazz;
}
}
| gpl-3.0 |
jay-to-the-dee/EthToolGUI | src/model/property/SupportedLinkModes.java | 1083 | /*
* Copyright (C) 2015 jay-to-the-dee <jay-to-the-dee@users.noreply.github.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package model.property;
import java.util.*;
/**
*
* @author jay-to-the-dee <jay-to-the-dee@users.noreply.github.com>
*/
public class SupportedLinkModes extends AbstractLinkModes
{
public SupportedLinkModes(Set<String> values)
{
super("Supported link modes", true);
value = convertStringSetToEnumValues(values);
}
}
| gpl-3.0 |
csimons/primula-vulgaris | src/main/java/RBNExceptions/RBNioException.java | 428 | package RBNExceptions;
public class RBNioException extends java.lang.RuntimeException {
/**
* Creates new <code>RBNBadSampleException</code> without detail message.
*/
public RBNioException() {
}
/**
* Constructs an <code>RBNBadSampleException</code> with the specified detail message.
* @param msg the detail message.
*/
public RBNioException(String msg) {
super(msg);
}
}
| gpl-3.0 |
applenick/RegionFX | src/main/java/com/applenick/RegionFX/regions/EffectRegionManager.java | 4756 | package com.applenick.RegionFX.regions;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType;
import com.applenick.RegionFX.RegionFX;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
/************************************************
Created By AppleNick
Copyright © 2016 , AppleNick, All rights reserved.
http://applenick.com
*************************************************/
public class EffectRegionManager {
private HashMap<ProtectedRegion,EffectRegion> loaded_regions;
private List<EffectPlayer> effected_players;
public EffectRegionManager(){
this.loaded_regions = Maps.newHashMap();
this.effected_players = Lists.newArrayList();
for(String s : RegionFX.get().getConfig().getStringList("regions")){
String[] info = StringUtils.splitByWholeSeparator(s, ":");
if(info.length < 5 || info == null){
RegionFX.get().console(ChatColor.DARK_RED + "There was an empty or incomplete entry saved. Please delete config or restore it to an eariler save.");
RegionFX.get().getServer().getPluginManager().disablePlugin(RegionFX.get());
break;
}
String name = info[0];
String effect = info[1];
int level = Integer.parseInt(info[2]);
boolean active = Boolean.parseBoolean(info[3]);
String world = info[4];
if(PotionEffectType.getByName(effect) != null){
if(Bukkit.getWorld(world) != null){
ProtectedRegion region = getRegion(name , Bukkit.getWorld(world));
if(region != null){
EffectRegion eRegion = new EffectRegion(name , PotionEffectType.getByName(effect) , level, active , Bukkit.getWorld(world));
eRegion.setRegion(region);
this.loaded_regions.put(region, eRegion);
RegionFX.get().console(name + ChatColor.GREEN + " has been loaded and activated");
}else{
RegionFX.get().console(name + ChatColor.GREEN + "'s region could not be found. \n Please use /regionfx delete" + name + " if this region has been deleted by World Guard");
}
}else{
RegionFX.get().console(ChatColor.AQUA + name + ChatColor.RED + " could not locate it's world " + ChatColor.GRAY + world);
return;
}
}else{
RegionFX.get().console(ChatColor.AQUA + name + ChatColor.RED + " is not using a valid effect " + ChatColor.DARK_RED + effect);
}
}
}
public HashMap<ProtectedRegion,EffectRegion> getLoadedRegions(){
return this.loaded_regions;
}
public EffectRegion getEffectRegion(String name){
for(EffectRegion rg : this.getLoadedRegions().values()){
if(rg.getName().equalsIgnoreCase(name)){
return rg;
}
}
return null;
}
private boolean insideRegion(Player player, ProtectedRegion region){
LocalPlayer lp = RegionFX.getWorldGuard().wrapPlayer(player);
return region.contains(lp.getPosition());
}
public boolean insideRegion(Player player){
for(ProtectedRegion region : this.loaded_regions.keySet()){
if(insideRegion(player , region)){
return true;
}
}
return false;
}
public ProtectedRegion getPlayerRegion(Player player){
for(ProtectedRegion region : this.loaded_regions.keySet()){
if(insideRegion(player , region)){
return region;
}
}
return null;
}
public ProtectedRegion getRegion(String name , World world){
return RegionFX.getWorldGuard().getRegionManager(world).getRegion(name);
}
public void addEffectRegion(EffectRegion eRegion) {
this.loaded_regions.put(eRegion.getRegion(), eRegion);
}
public void addEffectedPlayer(EffectPlayer player){
this.effected_players.add(player);
}
public void removeEffectedPlayer(EffectPlayer player){
this.effected_players.remove(player);
}
public List<EffectPlayer> getEffectPlayers() {
return this.effected_players;
}
public EffectPlayer getEffectPlayer(Player player){
for(EffectPlayer ep : this.effected_players){
if(ep.getPlayer() == player){
return ep;
}
}
return null;
}
public boolean isPlayerEffected(Player player) {
for(EffectPlayer p : this.effected_players){
if(p.getPlayer() == player){
return true;
}
}
return false;
}
public void removeEffectRegion(EffectRegion region) {
for(Iterator<EffectPlayer> players = this.effected_players.iterator(); players.hasNext();){
EffectPlayer player = players.next();
if(player.getRegion() == region){
player.removeEffects();
players.remove();
}
}
this.loaded_regions.remove(region.getRegion());
}
}
| gpl-3.0 |
Betterverse/Craftbukkit | src/main/java/org/bukkit/craftbukkit/CraftSound.java | 7346 | package org.bukkit.craftbukkit;
import static org.bukkit.Sound.*;
import org.apache.commons.lang.Validate;
import org.bukkit.Sound;
public class CraftSound {
private static String[] sounds = new String[Sound.values().length];
static {
sounds[AMBIENCE_CAVE.ordinal()] = "ambient.cave.cave";
sounds[AMBIENCE_RAIN.ordinal()] = "ambient.weather.rain";
sounds[AMBIENCE_THUNDER.ordinal()] = "ambient.weather.thunder";
sounds[ARROW_HIT.ordinal()] = "random.bowhit";
sounds[ARROW_SHAKE.ordinal()] = "random.drr";
sounds[BREATH.ordinal()] = "random.breath";
sounds[BURP.ordinal()] = "random.burp";
sounds[CHEST_CLOSE.ordinal()] = "random.chestclosed";
sounds[CHEST_OPEN.ordinal()] = "random.chestopen";
sounds[CLICK.ordinal()] = "random.click";
sounds[DOOR_CLOSE.ordinal()] = "random.door_close";
sounds[DOOR_OPEN.ordinal()] = "random.door_open";
sounds[DRINK.ordinal()] = "random.drink";
sounds[EAT.ordinal()] = "random.eat";
sounds[EXPLODE.ordinal()] = "random.explode";
sounds[EXPLODE_OLD.ordinal()] = "random.old_explode";
sounds[FALL_BIG.ordinal()] = "damage.fallbig";
sounds[FALL_SMALL.ordinal()] = "damage.fallsmall";
sounds[FIRE.ordinal()] = "fire.fire";
sounds[FIRE_IGNITE.ordinal()] = "fire.ignite";
sounds[FIZZ.ordinal()] = "random.fizz";
sounds[FUSE.ordinal()] = "random.fuse";
sounds[HURT.ordinal()] = "random.hurt";
sounds[HURT_FLESH.ordinal()] = "damage.hurtflesh";
sounds[ITEM_BREAK.ordinal()] = "random.break";
sounds[ITEM_PICKUP.ordinal()] = "random.pop";
sounds[LAVA.ordinal()] = "liquid.lava";
sounds[LAVA_POP.ordinal()] = "liquid.lavapop";
sounds[LEVEL_UP.ordinal()] = "random.levelup";
sounds[NOTE_PIANO.ordinal()] = "note.harp";
sounds[NOTE_BASS_DRUM.ordinal()] = "note.bd";
sounds[NOTE_STICKS.ordinal()] = "note.hat";
sounds[NOTE_BASS_GUITAR.ordinal()] = "note.bassattack";
sounds[NOTE_SNARE_DRUM.ordinal()] = "note.snare";
// NOTE_BASS("note.bass"),
sounds[NOTE_PLING.ordinal()] = "note.pling";
sounds[ORB_PICKUP.ordinal()] = "random.orb";
sounds[PISTON_EXTEND.ordinal()] = "tile.piston.out";
sounds[PISTON_RETRACT.ordinal()] = "tile.piston.in";
sounds[PORTAL.ordinal()] = "portal.portal";
sounds[PORTAL_TRAVEL.ordinal()] = "portal.travel";
sounds[PORTAL_TRIGGER.ordinal()] = "portal.trigger";
sounds[SHOOT_ARROW.ordinal()] = "random.bow";
sounds[SPLASH.ordinal()] = "random.splash";
sounds[SPLASH2.ordinal()] = "liquid.splash";
sounds[STEP_GRAVEL.ordinal()] = "step.gravel";
sounds[STEP_SAND.ordinal()] = "step.sand";
sounds[STEP_SNOW.ordinal()] = "step.snow";
sounds[STEP_STONE.ordinal()] = "step.stone";
sounds[STEP_WOOD.ordinal()] = "step.wood";
sounds[STEP_WOOL.ordinal()] = "step.wool";
sounds[WATER.ordinal()] = "liquid.water";
sounds[WOOD_CLICK.ordinal()] = "random.wood click";
// Mob sounds
sounds[BLAZE_BREATH.ordinal()] = "mob.blaze.breath";
sounds[BLAZE_DEATH.ordinal()] = "mob.blaze.death";
sounds[BLAZE_HIT.ordinal()] = "mob.blaze.hit";
sounds[CAT_HISS.ordinal()] = "mob.cat.hiss";
sounds[CAT_HIT.ordinal()] = "mob.cat.hitt";
sounds[CAT_MEOW.ordinal()] = "mob.cat.meow";
sounds[CAT_PURR.ordinal()] = "mob.cat.purr";
sounds[CAT_PURREOW.ordinal()] = "mob.cat.purreow";
sounds[CHICKEN_IDLE.ordinal()] = "mob.chicken";
sounds[CHICKEN_HURT.ordinal()] = "mob.chickenhurt";
sounds[CHICKEN_EGG_POP.ordinal()] = "mob.chickenplop";
sounds[COW_IDLE.ordinal()] = "mob.cow";
sounds[COW_HURT.ordinal()] = "mob.cowhurt";
sounds[CREEPER_HISS.ordinal()] = "mob.creeper";
sounds[CREEPER_DEATH.ordinal()] = "mob.creeperdeath";
sounds[ENDERMAN_DEATH.ordinal()] = "mob.endermen.death";
sounds[ENDERMAN_HIT.ordinal()] = "mob.endermen.hit";
sounds[ENDERMAN_IDLE.ordinal()] = "mob.endermen.idle";
sounds[ENDERMAN_TELEPORT.ordinal()] = "mob.endermen.portal";
sounds[ENDERMAN_SCREAM.ordinal()] = "mob.endermen.scream";
sounds[ENDERMAN_STARE.ordinal()] = "mob.endermen.stare";
sounds[GHAST_SCREAM.ordinal()] = "mob.ghast.scream";
sounds[GHAST_SCREAM2.ordinal()] = "mob.ghast.affectionate scream";
sounds[GHAST_CHARGE.ordinal()] = "mob.ghast.charge";
sounds[GHAST_DEATH.ordinal()] = "mob.ghast.death";
sounds[GHAST_FIREBALL.ordinal()] = "mob.ghast.fireball";
sounds[GHAST_MOAN.ordinal()] = "mob.ghast.moan";
sounds[IRONGOLEM_DEATH.ordinal()] = "mob.irongolem.death";
sounds[IRONGOLEM_HIT.ordinal()] = "mob.irongolem.hit";
sounds[IRONGOLEM_THROW.ordinal()] = "mob.irongolem.throw";
sounds[IRONGOLEM_WALK.ordinal()] = "mob.irongolem.walk";
sounds[MAGMACUBE_WALK.ordinal()] = "mob.magmacube.small";
sounds[MAGMACUBE_WALK2.ordinal()] = "mob.magmacube.big";
sounds[MAGMACUBE_JUMP.ordinal()] = "mob.magmacube.jump";
sounds[PIG_IDLE.ordinal()] = "mob.pig";
sounds[PIG_DEATH.ordinal()] = "mob.pigdeath";
sounds[SHEEP_IDLE.ordinal()] = "mob.sheep";
sounds[SILVERFISH_HIT.ordinal()] = "mob.silverfish.hit";
sounds[SILVERFISH_KILL.ordinal()] = "mob.silverfish.kill";
sounds[SILVERFISH_IDLE.ordinal()] = "mob.silverfish.say";
sounds[SILVERFISH_WALK.ordinal()] = "mob.silverfish.step";
sounds[SKELETON_IDLE.ordinal()] = "mob.skeleton";
sounds[SKELETON_DEATH.ordinal()] = "mob.skeletondeath";
sounds[SKELETON_HURT.ordinal()] = "mob.skeletonhurt";
sounds[SLIME_IDLE.ordinal()] = "mob.slime";
sounds[SLIME_ATTACK.ordinal()] = "mob.slimeattack";
sounds[SPIDER_IDLE.ordinal()] = "mob.spider";
sounds[SPIDER_DEATH.ordinal()] = "mob.spiderdeath";
sounds[WOLF_BARK.ordinal()] = "mob.wolf.bark";
sounds[WOLF_DEATH.ordinal()] = "mob.wolf.death";
sounds[WOLF_GROWL.ordinal()] = "mob.wolf.growl";
sounds[WOLF_HOWL.ordinal()] = "mob.wolf.howl";
sounds[WOLF_HURT.ordinal()] = "mob.wolf.hurt";
sounds[WOLF_PANT.ordinal()] = "mob.wolf.panting";
sounds[WOLF_SHAKE.ordinal()] = "mob.wolf.shake";
sounds[WOLF_WHINE.ordinal()] = "mob.wolf.whine";
sounds[ZOMBIE_METAL.ordinal()] = "mob.zombie.metal";
sounds[ZOMBIE_WOOD.ordinal()] = "mob.zombie.wood";
sounds[ZOMBIE_WOODBREAK.ordinal()] = "mob.zombie.woodbreak";
sounds[ZOMBIE_IDLE.ordinal()] = "mob.zombie";
sounds[ZOMBIE_DEATH.ordinal()] = "mob.zombiedeath";
sounds[ZOMBIE_HURT.ordinal()] = "mob.zombiehurt";
sounds[ZOMBIE_PIG_IDLE.ordinal()] = "mob.zombiepig.zpig";
sounds[ZOMBIE_PIG_ANGRY.ordinal()] = "mob.zombiepig.zpigangry";
sounds[ZOMBIE_PIG_DEATH.ordinal()] = "mob.zombiepig.zpigdeath";
sounds[ZOMBIE_PIG_HURT.ordinal()] = "mob.zombiepig.zpighurt";
}
public static String getSound(final Sound sound) {
Validate.notNull(sound, "Sound cannot be null");
return sounds[sound.ordinal()];
}
private CraftSound() {}
}
| gpl-3.0 |
daftano/dl-learner | components-core/src/test/java/org/dllearner/algorithms/qtl/GeneralisationTest.java | 4902 | package org.dllearner.algorithms.qtl;
import java.util.Arrays;
import java.util.HashSet;
import org.dllearner.algorithms.qtl.datastructures.QueryTree;
import org.dllearner.algorithms.qtl.filters.QuestionBasedStatementFilter;
import org.dllearner.algorithms.qtl.filters.QuestionBasedStatementFilter2;
import org.dllearner.algorithms.qtl.impl.QueryTreeFactoryImpl;
import org.dllearner.algorithms.qtl.impl.QueryTreeFactoryImpl2;
import org.dllearner.algorithms.qtl.operations.Generalisation;
import org.junit.Test;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
public class GeneralisationTest {
private static final int RECURSION_DEPTH = 2;
private int maxModelSizePerExample = 3000;
private final static int LIMIT = 1000;
private final static int OFFSET = 1000;
private static final String ENDPOINT_URL = "http://dbpedia.org/sparql";
@Test
public void test(){
}
// @Test
public void generalisationTest1(){
String resource = "http://dbpedia.org/resource/Chelsea_F.C.";
Generalisation<String> gen = new Generalisation<String>();
Model model = getModelForExample(resource, maxModelSizePerExample);
QueryTree<String> tree = new QueryTreeFactoryImpl().getQueryTree(resource, model);
System.out.println(tree.toSPARQLQueryString());
QueryTree<String> genTree = gen.generalise(tree);
String query = genTree.toSPARQLQueryString();
System.out.println(query);
System.out.println(tree.toQuery());
}
// @Test
public void generalisationTest2(){
// String resource = "http://dbpedia.org/resource/Interview_with_the_Vampire:_The_Vampire_Chronicles";
String resource = "http://dbpedia.org/resource/Arsenal_F.C.";
Generalisation<String> gen = new Generalisation<String>();
Model model = getModelForExample(resource, maxModelSizePerExample);
QueryTreeFactory<String> treeFactory = new QueryTreeFactoryImpl2();
QuestionBasedStatementFilter2 filter = new QuestionBasedStatementFilter2(new HashSet(
// Arrays.asList(new String[]{"film", "starring", "Brad Pitt"})));
Arrays.asList(new String[]{"soccer club", "Premier League", "manager", "France"})));
filter.setThreshold(0.6);
treeFactory.setStatementFilter(filter);
QueryTree<String> tree = treeFactory.getQueryTree(resource, model);
System.out.println(tree.getStringRepresentation());
QueryTreeFactory<String> treeFactory2 = new QueryTreeFactoryImpl();
QuestionBasedStatementFilter filter2 = new QuestionBasedStatementFilter(new HashSet(
// Arrays.asList(new String[]{"film", "starring", "Brad Pitt"})));
Arrays.asList(new String[]{"soccer club", "Premier League", "manager", "France"})));
filter2.setThreshold(0.6);
treeFactory2.setStatementFilter(filter2);
QueryTree<String> tree2 = treeFactory2.getQueryTree(resource, model);
System.out.println(tree2.getStringRepresentation());
}
private Model getModelForExample(String example, int maxSize){
Query query = makeConstructQuery(example, LIMIT, 0);
QueryExecution qexec = QueryExecutionFactory.sparqlService(ENDPOINT_URL, query);
Model all = ModelFactory.createDefaultModel();
Model model = qexec.execConstruct();
all.add(model);
qexec.close();
int i = 1;
while(model.size() != 0 && all.size() < maxSize){
query = makeConstructQuery(example, LIMIT, i * OFFSET);
qexec = QueryExecutionFactory.sparqlService(ENDPOINT_URL, query);
model = qexec.execConstruct();
all.add(model);
qexec.close();
i++;
}
return all;
}
private Query makeConstructQuery(String example, int limit, int offset){
StringBuilder sb = new StringBuilder();
sb.append("CONSTRUCT {\n");
sb.append("<").append(example).append("> ").append("?p0 ").append("?o0").append(".\n");
for(int i = 1; i < RECURSION_DEPTH; i++){
sb.append("?o").append(i-1).append(" ").append("?p").append(i).append(" ").append("?o").append(i).append(".\n");
}
sb.append("}\n");
sb.append("WHERE {\n");
sb.append("<").append(example).append("> ").append("?p0 ").append("?o0").append(".\n");
for(int i = 1; i < RECURSION_DEPTH; i++){
sb.append("OPTIONAL{?o").append(i-1).append(" ").append("?p").append(i).append(" ").append("?o").append(i).append(".}\n");
}
sb.append("FILTER (!regex (?p0, \"http://dbpedia.org/property/wikiPage\") && !regex(?p1, \"http://dbpedia.org/property/wikiPage\"))");
sb.append("}\n");
// sb.append("ORDER BY ");
// for(int i = 0; i < RECURSION_DEPTH; i++){
// sb.append("?p").append(i).append(" ").append("?o").append(i).append(" ");
// }
sb.append("\n");
sb.append("LIMIT ").append(limit).append("\n");
sb.append("OFFSET ").append(offset);
Query query = QueryFactory.create(sb.toString());
System.out.println(sb.toString());
return query;
}
}
| gpl-3.0 |
bjaskj/BukkitPlugins | BjarteWelcome/src/main/java/com/bjarte/bukkit/welcome/WelcomePlayer.java | 666 | package com.bjarte.bukkit.welcome;
import com.bjarte.bukkit.service.ConfigService;
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
public class WelcomePlayer implements Listener {
private ConfigService configService;
public WelcomePlayer(ConfigService configService)
{
this.configService = configService;
}
@EventHandler
public void playerJoin(PlayerJoinEvent event) {
// On player join send them the message from config.yml
event.getPlayer().sendMessage(ChatColor.YELLOW + configService.getMessage());
}
}
| gpl-3.0 |
LO23TD01/LO23TD01 | src/network/server/ComServerInterface.java | 7116 | package network.server;
import java.util.List;
import java.util.UUID;
import data.ChatMessage;
import data.GameTable;
import data.Profile;
import data.State;
import data.TurnState;
import data.User;
/**
* Interface for server methods
*
*/
public interface ComServerInterface {
/**
* Sends dice throw result to all the players
* @param receivers List of receivers' ID
* @param r1 Value of first dice
* @param r2 Value of second dice
* @param r3 Value of third dice
*/
public void sendResult(List<UUID> receivers, UUID user, int r1, int r2, int r3);
/**
* Sends message to all players
* @param receivers List of receivers' ID
* @param msg Message to send
*/
public void sendMessage(List<UUID> receivers, ChatMessage msg);
/**
* Sends timer to all players
* @param receivers List of receivers' ID
*/
public void showTimer(List<UUID> receivers); // ajouté List<UUID> au lieu de UUID : corrigé avec le diagramme de sequence "Commencer Partie"
/**
* Adds new table with associated players
* @param receiver Receiver's ID
* @param receivers List of receivers' ID
* @param tableinfo Table's infos
*/
public void addNewTable(UUID receiver,List<UUID> receivers, GameTable tableinfo); // ajouté l'UUID du receiver unique
/**
* Sends die selection of a player to all players
* @param receivers List of receivers' ID
* @param player ID of player selecting the die
* @param d1 True if first die is selected
* @param d2 True if second die is selected
* @param d3 True if third die is selected
*/
public void sendSelection(List<UUID> receivers, UUID player, boolean d1, boolean d2, boolean d3);
/**
* Sends quantity of chips won by a player to all the players
* @param receivers List of receivers' ID
* @param player Player's ID
* @param nb Quantity of chips
*/
public void updateChips(List<UUID> receivers, UUID player, int nb);
/**
* Sends quantity of chips lost by a player to another's profit
* @param receivers List of receivers' ID
* @param win Winning player's ID
* @param lose Losing player's ID
* @param nb Quantity of chips
*/
public void updateChips(List<UUID> receivers, UUID win, UUID lose, int nb);
/**
* Sends the winning player's ID to all players
* @param receivers List of receivers' ID
* @param winner Winning player's ID
*/
public void hasWon(List<UUID> receivers, UUID winner);
/**
* Starts a new turn
* @param receivers List of receivers' ID
* @param player First player's ID
* @param isLastLaunch True if last turn
*/
public void startTurn(List<UUID> receivers, UUID player, boolean isLastLaunch);
/**
* Sends a player's profile to all players
* @param receivers List of receivers' ID
* @param userUpdated Profile's user ID
* @param data Profile to send
*/
public void sendProfileUpdate(List<UUID> receivers, UUID userUpdated, Profile data); // plus necessaire (changement lié au professeur et à "modifier profil")
/**
* Sends a profile to a player
* @param receivers Receiver's ID
* @param data Profile to send
*/
public void sendProfile(UUID receivers, Profile data);
/**
* Kicks a list of players and sends a message to all of them
* @param receivers List of receivers' ID
* @param msg Message to send to kicked players
*/
public void kick(List<UUID> receivers, String msg);
/**
* Sends to all players message asking if they want to stop the game
* @param receivers List of receivers' ID
*/
public void askStopGameEveryUser(List<UUID> receivers);
/**
* Notifies all players the game has stopped
* @param receivers List of receivers' ID
*/
public void stopGameAccepted(List<UUID> receivers);
/**
* Sends list of all players to a player
* @param user Receiver's ID
* @param userList Liste of all players
*/
public void refreshUserList(UUID user, List<User> userList);
/**
* Sends list of all players to a player
* @param user Receiver's ID
* @param userList Liste of all players
*/
public void refreshTableList(List<UUID> receivers, List<GameTable> tableList);
/**
* Raises an exception
* @param user Receiver's ID
* @param msg Message of the exception
*/
public void raiseException(UUID user, String msg);
/**
* Raises an exception
* @param user Receivers's ID
* @param msg Message of the exception
*/
public void raiseException(List<UUID> receivers, String msg);
/**
* Adds a player to a table
* @param receivers List of receivers' ID
* @param user New user's profile
* @param tableInfo Table info
*/
public void newPlayerOnTable(List<UUID> receivers, Profile user, GameTable tableInfo);
/**
* Add a spectator to a table
* @param receivers List of receivers' ID
* @param user New spectator's ID
* @param tableInfo Table info
*/
public void newSpectatorOnTable(List<UUID> receivers, Profile user, GameTable tableInfo);
/**
*
* @param user
* @param receivers List of receivers' ID
*/
public void hasAccepted(UUID user,List<UUID> receivers);
/**
*
* @param user
* @param receivers List of receivers' ID
*/
public void hasRefused(UUID user,List<UUID> receivers);
/**
* Adds a user to the game
* @param receivers List of receivers' ID
* @param user New user's profile
*/
public void newUser(List<UUID> receivers, Profile user);
/**
* Sends all tables to all users
* @param userList List of all users
* @param tableList List of all tables
* @param user Receiver's profile
*/
public void sendTablesUsers(List<User> userList, List<GameTable> tableList, Profile user);
/**
* Notifies a player has quit a table
* @param receivers List of receivers' ID
* @param user Quitting user's ID
*/
public void playerQuitGame(List<UUID> receivers, UUID user);
/**
* Stops a game
* @param receivers List of receivers' ID
* @param answer True if players have voted to stop the game
*/
public void stopGame(List<UUID> receivers, boolean answer);
/**
* Notifies all players who lost
* @param receivers List of receivers' ID
* @param winner Losing player's ID
*/
public void hasLost(List<UUID> receivers, UUID winner);
/**
* Changes game state
* @param receivers List of receivers' ID
* @param state State to which the game will be changed
*/
public void changeState(List<UUID> receivers, State state);
/**
* Changes turn state
* @param receivers List of receivers' ID
* @param turnState State to which the turn will be changed
*/
public void changeTurnState(List<UUID> receivers, TurnState turnState);
/**
* Sets a player as the game creator
* @param receivers List of receivers' ID
* @param creator ID of the creator
*/
public void setCreator(List<UUID> receivers, UUID creator);
/**
* Notify players of an exaequo result
* @param receivers List of receivers' ID
* @param users Users that are exaequo
*/
public void exAequoCase(List<UUID> receivers, List<User> users, boolean win);
/**
* Notify players of replay
* @param receivers List of receivers' ID
* @param users Users that are exaequo
*/
public void replay(List<UUID> receivers);
}
| gpl-3.0 |
jmacauley/OpenDRAC | Clients/AdminConsole/src/main/java/com/nortel/appcore/app/drac/client/lpcpadminconsole/topology/TopologyPopupMenu.java | 40577 | /**
* <pre>
* The owner of the original code is Ciena Corporation.
*
* Portions created by the original owner are Copyright (C) 2004-2010
* the original owner. All Rights Reserved.
*
* Portions created by other contributors are Copyright (C) the contributor.
* All Rights Reserved.
*
* Contributor(s):
* (Contributors insert name & email here)
*
* This file is part of DRAC (Dynamic Resource Allocation Controller).
*
* DRAC is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* DRAC is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
* </pre>
*/
package com.nortel.appcore.app.drac.client.lpcpadminconsole.topology;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JPopupMenu;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.nortel.appcore.app.drac.client.lpcpadminconsole.NeCache;
import com.nortel.appcore.app.drac.client.lpcpadminconsole.OpenDracDesktop;
import com.nortel.appcore.app.drac.client.lpcpadminconsole.util.ServerOperation;
import com.nortel.appcore.app.drac.common.FacilityConstants;
import com.nortel.appcore.app.drac.common.graph.DracEdge;
import com.nortel.appcore.app.drac.common.graph.DracVertex;
import com.nortel.appcore.app.drac.common.graph.NeStatus;
import com.nortel.appcore.app.drac.common.graph.NeType;
import com.nortel.appcore.app.drac.common.types.Facility;
import com.nortel.appcore.app.drac.common.types.NetworkElementHolder;
import com.nortel.appcore.app.drac.common.types.NetworkElementHolder.NETWORK_ELEMENT_MODE;
import com.nortel.appcore.app.drac.common.types.NetworkElementHolder.PROTOCOL_TYPE;
import com.nortel.appcore.app.drac.common.utility.CryptoWrapper;
import com.nortel.appcore.app.drac.common.utility.CryptoWrapper.CryptedString;
import edu.uci.ics.jung.visualization.VisualizationViewer;
/**
* @author pitman
*/
@SuppressWarnings("serial")
public final class TopologyPopupMenu extends JPopupMenu {
private static final Logger log = LoggerFactory.getLogger(TopologyPopupMenu.class);
static class LinkDialogPopulator implements Runnable {
private final JComboBox srcPort;
private final JComboBox destPort;
private final JDialog dialog;
private final DracVertex src;
private final DracVertex dest;
public LinkDialogPopulator(DracVertex src, DracVertex dest,
JComboBox srcPort, JComboBox destPort, JDialog dialog) {
log.debug("LinkDialogPopulator from " + src + " " + dest);
this.srcPort = srcPort;
this.destPort = destPort;
this.dialog = dialog;
srcPort.setEnabled(false);
destPort.setEnabled(false);
this.src = src;
this.dest = dest;
}
@Override
public void run() {
try {
try {
String srcNeId = src.getIeee();
String dstNeId = dest.getIeee();
java.util.List<Facility> srcFacilities = new ServerOperation()
.listFacalities(srcNeId);
java.util.List<Facility> dstFacilities = new ServerOperation()
.listFacalities(dstNeId);
log.debug("LinkDialogPopulator src facilities from " + srcNeId
+ " are:" + srcFacilities + " " + dstNeId + " are:"
+ dstFacilities);
if (srcFacilities != null) {
log.debug("Found source " + srcFacilities.size() + " facilities.");
Facility[] sortedFacs = OpenDracDesktop
.sortFacilities(srcFacilities);
for (Facility f : sortedFacs) {
if (f.getAid() != null) // &&
{
if (FacilityConstants.SIGNAL_TYPE.ENNI.toString()
.equalsIgnoreCase(f.getSigType())
|| FacilityConstants.SIGNAL_TYPE.INNI.toString()
.equalsIgnoreCase(f.getSigType())) {
srcPort.addItem(f.getAid());
}
}
}
}
if (dstFacilities != null) {
log.debug("Found dest " + dstFacilities.size() + " facilities.");
Facility[] sortedFacs = OpenDracDesktop
.sortFacilities(dstFacilities);
for (Facility f : sortedFacs) {
if (f.getAid() != null) // &&
// !f.getAid().startsWith("WAN"))
{
if (FacilityConstants.SIGNAL_TYPE.ENNI.toString()
.equalsIgnoreCase(f.getSigType())
|| FacilityConstants.SIGNAL_TYPE.INNI.toString()
.equalsIgnoreCase(f.getSigType())) {
destPort.addItem(f.getAid());
}
}
}
}
}
catch (Exception e) {
log.error("ERROR populating link dialog ", e);
}
finally {
srcPort.setEnabled(true);
destPort.setEnabled(true);
}
}
finally {
dialog.setCursor(OpenDracDesktop.DEFAULT_CURSOR);
}
}
}
public TopologyPopupMenu(final JungTopologyPanel jung, final Frame parent,
final DracEdge edge, final VisualizationViewer<DracVertex, DracEdge> vv) {
super();
// POPUP menu for a EDGE
add(new AbstractAction("Edge properties") {
@Override
public void actionPerformed(ActionEvent e) {
showEdgeProperties(jung, parent, edge);
vv.repaint();
}
});
AbstractAction removeLink = new AbstractAction("Remove link") {
@Override
public void actionPerformed(ActionEvent e) {
HashMap<String, String> args = new HashMap<String, String>();
args.put("SRCNEID", edge.getSource().getIeee());
args.put("DSTNEID", edge.getTarget().getIeee());
args.put("SRCPORT", edge.getSourceAid());
args.put("DSTPORT", edge.getTargetAid());
jung.notifyListeners(
TopologyViewEventHandler.EVENT_TYPE.REMOVELINK_EVENT, args);
vv.repaint();
}
};
removeLink.setEnabled(edge.isManual());
add(removeLink);
AbstractAction generateManual = new AbstractAction("Generate manual link") {
@Override
public void actionPerformed(ActionEvent e) {
HashMap<String, String> args = new HashMap<String, String>();
args.put("SRCNEIEEE", edge.getSource().getIeee());
args.put("DSTNEIEEE", edge.getTarget().getIeee());
args.put("SRCPORT", edge.getSourceAid());
args.put("DSTPORT", edge.getTargetAid());
jung.notifyListeners(
TopologyViewEventHandler.EVENT_TYPE.GENERATEMANUALLINK_EVENT, args);
vv.repaint();
}
};
generateManual
.setEnabled(!edge.isManual() && !edge.hasEclipsedManualLink());
add(generateManual);
}
public TopologyPopupMenu(final JungTopologyPanel jung, final Frame parent,
final DracVertex vertex,
final VisualizationViewer<DracVertex, DracEdge> vv) {
// POPUP menu for a Vertex
super();
add(new AbstractAction("Add Link") {
@Override
public void actionPerformed(ActionEvent e) {
if (vv.getPickedVertexState().getPicked().size() != 2) {
JOptionPane
.showMessageDialog(
parent,
"To add a manual topological link you must first select two NEs before selecting this option",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
DracVertex[] a = vv.getPickedVertexState().getPicked()
.toArray(new DracVertex[2]);
DracVertex src = a[0];
DracVertex dest = a[1];
Map<String, String> map = new HashMap<String, String>();
map.put("SRCIEEE", src.getIeee());
map.put("SRCIP", src.getIp());
map.put("SRCLABEL", src.getLabel());
map.put("DESTIEEE", dest.getIeee());
map.put("DESTIP", dest.getIp());
map.put("DESTLABEL", dest.getLabel());
jung.notifyListeners(TopologyViewEventHandler.EVENT_TYPE.ADDLINK_EVENT,
map);
vv.repaint();
}
});
add(new AbstractAction("Remove NE") {
@Override
public void actionPerformed(ActionEvent e) {
int result = JOptionPane
.showConfirmDialog(
null,
"<HTML>Are you sure you want to remove "
+ vertex.getIp()
+ " ("
+ vertex.getLabel()
+ ") ?<BR><B>All manually provisioned data will be lost</B></HTML>",
"Remove Network Element", JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
NetworkElementHolder ne = new NetworkElementHolder(vertex.getIp(),
vertex.getPort(), null, null, null, NeStatus.NE_UNKNOWN, null,
null, 0, null, null, vertex.getIeee(), null, false, "Unknown", null, null,
null);
jung.notifyListeners(
TopologyViewEventHandler.EVENT_TYPE.UNMANAGE_EVENT, ne);
}
vv.repaint();
JungTopologyPanel.resetTopology();
}
});
add(new AbstractAction("Create Schedule") {
@Override
public void actionPerformed(ActionEvent e) {
if (vv.getPickedVertexState().getPicked().size() != 2
&& vv.getPickedVertexState().getPicked().size() != 1) {
JOptionPane
.showMessageDialog(
parent,
"To create a schedule you must first select two NEs before selecting this option",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
DracVertex[] a;
DracVertex src;
DracVertex dest;
if (vv.getPickedVertexState().getPicked().size() == 2) {
a = vv.getPickedVertexState().getPicked().toArray(new DracVertex[2]);
src = a[0];
dest = a[1];
}
else {
a = vv.getPickedVertexState().getPicked().toArray(new DracVertex[1]);
src = a[0];
dest = a[0];
}
Map<String, String> m = new HashMap<String, String>();
m.put("srcIeee", src.getIeee());
m.put("dstIeee", dest.getIeee());
m.put("srcLabel", src.getLabel());
m.put("dstLabel", dest.getLabel());
m.put("srcMode", src.getMode());
m.put("dstMode", dest.getMode());
jung.notifyListeners(TopologyViewEventHandler.EVENT_TYPE.SPF_EVENT, m);
vv.repaint();
}
});
add(new AbstractAction("Toggle NE Communications Link") {
@Override
public void actionPerformed(ActionEvent e) {
int result = JOptionPane
.showConfirmDialog(
null,
"<HTML>Are you sure you want to toggle the communication link to "
+ vertex.getIp()
+ " ("
+ vertex.getLabel()
+ ") ?<BR><B>Communications will temporarily be lost</B></HTML>",
"Toggle Network Element Communications",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
NetworkElementHolder ne = new NetworkElementHolder(vertex.getIp(),
vertex.getPort(), null, null, null, NeStatus.NE_UNKNOWN, null,
null, 0, null, null, null, null, false, "Unknown", null, null, null);
jung.notifyListeners(
TopologyViewEventHandler.EVENT_TYPE.TOGGLE_NE_EVENT, ne);
}
vv.repaint();
}
});
add(new AbstractAction("Properties") {
@Override
public void actionPerformed(ActionEvent e) {
showNEProperties(jung, parent, vertex);
vv.repaint();
}
});
}
public TopologyPopupMenu(final JungTopologyPanel jung, final Frame parent,
final VisualizationViewer<DracVertex, DracEdge> vv) {
// POPUP menu for the entire graph
super();
add(new AbstractAction("Add NE") {
@Override
public void actionPerformed(ActionEvent e) {
addNEDialog(parent);
}
});
add(new AbstractAction("Graph properties") {
@Override
public void actionPerformed(ActionEvent e) {
showGraphProperties(jung, parent);
vv.repaint();
}
});
}
public static void addLinkDialog(final JFrame parent, final String ne1IEEE,
final String ne1IP, final String ne1LABEL, final String ne2IEEE,
final String ne2IP, final String ne2LABEL) {
final JDialog d = new JDialog(parent);
final JTextField neighbour1 = new JTextField();
final JTextField neighbour2 = new JTextField();
final JTextField n1IP = new JTextField();
final JTextField n2IP = new JTextField();
final JComboBox sourcePort = new JComboBox();
final JComboBox destPort = new JComboBox();
// final JTextField weightField = new JTextField();
final String dialogTitle = "Add Link";
// final int DIALOG_WIDTH = 525;
// final int DIALOG_HEIGHT = 250;
JTextArea explain = new JTextArea(
"Add manual topological links between unconnected ENNI or INNI designated facilities.\n"
+ "Warning: To avoid traffic problems with schedules only provision manual "
+ "topology between facilities that are directly interconnected and capable "
+ "of carrying traffic between the two facilities.\n", 4, 80);
explain.setLineWrap(true);
explain.setWrapStyleWord(true);
explain.setEditable(false);
JPanel explainP = new JPanel(new BorderLayout(1, 1));
explainP.add(explain, BorderLayout.CENTER);
JPanel basePanel = new JPanel(new BorderLayout(1, 1));
JPanel anotherPanel = new JPanel(new BorderLayout(1, 1));
JPanel mainPanel = new JPanel(new GridLayout(1, 2));
JPanel southPanel = new JPanel(new BorderLayout(1, 1));
JPanel buttonPanel = new JPanel(new GridLayout(1, 2, 5, 5));
// JPanel weightPanel = new JPanel(new GridLayout(1, 2));
JLabel sourceLabel = new JLabel("Network Element:");
JLabel sourceIpLabel = new JLabel("IP:");
JLabel destLabel = new JLabel("Network Element:");
JLabel destIpLabel = new JLabel("IP:");
JLabel sourcePortLabel = new JLabel("Port: ");
JLabel destPortLabel = new JLabel("Port: ");
// JLabel weightLabel = new JLabel("Weight: ");
JButton linkButton = new JButton("Link");
JButton cancelButton = new JButton("Cancel");
JPanel srcPanel = new JPanel();
JPanel dstPanel = new JPanel();
d.setTitle(dialogTitle);
d.getContentPane().setLayout(new GridLayout(1, 1));
srcPanel.setLayout(new GridLayout(4, 2));
dstPanel.setLayout(new GridLayout(4, 2));
srcPanel.setBorder(BorderFactory.createTitledBorder("Source:"));
dstPanel.setBorder(BorderFactory.createTitledBorder("Destination:"));
srcPanel.add(sourceLabel);
srcPanel.add(neighbour1);
srcPanel.add(sourceIpLabel);
srcPanel.add(n1IP);
srcPanel.add(sourcePortLabel);
srcPanel.add(sourcePort);
dstPanel.add(destLabel);
dstPanel.add(neighbour2);
dstPanel.add(destIpLabel);
dstPanel.add(n2IP);
dstPanel.add(destPortLabel);
dstPanel.add(destPort);
buttonPanel.add(linkButton);
buttonPanel.add(cancelButton);
southPanel.add(buttonPanel, BorderLayout.EAST);
linkButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
if (sourcePort.getSelectedItem() == null
|| destPort.getSelectedItem() == null) {
JOptionPane.showMessageDialog(d, "No ports selected");
}
else {
String srcPort = (String) sourcePort.getSelectedItem();
String dstPort = (String) destPort.getSelectedItem();
int result = JOptionPane
.showConfirmDialog(
null,
"<HTML>Are you sure you want to create a manual topological link between '"
+ ne1LABEL
+ "' ("
+ ne1IP
+ ") "
+ srcPort
+ " and '"
+ ne2LABEL
+ "' ("
+ ne2IP
+ ") "
+ dstPort
+ " ?<BR><B>Adding invalid topological links may cause OpenDRAC to malfunction!</B></HTML>",
"Create manual topological link", JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
try {
new ServerOperation().addAjacency(ne1IEEE, sourcePort
.getSelectedItem().toString(), ne2IEEE, destPort
.getSelectedItem().toString());
}
catch (Exception e) {
log.error("Error: ", e);
JOptionPane.showMessageDialog(parent,
"Failed to add topological link (" + ne1IEEE + ","
+ sourcePort.getSelectedItem().toString() + "," + ne2IEEE
+ "," + destPort.getSelectedItem().toString()
+ ") \nmessage: " + e);
}
}
d.setVisible(false);
}
}
});
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
d.setVisible(false);
d.dispose();
}
});
neighbour1.setEditable(false);
neighbour2.setEditable(false);
neighbour1.setText(ne1LABEL);
neighbour2.setText(ne2LABEL);
n1IP.setText(ne1IP);
n2IP.setText(ne2IP);
n1IP.setEditable(false);
n2IP.setEditable(false);
mainPanel.add(srcPanel);
mainPanel.add(dstPanel);
basePanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
anotherPanel.add(mainPanel, BorderLayout.NORTH);
anotherPanel.add(southPanel, BorderLayout.SOUTH);
basePanel.add(explainP, BorderLayout.NORTH);
basePanel.add(anotherPanel, BorderLayout.SOUTH);
DracVertex src = NeCache.INSTANCE.getVertex(ne1IEEE);
DracVertex dest = NeCache.INSTANCE.getVertex(ne2IEEE);
Thread linkDialogPopulatorThread = new Thread(new LinkDialogPopulator(src,
dest, sourcePort, destPort, d));
linkDialogPopulatorThread.setDaemon(true);
linkDialogPopulatorThread.start();
d.getContentPane().add(basePanel);
d.setCursor(OpenDracDesktop.WAIT_CURSOR);
d.pack();
d.setLocationRelativeTo(parent);
d.setVisible(true);
}
private static double getAlmostRandom(int min, int max) {
return min + (int) (Math.random() * ((max - min) + 1));
}
public static void addNEDialog(final Frame parent) {
final JDialog d = new JDialog(parent);
JPanel mainPanel = new JPanel(new GridLayout(5, 1, 3, 3));
JPanel namePanel = new JPanel(new GridLayout(1, 2, 5, 5));
JPanel ipPanel = new JPanel(new GridLayout(1, 2, 5, 5));
JPanel userPanel = new JPanel(new GridLayout(1, 2, 5, 5));
JPanel passPanel = new JPanel(new GridLayout(1, 2, 5, 5));
JPanel protocolPanel = new JPanel(new GridLayout(1, 2, 5, 5));
JPanel portPanel = new JPanel(new GridLayout(1, 2, 5, 5));
JLabel neName = new JLabel("Network Element Name:");
JLabel ip = new JLabel("IP Address:");
JLabel protocol = new JLabel("Protocol:");
JLabel userid = new JLabel("User ID:");
JLabel passwd = new JLabel("Password:");
JLabel port = new JLabel("Port:");
final JTextField userField = new JTextField();
final JPasswordField passField = new JPasswordField();
final JTextField neNameField = new JTextField();
final JTextField ipField = new JTextField();
JPanel buttonPanel = new JPanel(new BorderLayout(1, 1));
JPanel eastButtonPanel = new JPanel();
JButton okButton = new JButton("Ok");
JButton cancelButton = new JButton("Cancel");
neName.setHorizontalAlignment(SwingConstants.RIGHT);
ip.setHorizontalAlignment(SwingConstants.RIGHT);
protocol.setHorizontalAlignment(SwingConstants.RIGHT);
userid.setHorizontalAlignment(SwingConstants.RIGHT);
passwd.setHorizontalAlignment(SwingConstants.RIGHT);
port.setHorizontalAlignment(SwingConstants.RIGHT);
final JComboBox protocolBox = new JComboBox();
final JComboBox portBox = new JComboBox();
portBox.setEditable(true);
populateProtocolBox(protocolBox, portBox);
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
try {
String ip = ipField.getText().trim();
String port = ((String) portBox.getSelectedItem()).trim();
if (NeCache.INSTANCE.getVertex(ip, port) == null) {
CryptedString pw = CryptoWrapper.INSTANCE.encrypt(
new String(passField.getPassword()));
DracVertex v = new DracVertex("newly added NE", "", ip, port,
"unknown", NeType.UNKNOWN, userField.getText(), pw,
NeStatus.NE_UNKNOWN, "", getAlmostRandom(150, 200),
getAlmostRandom(150, 200));
try {
NeCache.INSTANCE.addVertex(v);
}
catch (Exception e) {
log.error("AddVertex failed ", e);
}
try {
NetworkElementHolder newNe = new NetworkElementHolder(ip, port,
userField.getText(), null, null, NeStatus.NE_UNKNOWN, null,
pw, 0, NETWORK_ELEMENT_MODE.Unknown, null, null,
(PROTOCOL_TYPE) protocolBox.getSelectedItem(), true, "Unknown", "", 50d,
50d);
new ServerOperation().enrollNetworkElement(newNe);
}
catch (Exception e) {
log.error("manageNe failed", e);
}
d.setVisible(false);
new ServerOperation().updateNetworkElementPosition(v.getIp(),
v.getPort(), v.getPositionX(), v.getPositionY());
}
else {
JOptionPane.showMessageDialog(null, "The NE with IP address: "
+ ipField.getText() + " is already managed by OpenDRAC");
}
}
catch (Exception e1) {
log.error("Error: ", e1);
}
}
});
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
d.setVisible(false);
d.dispose();
}
});
protocolBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
portBox.setSelectedIndex(protocolBox.getSelectedIndex());
}
});
eastButtonPanel.add(okButton);
eastButtonPanel.add(cancelButton);
buttonPanel.add(eastButtonPanel, BorderLayout.EAST);
d.setTitle("Manage NE");
d.setModal(true);
namePanel.add(neName);
namePanel.add(neNameField);
ipPanel.add(ip);
ipPanel.add(ipField);
protocolPanel.add(protocol);
protocolPanel.add(protocolBox);
userPanel.add(userid);
userPanel.add(userField);
passPanel.add(passwd);
passPanel.add(passField);
portPanel.add(port);
portPanel.add(portBox);
ipField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent fe) {
log.debug("Detected focus lost.. ipField.getText().indexOf(.) is: "
+ ipField.getText().indexOf("."));
if (ipField.getText().indexOf(".") < 0) {
ipField.setText(convertHostnameToFQDN(ipField.getText()));
}
}
});
mainPanel.add(ipPanel);
mainPanel.add(protocolPanel);
mainPanel.add(portPanel);
mainPanel.add(userPanel);
mainPanel.add(passPanel);
mainPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
d.getContentPane().setLayout(new BorderLayout(1, 1));
d.getContentPane().add(mainPanel, BorderLayout.NORTH);
d.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
d.setSize(new Dimension(300, 250));
d.setLocationRelativeTo(parent);
d.setVisible(true);
}
public static void showNEProperties(final JungTopologyPanel jung,
Frame parent, final DracVertex ne) {
final JDialog d = new JDialog(parent);
d.setTitle("Network Element Properties");
JPanel mainPanel = new JPanel(new BorderLayout(5, 5));
JPanel nePanel = new JPanel(new GridLayout(10, 2, 5, 5));
JPanel buttonPanel = new JPanel();
JLabel neNameLabel = new JLabel("Name:");
neNameLabel.setHorizontalAlignment(SwingConstants.RIGHT);
final JTextField neNameField = new JTextField();
neNameField.setText(ne.getLabel());
neNameField.setEditable(false);
JLabel neIeeeLabel = new JLabel("IEEE:");
neIeeeLabel.setHorizontalAlignment(SwingConstants.RIGHT);
final JTextField neIeeeField = new JTextField();
neIeeeField.setText(ne.getIeee());
neIeeeField.setEditable(false);
JLabel neTypeLabel = new JLabel("NE Type: ");
neTypeLabel.setHorizontalAlignment(SwingConstants.RIGHT);
final JTextField neTypeField = new JTextField();
neTypeField.setText(ne.getType().toString());
neTypeField.setEditable(false);
JLabel neStateLabel = new JLabel("State: ");
neStateLabel.setHorizontalAlignment(SwingConstants.RIGHT);
final JTextField neStateField = new JTextField();
neStateField.setText(ne.getStatus().toString());
neStateField.setEditable(false);
JLabel modeLabel = new JLabel("Mode:");
modeLabel.setHorizontalAlignment(SwingConstants.RIGHT);
final JTextField modeField = new JTextField();
modeField.setText(ne.getMode());
modeField.setEditable(false);
JLabel neIpLabel = new JLabel("Edit Address: ");
neIpLabel.setHorizontalAlignment(SwingConstants.RIGHT);
final JTextField ipField = new JTextField();
ipField.setText(ne.getIp());
ipField.setEditable(true);
ipField.setBackground(Color.LIGHT_GRAY);
JLabel portLabel = new JLabel("Edit Port: ");
portLabel.setHorizontalAlignment(SwingConstants.RIGHT);
final JTextField portField = new JTextField();
portField.setText(ne.getPort());
portField.setEditable(true);
portField.setBackground(Color.LIGHT_GRAY);
JLabel userLabel = new JLabel("Edit User Id: ");
userLabel.setHorizontalAlignment(SwingConstants.RIGHT);
final JTextField userField = new JTextField();
userField.setText(ne.getUserId());
userField.setBackground(Color.LIGHT_GRAY);
final String oldUser = userField.getText();
JLabel passLabel = new JLabel("Edit Password: ");
passLabel.setHorizontalAlignment(SwingConstants.RIGHT);
final JPasswordField passField = new JPasswordField();
passField.setBackground(Color.LIGHT_GRAY);
passField.setText(ne.getPassword().toString());
final String oldPass = new String(passField.getPassword());
final String oldIp = ipField.getText();
final String oldPort = portField.getText();
JButton okButton = new JButton("Ok");
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
try {
String user = userField.getText().trim();
String passwd = new String(passField.getPassword()).trim();
if ((!passwd.equals(oldPass) || !user.equals(oldUser))
&& !user.equals("") && !passwd.equals("")) {
int result = JOptionPane.showConfirmDialog(null,
"Are you sure you want to update the Network Element User Id and Password for "
+ ne.getIp() + " (" + ne.getLabel()
+ ") ? Network Element association will be toggled.",
"Confirm password change", JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
CryptedString newPw = CryptoWrapper.INSTANCE.encrypt(passwd);
NetworkElementHolder h = new NetworkElementHolder(ne.getIp(), ne
.getPort(), user, null, null, NeStatus.NE_UNKNOWN, null,
newPw, 0, null, null, null, null, false, "Unknown",null, null, null);
jung.notifyListeners(
TopologyViewEventHandler.EVENT_TYPE.CHANGE_NE_PASSWORD_EVENT,
h);
}
}
// Edit IP & Port
final String newIp = ipField.getText();
final String newPort = portField.getText();
if (!newIp.equals(oldIp) || !newPort.equals(oldPort)) {
int result = JOptionPane.showConfirmDialog(null,
"Are you sure you want to edit the Address/Port of Network Element '"
+ neNameField.getText() + "' ?", "Confirm Ip/Port change",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
result = JOptionPane.showConfirmDialog(null,
"Are You Really Sure? Topology update may take some time!",
"Confirm Ip/Port change", JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
final ServerOperation serverOperation = new ServerOperation();
serverOperation.updateAddressAndPort(oldIp,
Integer.parseInt(oldPort), newIp, Integer.parseInt(newPort));
serverOperation.toggleNeAssociation(new NetworkElementHolder(
newIp, newPort, user, null, null, NeStatus.NE_UNKNOWN, null,
CryptoWrapper.INSTANCE.encrypt(passwd), 0, null, null,
null, null, false, "Unknown", null, null, null));
}
}
}
d.setVisible(false);
d.dispose();
}
catch (Exception e) {
log.error("Error: ", e);
}
}
});
nePanel.add(neIpLabel);
nePanel.add(ipField);
nePanel.add(portLabel);
nePanel.add(portField);
nePanel.add(userLabel);
nePanel.add(userField);
nePanel.add(passLabel);
nePanel.add(passField);
nePanel.add(neNameLabel);
nePanel.add(neNameField);
nePanel.add(neIeeeLabel);
nePanel.add(neIeeeField);
nePanel.add(modeLabel);
nePanel.add(modeField);
nePanel.add(neTypeLabel);
nePanel.add(neTypeField);
nePanel.add(neStateLabel);
nePanel.add(neStateField);
buttonPanel.add(okButton);
mainPanel.add(buttonPanel, BorderLayout.EAST);
mainPanel.add(nePanel, BorderLayout.NORTH);
d.getContentPane().setLayout(new GridLayout(1, 1, 5, 5));
d.getContentPane().add(mainPanel);
d.setLocation(new Point(parent.getLocation().x + 250,
parent.getLocation().y + 400));
nePanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
d.pack();
d.setVisible(true);
}
private static String convertHostnameToFQDN(String name) {
InetAddress addr = null;
String ip = name;
try {
addr = InetAddress.getByName(name);
ip = addr.getCanonicalHostName();
}
catch (Exception e) {
log.error("Error: ", e);
}
return ip;
}
private static void populateProtocolBox(JComboBox protocolBox,
JComboBox portBox) {
protocolBox.removeAllItems();
portBox.removeAllItems();
for (PROTOCOL_TYPE p : PROTOCOL_TYPE.values()) {
protocolBox.addItem(p);
portBox.addItem(Integer.toString(p.getDefaultPortNumber()));
}
}
private void showEdgeProperties(final JungTopologyPanel jung, Frame parent,
final DracEdge edge) {
final JDialog d = new JDialog(parent);
d.setTitle("Link properties");
JPanel mainPanel = new JPanel(new BorderLayout(5, 5));
JPanel linkPanel = new JPanel(new GridLayout(5, 2, 5, 5));
final JTextField linkSrcField = new JTextField(edge.getSource().getLabel());
linkSrcField.setEditable(false);
final JTextField linkDstField = new JTextField(edge.getTarget().getLabel());
linkDstField.setEditable(false);
final JTextField linkSrcPortField = new JTextField(edge.getSourceAid());
linkSrcPortField.setEditable(false);
final JTextField linkDstPortField = new JTextField(edge.getTargetAid());
linkDstPortField.setEditable(false);
linkPanel.add(new JLabel("Source:"));
linkPanel.add(linkSrcField);
linkPanel.add(new JLabel("Destination:"));
linkPanel.add(linkDstField);
linkPanel.add(new JLabel("Source port:"));
linkPanel.add(linkSrcPortField);
linkPanel.add(new JLabel("Destination port: "));
linkPanel.add(linkDstPortField);
JButton okButton = new JButton("Ok");
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
d.setVisible(false);
d.dispose();
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(okButton);
mainPanel.add(buttonPanel, BorderLayout.EAST);
mainPanel.add(linkPanel, BorderLayout.NORTH);
d.getContentPane().setLayout(new GridLayout(1, 1, 5, 5));
d.getContentPane().add(mainPanel);
d.setLocation(new Point(parent.getLocation().x + 250,
parent.getLocation().y + 400));
linkPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
d.pack();
d.setVisible(true);
}
private void showGraphProperties(final JungTopologyPanel jung, Frame parent) {
final JDialog d = new JDialog(parent);
d.setTitle("Graph properties");
JPanel mainPanel = new JPanel(new BorderLayout(5, 5));
JPanel buttonPanel = new JPanel(new GridLayout(0, 2, 5, 5));
JPanel graphPanel = new JPanel(new GridLayout(0, 2, 5, 5));
graphPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
// Ne Labels
{
graphPanel.add(new JLabel("NE labels:"));
final JComboBox labels = new JComboBox(
JungGraphPreferences.NeLabels.values());
labels.setSelectedItem(jung.getGraphPreferences().getNeLabel());
graphPanel.add(labels);
labels.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
try {
jung.getGraphPreferences().setNeLabel(
(JungGraphPreferences.NeLabels) ((JComboBox) e.getSource())
.getSelectedItem());
jung.updateGraphPreferences();
}
catch (Exception e1) {
log.error("Error: ", e1);
}
}
});
}
// edge line style
{
graphPanel.add(new JLabel("Edge line style:"));
final JComboBox styles = new JComboBox(
JungGraphPreferences.LineStyles.values());
styles.setSelectedItem(jung.getGraphPreferences().getEdgeLineStyle());
graphPanel.add(styles);
styles.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
try {
jung.getGraphPreferences().setEdgeLineStyle(
(JungGraphPreferences.LineStyles) ((JComboBox) e.getSource())
.getSelectedItem());
jung.updateGraphPreferences();
}
catch (Exception e1) {
log.error("Error: ", e1);
}
}
});
}
// 'network-discovered only' edge color
{
JButton edgeColor = new JButton("'Network-Discovered Only' Edge Colour");
graphPanel.add(edgeColor);
edgeColor.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
try {
Color colour = JColorChooser.showDialog(d, "Choose Colour", jung
.getGraphPreferences().getEdgeColorNetworkDiscovered());
if (colour != null) {
jung.getGraphPreferences().setEdgeColorNetworkDiscovered(colour);
jung.updateGraphPreferences();
}
}
catch (Exception e1) {
log.error("Error: ", e1);
}
}
});
}
// 'manual only' edge color
{
JButton edgeColor = new JButton("'Manual Only' Edge Colour");
graphPanel.add(edgeColor);
edgeColor.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
try {
Color colour = JColorChooser.showDialog(d, "Choose Colour", jung
.getGraphPreferences().getEdgeColorManual());
if (colour != null) {
jung.getGraphPreferences().setEdgeColorManual(colour);
jung.updateGraphPreferences();
}
}
catch (Exception e1) {
log.error("Error: ", e1);
}
}
});
}
// 'network-discovered and manual' edge color
{
JButton edgeColor = new JButton(
"'Network-Discovered with Manual' Edge Colour");
graphPanel.add(edgeColor);
edgeColor.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
try {
Color colour = JColorChooser
.showDialog(d, "Choose Colour", jung.getGraphPreferences()
.getEdgeColorNetworkDiscoveredAndManual());
if (colour != null) {
jung.getGraphPreferences()
.setEdgeColorNetworkDiscoveredAndManual(colour);
jung.updateGraphPreferences();
}
}
catch (Exception e1) {
log.error("Error: ", e1);
}
}
});
}
// 'selected' edge color
{
JButton selectedEdgeColor = new JButton("Selected Edge Colour");
graphPanel.add(selectedEdgeColor);
selectedEdgeColor.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
try {
Color colour = JColorChooser.showDialog(d, "Choose Colour", jung
.getGraphPreferences().getEdgeColorSelected());
if (colour != null) {
jung.getGraphPreferences().setEdgeColorSelected(colour);
jung.updateGraphPreferences();
}
}
catch (Exception e1) {
log.error("Error: ", e1);
}
}
});
}
JButton resetButton = new JButton("Use defaults");
resetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
try {
jung.getGraphPreferences().resetToDefaults();
jung.updateGraphPreferences();
}
catch (Exception e1) {
log.error("Error: ", e1);
}
d.setVisible(false);
d.dispose();
}
});
buttonPanel.add(resetButton);
JButton okButton = new JButton("Ok");
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
d.setVisible(false);
d.dispose();
}
});
buttonPanel.add(okButton);
mainPanel.add(buttonPanel, BorderLayout.EAST);
mainPanel.add(graphPanel, BorderLayout.NORTH);
d.getContentPane().setLayout(new GridLayout(1, 1, 5, 5));
d.getContentPane().add(mainPanel);
d.setLocation(new Point(parent.getLocation().x + 250,
parent.getLocation().y + 400));
d.pack();
d.setVisible(true);
}
}
| gpl-3.0 |
bgd-point/daily-dhamma | app/src/main/java/red/point/dailydhamma/DailyDhamma.java | 467 | package red.point.dailydhamma;
import android.app.Application;
import com.google.firebase.database.FirebaseDatabase;
public class DailyDhamma extends Application {
public void onCreate() {
super.onCreate();
// your app writes the data locally to the device so your app can maintain state while
// offline, even if the user or operating system restarts the app
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
}
}
| gpl-3.0 |
talisman1234/service-api | src/test/java/com/epam/ta/reportportal/database/dao/DashboardRepositoryTest.java | 5361 | /*
* Copyright 2016 EPAM Systems
*
*
* This file is part of EPAM Report Portal.
* https://github.com/reportportal/service-api
*
* Report Portal is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Report Portal is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Report Portal. If not, see <http://www.gnu.org/licenses/>.
*/
package com.epam.ta.reportportal.database.dao;
import java.util.Date;
import java.util.List;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import com.epam.ta.BaseTest;
import com.epam.ta.reportportal.database.entity.Dashboard;
import com.epam.ta.reportportal.database.fixture.SpringFixture;
import com.epam.ta.reportportal.database.fixture.SpringFixtureRule;
import com.epam.ta.reportportal.ws.converter.builders.BuilderTestsConstants;
@SpringFixture("dashboardTriggerTest")
public class DashboardRepositoryTest extends BaseTest {
public static final String DASHBOARD_1_ID = "520e1f3818127ca383339f34";
public static final String DASHBOARD_2_ID = "520e1f3818127ca383339f35";
@Autowired
private DashboardRepository dashboardRepository;
@Rule
@Autowired
public SpringFixtureRule dfRule;
@Test
public void testFindOneLoadId() {
Dashboard dashboard = dashboardRepository.findOneLoadId(BuilderTestsConstants.USER, DASHBOARD_1_ID, BuilderTestsConstants.PROJECT);
Assert.assertNotNull(dashboard);
Assert.assertNull(dashboard.getName());
Assert.assertNull(dashboard.getAcl());
Assert.assertEquals(0, dashboard.getWidgets().size());
Assert.assertNull(dashboardRepository.findOneLoadId(BuilderTestsConstants.USER, DASHBOARD_1_ID, "1"));
Assert.assertNull(dashboardRepository.findOneLoadId("1", DASHBOARD_1_ID, BuilderTestsConstants.PROJECT));
}
@Test
public void testFindByUserAndId() {
Dashboard dashboard = dashboardRepository.findOne(BuilderTestsConstants.USER, DASHBOARD_2_ID, BuilderTestsConstants.PROJECT);
Assert.assertNotNull(dashboard);
Assert.assertEquals("testName", dashboard.getName());
Assert.assertEquals(BuilderTestsConstants.USER, dashboard.getAcl().getOwnerUserId());
Assert.assertNotNull(dashboard.getWidgets());
Assert.assertNull(dashboardRepository.findOne(BuilderTestsConstants.USER, DASHBOARD_2_ID, "1"));
Assert.assertNull(dashboardRepository.findOne("1", DASHBOARD_2_ID, BuilderTestsConstants.PROJECT));
}
@Test
public void testFindAll() {
Sort creationDateSort = new Sort(new Order(Direction.DESC, Dashboard.CREATION_DATE));
List<Dashboard> dashboards = dashboardRepository.findAll(BuilderTestsConstants.USER, creationDateSort,
BuilderTestsConstants.PROJECT);
Assert.assertEquals(dashboards.size(), 4);
Date currentDate = null;
for (Dashboard dashboard : dashboards) {
if (currentDate == null) {
currentDate = dashboard.getCreationDate();
} else {
Assert.assertTrue(currentDate.after(dashboard.getCreationDate()));
currentDate = dashboard.getCreationDate();
}
Assert.assertNotNull(dashboard.getAcl().getOwnerUserId());
Assert.assertNotNull(dashboard.getWidgets());
}
Assert.assertTrue(dashboardRepository.findAll(BuilderTestsConstants.USER, creationDateSort, "1").size() == 0);
Assert.assertTrue(dashboardRepository.findAll("1", creationDateSort, BuilderTestsConstants.PROJECT).size() == 0);
}
@Test
public void testFindDashboardById() {
Dashboard dashboard = dashboardRepository.findOne(DASHBOARD_2_ID);
Assert.assertEquals(DASHBOARD_2_ID, dashboard.getId());
Assert.assertNotNull(dashboard.getName());
Assert.assertNotNull(dashboard.getAcl().getOwnerUserId());
Assert.assertNotNull(dashboard.getWidgets());
}
@Test
public void testFindEntryById() {
Dashboard dashboard = dashboardRepository.findEntryById(DASHBOARD_2_ID);
Assert.assertEquals(DASHBOARD_2_ID, dashboard.getId());
Assert.assertNull(dashboard.getName());
Assert.assertNull(dashboard.getAcl());
Assert.assertEquals(0, dashboard.getWidgets().size());
}
@Test
public void testNullFindByProject() {
List<Dashboard> dashboards = dashboardRepository.findByProject(null);
Assert.assertNotNull(dashboards);
Assert.assertTrue(dashboards.isEmpty());
}
@Test
public void testFindByProject() {
List<Dashboard> dashboards = dashboardRepository.findByProject(BuilderTestsConstants.PROJECT);
Assert.assertNotNull(dashboards);
Assert.assertEquals(4, dashboards.size());
}
@Test
public void testFindOneLoadACL() {
Dashboard dashboard = dashboardRepository.findOneLoadACL(DASHBOARD_1_ID);
Assert.assertNotNull(dashboard);
Assert.assertNotNull(dashboard.getId());
Assert.assertNotNull(dashboard.getAcl());
Assert.assertNull(dashboard.getName());
Assert.assertNotNull(dashboard.getProjectName());
}
} | gpl-3.0 |
satishagrwal/Assignment | freeswitch_git/mod/languages/mod_java/src/org/freeswitch/HangupHook.java | 146 | package org.freeswitch;
public interface HangupHook
{
/** Called on hangup, usually in a different thread. */
public void onHangup();
}
| gpl-3.0 |