method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
044bb694-7637-454e-8804-b6f80f934c3a
3
public boolean addEdge(Tile tile1, Tile tile2, String direction1, String direction2, Item key, boolean crossable) { Edge e; Direction dir1 = Direction.valueOf(direction1.toUpperCase()); Direction dir2; if(dir1 != null) { if(direction2.isEmpty()) dir2 = dir1.getOppositeDirection(); else dir2 = Direction.valueOf(direction2.toUpperCase()); if(key != null) { e = new Exit(tile1, tile2, !crossable, dir1, dir2, key); } else { e = new Edge(tile1, tile2, crossable, dir1, dir2); } edgeList.add(e); return true; } return false; }
acb4d157-9191-4550-9006-a2086442638b
4
private void calculateElements(double t) throws JPLEphemerisException { ephemeris.calculatePositionAndVelocity(t, JPLEphemeris.NEPTUNE, position, velocity); position.rotate(OBLIQUITY, Vector.X_AXIS); velocity.rotate(OBLIQUITY, Vector.X_AXIS); position.multiplyBy(AU); velocity.multiplyBy(AU*K); double r = position.magnitude(); double v = velocity.magnitude(); double alpha = v * v - 2.0/r; double a = -1.0/alpha; double d0 = position.scalarProduct(velocity); double c0 = 1.0 + alpha * r; double ecc = Math.sqrt(c0 * c0 - alpha * d0 * d0); V0.linearCombination(velocity, r, position, -d0/r); V0.normalise(); double kt0 = c0/ecc; double st0 = d0/ecc; double xw0 = r * kt0 - d0 * st0; U0.copy(position); U0.normalise(); P.linearCombination(U0, kt0, velocity, -st0); P.normalise(); Q.linearCombination(U0, st0, velocity, xw0); Q.normalise(); Vector W = P.vectorProduct(Q); double xi = Math.sqrt(W.getX() * W.getX() + W.getY() * W.getY()); double yi = W.getZ(); double incl = Math.atan2(xi, yi); incl *= 180.0/Math.PI; double node = Math.atan2(W.getX(), -W.getY()); while (node < 0.0) node += TWO_PI; node %= TWO_PI; double apse = node + Math.atan2(P.getZ(), Q.getZ()); while (apse < 0.0) apse += TWO_PI; apse %= TWO_PI; double eAnomaly = Math.atan2(st0*Math.sqrt(-alpha), kt0); double mAnomaly = eAnomaly - ecc * Math.sin(eAnomaly); double lambda = apse + mAnomaly; while (lambda < 0.0) lambda += TWO_PI; node *= 180.0/Math.PI; apse *= 180.0/Math.PI; lambda *= 180.0/Math.PI; lambda -= MEAN_MOTION * (t - J2000); while (lambda < 0.0) lambda += 360.0; lambda %= 360.0; System.out.print(dfmt1.format(t)); System.out.print(' '); System.out.print(dfmt2.format(a)); System.out.print(' '); System.out.print(dfmt2.format(ecc)); System.out.print(' '); System.out.print(dfmt2.format(incl)); System.out.print(' '); System.out.print(dfmt2.format(node)); System.out.print(' '); System.out.print(dfmt2.format(apse)); System.out.print(' '); System.out.print(dfmt2.format(lambda)); System.out.println(); }
0c444fd4-4b52-46f6-8bc8-7b0abc07c2ab
9
@Override public boolean equals(Object other) { if (other == null) return false; if (other == this) return true; if (!(other instanceof Feature)) return false; Feature otherF = (Feature) other; boolean result = false; // Must be equal: name, value, language, category name if (name.equals(otherF.name) && value.equals(otherF.value) && category.getName().equals(otherF.category.getName()) ) { if (language != null && language.equals(otherF.language)) { result = true; } else if (language == null) { result = true; } } return result; }
23a8af4e-0064-4fbb-a06e-205f80b64703
3
protected void train(double limiar) { double[] err = new double[w.length]; double t = 9999; /*while (t > limiar) {*/ for(int k = 0; k < 100000; k++) { t = 0; for(int i = 0; i < w.length; i ++) { err[i] = erro(i); w[i] = w[i] - (ETA*erro(i)); err[i] = err[i] - erro(i); } for(int i = 0; i < err.length; i++) { t += err[i]; } //System.out.println("t = " + t); } //} }
fe1466a0-941d-455e-b25f-7108960a3284
2
@Override public void copyTo(MapLayer other) { for (int y = bounds.y; y < bounds.y + bounds.height; y++) { for (int x = bounds.x; x < bounds.x + bounds.width; x++) { ((TileLayer) other).setTileAt(x, y, getTileAt(x, y)); } } }
360550e5-2e9d-4639-87cf-f879f7c8aa53
9
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RecordSelectorNode other = (RecordSelectorNode) obj; if (selector == null) { if (other.selector != null) return false; } else if (!selector.equals(other.selector)) return false; if (subject == null) { if (other.subject != null) return false; } else if (!subject.equals(other.subject)) return false; return true; }
3cae3ebe-a73f-4f89-b071-e0e7df490318
7
private int setQuarter(int quarter, String description) { if (quarter == 5) { this.overtime = true; if (description.contains("1st")) { return 1; } else if (description.contains("2nd")) { return 2; } else if (description.contains("3rd")) { return 3; } else if (description.contains("4th")) { return 4; } else if (description.contains("5th")) { return 5; } else if (description.contains("6th")) { return 6; } else { return -1; } } else { return quarter; } }
88e79ccc-a05e-467e-9d68-4b2409d142d1
9
public void authenticate() throws ParseException, IOException { String string; Boolean exit = false; JSONObject json; // If not authenticated already, commence if (!authenticated) { try { // Keep reading output from server while ((string = bufferedreader.readLine()) != null) { // Log server output ActivationServiceClient.log(string); // Parse JSON from string json = (JSONObject)new JSONParser().parse(string); JSONObject reply = new JSONObject(); String message = (String) json.get("message"); // Server asking for authentication if (message.equals("authenticate")) { ActivationServiceClient.log("System asking for" + " authorization."); // Send username/password to server reply.put("message", "readKey"); reply.put("username", username); reply.put("password", password); bufferedwriter.write(reply.toJSONString() + "\r\n"); bufferedwriter.flush(); } // Authentication failed else if (message.equals("authenticationFailed")) { // Show the login panel again loginPanel("Please Login to continue."); ActivationServiceClient.log("Authentication Failed."); // Notify user using Pop Up JOptionPane.showMessageDialog(ActivationServiceClient.this, "Authentication Failed. Try again.", "Error Message", JOptionPane.ERROR_MESSAGE); return; } // Authentication with server successful else if (message.equals("authenticated")) { ActivationServiceClient.log("Authenticated."); authenticated = true; // Show Options after login optionPanel(); // Notify user using Pop Up JOptionPane.showMessageDialog(ActivationServiceClient.this, "Successfully logged in."); return; } // Server behaved unexpectedly, re-login else { // Show Login Panel loginPanel("Please Login to continue."); // Notify user using Pop Up JOptionPane.showMessageDialog(ActivationServiceClient.this, "Server responded in an unexpected way. Please" + " restart the application and try again.", "Error Message", JOptionPane.ERROR_MESSAGE); return; } } } catch (SocketException se) { ActivationServiceClient.log("Socket Exception, re-establishing" + " connection."); reconnect(); return; } catch (SSLHandshakeException ssl) { ActivationServiceClient.log("SSL Exception, re-establishing" + " connection"); reconnect(); return; } catch (IOException e) { ActivationServiceClient.log("IO Exception, re-establishing" + " connection."); reconnect(); return; } catch (Exception e) { ByteArrayOutputStream out = new ByteArrayOutputStream(); e.printStackTrace(new PrintStream(out)); ActivationServiceClient.log(new String(out.toByteArray())); reconnect(); return; } } // If already authenticated, show the Login screen and // notify using Pop Ups optionPanel(); JOptionPane.showMessageDialog(ActivationServiceClient.this, "You are already logged in."); return; }
a933690a-b71f-48d0-aba4-0e0edeb3a5c6
5
public static void main(String[] args) { System.out.println("main start"); new Thread(new Runnable() { @Override public void run() { for (int i=0; i<100; i++) { System.out.println("thread:" + i); //这里本意是要程序停止的 if (i == 10) { System.exit(0); } try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); System.out.println("main end"); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { for (int i=0; i<10; i++) { System.out.println("hook:" + i); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } })); }
a4f7ecee-1918-4431-99c1-316a29d89347
7
public static String[] convertSingleConsoleCommand(String command) throws InvalidCommandException { logger.trace("Converting single console command for ProcessBuilder: " + command); List<String> preparedResult = new ArrayList<String>(); String tmp = null; for (String currentlyCheckedString : command.split(" ")) { if (tmp != null) { tmp += " " + currentlyCheckedString; if (endOfGroup.matcher(currentlyCheckedString).find()) { preparedResult.add(tmp.substring(0, tmp.length() - 1)); tmp = null; } } else { if (singleWrapped.matcher(currentlyCheckedString).find()) preparedResult.add(currentlyCheckedString.substring(1, currentlyCheckedString.length() - 1)); else if (beginningOfGroup.matcher(currentlyCheckedString).find()) tmp = currentlyCheckedString.substring(1); else if (!currentlyCheckedString.isEmpty()) preparedResult.add(currentlyCheckedString); } } if (tmp != null) { logger.error("Failed to convert console command - command invalid (exception thrown)"); throw new InvalidCommandException("There is error in \"" + command + "\" command"); } logger.detailedTrace("\tConverted single console command: " + preparedResult); return preparedResult.toArray(new String[0]); }
66592995-6fb2-4b85-8455-270bf4c0f2c1
1
public String getDirectory() { return (isAValidDirectory()) ? args[0] : Constants.DEFAULT_SERVER_DIRECTORY; }
618659b9-331e-47d6-ac6d-23deb030d851
6
@Override public void build(JSONObject json, FieldsMetadata metadata, IContext context) { // iterate on all the simple text Iterator<?> iter = json.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<?,?> entry = (Map.Entry<?,?>)iter.next(); // add the text to the report's context context.put(entry.getKey().toString(), entry.getValue().toString()); } }
ba5e671b-1a9c-48fa-a1f6-ed2f8b6f3fab
6
public void takeTurn(int roll) { //calculate targets Board.calcTargets(currentPlayer.getLocation().y, currentPlayer.getLocation().x, roll); //take human turn if(currentPlayer == human) { this.setTurnDone(false); Board.setHumanTurn(true); Board.repaint(); } //take computer turn else { setTurnDone(true); currentPlayer.makeMove(Board.getTargets(), Board); //Code to make computer make suggestion if in a room if(!currentPlayer.getCurrentRoom().equals("Walkway") && ((ComputerPlayer) currentPlayer).isLastDisproved()) { Solution guess = ((ComputerPlayer) currentPlayer).createSuggestion(); Card returned = handleSuggestion(guess); if(returned == null) ((ComputerPlayer) currentPlayer).setLastDisproved(false); controlPanel.setGuess(guess); controlPanel.setRevealed(returned); } else if(!currentPlayer.getCurrentRoom().equals("Walkway")) { Solution guess = ((ComputerPlayer) currentPlayer).createSuggestion(); JOptionPane.showMessageDialog(this, currentPlayer.getName() + " has made an accusation of " + guess.getPerson() + " in the " + guess.getRoom() + " with the " + guess.getWeapon()); if(checkAccusation(guess)) { showWinScreen(); setGameDone(true); } } } //Board.setHumanTurn(false); }
996c0d5b-b153-4696-852d-be4e632f5d12
3
public static void main(String[] args){ //dirty log init org.apache.log4j.BasicConfigurator.configure(); Model model = ModelFactory.createDefaultModel(); File f = new File("rdf-model.xml"); FileReader fr; try { fr = new FileReader(f); model.read(fr, "http://imi.org/"); } catch (FileNotFoundException e) { System.out.println("IO ERROR: "+f.getAbsolutePath()); System.exit(1); } //creating Rooms Query query = QueryFactory.create("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " + "PREFIX ex: <http://imi.org/> " + "SELECT ?room ?constraint WHERE { ?room ex:hasConstraint ?constraint . " + " ?room rdf:type ex:Room }"); QueryExecution qe = QueryExecutionFactory.create(query, model); ResultSet rs = qe.execSelect(); HashMap<String,Room> roomMap = new HashMap<String, Room>(); while(rs.hasNext()) { QuerySolution sol = rs.next(); Resource resroom = sol.getResource("room"); Resource resconstraint = sol.getResource("constraint"); if(!roomMap.containsKey(resroom.getLocalName())){ roomMap.put(resroom.getLocalName(), new Room(resroom.getLocalName())); } //adding each constraint (or property) to the given room roomMap.get(resroom.getLocalName()).addPropertyByName(resconstraint.getLocalName()); } qe.close(); }
a4c95742-8853-4951-a9cb-d1703752f9ba
4
private void CalculateAttackSuccessButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CalculateAttackSuccessButtonActionPerformed PreparedStatement ps_update = null; Connection conn = null; try { if ((conn = JavaDBAccess.setConn()) != null) { System.out.println("Connected to database " + JavaDBAccess.getDatabaseName()); } else { throw new Exception("Not connected to database " + JavaDBAccess.getDatabaseName()); } conn.setAutoCommit(false); ps_update = conn.prepareStatement("UPDATE ATTACK_PAYLOADS SET ATTACK_RESULT='SUCCESSFUL' WHERE EXISTS (SELECT 1 FROM MYSQL_QUERIES Q1,MYSQL_PROXY_PACKETS P1,MYSQL_QUERIES Q2,MYSQL_PROXY_PACKETS P2 WHERE Q1.MYSQL_PROXY_PACKET_CLIENT=P1.ID AND P1.TARGET_PHP_FILES_RUNS_FUNCTION=ATTACK_PAYLOADS.TARGET_PHP_FILES_RUNS_FUNCTION AND Q2.MYSQL_PROXY_PACKET_CLIENT=P2.ID AND P2.TARGET_PHP_FILES_RUNS_FUNCTION=ATTACK_PAYLOADS.ATTACK_TARGET_PHP_FILES_RUNS_FUNCTION AND P1.HTTP_PACKET_SEQUENCE=P2.HTTP_PACKET_SEQUENCE AND Q1.MYSQL_QUERY_SEQUENCE=Q2.MYSQL_QUERY_SEQUENCE AND Q1.SQL_COMMAND_STRUCTURE <> Q2.SQL_COMMAND_STRUCTURE) AND ATTACK_RESULT='UNDEFINED'"); ps_update.executeUpdate(); conn.commit(); ps_update = conn.prepareStatement("UPDATE ATTACK_PAYLOADS SET ATTACK_RESULT='NOT SUCCESSFUL' WHERE EXISTS (SELECT 1 FROM MYSQL_QUERIES Q1,MYSQL_PROXY_PACKETS P1,MYSQL_QUERIES Q2,MYSQL_PROXY_PACKETS P2 WHERE Q1.MYSQL_PROXY_PACKET_CLIENT=P1.ID AND P1.TARGET_PHP_FILES_RUNS_FUNCTION=ATTACK_PAYLOADS.TARGET_PHP_FILES_RUNS_FUNCTION AND Q2.MYSQL_PROXY_PACKET_CLIENT=P2.ID AND P2.TARGET_PHP_FILES_RUNS_FUNCTION=ATTACK_PAYLOADS.ATTACK_TARGET_PHP_FILES_RUNS_FUNCTION AND P1.HTTP_PACKET_SEQUENCE=P2.HTTP_PACKET_SEQUENCE AND Q1.MYSQL_QUERY_SEQUENCE=Q2.MYSQL_QUERY_SEQUENCE AND Q1.SQL_COMMAND_STRUCTURE = Q2.SQL_COMMAND_STRUCTURE) AND ATTACK_RESULT='UNDEFINED'"); ps_update.executeUpdate(); ps_update.close(); conn.commit(); ps_update = conn.prepareStatement("UPDATE ATTACK_PAYLOADS SET IDS_COMMAND_DETECTION_RESULT='NOT SUCCESSFUL' WHERE IDS_COMMAND_DETECTION_RESULT='UNDEFINED'"); ps_update.executeUpdate(); ps_update.close(); conn.commit(); if (UseIDSRadioButton.isSelected()) { ps_update = conn.prepareStatement("UPDATE ATTACK_PAYLOADS SET IDS_COMMAND_DETECTION_RESULT='SUCCESSFUL' WHERE UPPER(IDS_RESULT) LIKE '%MALICIOUS_COMMAND%'"); ps_update.executeUpdate(); ps_update.close(); conn.commit(); ps_update = conn.prepareStatement("UPDATE ATTACK_PAYLOADS SET IDS_TRANSACTION_DETECTION_RESULT='NOT SUCCESSFUL' WHERE IDS_TRANSACTION_DETECTION_RESULT='UNDEFINED'"); ps_update.executeUpdate(); ps_update.close(); conn.commit(); ps_update = conn.prepareStatement("UPDATE ATTACK_PAYLOADS SET IDS_TRANSACTION_DETECTION_RESULT='SUCCESSFUL' WHERE UPPER(IDS_RESULT) LIKE '%MALICIOUS_TRANSACTION%'"); ps_update.executeUpdate(); ps_update.close(); conn.commit(); } conn.close(); } catch (Throwable e) { System.out.println("Errors in ParsePHPFile!"); System.out.println("exception thrown:"); if (e instanceof SQLException) { JavaDBAccess.printSQLError((SQLException) e); } else { e.printStackTrace(); } } }
b844b60e-9485-4f04-a654-96dd0ac6dc2a
8
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(LoginGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch(InstantiationException ex) { java.util.logging.Logger.getLogger(LoginGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch(IllegalAccessException ex) { java.util.logging.Logger.getLogger(LoginGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch(javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(LoginGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> try { Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch(Exception ex) { Logger.getLogger(LoginGUI.class.getName()).log(Level.SEVERE, null, ex); } /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable(){ public void run(){ try { new LoginGUI(new javax.swing.JFrame(), true).setVisible(true); } catch(Exception ex) { Logger.getLogger(LoginGUI.class.getName()).log(Level.SEVERE, null, ex); } } }); }
73cf84f8-33b0-4596-859b-6c71eda403e6
0
public void setKodPocztowy(String kodPocztowy) { this.kodPocztowy = kodPocztowy; }
e1aa2081-d180-4358-b90c-ba10ae541496
9
private void saveInfo(String name) { FileWriter baseSave = null; String eol = System.getProperty("line.separator"); try { baseSave = new FileWriter(name+".rcf"); //Build the file header baseSave.write("Base Controller Info;" + eol); //The Base Controller Name baseSave.write(">name:"+strName+";"+eol); //Saves the screen type integer baseSave.write(">typ:"); if(dicernType == 1) baseSave.write("p;"); else if(dicernType == 2) baseSave.write("l;"); else if(dicernType == 3) baseSave.write("b;"); else if(dicernType == 4) baseSave.write("o;"); else baseSave.write("a;"); baseSave.write(eol); //Add device name nameList str = head; while(str != null) { if(selected == str) baseSave.write(">prior:"); else if(str.getApproved()) baseSave.write(">approv:"); else baseSave.write(">connect:"); baseSave.write(str.getName()+";"+eol); str = str.getNext(); } //End device list marker baseSave.write(">dev:;"+eol); //Write the IP address String h = getServerAddress(); if(!h.equals("No address")) baseSave.write(">IPAd:"+h+":"+getPort()+";"+eol); //End file marker baseSave.write(">end:;"); //Close the file baseSave.close(); } catch(IOException e) { System.err.println("Fatal saving error is BaseInfo.rcf"); } }
995a9278-c552-4f10-98bc-d4b3b82bbac7
1
protected void handleMousePressed(MouseEvent e) { synchronized (simulator) { if (simulator.isRunning()) { simulator.stop(); } else { simulator.start(); } } }
d8f9586f-7809-4c82-8839-f3a78f0cb49e
8
public static void printTree(MyTreeNode<Integer> root){ if(root == null) return; Stack<MyTreeNode<Integer>> stack = new Stack<>(); MyTreeNode<Integer> temp = root; stack.add(temp); MyTreeNode<Integer> head = null; while (!stack.isEmpty()) { temp = stack.peek(); if (temp.getRight() == head || temp.getLeft() == head || (temp.getLeft() == null && temp.getRight() == null)) { stack.pop(); System.out.print(" "+temp.getData()); head = temp; } else { if (temp.getRight() != null) { stack.push(temp.getRight()); } if (temp.getLeft() != null) { stack.push(temp.getLeft()); } } } }
1174f465-a84a-46dc-802e-3fee784bf603
3
@EventHandler public void Mondo(PlayerChangedWorldEvent event) { for(String s:Main.jl.dati()) { System.out.println(s); } String name = event.getPlayer().getName(); if(!Main.jl.leggi(name)) { if(event.getPlayer().getWorld() == Main.server.getWorld(Main.conf.mondo)) { Location lc = Main.sp.coordinate(); lc.setWorld( Main.server.getWorld(Main.conf.mondo)); Main.server.dispatchCommand(Main.server.getConsoleSender(), "tppos " +name + " " + lc.getBlockX() + " " + lc.getBlockY() + " " + lc.getBlockZ()); event.getPlayer().sendMessage(ChatColor.RED +"Sei stato teletrasportato a caso nel mondo " + event.getPlayer().getWorld().getName()); //event.getPlayer().teleport(lc); Main.jl.aggiungi(name); Main m = (Main) Main.plugin; m.serializza(); } } }
7c1399a7-db3d-4633-9f8c-23274ec413ae
8
public double lru() { if(printAll) System.out.println("~~~~~ Least Recently Used ~~~~~"); int hits = 0; Page evictedPage; int prevPageRef = -1; int nextPage; for(int i=0;i<PAGE_REFERENCES;i++) { evictedPage = null; nextPage = nextReference(prevPageRef); prevPageRef = nextPage; for(int index=0;index<memory.size();index++) memory.get(index).incrementTimeSinceUsage(); //Print time since last usage //for(int x=0;x<memory.size();x++) // System.out.printf("%d: %d\n", memory.get(x).getIndex(), memory.get(x).getTimeSinceUsage()); if(!pageInMemory(nextPage)) { //Add page into memory if(memory.size() != MEMORY_SIZE)//Is memory full? {//No memory.add(program.get(nextPage)); } else {//Yes Collections.sort(memory, Page.recentComparator()); Page page = program.get(nextPage); evictedPage = memory.remove(0); memory.add(page); } } else hits++; if(printAll) { printMemory(); if(evictedPage != null) System.out.printf(" Page Referenced: %d | Page %d evicted\n", nextPage, evictedPage.getIndex()); else System.out.printf(" Page Referenced: %d | No eviction\n", nextPage); } } resetProgram(); memory.clear(); if(printAll) System.out.println(); return (double) hits / (double) PAGE_REFERENCES; }
d9e1dbeb-c678-4485-9362-fe097c0b5947
9
private void searchGoodWord(List<String> words) { if(words != null && !words.isEmpty()) { List<Keyword> keywordList = dictionary.getKeywordList(); int priority = -1; float distance = 1; int elementId = -1; int elementIdRegardingDistance = 0; for(int i = 0; i < words.size(); i++) { String[] possibleWords = words.get(i).split(";"); for(int j = 0; j < keywordList.size(); j++) { if(possibleWords[1].equals(keywordList.get(j).getWord()) && keywordList.get(j).getKeywordData().getPriority() > priority && (float)Integer.parseInt(possibleWords[2]) / possibleWords[1].length() < 0.2) { priority = keywordList.get(j).getKeywordData().getPriority(); elementId = i; } else if ((float)Integer.parseInt(possibleWords[2]) / possibleWords[1].length() < distance) { distance = (float)Integer.parseInt(possibleWords[2]) / possibleWords[1].length(); elementIdRegardingDistance = i; } } } if(elementId >= 0) { String[] possibleWord = words.get(elementId).split(";"); this.questionableWord = possibleWord[1]; words.remove(elementId); this.possibleWords = words; } else { String[] possibleWord = words.get(elementIdRegardingDistance).split(";"); this.questionableWord = possibleWord[1]; words.remove(elementIdRegardingDistance); this.possibleWords = words; } } else { this.possibleWords = null; } }
260c669d-496f-4100-ba47-d9dc9c910e44
4
public Question getNextQuestion() { if (nextQuestion == QueStatus.Q1_GAS_TYPE) return new Q1_GasType(gasSAXManager); else if (nextQuestion == QueStatus.Q2_ASK_BRAND) return new Q2_AskBrand(gasSAXManager); else if (nextQuestion == QueStatus.Q3_CHOOSE_BRANDS) return new Q3_ChooseBrands(gasSAXManager); else if (nextQuestion == QueStatus.Q4_PRICE_OR_DISTANCE) return new Q4_PriceDistance(gasSAXManager); return new Q1_GasType(gasSAXManager); }
73b4f90b-c8eb-402c-a429-efb4f5bac648
0
@Override public String toString() { return "fleming.entity.Entradas[ idEntrada=" + idEntrada + " ]"; }
da856ba4-9564-4ae3-aab8-23f1b97cf2f3
3
private boolean jj_3R_16() { if (jj_3R_18()) return true; Token xsp; while (true) { xsp = jj_scanpos; if (jj_3R_19()) { jj_scanpos = xsp; break; } } return false; }
22305dcb-df91-421f-ae34-f27e3d0bd0b1
8
public void defaultFlipping(CharacterAction action) { switch (action) { case DEFAULT: break; case IDLE: break; case ATTACK: break; case MOVELEFT: currentAction.setFlip(true); break; case JUMPLEFT: currentAction.setFlip(true); break; case JUMPRIGHT: currentAction.setFlip(false); break; case MOVERIGHT: currentAction.setFlip(false); break; case JUMP: break; } }
32192ad1-41c1-42f2-9383-e705c3ea7c52
5
@Override public void paint(Graphics g) { super.paint(g); Dimension koko = getSize(); int huippu = (int) koko.getHeight() - log.getRuudunKorkeus() * nelionKorkeus(); for (int i = 0; i < log.getRuudunKorkeus(); ++i) { for (int j = 0; j < log.getRuudunLeveys(); ++j) { Tetrominot palanmuoto = log.tetrominonMuoto(j, log.getRuudunKorkeus() - i - 1); if (palanmuoto != Tetrominot.EiMuotoa) { piirraNelio(g, 0 + j * nelionLeveys(), huippu + i * nelionKorkeus(), palanmuoto); } } } if (log.getPala().getMuoto() != Tetrominot.EiMuotoa) { for (int i = 0; i < 4; ++i) { int x = log.getNykyinenX() + log.getPala().x(i); int y = log.getNykyinenY() - log.getPala().y(i); piirraNelio(g, 0 + x * nelionLeveys(), huippu + (log.getRuudunKorkeus() - y - 1) * nelionKorkeus(), log.getPala().getMuoto()); } } }
2852b20f-0008-4d37-b4eb-ed14e151d644
5
public void setVinculo(Vinculo vinculo){ this.vinculo = vinculo; if(vinculo != null){ this.lblMatriculaValor.setText(vinculo.getMatricula()); if(vinculo.getLinhaDePesquisa() != null){ this.lblLinhaDePesquisaValor.setText(vinculo.getLinhaDePesquisa().getTema()); } if(vinculo.getPessoa() != null){ setPessoa(vinculo.getPessoa()); } if(vinculo instanceof Aluno){ this.setAluno((Aluno)vinculo); } else if(vinculo instanceof Docente){ this.setDocente((Docente)vinculo); } } }
f1080417-4f15-4ae8-b06f-149da81cd2fe
2
private void thresholdEdges() { for (int i = 0; i < picsize; i++) { data[i] = data[i] > 0 ? -1 : 0xff000000; } }
554c357f-7746-404f-8470-3f5a3be74cfe
8
public int getListOffset(RSyntaxTextArea textArea, TabExpander e, float x0, float x) { // If the coordinate in question is before this line's start, quit. if (x0 >= x) return offset; float currX = x0; // x-coordinate of current char. float nextX = x0; // x-coordinate of next char. float stableX = x0; // Cached ending x-coord. of last tab or token. Token token = this; int last = offset; FontMetrics fm = null; while (token!=null && token.isPaintable()) { fm = textArea.getFontMetricsForTokenType(token.type); char[] text = token.text; int start = token.textOffset; int end = start + token.textCount; for (int i=start; i<end; i++) { currX = nextX; if (text[i] == '\t') { nextX = e.nextTabStop(nextX, 0); stableX = nextX; // Cache ending x-coord. of tab. start = i+1; // Do charsWidth() from next char. } else { nextX = stableX + fm.charsWidth(text, start, i-start+1); } if (x>=currX && x<nextX) { if ((x-currX) < (nextX-x)) { return last + i-token.textOffset; } return last + i+1-token.textOffset; } } stableX = nextX; // Cache ending x-coordinate of token. last += token.textCount; token = token.getNextToken(); } // If we didn't find anything, return the end position of the text. return last; }
98dea368-66e1-4702-aca3-88fcadadc04c
1
public void Insert(TreeNode root,TreeNode node){ if(root == null){ root = node; } else{ insertRec(root,node); } }
9fe238ca-2c34-479f-9300-5cb3045861d3
7
public void mostrarDatosPantalla(String id, int nivel){ System.out.print("----"); System.out.print(id); System.out.println("----"); System.out.print("ExisteID: "); System.out.println(existeID(id, nivel)); System.out.print("Nivel: "); System.out.println(nivel); System.out.print("Clase: "); System.out.println(getPropiedades(id, nivel).getClaseDeclaracion()); System.out.print("tipo: "); System.out.println(this.getExprTipo(id, nivel).getT()); if (this.getExprTipo(id, nivel).getT().equals("ref")){ System.out.print("id: "); System.out.println(getExprTipo(id,nivel).getIdTipo()); System.out.print("ref_base ->: "); System.out.println(ref(getExprTipo(id, nivel)).getT()); } if (this.getExprTipo(id, nivel).getT().equals("tupla")){ System.out.println("-> Elementos :"); for (int i = 0; i < ((ExpTipoTupla) this.getExprTipo(id, nivel)).getTiposTupla().size(); i++){ System.out.print("---->"); System.out.print("t: "); if (((ExpTipoTupla) this.getExprTipo(id, nivel)).getTiposTupla().get(i).getExpTipo().getT().equals("ref")){ System.out.println("ref"); System.out.print("--->id: "); System.out.println(((ExpTipoTupla) this.getExprTipo(id, nivel)).getTiposTupla().get(i).getExpTipo().getIdTipo()); } else System.out.println(((ExpTipoTupla) this.getExprTipo(id, nivel)).getTiposTupla().get(i).getExpTipo().getT()); System.out.print("---->tam: "); System.out.println(((ExpTipoTupla) this.getExprTipo(id, nivel)).getTiposTupla().get(i).getExpTipo().getTam()); System.out.print("---->desp: "); System.out.println(((ExpTipoTupla) this.getExprTipo(id, nivel)).getTiposTupla().get(i).getDesp()); } } if (this.getExprTipo(id, nivel).getT().equals("proc")){ System.out.println("Params :"); Iterator<Param> it = ((ExpTipoProcedimiento) getExprTipo(id, nivel)).getListaParamEnOrden(); while (it.hasNext()){ Param p = it.next(); System.out.print("------> id: "); System.out.println(p.getId()); System.out.print("------> modo :"); System.out.println(p.getModo()); System.out.print("--> t: "); System.out.println(p.getTipo().getT()); if (p.getTipo().getT().equals("ref")){ System.out.print("--> id:"); System.out.println(p.getTipo().getIdTipo()); } System.out.print("--> tam:"); System.out.println(p.getTipo().getTam()); System.out.print("------> desp: "); System.out.println(p.getDesp()); System.out.println(","); } } System.out.print("dir: "); System.out.println(getDir(id, nivel)); System.out.print("tam: "); System.out.println(getPropiedades(id, nivel).getExpTipo().getTam()); }
87308d8b-06e8-4980-90d7-bbeeee17bdc0
7
public void move(int xa, int ya) { // this allows "sliding" on solid tile edges if(xa !=0 && ya != 0){ move(xa, 0); move(0, ya); return; } // movement handling if (ya < 0) dir = Direction.UP; if (ya > 0) dir = Direction.DOWN; if (xa < 0) dir = Direction.LEFT; if (xa > 0) dir = Direction.RIGHT; if (!collision(xa, ya)) { x += xa; y += ya; } }
21587834-efc4-4871-afb0-adf39af45651
0
public boolean isItemSent(Auction auction){ return auction.isItemSent(); }
1268069f-78b6-4f56-885f-d92d49e1682d
7
public Object nextContent() throws JSONException { char c; StringBuilder sb; do { c = next(); } while (Character.isWhitespace(c)); if (c == 0) { return null; } if (c == '<') { return XML.LT; } sb = new StringBuilder(); for (;;) { if (c == '<' || c == 0) { back(); return sb.toString().trim(); } if (c == '&') { sb.append(nextEntity(c)); } else { sb.append(c); } c = next(); } }
f327cb6a-760e-4503-a900-48e05a4b9335
5
public static Vector<Caddie> testCheckValideCaddie(Vector<Caddie> caddies, int formCaddie) throws ParseException, BDException{ Vector<Caddie> toDelete = new Vector<Caddie>(); // Vérification for(int i = 0 ; i< caddies.size() ; i++){ Caddie caddie = caddies.get(i); Date dNow = new Date( ); SimpleDateFormat ft = new SimpleDateFormat ("dd/MM/yyyy HH:mm"); long t1 = (new SimpleDateFormat("dd/MM/yyyy HH:mm")).parse(caddie.getDate()).getTime() ; long t2 = (new SimpleDateFormat("dd/MM/yyyy HH:mm")).parse(ft.format(dNow)).getTime(); if(t1 < t2){ Caddie delete = new Caddie(caddie.getId(), caddie.getNom(), caddie.getDate(), caddie.getNumS(), caddie.getZone(), caddie.getNomZ(), caddie.getQt()); toDelete.add(delete); } } // Suppression if(formCaddie > 0) { for(int i = 0 ; i< toDelete.size() ; i++){ Caddie caddie = toDelete.get(i); if(formCaddie == 1) BDRequetes.setQtCaddie(Integer.toString(caddie.getId()), 'd'); else CaddieVirtuel.setQt(Integer.toString(caddie.getId()), 'd'); } } return toDelete; }
c91431ad-c088-4dca-bc5f-1fdf4ed943a6
3
public boolean hasDupDumb(String str) { for (int i = 0; i < str.length() - 1; i++) { for (int j = i + 1; j < str.length(); j++) { if (str.charAt(i) == str.charAt(j)) return true; } } return false; }
3edc64b9-d3b4-4d1a-88e7-0250892229e2
7
public void addBuilding(Building newBuilding, Point2D location) throws InvalidLocationException { if (!isInVillage(location) || !isInVillage(new Point2D.Double(location.getX()+newBuilding.getWidth()-1, location.getY()+newBuilding.getHeight()-1))) throw new InvalidLocationException(); for (int i = (int) location.getX(); i < location.getX()+newBuilding.getWidth(); ++i) { for (int j = (int) location.getY(); j < location.getY()+newBuilding.getHeight(); ++j) { if (this.buildings[i][j] != null) { throw new InvalidLocationException(); } } } for (int i = (int) location.getX(); i < location.getX()+newBuilding.getWidth(); ++i) { for (int j = (int) location.getY(); j < location.getY()+newBuilding.getHeight(); ++j) { this.buildings[i][j] = newBuilding; } } }
f6715758-2afb-4c9c-8e97-a109fb805980
3
@EventHandler public void onPlayerDeath(final PlayerDeathEvent event) { final Player player = event.getEntity(); /*final removeEquipment removeEquipment = new removeEquipment();*/ StringBuilder flagPath = new StringBuilder(player.getName()); flagPath.append(".flag"); final FileConfiguration pFile = pCops.getPlayerFile().getFile(); String flag = pFile.getString(flagPath.toString()); if (flag == null) { } else if(flag.equalsIgnoreCase("cop")) { pFile.set(flagPath.toString(), null); player.sendMessage(ChatColor.DARK_RED + "You have died while being marked playing Cops and Robbers."); event.setKeepLevel(true); /*removeEquipment.onDeath(event, flag);*/ } else if(flag.equalsIgnoreCase("robber")) { pFile.set(flagPath.toString(), null); player.sendMessage(ChatColor.DARK_RED + "You have died while being marked playing Cops and Robbers."); event.setKeepLevel(true); /*removeEquipment.onDeath(event, flag);*/ } }
1dc25348-8ae9-486b-b5e3-56c2b6b2ebea
3
public List<String> getStrings(String xpath) { List<String> list = new ArrayList<>(); try { XPathExpression expr = xPath.compile(xpath); Object result = expr.evaluate(document, XPathConstants.NODESET); if (result != null) { NodeList nodeList = (NodeList) result; for (int i = 0; i < nodeList.getLength(); i++) { list.add(nodeList.item(i).getNodeValue()); } } } catch (XPathExpressionException e) { e.printStackTrace(); return null; } return list; }
c9937add-8c76-4d49-a05f-72111266b43c
3
@Override public String toString() { String s = "{ "; int aux = 0; for (int i = 0; i < listas.length; i++) { for (int j = 0; j < listas[i].size(); j++) { s += listas[i].get(j).toString() + ", "; if (++aux == 5) { s += "\n"; } } } return s + "}"; }
917e05bf-ce32-485a-887e-a610e646c6f3
8
@Override public boolean doChanged(ObservableValue<? extends String> observable, String oldValue, String newValue) { int i = 0; try { i = Integer.parseInt(newValue); } catch(NumberFormatException nfe) { label.setText("Must be an integer"); return false; } if(!acceptNegative && i < 0) { if(label != null)label.setText("Cannot be negative"); return false; } if(!acceptPositive && i > 0) { if(label != null)label.setText("Cannot be positive"); return false; } return true; }
e721436b-c7fe-44f7-8383-0c58a531f5ae
4
public void handleInput(Input input) { if (input.isKeyPressed(Input.KEY_S)) { if (currentWaveHasBeenCleared() || !wavesHaveBegun()) { if (!isFinalWave()) { startNextWave(); } } } }
1e03903c-41ab-4db7-a739-a170d6e7ce7e
9
public static int calcSoftTwo(Session aSession, Lecture aLecture) { int penalty = 0; Instructor anInstructor = aLecture.getInstructor(); if(anInstructor != null){ List<Lecture> coursesTaughtByInstructor = anInstructor.getInstructedLectures(); for(int i = 0; i < coursesTaughtByInstructor.size(); i++){ Session session1; session1 = coursesTaughtByInstructor.get(i).getSession(); if(session1==null){ continue; } if(session1.getDay().equals(aSession.getDay())&& !(session1.getRoom().equals(aSession.getRoom()))){ double timeDiff = session1.getTime().getDifference(aSession.getTime()); if(timeDiff == 0.0){ penalty+=20; } if(timeDiff > 0.0){ if(timeDiff < (double)aSession.getLength()){ penalty+=20; } } else{ if(Math.abs(timeDiff) < (double)session1.getLength()){ penalty+=20; } } } } } return penalty; }
7bea9ac0-1ca3-4a3e-9416-03f2ad254b2f
6
public static void justifyText(String[] words, int maxLength) { int[] justifyCost = new int[words.length+1]; int[] justificationPoints = new int[words.length +1]; List<String> result = new ArrayList<>(); justifyCost[words.length] = 0; for(int i = words.length-1; i >= 0; i--) { // assign justify cost to infinite for now justifyCost[i] = Integer.MAX_VALUE; for( int j = i+1; j<words.length+1; j++) { int length = 0; for( int k = i; k<j;k++) { length += words[k].length(); } //add spaces to the length as well length += j-i-1; int cost = Integer.MAX_VALUE; if(length <= maxLength) { cost = (maxLength - length) * (maxLength - length); } // find the minimum cost if(cost != Integer.MAX_VALUE && justifyCost[i] > justifyCost[j] + cost) { justifyCost[i] = justifyCost[j] + cost; justificationPoints[i] = j; } } } }
6d498b18-1bd3-4b61-b1f6-49c7e3a3b374
4
private static void sortResults(Map results) { // TODO Auto-generated method stub TreeSet sortedResults = new TreeSet( new Comparator(){ @Override public int compare(Object o1, Object o2) { // TODO Auto-generated method stub User user1 = (User)o1; User user2 = (User)o2; /*如果compareTo返回结果0,则认为两个对象相等,新的对象不会增加到集合中去 * 所以,不能直接用下面的代码,否则,那些个数相同的其他姓名就打印不出来。 * */ //return user1.value-user2.value; //return user1.value<user2.value?-1:user1.value==user2.value?0:1; if(user1.value<user2.value) { return -1; }else if(user1.value>user2.value) { return 1; }else { return user1.name.compareTo(user2.name); } } } ); Iterator iterator = results.keySet().iterator(); while(iterator.hasNext()) { String name = (String)iterator.next(); Integer value = (Integer)results.get(name); if(value > 0) { sortedResults.add(new User(name,value)); } } printResults(sortedResults); }
abd87eba-9369-41d6-a326-8dc5c9ec33af
4
public void teleport(Player player, int playerNumber) { if (playerNumber == 1) { if (getSpawnLocation1() == null) { player.sendMessage("Location not set yet."); return; } player.teleport(getSpawnLocation1()); } else if (playerNumber == 2) { if (getSpawnLocation2() == null) { player.sendMessage("Location not set yet."); return; } player.teleport(getSpawnLocation2()); } else { player.sendMessage(ChatColor.RED + "Bad number please pick 1 or 2 only"); } }
7c749294-2a19-46a9-841d-3227fa07da5a
7
public boolean interact(Level level, int xt, int yt, Player player, Item item, int attackDir) { if (item instanceof ToolItem) { ToolItem tool = (ToolItem) item; if (tool.type == ToolType.shovel) { if (player.payStamina(4 - tool.level)) { level.setTile(xt, yt, Tile.dirt, 0); Sound.monsterHurt.play(); if (random.nextInt(5) == 0) { level.add(new ItemEntity(new ResourceItem(Resource.seeds), xt * 16 + random.nextInt(10) + 3, yt * 16 + random.nextInt(10) + 3)); return true; } } } if (tool.type == ToolType.hoe) { if (player.payStamina(4 - tool.level)) { Sound.monsterHurt.play(); if (random.nextInt(5) == 0) { level.add(new ItemEntity(new ResourceItem(Resource.seeds), xt * 16 + random.nextInt(10) + 3, yt * 16 + random.nextInt(10) + 3)); return true; } level.setTile(xt, yt, Tile.farmland, 0); return true; } } } return false; }
4c715130-b5dd-4a07-a509-3097cb640c30
6
public void paintComponent(Graphics g) { super.paintComponent(g); if(count<7 && count>0) { g.setColor(Color.YELLOW); g.fillRect(1,200,200,20); g.fillRect(250,200,200,20); g.fillRect(500,200,200,20); g.fillRect(750,200,200,20); g.fillRect(1,450,200,20); g.fillRect(250,450,200,20); g.fillRect(500,450,200,20); g.fillRect(750,450,200,20); g.setColor(Color.BLACK); g.setFont(new Font("Serif", Font.BOLD, 70)); g.drawString("Level "+ count, 450,350); g.drawImage(run[picnum],x,y,this); g.drawImage(run[1],car1x,100,this); g.drawImage(run[4],car4x,255,this); g.drawImage(run[3],car3x,355,this); g.drawImage(run[2],car2x,500,this); } if(count>6) { g.setColor(Color.BLACK); g.fillRect(0,0,1000,800); g.setColor(Color.WHITE); g.setFont(new Font("Serif", Font.BOLD, 100)); g.drawString("WINNER!",300,350); g.setFont(new Font("Serif", Font.BOLD, 40)); g.drawString("Press any Spacebar to Continue",300,450); if(space==true) { count=0; space=false; car1dx = 7; car2dx = 4; car3dx = 6; car4dx = 5; x=500; y=632; } } if(count==0) { g.setColor(Color.BLACK); g.fillRect(0,0,1000,800); g.setColor(Color.WHITE); g.setFont(new Font("Serif", Font.BOLD, 40)); g.drawImage(run[7],225,415,this); g.drawImage(run[7],725,415,this); g.drawString("Press Spacebar to Start",300,450); if(space==true) { count=1; space=false; } } }
7f9f3127-0297-4c11-be87-86f1a708c3b2
0
public static void main(String[] args) { Set<Integer> linkedHashSet = new LinkedHashSet<Integer>(); linkedHashSet.add(1); linkedHashSet.add(2); linkedHashSet.add(0); linkedHashSet.add(4); linkedHashSet.add(8); linkedHashSet.add(6); System.out.println("linkedHashSet: " + linkedHashSet); Set<Integer> hashSet = new HashSet<Integer>(linkedHashSet); System.out.println("hashSet: " + hashSet); Set<Integer> treeSet = new TreeSet<Integer>(linkedHashSet); System.out.println("treeSet: " + treeSet); }
1e324b36-9102-4f5f-84bb-6e0212192420
9
public static Polygon interpolate(Polygon p, int points) { if (points < 1) return p; Polygon ret = new Polygon(); ret.setClosed(p.closed()); for (int i = 0; i < p.getPointCount(); i++) { float[] point = p.getPoint(i), pointNext = i < p.getPointCount()-1 ? p.getPoint(i+1) : (p.closed() ? p.getPoint(0) : null), pointPrev = i > 0 ? p.getPoint(i-1) : (p.closed() ? p.getPoint(p.getPointCount()-1) : null); if (pointNext == null || pointPrev == null) ret.addPoint(point[0],point[1]); else { for (int i2 = 1; i2 <= points; i2++) { float t = 1f/(points+1)*i2; ret.addPoint((1f-t)*(1f-t)*pointPrev[0]+2f*(1f-t)*t*point[0]+t*t*pointNext[0],(1f-t)*(1f-t)*pointPrev[1]+2f*(1f-t)*t*point[1]+t*t*pointNext[1]); } ret.addPoint(pointNext[0],pointNext[1]); i++; } } return ret; }
f726a483-ae1e-4f66-80ba-d346dbff17ad
8
private void installListeners() { button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String folderPath = MainWindow.this.getTextField().getText(); File file = new File(folderPath); int modifiers = e.getModifiers(); if ( StringUtils.equals("Valider" , e.getActionCommand()) && checkMod(modifiers, ActionEvent.CTRL_MASK)){ buildValidationUriMsgPane(file); } if (!file.exists()) { MainWindow.this.buildInfoPanel("l'uri renseignée n'est pas valide"); } else if (!file.isDirectory()) { MainWindow.this.buildInfoPanel("l'uri renseignée ne désigne pas un repertoire"); } else { MainWindow.this.buildMainPanel( FilesystemUtils.getFolderContent(file)); } } }); fileTreePane.getArbre().addTreeSelectionListener(new TreeSelectionListener(){ public void valueChanged(TreeSelectionEvent event) { if(fileTreePane.getArbre().getLastSelectedPathComponent() != null){ //La méthode getPath retourne un objet TreePath textField.setText(getAbsolutePath(event.getPath())); } } private String getAbsolutePath(TreePath treePath){ String str = ""; //On balaie le contenu de l'objet TreePath for(Object name : treePath.getPath()){ //Si l'objet a un nom, on l'ajoute au chemin if(name != null && StringUtils.isNotEmpty(name.toString())) str += name.toString(); } return str; } }); }
329004b9-6db7-4f0c-b2b1-7740416bfc92
3
private void cancelBuild(){ if (placeHolder != null){ //cancels the building of a tower removeObject(placeHolder); placeHolder = null; place = false; removeObject (r); r = null; } else if (selectedTower != null){ //cancels the selection of a tower ui.changeUi (0); showRange (0, false); selectedTower = null; } if (ui.getId () != 0){ ui.changeUi (0); } resetDefaultUi(); }
bc0a8694-3263-4faa-aeb9-8c27a06cdd27
4
@Override public Receiver createReceiver(byte code, KadServer server) { switch (code) { case ConnectMessage.CODE: return new ConnectReceiver(server, this.localNode); case ContentLookupMessage.CODE: return new ContentLookupReceiver(server, this.localNode, this.dht, this.config); case NodeLookupMessage.CODE: return new NodeLookupReceiver(server, this.localNode, this.config); case StoreContentMessage.CODE: return new StoreContentReceiver(server, this.localNode, this.dht); default: //System.out.println("No receiver found for message. Code: " + code); return new SimpleReceiver(); } }
41506de4-363f-4574-aa7b-c93a9b141298
0
@Override public int compareTo(Vertex o) { return this.distance - o.getDistance(); }
1e79e975-a847-42d3-a181-f13807647ab9
3
public void endGame() { blackFood = 0; redFood = 0; for (int[] i : world.getAnthillCells()) { if (world.getCell(i).anthill.equalsIgnoreCase("black")) { blackFood += world.getCell(i).getFood(); } else if (world.getCell(i).anthill.equalsIgnoreCase("red")) { redFood += world.getCell(i).getFood(); } } System.out.println("Black Food: " + blackFood); System.out.println("Red Food: " + redFood); }
9628884c-ed79-41fd-a21e-e8ff839291bc
5
@Override public Object getPage(int pageNum, int width, int height) throws NoSuchPageException { if (pageNum < 1 || pageNum > pdffile.getNumPages()) throw new NoSuchPageException(); PDFPage page = pdffile.getPage(pageNum); int sourceWidth = (int) page.getBBox().getWidth(); int sourceHeight = (int) page.getBBox().getHeight(); int thumbWidth, thumbHeight; if (sourceWidth > sourceHeight) { thumbWidth = width; thumbHeight = thumbWidth * sourceHeight / sourceWidth; } else { thumbHeight = height; thumbWidth = thumbHeight * sourceWidth / sourceHeight; } if (thumbWidth > width) { thumbWidth = width; thumbHeight = thumbWidth * sourceHeight / sourceWidth; } else if (thumbHeight > height) { thumbHeight = height; thumbWidth = thumbHeight * sourceWidth / sourceHeight; } final Rectangle2D rect = page.getBBox(); Image img = page.getImage( thumbWidth, thumbHeight, //width & height rect, // clip rect null, // null for the ImageObserver true, // fill background with white true // block until drawing is done ); return img; }
41029214-e4bb-4682-9d82-81a500231217
9
private void skipPastAnyPrefixJunk(InputStream in) { if (!in.markSupported()) return; try { final int scanLength = 2048; final String scanFor = "%PDF-1."; int scanForIndex = 0; boolean scanForWhiteSpace = false; in.mark(scanLength); for (int i = 0; i < scanLength; i++) { int data = in.read(); if (data < 0) { in.reset(); return; } if (scanForWhiteSpace) { if (Parser.isWhitespace((char) data)) { return; } } else { if (data == scanFor.charAt(scanForIndex)) { scanForIndex++; if (scanForIndex == scanFor.length()) { // Now read until we find white space scanForWhiteSpace = true; } } else scanForIndex = 0; } } // Searched through scanLength number of bytes and didn't find it, // so reset, in case it was never there to find in.reset(); } catch (IOException e) { try { in.reset(); } catch (IOException e2) { } } }
9353c63a-0522-42aa-a28f-95a573c9e970
4
public boolean canSummon(Familiar familiar) { return familiar != null && points() >= familiar.requiredPoints() && (!summoned() || timeLeft() <= 150) && !ctx.backpack.select().id(familiar.pouchId()).isEmpty(); }
8821607e-1924-4c64-8752-dfa764e6cd9c
1
protected boolean getFlipY (Node contNode) throws ParseException { logger.entering(getClass().getName(), "getFlipY", contNode); boolean flipY = false; String strValue = getProcessingInstructionValue(contNode, "flip-y"); if (strValue != null) flipY = strValue.equalsIgnoreCase("true"); logger.exiting(getClass().getName(), "getFlipY", flipY); return flipY; }
003cab6b-6319-412d-9680-5061c9ce2541
4
private void parsePidstatMetrics(String wholeMetricsText, List<JvmModel> list) { JvmModel cjm = list.get(list.size() - 1); String[] lines = wholeMetricsText.split("\\n"); int RSS = 0; for (String line : lines) { if (line.length() == 0 || line.charAt(0) == '#') continue; String parameters[] = line.trim().split("\\s+"); if (parameters.length == 16) { // 16 parameters totally //long VSZ = Long.parseLong(parameters[9]) / 1024; RSS = (int) Math.max(RSS, Long.parseLong(parameters[10]) / 1024); } } cjm.setRSS(RSS); }
12fd850f-4e9d-40ff-99e3-038be5e27c40
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; }
fd649071-b88f-4d8d-bf13-d61d2de6aa3d
3
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); Connection conn; Statement stmt; ResultSet rs; HttpSession hs=request.getSession(true); hs.setAttribute("Que1", 2); try { Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/chaitanya","root",""); System.out.println("conn succccsss!"); stmt=conn.createStatement(); rs=stmt.executeQuery("select comment,op1,op2,op3,op4 from comment where no=2"); if(rs.next()==true) { out.println("<html>"); out.println("<head>"); out.println("<h2>"); out.println("QUESTION NO 2"); out.println("</h2>"); out.println("</head>"); out.println("<body>"); out.println("<b>"+rs.getString("comment")+"</b>"); out.println("<form method=\"post\" action=\"http://localhost:8080/ExaminationSoftware/SavServlet\">"); out.println("<input type=\"radio\" name=\"option\" value="+rs.getString("op1")+">"+rs.getString("op1")+""); out.println("<br>"); out.println("<input type=\"radio\" name=\"option\" value="+rs.getString("op2")+">"+rs.getString("op2")+""); out.println("<br>"); out.println("<input type=\"radio\" name=\"option\" value="+rs.getString("op3")+">"+rs.getString("op3")+""); out.println("<br>"); out.println("<input type=\"radio\" name=\"option\" value="+rs.getString("op4")+">"+rs.getString("op4")+""); out.println("<br>"); out.println("<input type=\"submit\" value=\"CONFIRM\">"); out.println("</form>"); out.println("</form>"); out.println("<br>"); out.println("<br>"); out.println("<br>"); out.println("<br>"); out.println("<form method=\"post\" action=\"http://localhost:8080/ExaminationSoftware/QueServlet3\">"); out.println("<input type=\"submit\" value=\"NEXT\">"); out.println("</form>"); out.println("</body>"); out.println("</html>"); } else { out.println("<html>"); out.println("<head>"); out.println("<h2>"); out.println("QUESTION NOT AVAILABLE!"); out.println("</h2>"); out.println("</head>"); } } catch(SQLException e1) { } catch(ClassNotFoundException e2) { } }
3a5888bb-73e5-4691-be74-385205e7ea24
7
static final void method1428(byte byte0, int i) { if (byte0 != -41) { return; } if (!Class99.aBoolean1680) { i = -1; } if (~i == ~Class105.anInt1733) { return; } if (i != -1) { Class116 class116 = Class142_Sub8_Sub31.method1445(i, false); Class142_Sub27_Sub12_Sub1 class142_sub27_sub12_sub1 = class116.method1055(false); if (class142_sub27_sub12_sub1 != null) { Class112.signlink.method178(NPC.gameCanvas, true, new Point(class116.anInt1847, class116.anInt1852), class142_sub27_sub12_sub1.method1857(), ((Class142_Sub27_Sub12) (class142_sub27_sub12_sub1)).anInt4837, ((Class142_Sub27_Sub12) (class142_sub27_sub12_sub1)).anInt4830); Class105.anInt1733 = i; } else { i = -1; } } if (i == -1 && Class105.anInt1733 != -1) { Class112.signlink.method178(NPC.gameCanvas, true, new Point(), null, -1, -1); Class105.anInt1733 = -1; } }
52b62522-0ce5-4d25-ab96-62f9d45246e7
3
public void run(){ while(keepRunning){ synchronized(syncObject){ if(wait){ try { syncObject.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
5a2f5509-4475-49e4-892f-ad6be72d2ada
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(AxpherPicture.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AxpherPicture.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AxpherPicture.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AxpherPicture.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 AxpherPicture().setVisible(true); } }); }
d1c6fe19-2698-48e7-b604-6a5460b18326
5
public static void loadAllFusions() { int c; File[] files = PluginVars.dirCards.listFiles(); List<File> fusion_configs = new ArrayList<File>(); List<String> set_names = new ArrayList<String>(); for(File f : files) { if(!f.getName().substring(0,4).equalsIgnoreCase("fus_")) continue; fusion_configs.add(f); set_names.add(f.getName()); } for(File f : fusion_configs) { Fusion.loadFusions(f); } String foundsets = "Found fusion sets: "; for(c = 0; c < set_names.size(); c++) { if(c+1 >= set_names.size()) foundsets += set_names.get(c) + "."; else foundsets += set_names.get(c) + ", "; } PluginVars.plugin.getLogger().info(foundsets); }
f08bf2d5-8071-49ff-8c90-bfd7c10de360
5
public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_SPACE && !getMidair()) { setDY(-4 * Board.getInstance().getGravity()); setMidair(true); } if (key == KeyEvent.VK_LEFT) { setDX(-2); } if (key == KeyEvent.VK_RIGHT) { setDX(2); } if (key == KeyEvent.VK_E) { Board.getInstance().toggleGravity(); setDY(-0.5); } }
a793c028-dbca-4b6f-9171-b90fa4cb550b
9
public void init() throws IOException { ServerSocketChannel channel = ServerSocketChannel.open(); //Creates an unbound ServerSocketChannel System.out.println("Server Launched!"); //Bind the channel to an address. The channel starts listening to incoming connections channel.bind(new InetSocketAddress(host, port)); //Mark the ServerSocketChannel as non blocking channel.configureBlocking(false); //Creates a selector that will be used for multiplexing(?). The selector registers the ServerSocketChannel as //well as all SocketChannel's that are created Selector selector = Selector.open(); //Registers the ServerSocketChannel with the selector. The OP_ACCEPT option marks a selection key as ready when //the channel accepts a new connection. When the ServerSocket accepts a connection this key is added to the list //of selected keys of the selector. When asked for the selected keys, this key is returned and hence we know that //a new connection has been accepted SelectionKey socketServerSelectionKey = channel.register(selector, SelectionKey.OP_ACCEPT); //Set property in the key that identifies the channel Map<String, String> properties = new HashMap<String, String>(); properties.put(channelType, serverChannel); socketServerSelectionKey.attach(properties); //Wait for the selected keys for(;;) { //The select method is a blocking method which returns when at least one of the registered channels is selected //In this example, when the socket accepts a new connection, this method will return. Once a SocketClient is added //to the list of registered channels, then this method would also return when one of the clients has data to be read //or written. It is also possible to perform a nonblocking select using the selectNow() function. We can also //specify the maximum time for which a select function can be blocked using the select(long timeout) function if(selector.select() == 0) { continue; //start from the beginning of the loop again } //The select method returns with a list of selected keys Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> iterator = selectedKeys.iterator(); while(iterator.hasNext()) { SelectionKey key = iterator.next(); //The selection key could either be the ServerSocket informing that a new connection has been made, or a socket //client that is ready for read/write //We use the properties object attached to the channel to find out the type of channel if(((Map) key.attachment()).get(channelType).equals(serverChannel)) { //A new connection has been obtained. This channel is therefor a ServerSocket ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); System.out.println("New connection obtained"); //Accepts the new connection on the ServerSocket. Since the server socket channel is marked as non-block, this //channel will return null if no client is connected SocketChannel clientSocketChannel = serverSocketChannel.accept(); if(clientSocketChannel != null) { System.out.println("Client Connected!"); //Set the client connection to be non-blocking clientSocketChannel.configureBlocking(false); SelectionKey clientKey = clientSocketChannel.register(selector, SelectionKey.OP_READ, SelectionKey.OP_WRITE); Map<String, String> clientProperties = new HashMap<String, String>(); clientProperties.put(channelType, clientChannel); clientKey.attach(clientProperties); //Write something to the new created client CharBuffer buffer = CharBuffer.wrap("Hello Client"); while(buffer.hasRemaining()) { clientSocketChannel.write(Charset.defaultCharset().encode(buffer)); } buffer.clear(); } } else { //Data is available for read //Buffer for reading ByteBuffer buffer = ByteBuffer.allocate(20); SocketChannel clientChannel = (SocketChannel) key.channel(); int bytesRead = 0; if(key.isReadable()) { //The channel is non-blocking, so keep it open till the count is >=0 if((bytesRead - clientChannel.read(buffer)) > 0) { buffer.flip(); System.out.println(Charset.defaultCharset().decode(buffer)); buffer.clear(); } if(bytesRead < 0) { //They key is automatiicaly invalidated once the channel is closed clientChannel.close(); } } } //Once a key is handled, it needs to be removed iterator.remove(); } } }
5bc2fa50-4c01-44c1-9a92-51e43e8e4e84
5
public static int minimumTotal(List<List<Integer>> triangle) { if (null == triangle) { return 0; } else if (1 == triangle.size()) { return triangle.get(0).get(0); } int[] minlen = new int[triangle.size()]; for (int level = triangle.size() - 1; level >= 0; level--) { for (int i = 0; i < triangle.get(level).size(); i++) { if (level == triangle.size() - 1) { minlen[i] = triangle.get(level).get(i); } else { minlen[i] = triangle.get(level).get(i) + min(minlen[i], minlen[i + 1]); } } } return minlen[0]; }
e90ce23e-7401-48a4-80a8-d0fa1ad7bfd9
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(AddNonMember.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AddNonMember.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AddNonMember.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AddNonMember.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 AddNonMember().setVisible(true); } }); }
4e80d6a5-9f74-4ccf-838d-5c4ba0f03914
4
public Manacher(String s) { this.s = s.toCharArray(); t = preprocess(); p = new int[t.length]; int center = 0, right = 0; for (int i = 1; i < t.length - 1; i++) { int mirror = 2 * center - i; if (right > i) p[i] = Math.min(right - i, p[mirror]); // attempt to expand palindrome centered at i while (t[i + (1 + p[i])] == t[i - (1 + p[i])]) p[i]++; // if palindrome centered at i expands past right, // adjust center based on expanded palindrome. if (i + p[i] > right) { center = i; right = i + p[i]; } } }
f2be345d-d0bd-4fb7-9fed-4e215d1a2414
8
public static double getDet(double[][] A){ if(A.length != A[0].length) return Double.NaN; double det = 0; int cofact = 0; if(A.length == 1) return A[0][0]; for(int i = 0; i<A.length; i++){ double[][] T = new double[A.length-1][A.length-1]; for(int j = 1; j<A.length; j++){ for(int k = 0; k<A.length; k++){ if(k<i) T[j-1][k] = A[j][k]; else if(k >i) T[j-1][k-1] = A[j][k]; } } if(i%2 == 0) cofact = 1; else cofact = -1; det += cofact*A[0][i]*(getDet(T)); } return det; } //end getDet method
2a1bc1bd-bb44-4a62-a13a-cea76b560afe
4
public JSONWriter key(String s) throws JSONException { if (s == null) { throw new JSONException("Null key."); } if (this.mode == 'k') { try { if (this.comma) { this.writer.write(','); } stack[top - 1].putOnce(s, Boolean.TRUE); this.writer.write(JSONObject.quote(s)); this.writer.write(':'); this.comma = false; this.mode = 'o'; return this; } catch (IOException e) { throw new JSONException(e); } } throw new JSONException("Misplaced key."); }
63c820c2-af76-47bf-a822-d9a9f2a618a4
4
public static void check_intersect(double Hy, double Hxl, double Hxr, double Vx, double Vyt, double Vyb) { if (Hy < Vyt && Hy > Vyb && Vx > Hxl && Vx < Hxr) { //if the y-value of the horizontal component is within the range of the y-values of the vertical //component and the x-values of the vertical component is within the range of the x-values of //the horizontal component, then the two segments/lines intersect System.out.println("The vertical and horizontal segments intersect."); } else { //if not, then they don't System.out.println("The vertical and horizontal segments do not intersect."); } }
ffdf39bf-d37c-43c9-9586-6d9ac360e673
5
public Image contrast(Image im, int width, int height, int contrast) { int pix[] = JIPTUtilities.getPixelArray(im); int new_pix[] = new int[width*height]; int mean_luminance = 0; mean_luminance = getMeanLuminance(pix); for(int i = 0; i < pix.length; i++) { //////// Get pixels /////////////////// int alpha = (pix[i] >> 24) & 0xff; int red = (pix[i] >> 16) & 0xff; int green = (pix[i] >> 8) & 0xff; int blue = (pix[i] ) & 0xff; ////// Adjust for contrast ///////// if(contrast <= 0) { red = red + (int) ((red - mean_luminance)*(contrast/100.0)); green = green + (int) ((green - mean_luminance)*(contrast/100.0)); blue = blue + (int) ((blue - mean_luminance)*(contrast/100.0)); } else { if(red - mean_luminance > 0) red = red + (int) ((255-red)*contrast/100.0); else red = red - (int) (red*contrast/100.0); if(green - mean_luminance > 0) green = green + (int) ((255-green)*contrast/100.0); else green = green - (int) (green*contrast/100.0); if(blue - mean_luminance > 0) blue = blue + (int) ((255-blue)*contrast/100.0); else blue = blue - (int) (blue*contrast/100.0); } ///// Put in correct range (0...255) ///// red = putInRange(red); green = putInRange(green); blue = putInRange(blue); new_pix[i] = 0; new_pix[i] += (alpha << 24); // alpha new_pix[i] += (red << 16); // r new_pix[i] += (green << 8); // g new_pix[i] += (blue ); // b } Image new_im = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(width, height, new_pix, 0, width)); return new_im; }
8643025c-6a1d-476f-8b60-68678b39e51f
8
protected Dimension doLayout(Container target) { // Pass 1 - get preferred sizes minw = minh = 0; curComps = target.getComponents(); for (int i = 0; i<curComps.length; i++) { Component tc = curComps[i]; Dimension d = tc.getPreferredSize(); minw = Math.max(minw, d.width); minh = Math.max(minh, d.height); } // Pass 2 - move & resize components int x = hPadding, y = vPadding; for (int i = 0; i<curComps.length; i++) { Component tc = curComps[i]; Dimension d = tc.getPreferredSize(); int cx, cy, cw, ch; switch (alignment) { case X_AXIS: if (tc instanceof Spacer) cw = d.width; else cw = minw; ch = minh; // d.height; cx = x; x += cw+hPadding; cy = vPadding; y = ch; break; case Y_AXIS: cw = minw; // d.width; if (tc instanceof Spacer) ch = d.height; else ch = minh; cx = hPadding; x = cw; cy = y; y += ch+vPadding; break; default: throw new IllegalArgumentException("Invalid alignment"); } tc.setBounds(cx, cy, cw, ch); } switch (alignment) { case X_AXIS: return new Dimension(x, y+2*vPadding); case Y_AXIS: return new Dimension(x+2*hPadding, y); default: throw new IllegalArgumentException("Invalid alignment"); } }
2795e062-9ce3-4bd2-b327-bcc38454de8d
8
private void initialize(String fileName) throws IOException { BufferedReader br = new BufferedReader(new FileReader(fileName)); String nextLine; while ((nextLine = br.readLine()) != null) { if (nextLine.trim().equals("DESTINATIONS")) { while (!(nextLine = br.readLine().trim()) .equals("END_DESTINATIONS")) { if (!nextLine.isEmpty()) { String[] destParams = nextLine.split(" "); this.destinations.add(new Destination( Integer.parseInt(destParams[1]), Integer.parseInt(destParams[2]), destParams[0])); } // if - line not empty } // while - still loading destinations } // if - loading destinations else if (nextLine.trim().equals("GROUP_CONTROLLERS")) { while (!(nextLine = br.readLine().trim()) .equals("END_GROUP_CONTROLLERS")) { if (!nextLine.isEmpty()) { String[] gcParams = nextLine.split(" ", 4); GroupController controller = new GroupController( Integer.parseInt(gcParams[1]), Integer.parseInt(gcParams[2]), gcParams[0], gcParams[3]); addressMap.put( new XBeeAddress64(gcParams[3]), controller); while (!(nextLine = br.readLine().trim()) .equals("END_SPACES")) { String[] spaceParams = nextLine.split(" "); this.spaces.add(controller.addSpace( Integer.parseInt(spaceParams[1]), Integer.parseInt(spaceParams[2]), controller.getId() + "." + spaceParams[0])); } // while - adding spaces } // if - line not empty } // while - still loading group controllers/parking spaces } // else if - loading group controllers/parking spaces } // while - not end of file br.close(); } // initialize
ab904eb0-311f-405d-84ad-637aa59098ec
3
@WebMethod(operationName = "ReadCountry") public ArrayList<Country> ReadCountry(@WebParam(name = "cnt_id") String cnt_id) { Country cnt = new Country(); ArrayList<Country> cnts = new ArrayList<Country>(); ArrayList<QueryCriteria> qc = new ArrayList<QueryCriteria>(); if(!cnt_id.equals("-1")){ qc.add(new QueryCriteria("cnt_id", cnt_id, Operand.EQUALS)); } ArrayList<String> fields = new ArrayList<String>(); ArrayList<QueryOrder> order = new ArrayList<QueryOrder>(); try { cnts = cnt.Read(qc, fields, order); } catch (SQLException ex) { Logger.getLogger(JAX_WS.class.getName()).log(Level.SEVERE, null, ex); } if(cnts.isEmpty()){ return null; } return cnts; }
2a251345-d0e0-45d4-b05c-681671ea9a8a
4
private void generateChests() { int chestWidth = 34; int chestHeight = 23; int[] chestLevels = {2, 2, 3, 3, 4, 5}; for (int level = 0; level < chestLevels.length; level++) { for (int count = 0; count < chestLevels[level]; count++) { boolean chestPlaced = false; do { Point p = this.getNewXY(gameController.getMapWidth(), chestHeight, level); int y = findNextFloor(p.x + chestWidth, p.y, chestHeight); if (p.y == y) { //make sure the chest isn't spawned in view Placeable chest = loadChest(p.x, p.y - 16); chestPlaced = true; } } while (!chestPlaced); } } }
e3e000dc-1151-499a-8ecd-6bd376c87371
0
public int read() throws IOException { //init(); isInited = true; return internalIn.read(); }
74b04d0a-907c-4525-ad6d-90e203553d35
8
protected void cellResized(Object cell) { mxGraph graph = getGraph(); mxGraphView view = graph.getView(); mxIGraphModel model = graph.getModel(); mxCellState state = view.getState(cell); mxCellState pstate = view.getState(model.getParent(cell)); if (state != null && pstate != null) { Object[] cells = getCellsToShift(state); mxGeometry geo = model.getGeometry(cell); if (cells != null && geo != null) { mxPoint tr = view.getTranslate(); double scale = view.getScale(); double x0 = state.getX() - pstate.getOrigin().getX() - tr.getX() * scale; double y0 = state.getY() - pstate.getOrigin().getY() - tr.getY() * scale; double right = state.getX() + state.getWidth(); double bottom = state.getY() + state.getHeight(); double dx = state.getWidth() - geo.getWidth() * scale + x0 - geo.getX() * scale; double dy = state.getHeight() - geo.getHeight() * scale + y0 - geo.getY() * scale; double fx = 1 - geo.getWidth() * scale / state.getWidth(); double fy = 1 - geo.getHeight() * scale / state.getHeight(); model.beginUpdate(); try { for (int i = 0; i < cells.length; i++) { if (cells[i] != cell && isCellShiftable(cells[i])) { shiftCell(cells[i], dx, dy, x0, y0, right, bottom, fx, fy, isExtendParents() && graph.isExtendParent(cells[i])); } } } finally { model.endUpdate(); } } } }
4e2f1b3c-90a7-4b23-869b-b2ca57e9e5af
8
@Override public void iterate(){ matcount += 1; if(matcount >= mat){matcount = 0; calculate(); } if(ages){ if(active){ if(age == 0){age = 1;} else{age += 1;}}else{ age = 0;} if(fades){ if( age >= fade){ purgeState(); age = 0;}} if( age > 1023){ age = 1023; }state = agify(age);} else{if(active){state = 1;}else{state = 0;}} }
7cf84985-a826-475b-8322-4ccc94db2f45
9
public boolean commandProcessing(String userInput) /* processes user commands */ { boolean successfulMove = false; if(userInput.startsWith("clear")) { clear(); } else if(userInput.startsWith("go")) { successfulMove = go(userInput); } else if(userInput.startsWith("help")) { printHelp(); } else if(userInput.startsWith("look")) { look(); } else if(userInput.startsWith("open")) { open(userInput); } else if(userInput.startsWith("stats")) { stats(); } else if(userInput.startsWith("inventory")) { inventory(); } else if(userInput.startsWith("spawn")) { encounter(); } else if(userInput.startsWith("quit")) { System.out.printf("Quitting.\n"); System.exit(0); } else { System.out.printf("Default case.\n"); } return successfulMove; }
b1c72dd7-6cf0-4458-ab47-b38286a039d0
1
public MFEVersionCommand(CommandParameter par) { if(par == null) throw new NullPointerException("MFEVersionCommand has a null CommandParameter"); this.par= par; }
77024a5c-815f-4ea2-8285-27cdd5122913
8
public static void menu() { while(true) { print("**********************\n"); print("* SPN Demo *\n"); print("**********************\n"); print("* 1 - Create *\n"); print("* 2 - List *\n"); print("* 3 - Verify *\n"); print("* 4 - Start *\n"); print("* 5 - Stop *\n"); print("* 6 - Decommission *\n"); print("* 0 - Exit the demo *\n"); print("**********************\n"); print("Please choose your operation:\n"); switch(Integer.valueOf(read())) { case 0: bye(); return; case 1: create(); break; case 2: list(); break; case 3: verify(); break; case 4: start(); break; case 5: stop(); break; case 6: decommission(); break; default: print("Wrong choice!\n"); break; } } }
01ca95af-dc62-42f9-ba40-b080a39629c7
2
public void checkConsistent() { super.checkConsistent(); StructuredBlock sb = outer; while (sb != continuesBlock) { if (sb == null) throw new RuntimeException("Inconsistency"); sb = sb.outer; } }
d386553b-f2b8-4e7c-bf05-48bc1b13d57e
0
public Being bear() { dynamicStats.get(StatType.D_EATEN).addToValue(-30.0); int newClassID = WorldPhysics.nextID(); return new CellCreature(new Point3(pos), constStats.mutateClone(), childDynamicStats.clone(), newClassID); }
8f9165b5-7ce5-4e06-9146-45411a83cf68
0
public Nan() { super("Nan", 29780, 600, 9001, 500, as); as.setSkill(0, "Logic", 10000, 50, "Nan uses the power of logic to smite his enemy."); as.setSkill(1, "Righteous Fury", 25000, 100, "Nan unleashes righteous fury."); as.setSkill(2, "Lance Of Longinus", 90001, 150, "Nan sends the holy Lance of Longinus at his enemy."); as.setSkill(3, "Ascension", 1000000, 250, "Nan ascends into a higher existence."); }
3ae83ba3-26ae-4f23-8e38-0fb68b70315f
7
public void removeSecondaryEdge(ComparableNode source, ComparableNode target) throws MaltChainedException { if (source == null || target == null || source.getBelongsToGraph() != this || target.getBelongsToGraph() != this) { throw new SyntaxGraphException("Head or dependent node is missing."); } else if (!target.isRoot()) { Iterator<Edge> ie = ((Node)target).getIncomingEdgeIterator(); while (ie.hasNext()) { Edge e = ie.next(); if (e.getSource() == source) { ie.remove(); graphEdges.remove(e); edgePool.checkIn(e); } } } }
b6e8d7c0-52ec-498b-96db-3d9675db6900
6
public void saveTracks(String folderToSave) { File folder = new File(folderToSave); boolean success = folder.mkdirs(); System.out.println("created folder: " + folder.getAbsolutePath() + " " + (success ? "created" : "")); MyDownloadExecutor executor = new MyDownloadExecutor(nThreads); for (Track track : tracks) { String fileName = fixWindowsFileName(track.getFileName()) + ".mp3"; File dest = new File(folder.getAbsolutePath() + "/" + fileName); if (!dest.exists() || dest.length() < MINIMUM_TRACK_SIZE) { executor.jobsCountInc(); executor.execute(new Downloader(track.getUrl(), dest, executor)); downloadedTracksCount++; } else { System.out.println(dest + " already exists"); } } if (downloadedPhotosCount == 0) { executor.shutdown(); } try { executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("All tracks try to download."); }
00e12a49-178d-448b-8ea0-b1c4fee658e1
6
public static void start() { running = true; Runnable runnable = new Runnable() {@Override public void run() { long lastMillis = System.currentTimeMillis(); long deltaLastMillis = System.currentTimeMillis(); while (running) { long newMillis = System.currentTimeMillis(); long sleep = 15 - (newMillis - lastMillis); lastMillis = newMillis; if (sleep > 1) try {Thread.sleep(sleep);} catch (InterruptedException ex) {} long deltaNewMillis = System.currentTimeMillis(); final float delta = (deltaNewMillis - deltaLastMillis) / 1000f; try { SwingUtilities.invokeAndWait(new Runnable() {@Override public void run() { for (int i=0, n=tweenManagers.size(); i<n; i++) tweenManagers.get(i).update(delta); }}); } catch (InterruptedException ex) { } catch (InvocationTargetException ex) { } deltaLastMillis = newMillis; } }}; new Thread(runnable).start(); }
a09c71f6-980e-4652-800c-3021a59de182
2
public int tLineCount(){ int tCount = 0; if(statement.toString()!=null) tCount = statement.tLineCount(); if(statements.toString()!=null){ tCount += statements.tLineCount(); } return tCount; }
eb968a32-ca77-46c0-bcc4-8c5fe12baa8a
0
public void setIntelligence(double intelligence) { this.intelligence = intelligence; }
d7ded1b3-c4d2-4378-a76c-dde3d866fcd9
5
public List<List<Gate>> getGates() { List<List<Gate>> layersOfGates = new ArrayList<List<Gate>>(); boolean firstLine = true; try { BufferedReader fbr = new BufferedReader(new InputStreamReader( new FileInputStream(circuitFile), Charset.defaultCharset())); String line; //hack to skip first line List<Gate> currentLayer = null; while ((line = fbr.readLine()) != null) { if (line.isEmpty()){ } else if (firstLine) { headerLine = line; String[] split = headerLine.split(" "); numberOfInputs = Integer.parseInt(split[0]); numberOfInputs = Integer.parseInt(split[1]); numberOfWires = Integer.parseInt(split[2]); numberOfANDGates = Integer.parseInt(split[5]); firstLine = false; } else if (line.startsWith("*")) { currentLayer = new ArrayList<Gate>(); layersOfGates.add(currentLayer); } else { // Parse each gate line and count numberOfNonXORGates Gate g = new Gate(line, InputGateType.CUDA); currentLayer.add(g); } } fbr.close(); } catch (IOException e) { e.printStackTrace(); } return layersOfGates; }
9f721a51-59c3-4122-a500-2dbe1e8b4519
6
public void clicked(String sender) { if (sender == "hud") { for (int i = 0; i < HUD.qSlots.length; i++) { HUD.qSlots[i].selected = false; } selected = true; Player.selectedWeapon = this.weapon; } if (sender == "pane") { for (int i = 0; i < SpellSelectGUI.spells.size(); i++) { SpellSelectGUI.spells.get(i).selected = false; } selected = true; Player.dimSpell(spell.name); if (!Player.skill) { if (Player.target != null) { Player.startCast(); } } else { Player.startCast(); } } }
1cd99494-73d1-430e-9b72-f0143bd47e28
2
public Option getOption(String ID) { for (Option o: options) { if (o.getID().equals(ID)) { return o; } } return null; }
80d215df-e3cc-49b5-ad3a-4b59edaec60d
5
private boolean setupSQL() { if (config.getSQLValue().equalsIgnoreCase("MySQL")) { dataop = new MySQLOptions(config.getHostname(), config.getPort(), config.getDatabase(), config.getUsername(), config.getPassword()); } else if (config.getSQLValue().equalsIgnoreCase("SQLite")) { dataop = new SQLiteOptions(new File(getDataFolder()+"/coupon_data.db")); } else if (!config.getSQLValue().equalsIgnoreCase("MySQL") && !config.getSQLValue().equalsIgnoreCase("SQLite")) { sendErr("The SQLType has the unknown value of: "+config.getSQLValue()); return false; } sql = new SQL(this, dataop); try { sql.open(); sql.createTable("CREATE TABLE IF NOT EXISTS couponcodes (name VARCHAR(24), ctype VARCHAR(10), usetimes INT(10), usedplayers TEXT(1024), ids VARCHAR(255), money INT(10), groupname VARCHAR(20), timeuse INT(100), xp INT(10))"); cm = new CouponManager(this, sql); } catch (SQLException e) { e.printStackTrace(); return false; } return true; }
d34c8fbb-1734-48c7-a497-4028cca5920d
8
@SuppressWarnings("static-access") public boolean doIt(int width, int height, int frameRate, List<String> inFiles, MediaLocator outML, String type) { this.fRate = frameRate; ImageDataSource ids = new ImageDataSource(width, height, frameRate, inFiles); Processor p; try { //System.err.println("- create processor for the image datasource ..."); p = Manager.createProcessor(ids); } catch (Exception e) { System.err.println("Yikes! Cannot create a processor from the data source."); return false; } p.addControllerListener(this); // Put the Processor into configured state so we can set // some processing options on the processor. p.configure(); if (!waitForState(p, p.Configured)) { System.err.println("Failed to configure the processor."); return false; } // Set the output content descriptor to QuickTime. p.setContentDescriptor(new ContentDescriptor(type)); // Query for the processor for supported formats. // Then set it on the processor. TrackControl tcs[] = p.getTrackControls(); Format f[] = tcs[0].getSupportedFormats(); if (f == null || f.length <= 0) { System.err.println("The mux does not support the input format: " + tcs[0].getFormat()); return false; } tcs[0].setFormat(f[0]); //System.err.println("Setting the track format to: " + f[0]); // We are done with programming the processor. Let's just // realize it. p.realize(); if (!waitForState(p, p.Realized)) { System.err.println("Failed to realize the processor."); return false; } // Now, we'll need to create a DataSink. DataSink dsink; if ((dsink = createDataSink(p, outML)) == null) { System.err.println("Failed to create a DataSink for the given output MediaLocator: " + outML); return false; } dsink.addDataSinkListener(this); fileDone = false; System.err.println("start processing..."); // OK, we can now start the actual transcoding. try { p.start(); dsink.start(); } catch (IOException e) { System.err.println("IO error during processing"); return false; } // Wait for EndOfStream event. waitForFileDone(); // Cleanup. try { dsink.close(); } catch (Exception e) {} p.removeControllerListener(this); System.err.println("...done processing."); return true; }