method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
6c980c40-187a-45fe-9c40-b3d05d1f5a1e
| 9 |
private void evaluateInput(String message) throws Exception {
// Parse the input message
Matcher matcher = pattern.matcher(message);
if (matcher.matches() == false) {
throw new IllegalArgumentException(
"Syntax error: " + message);
}
// Parse the received command
String command = matcher.group(1);
String params = matcher.group(2);
if ("id".equals(command)) {
parseID(params);
} else if ("uciok".equals(command)) {
parseUCIOk(params);
} else if ("readyok".equals(command)) {
parseReadyOk(params);
} else if ("bestmove".equals(command)) {
parseBestMove(params);
} else if ("copyprotection".equals(command)) {
parseCopyProtection(params);
} else if ("registration".equals(command)) {
parseRegistration(params);
} else if ("info".equals(command)) {
parseInfo(params);
} else if ("option".equals(command)) {
parseOption(params);
} else {
throw new IllegalArgumentException(
"Unknown engine command: " + command);
}
}
|
c10b474c-f897-4243-92a2-627480fdc33b
| 3 |
public void connect(Message m) {
String message = m.getMessage();
if (message.startsWith(Protocol.CONNECT)) {
message = message.replace(Protocol.CONNECT, "");
if (!message.equals("")) {
if (!users.containsValue(m.getIClient())) {
m.getIClient().setName(message);
registrerClients(message, m.getIClient());
notifyUsers(Protocol.ONLINE + getUsers());
} else {
notifyReciever(Protocol.SERVER_ONLINE_RESPONSE, m.getIClient());
System.out.println("shiiit");
}
}
}
}
|
7a31fcd4-e1dc-4934-9b83-39a151598dac
| 3 |
@Override
public ArrayList<? extends Object> getOptions() {
if (options == null) {
options = new ArrayList<Source>();
for (Source s : Source.values())
options.add(s);
}
return options;
}
|
9a544aae-5465-4f75-a637-2e83de5e5e38
| 6 |
public static void main(String[] args) {
logger.setLevel(Level.SEVERE);
ConsoleHandler handler = new ConsoleHandler();
handler.setLevel(Level.SEVERE);
logger.addHandler(handler);
if (args.length == 0) {
logger.warning("Invalid arguments count.");
return;
}
try {
int k0 = Integer.parseInt(args[0]);
int k1 = Integer.parseInt(args[1]);
String alphabet = args[2];
String file = args[3];
String dir = args[4];
BufferedReader in = new BufferedReader(new FileReader(file));
while (in.ready()) {
if (dir.equals("0")) {
String ret = encrypt(k0,k1, in.readLine(),alphabet);
System.out.println(ret);
} else if(dir.equals("1")){
String ret = decrypt(k0,k1, in.readLine(),alphabet);
System.out.println(ret);
} else {
String ret = encrypt(k0,k1, in.readLine(),alphabet);
System.out.println(ret);
ret = decrypt(k0,k1, ret,alphabet);
System.out.println(ret);
}
}
} catch (NumberFormatException | FileNotFoundException ex) {
logger.log(Level.SEVERE, null, ex);
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
}
}
|
c9e12ba6-29f6-424e-9458-6582f926f4e0
| 6 |
@EventHandler
public void PlayerHunger(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getPlayerConfig().getDouble("Player.Hunger.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
} if (plugin.getPlayerConfig().getBoolean("Player.Hunger.Enabled", true) && damager instanceof Player && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.HUNGER, plugin.getPlayerConfig().getInt("Player.Hunger.Time"), plugin.getPlayerConfig().getInt("Player.Hunger.Power")));
}
}
|
fc2f0c6a-e6ea-49af-9186-cf5ea60d6ea3
| 7 |
@Override
public State run(final String program, final State s) {
Map<String, Integer> methodMap = Utils.getMethods(program);
ClassWriter cw = new ClassWriter(0);
MethodVisitor mv;
final String stateClass = Type.getInternalName(s.getClass());
cw.visit(V1_6, ACC_PUBLIC + ACC_SUPER, CLASS_NAME, null, "java/lang/Object", null);
cw.visitSource(CLASS_NAME + ".java", null);
mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
Label l0 = new Label();
mv.visitLabel(l0);
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
mv.visitInsn(RETURN);
Label l1 = new Label();
mv.visitLabel(l1);
mv.visitLocalVariable("this", "LHelloWorld;", null, l0, l1, 0);
mv.visitMaxs(1, 1);
mv.visitEnd();
mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "run", "(L" + stateClass + ";)V", null, null);
mv.visitCode();
convertMethod2BC(mv, methodMap, program, false, stateClass, s instanceof StatusState);
mv.visitInsn(RETURN);
mv.visitMaxs(2, 1);
mv.visitEnd();
for (Map.Entry<String, Integer> entry : methodMap.entrySet()) {
mv = cw.visitMethod(ACC_PRIVATE + ACC_STATIC, "meth" + entry.getValue(), "(L" + stateClass + ";)V", null,
null);
mv.visitCode();
convertMethod2BC(mv, methodMap, entry.getKey(), true, stateClass, s instanceof StatusState);
mv.visitInsn(RETURN);
mv.visitMaxs(2, 1);
mv.visitEnd();
}
DynamicClassLoader loader = new DynamicClassLoader();
Class<?> helloWorldClass = loader.define(CLASS_NAME, cw.toByteArray());
try {
helloWorldClass.getMethod("run", s.getClass()).invoke(null, s);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
return null;
}
|
cecdd609-f699-4971-b5d4-a96a90cabafa
| 8 |
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.HIGHEST)
public void onInventoryClick(InventoryClickEvent event) {
Player player = (Player) event.getWhoClicked();
// sprawdza czy to inventory tego pluginu
if(event.getInventory().getName().equalsIgnoreCase(this.plugin.dInvName)) {
// jeśli to górne inventory to...
if(event.getRawSlot() < 54) {
// zezwolone w górnum inv
if(event.getAction() == InventoryAction.PICKUP_ALL ||
event.getAction() == InventoryAction.PICKUP_HALF ||
event.getAction() == InventoryAction.PICKUP_ONE ||
event.getAction() == InventoryAction.PICKUP_SOME ||
event.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY) {
return;
}
event.setCancelled(true);
player.updateInventory();
} else {
// zabronione w dolnym inv
if(event.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY) {
event.setCancelled(true);
player.updateInventory();
}
}
}
}
|
adcf56fc-20b5-4a0f-8396-7151834ba6ee
| 5 |
public static void main(String[] args)
{
if (args.length == 1)
{
try
{
echoTCP(args[0]);
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
else if (args.length == 2 && args[0].equals("-udp"))
{
try
{
echoUDP(args[1]);
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
else
{
System.err.println("Usage: echo [-udp] <hostname>");
System.exit(1);
}
}
|
0f841a1a-a0aa-4ee8-9d57-5346327d78d9
| 9 |
public static void dump(DataInputStream ios, int length) {
try {
String s;
String a = "";
for (int i = 0, j = 0; i < length; i++) {
int val = ios.read();
if (val < 0) System.exit(0);
if (j == 0) {
System.out.println(" " + a);
a = "";
s = Integer.toHexString(i);
s = s + " ".substring(s.length());
System.out.print(s + " ");
}
if (j == 8) System.out.print(" ");
s = Integer.toHexString(val);
if (s.length() < 2) s = "0" + s;
System.out.print(s + " ");
if ((val > 32) && (val < 128)) a += (char)val; else a += ' ';
if (++j == 16) j = 0;
}
System.out.println("");
} catch(IOException e) {
System.out.println(e);
}
}
|
10182c71-a086-4fd3-bc54-c36604aab0e6
| 0 |
protected int processRecord (int recordCounter, byte[] recordData, short recordAttributes, int recordUniqueID)
{
// TBD
// if (Outliner.DEBUG) { System.out.println
// ("\tStan_Debug:\tPdbReaderWriter:processRecord for record #" + (recordCounter+1)); }
return SUCCESS ;
} // end protected method processRecord
|
536f0543-daa3-41fa-a7b3-17385f1c5484
| 7 |
public Integer insert(ProductosBeans producto) throws DAOException {
PreparedStatement pst = null;
ResultSet generatedKeys = null;
try {
pst = con.prepareStatement(sql.getString("INSERT_PRODUCTOS"),
Statement.RETURN_GENERATED_KEYS);
pst.setString(1, producto.getNombreP());
pst.setString(2, producto.getDescripcion());
pst.setInt(3, producto.getActivo());
pst.setInt(4, producto.getIdTipoProducto());
if (pst.executeUpdate() != 1)
throw new DAOException("No se pudo insertar la solicitud");
generatedKeys = pst.getGeneratedKeys();
generatedKeys.first();
ResultSetMetaData rsmd = generatedKeys.getMetaData();
if (rsmd.getColumnCount() > 1) {
throw new DAOException("Se genero mas de una llave");
}
//con.commit();
return generatedKeys.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
throw new DAOException(e.getMessage());
} catch (Exception e) {
throw new DAOException(e.getMessage());
} finally {
try {
if (pst != null)
pst.close();
if (generatedKeys != null)
generatedKeys.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
d89293f3-3880-4f3a-9ff8-b5492b0a6b45
| 0 |
public void talk(String msg) {
System.out.println(msg + "!你好,我是" + username + ",我年龄是" + age);
}
|
a7be51b6-b5c1-4f01-b9f9-1a5b5ac852d2
| 3 |
public void addBuilding(CastleBuilding b)
{
if (b.type == null || b.type == type) {
if (!buildings.contains(b)) {
buildings.add(b);
b.buyBonus(Mission.getLastInstance().getActivePlayer(), this);
System.out.println("ADD BUILDING: "+b.name);
}
}
}
|
b217350f-6fac-499e-a4b5-fb07bbfbe9de
| 4 |
protected java.util.List<ThreeTuple<Vector2, Vector2, Vector2>> parse(BufferedImage image) {
ArrayList<ThreeTuple<Vector2, Vector2, Vector2>> ret = new ArrayList<ThreeTuple<Vector2, Vector2, Vector2>>();
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
// boolean values default to false, so no need to set them.
boolean[][] searched = new boolean[imageWidth][imageHeight];
// Stack should be ok? Doubt we need a Queue.
Color background = new Color(image.getRGB(0, 0), true);
for (int y = 0; y < imageHeight; y++) {
for (int x = 0; x < imageWidth; x++) {
if (!searched[x][y]) {
if (image.getRGB(x, y) != background.getRGB()) {
TwoTuple<Point, Point> found = extractSprite(image, background, searched, new Point(x, y));
int width = found.two.x - found.one.x;
int height = found.two.y - found.one.y;
Vector2 loc = new Vector2(found.one.x / (float) imageWidth, found.one.y / (float) imageHeight);
Vector2 size = new Vector2(width / imageWidth,
width / imageHeight);
ret.add(new ThreeTuple<Vector2, Vector2, Vector2>(loc, size,
new Vector2(width, height)));
}
searched[x][y] = true;
}
}
}
return ret;
}
|
5c0ac082-6fac-4e03-98ec-c040b27479ad
| 2 |
public static void printList(ListNode x) {
if(x != null){
System.out.print(x.val + " ");
while (x.next != null) {
System.out.print(x.next.val + " ");
x = x.next;
}
System.out.println();
}
}
|
f8d6a6f8-a087-4748-85f0-0a755da6253e
| 3 |
public void update() {
for (int i = 0; i < players.size(); i++) {
players.get(i).update();
}
for (int i = 0; i < entities.size(); i++) {
entities.get(i).update();
}
for (int i = 0; i < projectiles.size(); i++) {
projectiles.get(i).update();
}
clear();
}
|
822a074b-e1d1-43fe-81c5-c95f37242649
| 2 |
public boolean subComponentOf(GUIComponentGroup componentGroup) {
if (this == componentGroup) {
return true;
}
if (this.superGroup == null) {
return false;
}
return this.superGroup.subComponentOf(componentGroup);
}
|
f5e74571-a063-4cd6-8c05-1946ca2a7a08
| 9 |
private void init() {
this.x.set(0.);
/*
* Set up y for the first Lanczos vector. y and beta1 will be zero
* if b = 0.
*/
this.r1 = this.b.copy();
this.y = this.minv == null ? this.b.copy() : this.minv.operate(this.r1);
if ((this.minv != null) && check) {
checkSymmetry(this.minv, this.r1, this.y, this.minv.operate(this.y));
}
this.beta1 = this.r1.dotProduct(this.y);
if (this.beta1 < 0.) {
throwNPDLOException(this.minv, this.y);
}
if (this.beta1 == 0.) {
/* If b = 0 exactly, stop with x = 0. */
return;
}
this.beta1 = FastMath.sqrt(this.beta1);
/* At this point
* r1 = b,
* y = M^(-1) * b,
* beta1 = beta[1].
*/
final RealVector v = this.y.mapMultiply(1. / this.beta1);
this.y = this.a.operate(v);
if (check) {
checkSymmetry(this.a, v, this.y, this.a.operate(this.y));
}
/*
* Set up y for the second Lanczos vector. y and beta will be zero
* or very small if b is an eigenvector.
*/
daxpy(-this.shift, v, this.y);
final double alpha = v.dotProduct(this.y);
daxpy(-alpha / this.beta1, this.r1, this.y);
/*
* At this point
* alpha = alpha[1]
* y = beta[2] * M * P' * v[2]
*/
/* Make sure r2 will be orthogonal to the first v. */
final double vty = v.dotProduct(this.y);
final double vtv = v.dotProduct(v);
daxpy(-vty / vtv, v, this.y);
this.r2 = this.y.copy();
if (this.minv != null) {
this.y = this.minv.operate(this.r2);
}
this.oldb = this.beta1;
this.beta = this.r2.dotProduct(this.y);
if (this.beta < 0.) {
throwNPDLOException(this.minv, this.y);
}
this.beta = FastMath.sqrt(this.beta);
/*
* At this point
* oldb = beta[1]
* beta = beta[2]
* y = beta[2] * P' * v[2]
* r2 = beta[2] * M * P' * v[2]
*/
this.cgnorm = this.beta1;
this.gbar = alpha;
this.dbar = this.beta;
this.gammaZeta = this.beta1;
this.minusEpsZeta = 0.;
this.bstep = 0.;
this.snprod = 1.;
this.tnorm = alpha * alpha + this.beta * this.beta;
this.ynorm2 = 0.;
this.gmax = FastMath.abs(alpha) + MACH_PREC;
this.gmin = this.gmax;
if (this.goodb) {
this.wbar = new ArrayRealVector(this.a.getRowDimension());
this.wbar.set(0.);
} else {
this.wbar = v;
}
updateNorms();
}
|
5e13a6d6-b512-433d-9e4b-0fdd69351414
| 7 |
static final public void operadores_aritmetico() throws ParseException {
trace_call("operadores_aritmetico");
try {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case ATRIBUICAO:
jj_consume_token(ATRIBUICAO);
break;
case ADICAO:
jj_consume_token(ADICAO);
break;
case SUBTRACAO:
jj_consume_token(SUBTRACAO);
break;
case MULTIPLICACAO:
jj_consume_token(MULTIPLICACAO);
break;
case DIVISAO:
jj_consume_token(DIVISAO);
break;
case POTENCIA:
jj_consume_token(POTENCIA);
break;
default:
jj_la1[0] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
} finally {
trace_return("operadores_aritmetico");
}
}
|
2ab145f6-4c8b-45a6-9177-1aaba0553b70
| 1 |
@Override
public void batimentToFarm(Farm farm, List<Batiment> batiments) {
for(Batiment batiment:batiments){
batiment.setFarm(farm);
em.persist(batiment);
}
}
|
0db2c022-2a90-42f7-a397-7279745d79f9
| 1 |
public String toString() {
if (comment != null) {
return "label_" + index + " (" + comment + ")";
} else {
return "label_" + index;
}
}
|
15b4adfb-3175-485f-b31d-181ab0ba0a48
| 6 |
public static String numberToString(Number number) throws JSONException {
if (number == null) {
throw new JSONException("Null pointer");
}
testValidity(number);
// Shave off trailing zeros and decimal point, if possible.
String string = number.toString();
if (string.indexOf('.') > 0 && string.indexOf('e') < 0
&& string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
}
|
f5f829e5-39e7-4ae2-9352-5944b9a68d1a
| 5 |
private void switchProcess() {
Process process = cpu.getActiveProcess();
if(process != null){
process.leftCpu(clock);
cpu.addProcess(process);
process.enterCpuQueue(clock);
statistics.nofForcedProcessSwitch++;
}
process = cpu.startNextProcess();
if(process != null){
process.enterCpu(clock);
if(process.getTimeToIO() > cpu.getMaxCpuTime() && process.getRemainingCpuTime() > cpu.getMaxCpuTime()){
statistics.totalCpuTime+=cpu.getMaxCpuTime();
eventQueue.insertEvent(new Event(SWITCH_PROCESS, clock+cpu.getMaxCpuTime()));
}
else if(process.getTimeToIO()>process.getRemainingCpuTime()){
statistics.totalCpuTime+=process.getRemainingCpuTime();
eventQueue.insertEvent(new Event(END_PROCESS, clock+process.getRemainingCpuTime()));
}
else{
statistics.totalCpuTime+=process.getTimeToIO();
eventQueue.insertEvent(new Event(IO_REQUEST, clock+process.getTimeToIO()));
}
}
}
|
d6a8a675-4ee7-4652-b757-72ddd4d6feda
| 0 |
private Supervisor(){}
|
3a3f60bf-bcfa-4fbc-87ee-4f27fd62533b
| 1 |
public Boolean eliminarProducto(String producto){
if(!this.stock.containsKey(producto)){
return false;
}
this.stock.remove(producto);
return true;
}
|
13972dc9-18f4-4223-a3db-65f886dd39de
| 5 |
private void pop(char c) throws JSONException {
if (this.top <= 0) {
throw new JSONException("Nesting error.");
}
char m = this.stack[this.top - 1] == null ? 'a' : 'k';
if (m != c) {
throw new JSONException("Nesting error.");
}
this.top -= 1;
this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k';
}
|
88944186-2f3b-4819-a108-19c6af55c687
| 2 |
public void cleanOldNatives() {
File root = new File(mcPath, "versions/");
//this.launcher.println("Looking for old natives to clean up...");
IOFileFilter ageFilter = new AgeFileFilter(System.currentTimeMillis() - 3600L);
for (File version : root.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY)) {
File[] fileList = version.listFiles( (FileFilter)
FileFilterUtils.and(new IOFileFilter[] {
new PrefixFileFilter(version.getName() + "-natives-"), ageFilter
})
);
for (File folder : fileList) {
//Launcher.getInstance().println("Deleting " + folder);
FileUtils.deleteQuietly(folder);
}
}
}
|
e0f4e28e-e105-4879-8ea0-55167d770c4b
| 7 |
void executePlayerCommand(PlayerCommand pc, int playerNumber)
{
int command = pc.command;
Player p;
if (playerNumber == 1)
p = server.gameState.player1;
else
p = server.gameState.player2;
switch (command)
{
case PlayerCommand.PRESS_RIGHT : p.run_right();
break;
case PlayerCommand.PRESS_LEFT : p.run_left();
break;
case PlayerCommand.PRESS_UP : {p.jump();}
break;
case PlayerCommand.RELEASE_RIGHT : p.stop_running_right();
break;
case PlayerCommand.RELEASE_LEFT : p.stop_running_left();
break;
case PlayerCommand.SHOOT : p.shoot();
break;
}
}
|
bb861cb3-dcbe-4b97-b78c-3634e87a8ce3
| 8 |
public void act() {
if(debut) {
debut = false;
ActionFactory.wait(10000, "end", true);
}
if(!clawsMoving) {
if(attente) {
ActionFactory.wait(500, "claws", true);
}
else {
clawsMoving = true;
ActionFactory.useClaws(nextclawsOpenure, true);
}
}
if(!robotMoving) {
robotMoving = true;
switch(state)
{
case 0 :
ActionFactory.goForward(500, true);
break;
case 1 :
ActionFactory.goBackward(500, true);
break;
case 2 :
ActionFactory.rotate(90, true);
}
}
if(end) {
stop();
}
}
|
b34c086a-4294-4f14-9678-b9804fd10019
| 1 |
public Organism getRepresentOrganism() {
if (getOrganisms().isEmpty()) {
System.err.println(this.toString());
}
return getOrganisms().get(representativeIndex);
}
|
8c1ded7f-00db-47ce-9c18-48bd04bd61f7
| 9 |
@Override
public double[] calculateJulia3DWithoutPeriodicity(Complex pixel) {
iterations = 0;
Complex tempz2 = new Complex(init_val2.getPixel(pixel));
Complex[] complex = new Complex[3];
complex[0] = new Complex(pixel);//z
complex[1] = new Complex(seed);//c
complex[2] = tempz2;
Complex zold = new Complex();
if(parser.foundS()) {
parser.setSvalue(new Complex(complex[0]));
}
if(parser2.foundS()) {
parser2.setSvalue(new Complex(complex[0]));
}
if(parser.foundP()) {
parser.setPvalue(new Complex());
}
if(parser2.foundP()) {
parser2.setPvalue(new Complex());
}
double temp;
for(; iterations < max_iterations; iterations++) {
if(bailout_algorithm.escaped(complex[0], zold)) {
Object[] object = {iterations, complex[0], zold};
temp = out_color_algorithm.getResult(object);
double[] array = {Math.abs(temp) - 100800, temp};
return array;
}
zold.assign(complex[0]);
function(complex);
if(parser.foundP()) {
parser.setPvalue(new Complex(zold));
}
if(parser2.foundP()) {
parser2.setPvalue(new Complex(zold));
}
}
Object[] object = {complex[0], zold};
temp = in_color_algorithm.getResult(object);
double result = temp == max_iterations ? max_iterations : max_iterations + Math.abs(temp) - 100820;
double[] array = {result, temp};
return array;
}
|
2150a5d3-87ad-4aec-970a-9edf5fbac8b6
| 4 |
@Override
public Set<DeliveryOption> call() throws Exception
{
Set<DeliveryOption> xs = new HashSet<>();
String city_name = null;
Region r;
if(rx.delivery != null)
while((r = rx.delivery.getRegion()) != null)
if(r.getType() == RegionType.CITY)
{
city_name = r.getName();
break;
}
if(city_name == null)
{
//TODO: by region?
}
else
xs.addAll(BitrixDeliveryRepository.i().getByCityName(city_name));
log.info("Got {} methods of delivery", xs.size());
return xs;
}
|
68573f07-5b87-4ed6-a9d0-f5e85f6f7b36
| 6 |
private static MaNode makeNode(Composante c) {
Type t = c.getType();
switch (t) {
case RESISTANCE:
int image = MaNode.NODE_RESISTANCE;
Resistance resis = (Resistance) c;
if (resis.isBurned()) {
image = MaNode.NODE_BURNED;
}
return new MaNode("Résistance", image, c.getNumero());
case PARALLELE:
MaNode m = new MaNode("Parallèle", MaNode.NODE_PARALLELE, c.getNumero());
for (Composante s : c.getComposantes()) {
m.addChild(makeNode(s));
}
return m;
case SERIE:
MaNode n = new MaNode("Branche", MaNode.NODE_BRANCHE, c.getNumero());
for (Composante comp : c.getComposantes()) {
n.addChild(makeNode(comp));
}
return n;
}
return null;
}
|
7540e367-1e75-4d50-8bad-7e793ba0bef1
| 8 |
@Override
public void affectCharState(MOB mob, CharState state)
{
super.affectCharState(mob,state);
if(mob.baseCharStats().getCurrentClass().ID().equals(ID()))
{
Ability A=null;
for(int a=0;a<mob.numAbilities();a++)
{
A=mob.fetchAbility(a);
if((A!=null)
&&((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_SPELL)
&&(!CMLib.ableMapper().getDefaultGain(ID(),false,A.ID())))
{
final int[] cost=A.usageCost(mob,true);
final int manaCost=cost[Ability.USAGEINDEX_MANA];
if(manaCost>0)
{
if(state.getMana()<manaCost)
{
mob.delAbility(A);
a--;
}
else
state.setMana(state.getMana()-manaCost);
}
}
}
if(mob.curState().getMana()>state.getMana())
mob.curState().setMana(state.getMana());
}
}
|
aa08c33d-35f6-4097-bced-7f560d41e5b1
| 4 |
public static String getRepeatString(int repeatTime, String metaString)
{
String repeatString = null;
if ((repeatTime > 0) && (metaString != null)) {
int intMetatStringLength = metaString.length();
if (intMetatStringLength == 0) {
repeatString = "";
} else {
StringBuffer tempStringBuffer = new StringBuffer(repeatTime * intMetatStringLength);
for (int i = 0; i < repeatTime; i++) {
tempStringBuffer.append(metaString);
}
repeatString = tempStringBuffer.toString();
}
}
return repeatString;
}
|
c1b5436f-1844-4ad1-8f63-01fac5dd670d
| 7 |
public static void startupGoalCaches() {
{ Object old$Module$000 = Stella.$MODULE$.get();
Object old$Context$000 = Stella.$CONTEXT$.get();
try {
Native.setSpecial(Stella.$MODULE$, Stella.getStellaModule("/LOGIC", Stella.$STARTUP_TIME_PHASE$ > 1));
Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get())));
if (Stella.currentStartupTimePhaseP(2)) {
_StartupGoalCaches.helpStartupGoalCaches1();
}
if (Stella.currentStartupTimePhaseP(4)) {
Logic.$SUCCEEDED_GOALS_CACHE$ = Vector.newVector(1541);
Logic.$FAILED_GOALS_CACHE$ = Vector.newVector(1541);
Logic.$UNIFICATION_VECTOR_1$.setDefaultValue(Vector.newVector(10));
Logic.$UNIFICATION_VECTOR_2$.setDefaultValue(Vector.newVector(10));
}
if (Stella.currentStartupTimePhaseP(5)) {
{ Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("GOAL-CACHE", "(DEFCLASS GOAL-CACHE (STANDARD-OBJECT) :DOCUMENTATION \"Cache of output bindings derived for a particular goal\nand set of input bindings.\" :SLOTS ((CACHED-BINDINGS :TYPE (LIST OF GOAL-BINDINGS) :ALLOCATION :EMBEDDED) (TIMESTAMP :TYPE TIMESTAMP) (PROPOSITION :TYPE PROPOSITION) (REVERSE-POLARITY? :TYPE BOOLEAN) (CACHE-CONTEXT :TYPE CONTEXT)))");
renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.powerloom.logic.GoalCache", "newGoalCache", new java.lang.Class [] {});
renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.powerloom.logic.GoalCache", "accessGoalCacheSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.GoalCache"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE});
}
Stella.defineStellaTypeFromStringifiedSource("(DEFTYPE GOAL-CACHE-TABLE (KEY-VALUE-LIST OF CONTEXT GOAL-CACHE))");
{ Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("ATOMIC-GOAL-CACHE", "(DEFCLASS ATOMIC-GOAL-CACHE (STANDARD-OBJECT) :DOCUMENTATION \"Cache data structure to store the result of proving an atomic\nand possibly open `proposition' relative to a set of variable `bindings'.\" :SLOTS ((GOAL-CONTEXT :TYPE CONTEXT) (TIMESTAMP :TYPE TIMESTAMP) (TRUTH-VALUE :TYPE TRUTH-VALUE) (REVERSE-POLARITY? :TYPE BOOLEAN) (PROPOSITION :TYPE PROPOSITION) (BINDINGS :TYPE GOAL-BINDINGS) (JUSTIFICATION :TYPE JUSTIFICATION) (POSITIVE-SCORE :TYPE PARTIAL-MATCH-SCORE) (NEGATIVE-SCORE :TYPE PARTIAL-MATCH-SCORE) (PREVIOUS :TYPE ATOMIC-GOAL-CACHE) (NEXT :TYPE ATOMIC-GOAL-CACHE)) :PRINT-FORM (PRINT-ATOMIC-GOAL-CACHE SELF STREAM))");
renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.powerloom.logic.AtomicGoalCache", "newAtomicGoalCache", new java.lang.Class [] {});
renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.powerloom.logic.AtomicGoalCache", "accessAtomicGoalCacheSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.AtomicGoalCache"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE});
}
{ Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("ATOMIC-GOAL-CACHE-ITERATOR", "(DEFCLASS ATOMIC-GOAL-CACHE-ITERATOR (ITERATOR) :PARAMETERS ((ANY-VALUE :TYPE ATOMIC-GOAL-CACHE)) :SLOTS ((GOAL :TYPE CONTROL-FRAME) (CACHE-LIST :TYPE ATOMIC-GOAL-CACHE)))");
renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.powerloom.logic.AtomicGoalCacheIterator", "newAtomicGoalCacheIterator", new java.lang.Class [] {});
renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.powerloom.logic.AtomicGoalCacheIterator", "accessAtomicGoalCacheIteratorSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.AtomicGoalCacheIterator"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE});
}
}
if (Stella.currentStartupTimePhaseP(6)) {
Stella.finalizeClasses();
}
if (Stella.currentStartupTimePhaseP(7)) {
Stella.defineFunctionObject("TRACE-GOAL-CACHE", "(DEFUN TRACE-GOAL-CACHE ((STRING STRING) (FRAME CONTROL-FRAME)))", Native.find_java_method("edu.isi.powerloom.logic.Logic", "traceGoalCache", new java.lang.Class [] {Native.find_java_class("java.lang.String"), Native.find_java_class("edu.isi.powerloom.logic.ControlFrame")}), null);
Stella.defineFunctionObject("REMOVE-OBSOLETE-GOAL-CACHES", "(DEFUN REMOVE-OBSOLETE-GOAL-CACHES ((TABLE (KEY-VALUE-LIST OF CONTEXT GOAL-CACHE))))", Native.find_java_method("edu.isi.powerloom.logic.Logic", "removeObsoleteGoalCaches", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.KeyValueList")}), null);
Stella.defineExternalSlotFromStringifiedSource("(DEFSLOT NAMED-DESCRIPTION GOAL-CACHE-TABLE :TYPE GOAL-CACHE-TABLE :DOCUMENTATION \"Allows attachment of goal caches to classes or slots.\" :ALLOCATION :DYNAMIC)");
Stella.defineExternalSlotFromStringifiedSource("(DEFSLOT NAMED-DESCRIPTION NEGATED-GOAL-CACHE-TABLE :TYPE GOAL-CACHE-TABLE :DOCUMENTATION \"Allows attachment of goal caches to classes or slots.\" :ALLOCATION :DYNAMIC)");
Stella.defineFunctionObject("YIELD-GOAL-BINDINGS", "(DEFUN (YIELD-GOAL-BINDINGS GOAL-BINDINGS) ((GOAL PROPOSITION)))", Native.find_java_method("edu.isi.powerloom.logic.Proposition", "yieldGoalBindings", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.Proposition")}), null);
Stella.defineFunctionObject("FIND-GOAL-CACHE-TABLE", "(DEFUN (FIND-GOAL-CACHE-TABLE GOAL-CACHE-TABLE) ((GOAL PROPOSITION)))", Native.find_java_method("edu.isi.powerloom.logic.Proposition", "findGoalCacheTable", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.Proposition")}), null);
Stella.defineFunctionObject("CREATE-GOAL-CACHE?", "(DEFUN (CREATE-GOAL-CACHE? BOOLEAN) ((FRAME CONTROL-FRAME)))", Native.find_java_method("edu.isi.powerloom.logic.ControlFrame", "createGoalCacheP", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame")}), null);
Stella.defineFunctionObject("LOOKUP-GOAL-CACHE", "(DEFUN (LOOKUP-GOAL-CACHE GOAL-CACHE) ((TABLE GOAL-CACHE-TABLE)))", Native.find_java_method("edu.isi.powerloom.logic.Logic", "lookupGoalCache", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.KeyValueList")}), null);
Stella.defineFunctionObject("FIND-GOAL-CACHE", "(DEFUN (FIND-GOAL-CACHE GOAL-CACHE) ((FRAME CONTROL-FRAME)))", Native.find_java_method("edu.isi.powerloom.logic.ControlFrame", "findGoalCache", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame")}), null);
Stella.defineFunctionObject("UPDATE-GOAL-CACHE", "(DEFUN UPDATE-GOAL-CACHE ((FRAME CONTROL-FRAME) (SUCCESS? BOOLEAN)))", Native.find_java_method("edu.isi.powerloom.logic.ControlFrame", "updateGoalCache", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), java.lang.Boolean.TYPE}), null);
Stella.defineFunctionObject("YIELD-RELATIVE-GOAL-BINDINGS", "(DEFUN (YIELD-RELATIVE-GOAL-BINDINGS GOAL-BINDINGS) ((FRAME CONTROL-FRAME)))", Native.find_java_method("edu.isi.powerloom.logic.ControlFrame", "yieldRelativeGoalBindings", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame")}), null);
Stella.defineFunctionObject("CONTINUE-CACHED-BINDINGS-PROOF", "(DEFUN (CONTINUE-CACHED-BINDINGS-PROOF KEYWORD) ((FRAME CONTROL-FRAME) (LASTMOVE KEYWORD)))", Native.find_java_method("edu.isi.powerloom.logic.ControlFrame", "continueCachedBindingsProof", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), Native.find_java_class("edu.isi.stella.Keyword")}), null);
Stella.defineFunctionObject("TOP-LEVEL-QUERY-CONTEXT?", "(DEFUN (TOP-LEVEL-QUERY-CONTEXT? BOOLEAN) ((SELF CONTEXT)))", Native.find_java_method("edu.isi.powerloom.logic.Logic", "topLevelQueryContextP", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Context")}), null);
Stella.defineFunctionObject("CACHE-QUERY-RESULTS?", "(DEFUN (CACHE-QUERY-RESULTS? BOOLEAN) () :GLOBALLY-INLINE? TRUE (RETURN (AND (OR *CACHE-SUCCEEDED-GOALS?* *CACHE-FAILED-GOALS?*) (EQL? *DUPLICATE-SUBGOAL-STRATEGY* :DUPLICATE-GOALS) (NOT (PARTIAL-MATCH-MODE?)))))", Native.find_java_method("edu.isi.powerloom.logic.Logic", "cacheQueryResultsP", new java.lang.Class [] {}), null);
Stella.defineFunctionObject("TOGGLE-GOAL-CACHING", "(DEFUN (TOGGLE-GOAL-CACHING STRING) () :COMMAND? TRUE)", Native.find_java_method("edu.isi.powerloom.logic.Logic", "toggleGoalCaching", new java.lang.Class [] {}), Native.find_java_method("edu.isi.powerloom.logic.Logic", "toggleGoalCachingEvaluatorWrapper", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}));
Stella.defineFunctionObject("PRINT-ATOMIC-GOAL-CACHE", "(DEFUN PRINT-ATOMIC-GOAL-CACHE ((SELF ATOMIC-GOAL-CACHE) (STREAM NATIVE-OUTPUT-STREAM)))", Native.find_java_method("edu.isi.powerloom.logic.AtomicGoalCache", "printAtomicGoalCache", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.AtomicGoalCache"), Native.find_java_class("org.powerloom.PrintableStringWriter")}), null);
Stella.defineFunctionObject("CLEAR-QUERY-RESULTS-CACHE", "(DEFUN CLEAR-QUERY-RESULTS-CACHE ())", Native.find_java_method("edu.isi.powerloom.logic.Logic", "clearQueryResultsCache", new java.lang.Class [] {}), null);
Stella.defineFunctionObject("PRINT-QUERY-RESULTS-CACHE", "(DEFUN PRINT-QUERY-RESULTS-CACHE ((LIMIT INTEGER)))", Native.find_java_method("edu.isi.powerloom.logic.Logic", "printQueryResultsCache", new java.lang.Class [] {java.lang.Integer.TYPE}), null);
Stella.defineFunctionObject("SUCCEEDED-GOAL-INDEX", "(DEFUN (SUCCEEDED-GOAL-INDEX INTEGER) ((FRAME CONTROL-FRAME)) :GLOBALLY-INLINE? TRUE (RETURN (HASHMOD (GOAL-HASH-CODE FRAME) 1541)))", Native.find_java_method("edu.isi.powerloom.logic.ControlFrame", "succeededGoalIndex", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame")}), null);
Stella.defineFunctionObject("FAILED-GOAL-INDEX", "(DEFUN (FAILED-GOAL-INDEX INTEGER) ((FRAME CONTROL-FRAME)) :GLOBALLY-INLINE? TRUE (RETURN (HASHMOD (GOAL-HASH-CODE FRAME) 1541)))", Native.find_java_method("edu.isi.powerloom.logic.ControlFrame", "failedGoalIndex", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame")}), null);
Stella.defineFunctionObject("GOAL-HASH-CODE", "(DEFUN (GOAL-HASH-CODE INTEGER) ((FRAME CONTROL-FRAME)))", Native.find_java_method("edu.isi.powerloom.logic.ControlFrame", "goalHashCode", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame")}), null);
Stella.defineFunctionObject("HASH-UNBOUND-GOAL-VARIABLE", "(DEFUN (HASH-UNBOUND-GOAL-VARIABLE INTEGER) ((VAR PATTERN-VARIABLE) (ARGUMENTS VECTOR) (CODE INTEGER)))", Native.find_java_method("edu.isi.powerloom.logic.PatternVariable", "hashUnboundGoalVariable", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.PatternVariable"), Native.find_java_class("edu.isi.stella.Vector"), java.lang.Integer.TYPE}), null);
Stella.defineFunctionObject("HASH-GOAL-ARGUMENT", "(DEFUN (HASH-GOAL-ARGUMENT INTEGER) ((ARG OBJECT) (CODE INTEGER)))", Native.find_java_method("edu.isi.powerloom.logic.Logic", "hashGoalArgument", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Integer.TYPE}), null);
Stella.defineExternalSlotFromStringifiedSource("(DEFSLOT NAMED-DESCRIPTION GOAL-CACHE-LIST :TYPE ATOMIC-GOAL-CACHE :DOCUMENTATION \"Points at the beginning of a chain of cached values\nfor some named description\" :ALLOCATION :DYNAMIC)");
Stella.defineFunctionObject("CACHED-GOAL-OPERATOR", "(DEFUN (CACHED-GOAL-OPERATOR SURROGATE) ((GOAL PROPOSITION)))", Native.find_java_method("edu.isi.powerloom.logic.Proposition", "cachedGoalOperator", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.Proposition")}), null);
Stella.defineFunctionObject("GET-GOAL-CACHE-LIST", "(DEFUN (GET-GOAL-CACHE-LIST ATOMIC-GOAL-CACHE) ((GOAL PROPOSITION)))", Native.find_java_method("edu.isi.powerloom.logic.Proposition", "getGoalCacheList", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.Proposition")}), null);
Stella.defineFunctionObject("SET-GOAL-CACHE-LIST", "(DEFUN (SET-GOAL-CACHE-LIST ATOMIC-GOAL-CACHE) ((GOAL PROPOSITION) (FIRSTCACHE ATOMIC-GOAL-CACHE)))", Native.find_java_method("edu.isi.powerloom.logic.Proposition", "setGoalCacheList", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.Proposition"), Native.find_java_class("edu.isi.powerloom.logic.AtomicGoalCache")}), null);
Stella.defineFunctionObject("CREATE-ATOMIC-GOAL-CACHE", "(DEFUN (CREATE-ATOMIC-GOAL-CACHE ATOMIC-GOAL-CACHE) ((FRAME CONTROL-FRAME) (CACHE ATOMIC-GOAL-CACHE) (SUCCESS? BOOLEAN)))", Native.find_java_method("edu.isi.powerloom.logic.ControlFrame", "createAtomicGoalCache", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), Native.find_java_class("edu.isi.powerloom.logic.AtomicGoalCache"), java.lang.Boolean.TYPE}), null);
Stella.defineFunctionObject("CACHE-MATCHES-GOAL?", "(DEFUN (CACHE-MATCHES-GOAL? BOOLEAN) ((CACHE ATOMIC-GOAL-CACHE) (GOAL CONTROL-FRAME) (SUCCESS? BOOLEAN) (MODE KEYWORD)))", Native.find_java_method("edu.isi.powerloom.logic.AtomicGoalCache", "cacheMatchesGoalP", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.AtomicGoalCache"), Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), java.lang.Boolean.TYPE, Native.find_java_class("edu.isi.stella.Keyword")}), null);
Stella.defineFunctionObject("GOAL-INSTANTIATES-CACHE?", "(DEFUN (GOAL-INSTANTIATES-CACHE? BOOLEAN) ((GOAL CONTROL-FRAME) (CACHE ATOMIC-GOAL-CACHE) (SUCCESS? BOOLEAN)) :GLOBALLY-INLINE? TRUE (RETURN (CACHE-MATCHES-GOAL? CACHE GOAL SUCCESS? :GOAL-INSTANTIATES-CACHE)))", Native.find_java_method("edu.isi.powerloom.logic.ControlFrame", "goalInstantiatesCacheP", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), Native.find_java_class("edu.isi.powerloom.logic.AtomicGoalCache"), java.lang.Boolean.TYPE}), null);
Stella.defineFunctionObject("CACHE-INSTANTIATES-GOAL?", "(DEFUN (CACHE-INSTANTIATES-GOAL? BOOLEAN) ((CACHE ATOMIC-GOAL-CACHE) (GOAL CONTROL-FRAME) (SUCCESS? BOOLEAN)) :GLOBALLY-INLINE? TRUE (RETURN (CACHE-MATCHES-GOAL? CACHE GOAL SUCCESS? :CACHE-INSTANTIATES-GOAL)))", Native.find_java_method("edu.isi.powerloom.logic.AtomicGoalCache", "cacheInstantiatesGoalP", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.AtomicGoalCache"), Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), java.lang.Boolean.TYPE}), null);
Stella.defineFunctionObject("DONT-CACHE-GOAL-FAILURE-BETWEEN-FRAMES", "(DEFUN DONT-CACHE-GOAL-FAILURE-BETWEEN-FRAMES ((TOPFRAME CONTROL-FRAME) (BOTTOMFRAME CONTROL-FRAME)))", Native.find_java_method("edu.isi.powerloom.logic.ControlFrame", "dontCacheGoalFailureBetweenFrames", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), Native.find_java_class("edu.isi.powerloom.logic.ControlFrame")}), null);
Stella.defineFunctionObject("CACHE-GOAL", "(DEFUN CACHE-GOAL ((FRAME CONTROL-FRAME) (SUCCESS? BOOLEAN) (KEEPFRAME? BOOLEAN) (CLOCKTICKS INTEGER)))", Native.find_java_method("edu.isi.powerloom.logic.ControlFrame", "cacheGoal", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), java.lang.Boolean.TYPE, java.lang.Boolean.TYPE, java.lang.Integer.TYPE}), null);
Stella.defineFunctionObject("FIND-CACHED-GOAL", "(DEFUN (FIND-CACHED-GOAL ATOMIC-GOAL-CACHE) ((FRAME CONTROL-FRAME) (SUCCESSORFAILURE KEYWORD)))", Native.find_java_method("edu.isi.powerloom.logic.ControlFrame", "findCachedGoal", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame"), Native.find_java_class("edu.isi.stella.Keyword")}), null);
Stella.defineFunctionObject("ALL-CACHED-PROPOSITIONS", "(DEFUN (ALL-CACHED-PROPOSITIONS ATOMIC-GOAL-CACHE-ITERATOR) ((GOAL CONTROL-FRAME)))", Native.find_java_method("edu.isi.powerloom.logic.ControlFrame", "allCachedPropositions", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.ControlFrame")}), null);
Stella.defineMethodObject("(DEFMETHOD (NEXT? BOOLEAN) ((SELF ATOMIC-GOAL-CACHE-ITERATOR)))", Native.find_java_method("edu.isi.powerloom.logic.AtomicGoalCacheIterator", "nextP", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null)));
Stella.defineFunctionObject("STARTUP-GOAL-CACHES", "(DEFUN STARTUP-GOAL-CACHES () :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.logic._StartupGoalCaches", "startupGoalCaches", new java.lang.Class [] {}), null);
{ MethodSlot function = Symbol.lookupFunction(Logic.SYM_LOGIC_STARTUP_GOAL_CACHES);
KeyValueList.setDynamicSlotValue(function.dynamicSlots, Logic.SYM_STELLA_METHOD_STARTUP_CLASSNAME, StringWrapper.wrapString("_StartupGoalCaches"), Stella.NULL_STRING_WRAPPER);
}
}
if (Stella.currentStartupTimePhaseP(8)) {
Stella.finalizeSlots();
Stella.cleanupUnfinalizedClasses();
}
if (Stella.currentStartupTimePhaseP(9)) {
Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("LOGIC")))));
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *CACHE-SUCCEEDED-GOALS?* BOOLEAN TRUE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *CACHE-FAILED-GOALS?* BOOLEAN TRUE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *CACHE-GOAL-QUANTUM* INTEGER 5 :DOCUMENTATION \"Only goals whose success or failure took at least this\nnumber of query clock ticks will be cached.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *SUCCEEDED-GOALS-CACHE* (VECTOR OF ATOMIC-GOAL-CACHE) (NEW VECTOR :ARRAY-SIZE 1541))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *FAILED-GOALS-CACHE* (VECTOR OF ATOMIC-GOAL-CACHE) (NEW VECTOR :ARRAY-SIZE 1541))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *UNIFICATION-VECTOR-1* VECTOR (NEW VECTOR :ARRAY-SIZE 10))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *UNIFICATION-VECTOR-2* VECTOR (NEW VECTOR :ARRAY-SIZE 10))");
}
} finally {
Stella.$CONTEXT$.set(old$Context$000);
Stella.$MODULE$.set(old$Module$000);
}
}
}
|
22089c01-e26b-4287-83b9-8f5cb53f6904
| 7 |
public static String doubleToString(double d) {
if (Double.isInfinite(d) || Double.isNaN(d)) {
return "null";
}
// Shave off trailing zeros and decimal point, if possible.
String string = Double.toString(d);
if (string.indexOf('.') > 0 && string.indexOf('e') < 0
&& string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
}
|
f351df05-ead8-457f-9e1f-85200652d18b
| 2 |
private Meeting getMeetingFromID(int id) {
Iterator meetingIterator = allMeetings.iterator();
Meeting nextMeeting;
while(meetingIterator.hasNext()) {
nextMeeting = (Meeting) meetingIterator.next();
if(nextMeeting.getId() == id) {
return nextMeeting;
}
}
return null;
}
|
6a8792aa-3970-4264-92e3-86f665f2396a
| 2 |
public void getMoveTarget() {
if(Application.get().getLogic().getGame().getSector(currentSector) != null) {
EnemyLocation loc = Application.get().getLogic().getGame().getSector(currentSector).getBossLocation();
if(loc != null) {
targetX = loc.x();
targetY = loc.y();
timeForNewTarget = false;
}
/*
ArrayList<EnemyLocation> possibleLocations = Application.get().getLogic().getGame().getSector(currentSector).getEnemyLocations();
int rn = Application.get().getRNG().nextInt(possibleLocations.size());
if(!possibleLocations.get(rn).taken()) {
targetX = possibleLocations.get(rn).x();
targetY = possibleLocations.get(rn).y();
currentLocation = rn;
possibleLocations.get(rn).reserve(owner);
timeForNewTarget = false;
}
*
*/
}
}
|
0c318bef-0f0b-4f78-a6e7-39e247479dcb
| 5 |
public static int[] decompileNumberInFactors(int numToDecompile){
if (isNumberFirst(numToDecompile)){
return new int[]{numToDecompile};
}
List<Integer> list = new ArrayList<Integer>();
int divisor = 0;
while (divisor < numToDecompile){
divisor++;
if (!isNumberFirst(divisor)){
continue;
}
int rest = numToDecompile % divisor;
if (rest == 0){
list.add(divisor);
numToDecompile = numToDecompile / divisor;
divisor = 0;
}
}
int[] ints = new int[list.size()];
for (int j = 0 ; j < list.size() ; j++){
ints[j] = list.get(j);
}
return ints;
}
|
1321969f-7683-4483-8579-d621c4f9ebd8
| 5 |
public void mouseDragged(MouseEvent e) {
if (!editable)
return;
if (!boardBox.contains(e.getPoint()))
return;
if (lastLineStart == null)
lastLineStart = e.getPoint();
else if (lastLineStart != null
&& e.getPoint().distance(lastLineStart) > 3) {
lastLine = new Line2D.Double(Board.fromScreenSpace(lastLineStart),
Board.fromScreenSpace(e.getPoint()));
}
repaint();
}
|
3fd9cf84-c3ed-4307-abea-216ade653eaa
| 8 |
@Test public void testUpgradeWriteDeadlock() throws Exception {
System.out.println("testUpgradeWriteDeadlock constructing deadlock:");
LockGrabber lg1Read = startGrabber(tid1, p0, Permissions.READ_ONLY);
LockGrabber lg2Read = startGrabber(tid2, p0, Permissions.READ_ONLY);
// allow read locks to acquire
Thread.sleep(POLL_INTERVAL);
LockGrabber lg1Write = startGrabber(tid1, p0, Permissions.READ_WRITE);
LockGrabber lg2Write = startGrabber(tid2, p0, Permissions.READ_WRITE);
while (true) {
Thread.sleep(POLL_INTERVAL);
assertFalse(lg1Write.acquired() && lg2Write.acquired());
if (lg1Write.acquired() && !lg2Write.acquired()) break;
if (!lg1Write.acquired() && lg2Write.acquired()) break;
if (lg1Write.getError() != null) {
lg1Read.stop(); lg1Write.stop();
bp.transactionComplete(tid1);
Thread.sleep(rand.nextInt(WAIT_INTERVAL));
tid1 = new TransactionId();
lg1Read = startGrabber(tid1, p0, Permissions.READ_ONLY);
lg1Write = startGrabber(tid1, p0, Permissions.READ_WRITE);
}
if (lg2Write.getError() != null) {
lg2Read.stop(); lg2Write.stop();
bp.transactionComplete(tid2);
Thread.sleep(rand.nextInt(WAIT_INTERVAL));
tid2 = new TransactionId();
lg2Read = startGrabber(tid2, p0, Permissions.READ_ONLY);
lg2Write = startGrabber(tid2, p0, Permissions.READ_WRITE);
}
}
System.out.println("testUpgradeWriteDeadlock resolved deadlock");
}
|
70f45b85-64b8-486b-8c07-4881d887c171
| 9 |
public String getValueAsString() {
if (value == null)
return null;
logger.debug("field is " + this.getName() + " and val is |" + value + "|");
switch (type) {
case DAOutils.STRING_TYPE:
if (this.getHtmlType() == DAOutils.Y_OR_N) {
return ((String) value).trim().equalsIgnoreCase("Y") ? "Y" : "N";
}
return (String) value;
case DAOutils.INT_TYPE:
return ((Integer) value).toString();
case DAOutils.TIMESTAMP_TYPE:
return ((Timestamp) value).toString();
case DAOutils.FLOAT_TYPE:
return ((Float) value).toString();
case DAOutils.DATE_TYPE:
return ((Date) value).toString();
case DAOutils.PASSWORD_TYPE:
return (String) value;
}
logger.debug("should never be here");
return "";
}
|
69c11da7-dc0f-400e-9554-415cad4325c6
| 4 |
public void flush(){
LinkedList<PlayerReinforcement> toSave = new LinkedList<PlayerReinforcement>();
LinkedList<PlayerReinforcement> toDelete = new LinkedList<PlayerReinforcement>();
for (PlayerReinforcement pr : pendingDbUpdate) {
if (pr.getDbAction() == DbUpdateAction.DELETE) {
toDelete.add(pr);
} else { // INSERT or SAVE
toSave.add(pr);
}
pr.setDbAction(DbUpdateAction.NONE);
}
pendingDbUpdate.clear();
if (toSave.size() > 0) {
dao.addCounterReinforcementsSaved(
AttemptSave(toSave));
}
if (toDelete.size() > 0) {
dao.addCounterReinforcementsDeleted(
AttemptDelete(toDelete));
}
}
|
657ea795-ed57-41aa-b476-bbdc2d14114f
| 5 |
@Override
public void afterPhase(PhaseEvent event) {
// TODO Auto-generated method stub
System.out.println("Inside phase listner");
FacesContext facesContext = event.getFacesContext();
String currentUser = facesContext.getViewRoot().getViewId();
boolean isLoginPage = (currentUser.lastIndexOf("index.jsp") > -1);
HttpSession session = (HttpSession) facesContext.getExternalContext()
.getSession(false);
if (session == null) {
System.out.println("session is null");
NavigationHandler nh = facesContext.getApplication()
.getNavigationHandler();
nh.handleNavigation(facesContext, null, "index");
}
if (!isLoginPage && (currentUser == null || currentUser == "")) {
{
String userId = (String) session.getAttribute("username");
if (userId == null) {
System.out.println("session is null");
NavigationHandler nh = facesContext.getApplication()
.getNavigationHandler();
nh.handleNavigation(facesContext, null, "index");
}
}
}
}
|
558c67d9-06f0-4c09-92ab-c1d692c6c9f2
| 2 |
private static void loadFinished(HashSet<Long> finished) throws Exception {
ArrayList<File> finishedList = new ArrayList<File>(Arrays.asList(new File("./Finished/").listFiles()));
int cnt = 0;
for (File file : finishedList) {
BufferedReader buff = new BufferedReader(new FileReader(file));
String id;
int i = 0;
while ((id = buff.readLine()) != null) {
finished.add(new Long(id));
cnt++;
i++;
}
System.out.println(file.getName() + " " + i);
buff.close();
}
System.out.println("\n" + cnt + " finished user loaded.");
System.out.println(finished.size() + " Unique users");
}
|
255f5b54-4d38-4236-9cb1-10d1ffb60ffc
| 6 |
@Override
protected void xMovement(double time) {
if (!xObstacleAhead(time)) {
if (currentCoord.getX() + 30 > 800) {
if (AppFrame.incFrameNumber()) {
currentCoord.setX(0);
} else {
gameOver = true;
}
} else if (currentCoord.getX() < 0) {
if (AppFrame.decFrameNumber()) {
currentCoord.setX(800 - 60);
} else {
currentCoord.setX(0);
}
} else {
if (!(XForces.size() == 0)) {
currentCoord.setX(currentCoord.getX() + (int) Math.round(currentHorizontalSpeed * time));
currentHorizontalSpeed = currentHorizontalSpeed
+ Mechanics.countResultAcceleration(this.mass, XForces.values()) * time;
} else {
currentCoord.setX(currentCoord.getX() + (int) Math.round(heroOwnHorizontalSpeed * time));
}
}
}
}
|
4384904a-d080-4896-943c-b197ac914b10
| 6 |
public static void main(String args[])
{
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try
{
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
{
if ("Nimbus".equals(info.getName()))
{
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex)
{
java.util.logging.Logger.getLogger(NewDiagDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex)
{
java.util.logging.Logger.getLogger(NewDiagDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex)
{
java.util.logging.Logger.getLogger(NewDiagDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex)
{
java.util.logging.Logger.getLogger(NewDiagDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
NewDiagDialog dialog = new NewDiagDialog(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter()
{
@Override
public void windowClosing(java.awt.event.WindowEvent e)
{
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
|
2b408c93-3d83-4252-a136-4c3346aaf152
| 4 |
private void onOpen() {
logger.fine("socket open");
this.readyState = ReadyState.OPEN;
Socket.priorWebsocketSuccess = WebSocket.NAME.equals(this.transport.name);
this.emit(EVENT_OPEN);
this.flush();
if (this.readyState == ReadyState.OPEN && this.upgrade && this.transport instanceof Polling) {
logger.fine("starting upgrade probes");
for (String upgrade: this.upgrades) {
this.probe(upgrade);
}
}
}
|
7fd25b02-cb48-4ccd-bcf6-c39469e853cd
| 7 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Piece other = (Piece) obj;
if (canCastle != other.canCastle)
return false;
if (color != other.color)
return false;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
|
681b57c6-98ad-4471-aafd-edd2d274bb2f
| 9 |
static public OTAMessageIntf recv(DataInputStream input) throws Exception{
OTAMessageIntf msg = null;
int ret = 0;
try {
byte [] header_temp = new byte[header_size];
ret = input.read(header_temp);
if(ret == -1)
throw new Exception ("Socket read failed - header");
OTAMessageHeader header = new OTAMessageHeader(header_temp);
switch((byte)header.getMessage_type())
{
case MOBILE_ORIGINATED_EVENT:
msg = new OTAMessageMOE(header);
break;
case MOBILE_ORIGINATED_ACK:
msg = new OTAMessageMOA(header);
break;
case MOBILE_TERMINATED_EVENT:
msg = new OTAMessageMTE(header);
break;
case MOBILE_TERMINATED_ACK:
msg = new OTAMessageMTA(header);
break;
default:
throw new Exception("UNRECOGNIZED MESSAGE");
}
msg.readObjs(input);
int in_crc = input.read();
if(in_crc == -1)
throw new Exception ("Socket read failed - crc");
//int my_crc = (int) msg.updateCRC();
byte recvCRC = (byte) (in_crc & 0x000000FF);
byte myCRC = msg.updateCRC();
if (recvCRC != myCRC)
throw new Exception (" Mismatched crc. Recvd CRC = " + recvCRC + ", My CRC = " + myCRC);
}
catch (IOException e)
{
throw e;
}
catch (Exception e)
{
throw e;
}
return msg;
}
|
ceab581c-9850-47a3-87a9-44283e255ffc
| 8 |
public static Stella_Object uMinusConstraint(IntegerWrapper missingArgument, DimNumberLogicWrapper x1, DimNumberLogicWrapper x2, DimNumberLogicWrapper x3) {
{ Stella_Object value = null;
switch (missingArgument.wrapperValue) {
case -1:
value = (Stella_Object.eqlP(((DimNumber)(x1.wrapperValue)).subtract(((DimNumber)(x2.wrapperValue))), ((DimNumber)(x3.wrapperValue))) ? Stella.TRUE_WRAPPER : Stella.FALSE_WRAPPER);
break;
case 0:
value = (((DimNumber)(x3.wrapperValue)).pid.objectEqlP(((DimNumber)(x2.wrapperValue)).pid) ? Units.wrapDimNumber(((DimNumber)(x3.wrapperValue)).add(((DimNumber)(x2.wrapperValue)))) : null);
break;
case 1:
value = (((DimNumber)(x3.wrapperValue)).pid.objectEqlP(((DimNumber)(x1.wrapperValue)).pid) ? Units.wrapDimNumber(((DimNumber)(x1.wrapperValue)).subtract(((DimNumber)(x3.wrapperValue)))) : null);
break;
case 2:
value = (((DimNumber)(x1.wrapperValue)).pid.objectEqlP(((DimNumber)(x2.wrapperValue)).pid) ? Units.wrapDimNumber(((DimNumber)(x1.wrapperValue)).subtract(((DimNumber)(x2.wrapperValue)))) : null);
break;
default:
break;
}
return (value);
}
}
|
d34fe03e-59c0-4c1a-b329-d470463a4c16
| 3 |
public RPC() {
setupEventListeners();
/**
* Thread will endlessly call executeNext() method
*/
// TODO: Move out from RPC
thread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
// TODO: run CheckVersion to determine connection state, and only then fire CE event
Logger.getInstance().info("RPC thread (re)started");
EventBusFactory.getDefault().fire(new RpcThreadStartedEvent());
EventBusFactory.getDefault().fire(new ConnectionEstablishedEvent());
while (true) {
Logger.getInstance().info("executeNext");
executeNext();
}
} catch (InterruptedException e) {
// Do nothing. Just continue loop.
}
}
}
}, "RPC worker");
clientConfig = new XmlRpcClientConfigImpl();
client = new XmlRpcClient();
client.setTypeFactory(new ESTypeFactoryImpl(client));
loadConfig();
//TODO: is it needed?
//thread.setDaemon(true);
thread.start();
}
|
115dd7fc-c608-4198-aac3-8a79a73fa456
| 5 |
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Projet)) {
return false;
}
Projet other = (Projet) object;
if ((this.num == null && other.num != null) || (this.num != null && !this.num.equals(other.num))) {
return false;
}
return true;
}
|
83746b3f-a5d2-4f11-a5c4-376e6f382da4
| 7 |
public void act() {
jMan.act(this);
jMan.setActed(true);
// Make every other piece act.
for (int i= 0; i < width; i= i+1){
for (int j= 0; j < height; j= j+1){
Piece p= board[i][j];
if (p != null && !p.hasActed()){
p.act(this);
p.setActed(true);
}
}
}
// Set all the act flags to false.
for (int i= 0; i < width; i= i+1){
for (int j= 0; j < height; j= j+1){
Piece piece = board[i][j];
if (piece != null){
piece.setActed(false);
}
}
}
}
|
dbd49a24-7de6-45e9-9daa-cdce22aad5a2
| 7 |
private boolean objectSelection(FrameBuffer buffer) {
PhysObject3D obj;
SimpleVector objCenBuf;
SimpleVector objBound;
SimpleVector shiftCenObj;
Enumeration<PhysObject3D> objs = gameWorld.getWorld().getObjects();
float radius;
while (objs.hasMoreElements()) {
obj = objs.nextElement();
float fov = convertRADAngleIntoFOV(obj.getTransformedCenter().calcSub(getPosition()).calcAngle(getDirection()));
if(fov <= cam.getMaxFOV()) {
objCenBuf = Interact2D.projectCenter3D2D(buffer, obj);
if((objCenBuf.x > 0 && objCenBuf.x < width) && (
objCenBuf.y > 0 && objCenBuf.y < height)) {
shiftCenObj = cam.getSideVector();
shiftCenObj.scalarMul(obj.getCharacteristicSize()[0]);
objBound = obj.getTransformedCenter().calcAdd(shiftCenObj);
radius = objCenBuf.calcSub(Interact2D.project3D2D(cam, buffer, objBound)).length();
if(objCenBuf.calcSub(new SimpleVector(mouseListener.getMouseX(),
mouseListener.getMouseY(), 0)).length() < radius) {
gameWorld.setSelectObject(obj);
return true;
}
}
}
}
return false;
}
|
008b90ca-007c-4dd2-a48f-2ef4cab64492
| 3 |
private static void readXmlData() {
setXmlFolder();
accountings = new Accountings(xmlFolder, xslFolder, htmlFolder);
if(!xmlFolder.exists()){
xmlFolder.mkdirs();
}
File subFolder = new File(xmlFolder, Accountings.ACCOUNTINGS);
if(!subFolder.exists()){
subFolder.mkdir();
}
File file = new File(xmlFolder, "Accountings.xml");
if(file.exists()){
XMLReader.readCollection(accountings, xmlFolder);
}
}
|
c3b601ca-e13c-4765-a216-c0d0c1283016
| 9 |
private synchronized void check(MarketState ms) throws InvalidMarketStateTransition {
if (state == MarketState.CLOSED) {
if (ms == MarketState.OPEN) {
throw new InvalidMarketStateTransition("InvalidMarketStateTransition: Market cannot go directly from CLOSED to OPEN.");
} else if (ms == MarketState.CLOSED) {
throw new InvalidMarketStateTransition("InvalidMarketStateTransition: Market is already CLOSED.");
}
} else if (state == MarketState.OPEN) {
if (ms == MarketState.PREOPEN) {
throw new InvalidMarketStateTransition("InvalidMarketStateTransition: Market cannot go from OPEN to PREOPEN.");
} else if (ms == MarketState.OPEN) {
throw new InvalidMarketStateTransition("InvalidMarketStateTransition: Market is already OPEN.");
}
} else if (state == MarketState.PREOPEN) {
if (ms == MarketState.CLOSED) {
throw new InvalidMarketStateTransition("InvalidMarketStateTransition: Market cannot go from PREOPEN to CLOSED.");
} else if (ms == MarketState.PREOPEN) {
throw new InvalidMarketStateTransition("InvalidMarketStateTransition: Market is already PREOPEN.");
}
} else {
//return the market state Transition is correct.
}
}
|
7de5d448-a5f2-4b33-8314-2863c406ff52
| 8 |
public Dumper(InputStream cramIS, ReferenceSource referenceSource, int nofStreams, String fastqBaseName,
boolean gzip, long maxRecords, boolean reverse, int defaultQS, AtomicBoolean brokenPipe)
throws IOException {
this.cramIS = cramIS;
this.referenceSource = referenceSource;
this.maxRecords = maxRecords;
this.reverse = reverse;
this.brokenPipe = brokenPipe;
outputs = new FileOutput[nofStreams];
for (int index = 0; index < outputs.length; index++)
outputs[index] = new FileOutput();
if (fastqBaseName == null) {
OutputStream joinedOS = System.out;
if (gzip)
joinedOS = (new GZIPOutputStream(joinedOS));
for (int index = 0; index < outputs.length; index++)
outputs[index].outputStream = joinedOS;
} else {
String extension = ".fastq" + (gzip ? ".gz" : "");
String path;
for (int index = 0; index < outputs.length; index++) {
if (index == 0)
path = fastqBaseName + extension;
else
path = fastqBaseName + "_" + index + extension;
outputs[index].file = new File(path);
OutputStream os = new BufferedOutputStream(new FileOutputStream(outputs[index].file));
if (gzip)
os = new GZIPOutputStream(os);
outputs[index].outputStream = os;
}
}
}
|
71e5c1cd-3179-4879-9f0f-de701f335336
| 1 |
public static void main(String[] args) {
Path zipFile = Paths.get("/home/xander/test/zippy.zip");
Path jarFile = Paths.get("/home/xander/test/zippy.jar");
try (FileSystem zipFileSys = FileSystems.newFileSystem(zipFile, null)) {
Files.deleteIfExists(Paths.get("/home/xander/test/passageExtracted.txt"));
Files.copy(zipFileSys.getPath("passage.txt"), Paths.get("/home/xander/test/passageExtracted.txt"));
Path plainFile = Paths.get("/home/xander/test/passageToZip.txt");
Files.deleteIfExists(zipFileSys.getPath("newFile.txt"));
Files.copy(plainFile, zipFileSys.getPath("newFile.txt"));
} catch (IOException e) {
e.printStackTrace();
}
}
|
cf0468f2-2acf-4597-af35-617cb145233f
| 1 |
@Override
@Command
public MessageResponse readQuorum() throws IOException {
if(initRMI()) return proxyRMI.readQuorum();
else return new MessageResponse("Cannot connect to Proxy via RMI");
}
|
4e8fcb68-edcc-41bd-98ae-6c5413f0b912
| 1 |
private double[] calculateCognitiveVelocity(int particle, double r1) {
double[] cognitiveVelocity = new double[position[particle].length];
for(int k = 0; k < cognitiveVelocity.length; k++){
cognitiveVelocity[k] = cognitiveConstant * r1 * (personalBest[particle][k] - position[particle][k]);
}
return cognitiveVelocity;
}
|
132e9372-8397-4c2a-a667-6f90e8a64c80
| 2 |
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onEntityRegainHealth(EntityRegainHealthEvent event) {
Entity entity = event.getEntity();
if (entity instanceof Player) {
xAuthPlayer xp = plyrMngr.getPlayer(((Player) entity).getName());
if (plyrMngr.isRestricted(xp, event))
event.setCancelled(true);
}
}
|
27ee06d1-6ba0-43d6-8495-0303fe679275
| 8 |
private void handleAction() {
if (actionButton.getText().equals("Find IP")) {
Integer ip = dnsDB.findIP(nameText.getText());
if (ip == null) {
JOptionPane.showMessageDialog(GUI.this,
"Could not find an IP address with host name: "
+ nameText.getText());
} else {
ipText.setText(DNSDB.IPToString(ip));
}
} else if (actionButton.getText().equals("Find Host Name")) {
Integer ip = DNSDB.stringToIP(ipText.getText());
if (ip == null) {
JOptionPane.showMessageDialog(GUI.this, "'" + ipText.getText()
+ "' is not a valid IP address.");
} else {
String name = dnsDB.findHostName(ip);
if (name == null) {
JOptionPane.showMessageDialog(GUI.this,
"Could not find a host name with IP address: "
+ ipText.getText());
} else {
nameText.setText(name);
}
}
} else if (actionButton.getText().equals("Test Name-IP Pair")) {
Integer ip = DNSDB.stringToIP(ipText.getText());
if (ip == null) {
JOptionPane.showMessageDialog(GUI.this, "'" + ipText.getText()
+ "' is not a valid IP address.");
} else {
boolean valid = dnsDB.testPair(ip, nameText.getText());
if (valid) {
JOptionPane.showMessageDialog(
GUI.this,
"'" + ipText.getText()
+ "' is correctly mapped to '"
+ nameText.getText() + "'.");
} else {
JOptionPane.showMessageDialog(GUI.this,
"'" + ipText.getText()
+ "' is not the IP address for '"
+ nameText.getText() + "'.");
}
}
}
}
|
7c7e5a4a-3bc4-4d88-9280-972dd3b2d2e9
| 8 |
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException, IOException {
if(args.length == 0) {
Updater.update();
} else {
new File("Updater.jar").delete();
}
os = System.getProperty("os.name").toLowerCase().contains("win") ? OS.WINDOWS
: System.getProperty("os.name").toLowerCase().contains("mac") ? OS.MAC
: System.getProperty("os.name").toLowerCase().contains("linux") ? OS.LINUX // Why did I even include Linux? Essentials isn't available on Linux.
: null;
if(os == null) {
JOptionPane.showMessageDialog(window, "Error determining OS.", "", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
switch(os) {
case WINDOWS:
break;
case MAC:
System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Essentials Launcher");
break;
case LINUX:
JOptionPane.showMessageDialog(window, "Linux not implemented.");
System.exit(0);
break;
}
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new EssentialsLauncher();
}
|
b6b2df7d-7961-401b-a369-762905016662
| 5 |
public final double grad(int par1, double par2, double par4)
{
int j = par1 & 15;
double d2 = (double)(1 - ((j & 8) >> 3)) * par2;
double d3 = j < 4 ? 0.0D : (j != 12 && j != 14 ? par4 : par2);
return ((j & 1) == 0 ? d2 : -d2) + ((j & 2) == 0 ? d3 : -d3);
}
|
533e532f-8398-47e0-87f4-5a22f98517c4
| 2 |
public ArrayList<ObjectMap> listeObjet (){
ArrayList<ObjectMap> l = new ArrayList<ObjectMap>();
for(int i = 0 ; i < this.personne.size(); i++){
l.add((ObjectMap)this.personne.get(i));
}
if(this.objet != null){
l.add(this.objet);
}
return l;
}
|
9f6dc405-6b41-45e5-a01e-687227223750
| 9 |
@Override
public void update() {
Action action = this.ctrl.action(this.game);
d.rotate(action.turn*STEER_RATE*Constants.DT);
//calc new v
v.add(d, MAG_ACC*Constants.DT*action.thrust);
v.mult(LOSS);
s.add(v, Constants.DT);
s.wrap(Constants.WORLD_WIDTH, Constants.WORLD_HEIGHT);
if (action.shoot && lastShot == 0) {
shootBullet();
lastShot = 20;
}
if (action.thrust == -1) {
SoundManager.play(SoundManager.thrust);
thrustParticles();
}
if (action.energyShield && !shield.active && shield.hasEnergy()) shield.activate();
else if (!action.energyShield && shield.active) shield.deactivate();
if (lastShot > 0) lastShot--;
}
|
f273e7d3-bcde-41a6-ac73-1bd4b875ad4d
| 6 |
public static int dehexchar(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - ('A' - 10);
}
if (c >= 'a' && c <= 'f') {
return c - ('a' - 10);
}
return -1;
}
|
4a25fa75-320d-4d2f-9b8d-46c64ef7577f
| 4 |
public static Matrix createSubMatrix(Matrix matrix, int excluding_row, int excluding_column) {
int rows = matrix.getRowDimension();
int columns = matrix.getColumnDimension();
Matrix subMatrix = new Matrix(rows - 1, columns - 1);
int r = -1;
for (int i = 0; i < rows; ++i) {
if (i == excluding_row)
continue;
++r;
int c = -1;
for (int j = 0; j < columns; ++j) {
if (j == excluding_column)
continue;
subMatrix.set(r, ++c, matrix.get(i, j));
}
}
return subMatrix;
}
|
e17463f4-6453-4800-9afb-bcca6e8f7bfa
| 5 |
public void characters(char buf[], int offset, int len) throws SAXException {
String s = new String(buf, offset, len);
if (!s.trim().equals("") && importType == "STRANGEBREW") {
// SBWin uses gr instead of g, fix it:
if (s.trim().equalsIgnoreCase("gr"))
s="g";
sbCharacters(s.trim());
}
else if (!s.trim().equals("") && importType == "QBREW") {
qbCharacters(s.trim());
}
}
|
4432e615-d80f-4441-a01e-a5125c73da71
| 0 |
public final int getBits() { return bits; }
|
a8683024-34b5-4e64-9d2a-953997bd301e
| 2 |
public ItemList() {
setTitle("Item List");
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setBounds(100, 100, 325, 500);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(new BorderLayout(0, 0));
{
JScrollPane scrollPane = new JScrollPane();
contentPanel.add(scrollPane, BorderLayout.CENTER);
{
list = new JList<String>();
list.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if(e.getClickCount() == 2 && !e.isConsumed()) {
makeSelection();
}
}
});
list.setModel(buildList());
scrollPane.setViewportView(list);
}
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
makeSelection();
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
setModalityType(ModalityType.APPLICATION_MODAL);
setVisible(true);
}
|
78852a3a-eb52-43bd-8a22-2f79b76d236a
| 0 |
@Override
public void gameRenderMobs() {
}
|
8b04e4d9-f355-4eaf-937c-a4540c7e4254
| 5 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GeoPoint geoPoint = (GeoPoint) o;
if (Double.compare(geoPoint.lat, lat) != 0) return false;
if (Double.compare(geoPoint.lon, lon) != 0) return false;
return true;
}
|
3bfadb0d-832c-4da7-87a4-be9c62de7054
| 2 |
public Object clone() {
try {
VariableSet other = (VariableSet) super.clone();
if (count > 0) {
other.locals = new LocalInfo[count];
System.arraycopy(locals, 0, other.locals, 0, count);
}
return other;
} catch (CloneNotSupportedException ex) {
throw new alterrs.jode.AssertError("Clone?");
}
}
|
3a828dce-3626-4db1-a2e4-2f67d1a2e063
| 4 |
public void addControlLogic() {
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (commandPanel != null) {
String filter = commandPanel.getCommandLine();
chainPanel.addFilter(filter);
}
}
});
insertAboveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (commandPanel != null) {
String filter = commandPanel.getCommandLine();
chainPanel.insertAbove(filter);
}
}
});
insertBelowButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (commandPanel != null) {
String filter = commandPanel.getCommandLine();
chainPanel.insertBelow(filter);
}
}
});
replaceButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (commandPanel != null) {
String filter = commandPanel.getCommandLine();
chainPanel.replaceFilter(filter);
}
}
});
deleteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
chainPanel.deleteFilter();
}
});
}
|
426b6307-6f51-4317-8778-9a16ce8fa3fe
| 3 |
private void runRouteCalculation()
{
if (fromNode != null && toNode != null)
{
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
wGraph.runDij(fromNode, toNode, isFastestRoute);
if (wGraph.hasRoute(toNode))
{
mapComponent.setRouteNodes(wGraph.calculateRoute(toNode));
printRoute.setEnabled(true);
displayDirections();
}
else
{
mapComponent.setRouteNodes(new ArrayList<Node>());
printRoute.setEnabled(false);
}
setCursor(Cursor.getDefaultCursor());
}
}
|
5331cebf-73e4-441f-a551-c587b50bdc7c
| 0 |
public void setCount(Integer count) {
this.count = count;
}
|
06c41513-3fff-4a67-adaa-969d68bf79e0
| 7 |
StringBuilder makeTotalScoreLine() {
StringBuilder stringBuilder = new StringBuilder();
calcScore();
if (nowFrame == 0) {
if (frameList.get(nowFrame).isFirstShotStrike())
stringBuilder.append(makeEachFrameScore(nowFrame));
else if (frameList.get(nowFrame).isSecondShotSpare())
stringBuilder.append(makeEachFrameScore(nowFrame));
else
stringBuilder.append(makeEachFrameScore(nowFrame + 1));
}
if (nowFrame > 0) {
if (frameList.get(nowFrame).isFirstShotStrike()) {
if (frameList.get(nowFrame-1).isFirstShotStrike())
stringBuilder.append(makeEachFrameScore(nowFrame - 1));
else
stringBuilder.append(makeEachFrameScore(nowFrame));
}
else if (frameList.get(nowFrame).isSecondShotSpare()) {
stringBuilder.append(makeEachFrameScore(nowFrame));
}
else
stringBuilder.append(makeEachFrameScore(nowFrame + 1));
}
return stringBuilder;
}
|
c005567a-a9dc-498d-84dc-2e519a5e3731
| 2 |
private static void createAndShowGUI() {
// GUI Look And Feel
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ignored) { }
JFrame frame = new JFrame("JCount");
frame.setLayout(new GridLayout(NUM_PANELS, 1));
for (int i = 0; i < NUM_PANELS; i++) {
JCount counter = new JCount();
counter.worker = counter.new WorkerThread(0,0);
frame.add(counter.panel);
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
|
285f2495-afe3-47a9-a236-6af71c2f67bc
| 4 |
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Geef de maand die onderzocht wordt (getal van 1 tot 12)");
int maand = scanner.nextInt();
if (maand >= 1 && maand <= 12) {
try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
PreparedStatement statement = connection.prepareStatement(SELECT_SQL)) {
statement.setInt(1, maand);
try (ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
System.out.println(resultSet.getDate("verkochtsinds") + " " + resultSet.getString("naam"));
}
}
} catch (SQLException ex) {
System.out.println(ex);
}
} else {
System.out.println("Geef een correcte maand op.");
}
}
}
|
ed176e54-e607-4c85-bfab-8385a94c4224
| 3 |
private double arrondir(double nombre) {
if(nombre != Double.NEGATIVE_INFINITY && nombre != Double.POSITIVE_INFINITY && nombre != Double.NaN){
double n = nombre * Math.pow(10, arrondissement);
n = Math.round(n);
n = n / Math.pow(10, arrondissement);
return n;
}
return nombre;
}
|
33ff66fd-9d60-439c-8e0f-16f50276b135
| 8 |
private int animationToInt(AllEnum.AnimationCommands commands){
if(commands == AllEnum.AnimationCommands.PUNCH1){
return 1;
}
if(commands == AllEnum.AnimationCommands.PUNCH2){
return 2;
}
if(commands == AllEnum.AnimationCommands.KICK1){
return 3;
}
if(commands == AllEnum.AnimationCommands.PUSH1){
return 4;
}
if(commands == AllEnum.AnimationCommands.PALM1){
return 5;
}
if(commands == AllEnum.AnimationCommands.PUSHKICK1){
return 6;
}
if(commands == AllEnum.AnimationCommands.RHKICK1){
return 7;
}
if(commands == AllEnum.AnimationCommands.POWER1){
return 8;
}
return 0;
}
|
9444fb2e-055f-4bca-9cbf-d846a707a3c4
| 9 |
@DataProvider(name = "neighbors")
public Object[][] neighborsData() {
List<Object[]> neighbors = new ArrayList<Object[]>();
for (int a = 0; a < 2; a++) {
for (int b = 0; b < 2; b++) {
for (int c = 0; c < 2; c++) {
for (int d = 0; d < 2; d++) {
for (int e = 0; e < 2; e++) {
for (int f = 0; f < 2; f++) {
for (int g = 0; g < 2; g++) {
for (int h = 0; h < 2; h++) {
for (int i = 0; i < 2; i++) {
neighbors.add(new Object[] {
new int[][] { { a, b, c },
{ d, e, f },
{ g, h, i } },
b + d + e,
a + c + d + e + f,
a + b + c + d + f + g + h
+ i,
b + c + e + h + i,
e + f + h });
}
}
}
}
}
}
}
}
}
return neighbors.toArray(new Object[][] {});
}
|
24a5f7cf-6f38-4c76-917e-e3108c201265
| 1 |
private boolean judgeConverge (int color) {
Matrix[] lambdaMat = lambda.getMatrix();
Matrix[] diagMat = diag.getMatrix();
Matrix[] residueMat = residue.getMatrix();
double diff = reshapedProductUVBaseMat[color].times(diagMat[color]).plus(residueMat[color]).minus(stackedToOneColMat[color]).norm2()/stackedToOneColMat[color].norm2();
// test
// if (color == 0) {
// // System.out.println(iter[color]);
// // System.out.println(diff);
// System.out.println(residueMat[color].norm1());
// }
if (diff < tolerance) {
System.out.println("Color: "+color);
System.out.println("iterating times = "+iter[color]);
System.out.println("Norm2Diff = "+diff);
System.out.println("Norm1 = "+residueMat[color].norm1()+"\n\n");
return true;
}
else {
return false;
}
}
|
8b945000-340a-4459-937b-f745a95a6a15
| 3 |
public TuringTrimmingTester(String filename)
{
int index=0;
Scanner sc;
prods=new Production[42];
try {
sc = new Scanner(new File(filename));
while (sc.hasNextLine())
{
String line=sc.nextLine()+" ";
String[] aa=line.split("->");
Production p=new Production(aa[0], aa[1]);
prods[index]=p;
index++;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
trim();
System.out.println("New Productions");
for (int i=0; i<prods.length; i++)
{
System.out.println(prods[i].getLHS()+"->"+prods[i].getRHS());
}
}
|
dab7bf3c-7cfa-4bc2-8abc-6f84ba2ea5b6
| 6 |
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Grafico.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Grafico.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Grafico.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Grafico.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Grafico().setVisible(true);
}
});
}
|
7e47e95e-496a-4071-a8cb-8e36d5e70cd1
| 8 |
public Boolean process() {
// Admin permission
if(!plugin.permission.canCreate(player)) {
noPermission();
return true;
}
// Valid command format
if(args.length == 2) {
// List slot machines
if(args[1].equalsIgnoreCase("slots")) {
sendMessage("Registered slot machines:");
for(SlotMachine slot : plugin.slotData.getSlots()) {
// If not admin, list only owned by player
if(isOwner(slot)) {
Block b = slot.getController();
String c = b.getX()+ "," +b.getY()+ "," +b.getZ();
sendMessage(slot.getName() + " - type: " + slot.getType() + " - owner: " + slot.getOwner() + " - managed: " + slot.isManaged().toString() +" @ " + c);
}
}
}
// List types
else if(args[1].equalsIgnoreCase("types")) {
sendMessage("Available types:");
for(Type type : plugin.typeData.getTypes()) {
// If not admin, list only permitted types
if(plugin.permission.canCreate(player, type)) {
sendMessage(type.getName() + " - cost: " + type.getCost());
}
}
}
// Invalid args
else {
sendMessage("Usage:");
sendMessage("/casino list slots - List slot machines");
sendMessage("/casino list types - List types");
}
}
// Incorrect command format
else {
sendMessage("Usage:");
sendMessage("/casino list slots - List slot machines");
sendMessage("/casino list types - List types");
}
return true;
}
|
305b8862-a810-4652-96de-4b72048ea96d
| 2 |
public MiniXMLToken getTokenAttributeName(MiniXMLToken oMiniXMLToken) {
oMiniXMLToken.setType(tAttrName);
while (true) {
if (!isNameChar(testNext()))
return oMiniXMLToken;
oMiniXMLToken.append(getNext());
}
}
|
9f7a6893-cfe5-4690-9001-4f5afb0227d5
| 7 |
public void rotarAtrasDerecha() {
if (direccion.equals(Direccion.derecha)) {
rotar(tipoTrans.enZ, -45);
} else if (direccion.equals(Direccion.adelante)) {
rotar(tipoTrans.enZ, -135);
} else if (direccion.equals(Direccion.atras)) {
rotar(tipoTrans.enZ, 45);
} else if (direccion.equals(Direccion.izquierda)) {
rotar(tipoTrans.enZ, 135);
} else if (direccion.equals(Direccion.atIzq)) {
rotar(tipoTrans.enZ, 90);
} else if (direccion.equals(Direccion.adDer)) {
rotar(tipoTrans.enZ, -90);
} else if (direccion.equals(Direccion.adIzq)) {
rotar(tipoTrans.enZ, 180);
}
direccion = Direccion.atDer;
}
|
7aac81ce-c01c-4182-a712-1dad3b19bf49
| 0 |
private static CategoryDataset getDataSet() {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(100, "北京", "苹果");
dataset.addValue(100, "上海", "苹果");
dataset.addValue(100, "广州", "苹果");
dataset.addValue(200, "北京", "梨子");
dataset.addValue(200, "上海", "梨子");
dataset.addValue(200, "广州", "梨子");
dataset.addValue(300, "北京", "葡萄");
dataset.addValue(300, "上海", "葡萄");
dataset.addValue(300, "广州", "葡萄");
dataset.addValue(400, "北京", "香蕉");
dataset.addValue(400, "上海", "香蕉");
dataset.addValue(400, "广州", "香蕉");
dataset.addValue(500, "北京", "荔枝");
dataset.addValue(500, "上海", "荔枝");
dataset.addValue(500, "广州", "荔枝");
return dataset;
}
|
bb873dc5-a4ba-4e2c-b7fd-458329e2a6e9
| 0 |
public String getContent(){
return this.content;
}
|
e956af83-bbc9-4fcd-8446-862639542aec
| 7 |
private MyGraph greedyCoverRandom(MyGraph network, double factor) {
ArrayList<MyEdge> candidateEdges = new ArrayList<MyEdge>(
network.getEdges());
for (MyEdge edge : candidateEdges) {
double w = edge.getWeight() + factor;
edge.setWeight(w);
}
ArrayList<MyEdge> chosenEdges = new ArrayList<MyEdge>();
MyGraph cover = new MyGraph(network.getNodes(), chosenEdges);
for (MyNode n : cover.getNodes()) {
n.setAdj(new ArrayList<MyNode>());
}
HashMap<MyNode, MyNode> twins = new HashMap<MyNode, MyNode>();
for (MyNode n : network.getNodes()) {
twins.put(n, n);
}
IdComparator comparatorId = new IdComparator();
weightComparator comparatorW = new weightComparator();
Collections.sort(candidateEdges, comparatorId);// ID sorting
Collections.shuffle(candidateEdges);
Collections.sort(candidateEdges, comparatorW);// weight sorting
Collections.reverse(candidateEdges);
while (!candidateEdges.isEmpty()) {
MyEdge candidate = candidateEdges.get(0);
MyNode source = candidate.getSource();
MyNode target = candidate.getTarget();
if (twins.get(source) == target) {
candidateEdges.remove(candidate);
} else {
cover.addEdge(candidate);
MyNode ps = twins.get(source);
MyNode pt = twins.get(target);
twins.put(ps, pt);
twins.put(pt, ps);
if (cover.nodeFromId(target.getId()).getDegree() > 1) {
ArrayList<MyEdge> a = network.inoutEdges(target);
candidateEdges.removeAll(a);
} else {
candidateEdges.remove(candidate);
}
if (cover.nodeFromId(source.getId()).getDegree() > 1) {
ArrayList<MyEdge> b = network.inoutEdges(source);
candidateEdges.removeAll(b);
} else {
candidateEdges.remove(candidate);
}
}
}
return cover;
}
|
0b3c240a-f8a2-4b44-9f60-5e194d36b783
| 3 |
public String getNewVariableThatBelongsInLambdaSet(Grammar grammar,
Set lambdaSet) {
String[] variables = grammar.getVariables();
for (int k = 0; k < variables.length; k++) {
if (!isInLambdaSet(variables[k], lambdaSet)
&& belongsInLambdaSet(variables[k], grammar, lambdaSet))
return variables[k];
}
return null;
}
|
2e72bbc1-c326-4de7-bb26-254f83402681
| 8 |
@Override
public void keyPressed(KeyEvent ke) {
switch (ke.getKeyCode()) {
case KeyEvent.VK_UP:
keyState[KeyCode.UP.ordinal()] = true;
break;
case KeyEvent.VK_DOWN:
keyState[KeyCode.DOWN.ordinal()] = true;
break;
case KeyEvent.VK_LEFT:
keyState[KeyCode.LEFT.ordinal()] = true;
break;
case KeyEvent.VK_RIGHT:
keyState[KeyCode.RIGHT.ordinal()] = true;
break;
case KeyEvent.VK_ENTER:
keyState[KeyCode.ENTER.ordinal()] = true;
break;
case KeyEvent.VK_SPACE:
keyState[KeyCode.SPACE.ordinal()] = true;
break;
case KeyEvent.VK_P:
keyState[KeyCode.P.ordinal()] = true;
break;
case KeyEvent.VK_ESCAPE:
keyState[KeyCode.ESCAPE.ordinal()] = true;
break;
default:
break;
}
}
|
dfd9e4bf-ad9e-4a64-8e0d-167c996787ab
| 6 |
static boolean isBoolean( String var ) {
if(
var.equalsIgnoreCase("true") ||
var.equalsIgnoreCase("false") ||
var.equals("1") ||
var.equals("0") ||
var.matches("^[tT].*$") ||
var.matches("^[fF].*$") ) {
return true;
}
return false;
}
|
4f83e928-fe67-4c5b-ad7a-ede84cd689cb
| 3 |
public static BiCubicSpline[] oneDarray(int nP, int mP, int lP){
if(mP<3 || lP<3)throw new IllegalArgumentException("A minimum of three x three data points is needed");
BiCubicSpline[] a =new BiCubicSpline[nP];
for(int i=0; i<nP; i++){
a[i]=BiCubicSpline.zero(mP, lP);
}
return a;
}
|
0fa09617-ad16-40bf-88e9-02600717747c
| 9 |
public void processPacket(String received) {
stringParts = received.split(" ");
try {
// auction- ended- notification
if (stringParts[0].equals("!auction-ended")) {
String describtion = "";
// user is the highest bidder
if (username.equals(stringParts[1].trim())) {
for (int i = 3; i < stringParts.length; i++) {
describtion += stringParts[i] + " ";
}
System.out.println("The auction '" + describtion +
"' has ended. You won with " + stringParts[2] + "!");
}
else {
// user is the owner- no one bid
if (stringParts[1].equals("none")) { // nobothy bid to this auction
for (int i = 3; i < stringParts.length; i++) {
describtion += stringParts[i] + " ";
}
System.out.println("The auction '" + describtion + "' has ended. " +
"Nobothy bid.");
}
// user is the woner and someone bid
else {
for (int i = 3; i < stringParts.length; i++) {
describtion += stringParts[i] + " ";
}
System.out.println("The auction ' " + describtion + "' has ended. " +
stringParts[1] + " won with " + stringParts[2] + ".");
}
}
}
// new bid- notification
if (stringParts[0].equals("!new-bid")) {
String describtion = "";
for (int i = 1; i < stringParts.length; i++) {
describtion += stringParts[i] + " ";
}
System.out.println("You have been overbid on '" + describtion + "'.");
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: message not correct!");
}
}
|
81c9c377-4247-4105-8632-459e58b9a6a4
| 7 |
public void setDefinition(String definition) {
// JavaMetadata will extract all modifiers for us
JavaMetadata metadata = new JavaMetadata(definition);
modifier = metadata.getModifier();
definition = metadata.getClassName();
context.getImports().addImports(metadata.getImports());
// Add any generics extracted
if (metadata.hasGenerics()){
generics.clear();
String[] generic = metadata.getGenerics();
for (String s : generic)
generics.add(s);
}
// Add the return type
int ind = definition.indexOf(' ');
returnType = definition.substring(0, ind);
definition = definition.substring(ind+1);
ind = returnType.lastIndexOf('.');
if (ind > 0) {
context.getImports().addImport(returnType);
returnType = returnType.substring(ind+1);
}
// Resolve parameters; reducing fqcn to import statements
ind = definition.indexOf('(');
assert ind > 0;
methodName = definition.substring(0, ind);
definition = definition.substring(ind+1, definition.lastIndexOf(')'));
for (String param : definition.split(",")) {
param = param.trim();
ind = param.lastIndexOf('.');
if (ind > 0) {
context.getImports().addImport(param.substring(0, param.indexOf(' ')));
param = param.substring(ind+1);
}
parameters.add(param);
}
if (methodName.contains(" "))
throw new CompilationFailed("Found ambiguous method definition in "+definition);
if (methodName.length() == 0)
throw new CompilationFailed("Did not have a class name in class definition "+definition);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.