text
stringlengths
14
410k
label
int32
0
9
private void remplirTournee(List<NoeudItineraire> noeuds) { int indexNoeuds = 0; //Entrepot List<Troncon> tronconsEntrepot = plan.getCheminlePlusCourt(noeuds.get(indexNoeuds).adresse,noeuds.get(indexNoeuds+1).adresse); indexNoeuds++; Trajet trajetEntrepot = new Trajet(tronconsEntrepot); entrepot.setTrajet(trajetEntrepot); etat = EtatItineraire.PRET; for(PlageHoraire p : this.plagesHoraire) { List<Livraison> livraisonsOrdonnees = new ArrayList<Livraison>(); for(int i=indexNoeuds ; i<indexNoeuds+p.getAllLivraison().size() ; i++) { livraisonsOrdonnees.add((Livraison)noeuds.get(i)); } p.setLivraisons(livraisonsOrdonnees); for(int i=0 ; i<p.getAllLivraison().size() ; i++) { List<Troncon> tronconsTrajet = plan.getCheminlePlusCourt(noeuds.get(indexNoeuds).adresse,noeuds.get(indexNoeuds+1).adresse); indexNoeuds++; Trajet trajet = new Trajet(tronconsTrajet); p.getLivraison(i).setTrajet(trajet); } } calculerHoraires(); }
3
@Test public void testWriteWriteDeadlock() throws Exception { System.out.println("testWriteWriteDeadlock constructing deadlock:"); LockGrabber lg1Write0 = startGrabber(tid1, p0, Permissions.READ_WRITE); LockGrabber lg2Write1 = startGrabber(tid2, p1, Permissions.READ_WRITE); // allow initial write locks to acquire Thread.sleep(POLL_INTERVAL); LockGrabber lg1Write1 = startGrabber(tid1, p1, Permissions.READ_WRITE); LockGrabber lg2Write0 = startGrabber(tid2, p0, Permissions.READ_WRITE); while (true) { Thread.sleep(POLL_INTERVAL); assertFalse(lg1Write1.acquired() && lg2Write0.acquired()); if (lg1Write1.acquired() && !lg2Write0.acquired()) break; if (!lg1Write1.acquired() && lg2Write0.acquired()) break; if (lg1Write1.getError() != null) { lg1Write0.stop(); lg1Write1.stop(); bp.transactionComplete(tid1); Thread.sleep(rand.nextInt(WAIT_INTERVAL)); tid1 = new TransactionId(); lg1Write0 = startGrabber(tid1, p0, Permissions.READ_WRITE); lg1Write1 = startGrabber(tid1, p1, Permissions.READ_WRITE); } if (lg2Write0.getError() != null) { lg2Write0.stop(); lg2Write1.stop(); bp.transactionComplete(tid2); Thread.sleep(rand.nextInt(WAIT_INTERVAL)); tid2 = new TransactionId(); lg2Write0 = startGrabber(tid2, p1, Permissions.READ_WRITE); lg2Write1 = startGrabber(tid2, p0, Permissions.READ_WRITE); } } System.out.println("testWriteWriteDeadlock resolved deadlock"); }
8
private void appendRow(StringBuilder sb, Puzzle p, int r) { sb.append("|"); for (int c = 0; c < p.getSide(); c++) { if (c > 0 && c % p.getBoxSize() == 0) { sb.append(" |"); } sb.append(" "); sb.append(p.getValue(c + r * p.getSide())); } sb.append(" |\n"); }
3
@Override public boolean fill() throws IOException { boolean changed = false; BufferedReader reader = new BufferedReader(new FileReader(filePath)); while (reader.ready()) { String line = reader.readLine(); if (line == null) { break; } line = line.trim(); if (line.startsWith("#") || line.isEmpty()) { // is a comment? continue; } String[] parts = line.split(":", 2); Preconditions.checkArgument(parts.length != 2 || parts[0].isEmpty() || parts[1].isEmpty(), "key or value not specified"); if (!changed && this.data.containsKey(parts[0]) && !(this.data.get(parts[0]).equals(parts[1]))) { changed = true; } this.data.put(parts[0], parts[1]); } return changed; }
9
@Override public Block.ExitStatus evaluate(IdentifierMap values) { for (int i = 0; i < conditions.size(); i++) { Value conditionValue = conditions.get(i).evaluate(values); if (conditionValue instanceof BooleanValue) { if (conditionValue == BooleanValue.TRUE) { if (blocks.get(i) == null) return Block.ExitStatus.NORMAL; Block.ExitStatus evaled = blocks.get(i).evaluate(values); if (evaled == Block.ExitStatus.RETURN) setReturnValue(blocks.get(i).getReturnValue()); return evaled; } } else // should this really be a syntax error? throw new SyntaxError("Expected a boolean for if statement condition: " + conditionValue); } if (elseBlock != null) { Block.ExitStatus evaled = elseBlock.evaluate(values); if (evaled == Block.ExitStatus.RETURN) setReturnValue(elseBlock.getReturnValue()); return evaled; } return Block.ExitStatus.NORMAL; }
7
public FTPFile parse(String serverString, String parentDirectory) throws ParseException { if(serverString.charAt(0) != '+') throw new ParseException("Not an EPLF LIST response (no '+' on line start)",0); serverString = serverString.substring(1); StringTokenizer st = new StringTokenizer(serverString,","); Date date = null; String fileName = ""; String mode = ""; long size = -1; boolean directory = false; while(st.hasMoreTokens()) { String token = st.nextToken(); switch(token.charAt(0)) { case 'r': mode += "r--r--r--"; break; case '/': directory=true; mode = "d" + mode; break; case 's': size = Long.parseLong(token.substring(1)); break; case 'm': date = new Date(Long.parseLong(token.substring(1)) * 1000); break; case '\011': fileName = token.trim(); break; default: log.debug("skip unnessacry token: " + token); break; } } if(mode.length() == 9) mode = "-" + mode; FTPFile file = new FTPFile(FTPFile.UNKNOWN,parentDirectory,fileName,serverString); file.setDate(date); file.setMode(mode); file.setDirectory(directory); file.setSize(size); return file; }
8
public AlgorithmIdentifierType createAlgorithmIdentifierType() { return new AlgorithmIdentifierType(); }
0
private boolean endOfTerms(String ch, int i) { boolean end = true; char tabChar[] = ch.toCharArray(); for (int j = i + 1; j < ch.length(); j++) { if (tabChar[j] == '1' || tabChar[j] == '0') { end = false; break; } } return end; }
3
public void CheckChatHistory(String currentUser) { String path = "resources/"; String files; File folder = new File(path); File[] listOfFiles = folder.listFiles(); //list all the files for (int i = 0; i < listOfFiles.length; i++) { //check if it is not a folder if (listOfFiles[i].isFile()) { files = listOfFiles[i].getName(); //check the extention of the file if (files.endsWith(".txt")) { //look if the user have old chat if(files.matches(currentUser+"-.*")){ //Reconized the name of the sender user String nameOfUser[] = files.split("-"); nameOfUser = nameOfUser[1].split(".txt"); System.out.println(nameOfUser[0]); //***********read the line **********// try{ BufferedReader br = new BufferedReader( new InputStreamReader( new FileInputStream(path+files))); String ligne; while ((ligne = br.readLine())!=null){ writeMessageToOnlineUser(currentUser, nameOfUser[0], ligne); } File f = new File(path+files); boolean success = f.delete(); if (!success) throw new IllegalArgumentException("Delete: deletion failed"); } catch (Exception e){ System.out.println(e.toString()); } //*********************// } } } } }
7
public boolean checkCollision(BallModel ball) { if (ball.getPosX() + ball.getDiameter()/2 > this.getPaddleX() && ball.getPosX() + ball.getDiameter()/2 < this.getPaddleX() + this.getPaddleWidth() && ball.getPosY() > this.getPaddleY() && ball.getPosY() < this.getPaddleY() + this.getPaddleHeight()) { handleCollision(ball); return true; } else if (ball.getCenterPosY() - ball.getRadius() < paddleY && ball.getCenterPrevPosX() > paddleY + paddleHeight) { return advancedCollison(ball); } else return false; }
6
private Object select(PreparedStatement st, Class ret) throws SQLException { ResultSet result = st.executeQuery(); boolean castToArray = false; if (ret.isArray()) { ret = ret.getComponentType(); castToArray = true; } Mapper retMapper = Mapper.Registry.get(ret); if (retMapper == null) { retMapper = new CastMapper(); } List resultList = new ArrayList(); while (result.next()) { resultList.add(retMapper.produceFrom(result)); } if (resultList.isEmpty()) { if (castToArray) return Array.newInstance(ret, 0); else return null; } else { if (castToArray) { Object[] array = (Object[]) Array.newInstance(ret, resultList.size()); int i = 0; for (Object o: resultList) { array[i] = o; i++; } return array; } else return resultList.get(0); } }
7
private void checkEvictionOrder(boolean lifo) throws Exception { SimpleFactory<Integer> factory = new SimpleFactory<Integer>(); GenericKeyedObjectPool<Integer, String> pool = new GenericKeyedObjectPool<Integer, String>(factory); pool.setNumTestsPerEvictionRun(2); pool.setMinEvictableIdleTimeMillis(100); pool.setLifo(lifo); for (int i = 0; i < 3; i ++) { Integer key = new Integer(i); for (int j = 0; j < 5; j++) { pool.addObject(key); } } // Make all evictable Thread.sleep(200); /* * Initial state (Key, Object) pairs in order of age: * * (0,0), (0,1), (0,2), (0,3), (0,4) * (1,5), (1,6), (1,7), (1,8), (1,9) * (2,10), (2,11), (2,12), (2,13), (2,14) */ pool.evict(); // Kill (0,0),(0,1) assertEquals(3, pool.getNumIdle(zero)); String objZeroA = pool.borrowObject(zero); assertTrue(lifo ? objZeroA.equals("04") : objZeroA.equals("02")); assertEquals(2, pool.getNumIdle(zero)); String objZeroB = pool.borrowObject(zero); assertTrue(objZeroB.equals("03")); assertEquals(1, pool.getNumIdle(zero)); pool.evict(); // Kill remaining 0 survivor and (1,5) assertEquals(0, pool.getNumIdle(zero)); assertEquals(4, pool.getNumIdle(one)); String objOneA = pool.borrowObject(one); assertTrue(lifo ? objOneA.equals("19") : objOneA.equals("16")); assertEquals(3, pool.getNumIdle(one)); String objOneB = pool.borrowObject(one); assertTrue(lifo ? objOneB.equals("18") : objOneB.equals("17")); assertEquals(2, pool.getNumIdle(one)); pool.evict(); // Kill remaining 1 survivors assertEquals(0, pool.getNumIdle(one)); pool.evict(); // Kill (2,10), (2,11) assertEquals(3, pool.getNumIdle(two)); String objTwoA = pool.borrowObject(two); assertTrue(lifo ? objTwoA.equals("214") : objTwoA.equals("212")); assertEquals(2, pool.getNumIdle(two)); pool.evict(); // All dead now assertEquals(0, pool.getNumIdle(two)); pool.evict(); // Should do nothing - make sure no exception // Currently 2 zero, 2 one and 1 two active. Return them pool.returnObject(zero, objZeroA); pool.returnObject(zero, objZeroB); pool.returnObject(one, objOneA); pool.returnObject(one, objOneB); pool.returnObject(two, objTwoA); // Remove all idle objects pool.clear(); // Reload pool.setMinEvictableIdleTimeMillis(500); factory.counter = 0; // Reset counter for (int i = 0; i < 3; i ++) { Integer key = new Integer(i); for (int j = 0; j < 5; j++) { pool.addObject(key); } Thread.sleep(200); } // 0's are evictable, others not pool.evict(); // Kill (0,0),(0,1) assertEquals(3, pool.getNumIdle(zero)); pool.evict(); // Kill (0,2),(0,3) assertEquals(1, pool.getNumIdle(zero)); pool.evict(); // Kill (0,4), leave (1,5) assertEquals(0, pool.getNumIdle(zero)); assertEquals(5, pool.getNumIdle(one)); assertEquals(5, pool.getNumIdle(two)); pool.evict(); // (1,6), (1,7) assertEquals(5, pool.getNumIdle(one)); assertEquals(5, pool.getNumIdle(two)); pool.evict(); // (1,8), (1,9) assertEquals(5, pool.getNumIdle(one)); assertEquals(5, pool.getNumIdle(two)); pool.evict(); // (2,10), (2,11) assertEquals(5, pool.getNumIdle(one)); assertEquals(5, pool.getNumIdle(two)); pool.evict(); // (2,12), (2,13) assertEquals(5, pool.getNumIdle(one)); assertEquals(5, pool.getNumIdle(two)); pool.evict(); // (2,14), (1,5) assertEquals(5, pool.getNumIdle(one)); assertEquals(5, pool.getNumIdle(two)); Thread.sleep(200); // Ones now timed out pool.evict(); // kill (1,6), (1,7) - (1,5) missed assertEquals(3, pool.getNumIdle(one)); assertEquals(5, pool.getNumIdle(two)); Object obj = pool.borrowObject(one); if (lifo) { assertEquals("19", obj); } else { assertEquals("15", obj); } }
9
public String toString(){ String toRet="\n"; toRet+= ("\n 0 1 2 3 4\t 0 1 2 3 4"); for (int row = 0; row < 5; row++) { String rowStr = row + " "; for (int col = 0; col < 5; col++) { rowStr += board[row][col] + " "; } rowStr += "\t" + row + " "; for (int col = 0; col < 5; col++) { switch (status[row][col]) { case NEUTRAL: rowStr += "_" + " "; break; case RED: rowStr += "r" + " "; break; case BLUE: rowStr += "b" + " "; break; case RED_DEFENDED: rowStr += "R" + " "; break; case BLUE_DEFENDED: rowStr += "B" + " "; break; default: rowStr += " " + " "; } } toRet += "\n"+rowStr; } toRet+="\n"; return toRet; }
8
protected void engineSetMode(String modeName) throws NoSuchAlgorithmException { if (modeName.length() >= 3 && modeName.substring(0, 3).equalsIgnoreCase("CFB")) { if (modeName.length() > 3) { try { int bs = Integer.parseInt(modeName.substring(3)); attributes.put(IMode.MODE_BLOCK_SIZE, new Integer(bs / 8)); } catch (NumberFormatException nfe) { throw new NoSuchAlgorithmException(modeName); } modeName = "CFB"; } } else { attributes.remove(IMode.MODE_BLOCK_SIZE); } mode = ModeFactory.getInstance(modeName, cipher, blockLen); if (mode == null) { throw new NoSuchAlgorithmException(modeName); } }
5
public Integer[] nextIntegerArray() throws Exception { String[] line = reader.readLine().trim().split(" "); Integer[] out = new Integer[line.length]; for (int i = 0; i < line.length; i++) { out[i] = Integer.valueOf(line[i]); } return out; }
1
public static int startsWith(String text, String match) { return StringTools.startsWith(text, match); }
0
public void selectedChanged(GameContext context, String message) { if (context.getSelectedTower() == null) { return; } URL imageURL = this.getClass().getClassLoader().getResource("com/creeptd/client/resources/panel"); // show SelectTowerInfoPanel if (message.equals("tower")) { // general info panel this.infoTower.setText(context.getSelectedTower().getType().getName()); this.infoSellPrice.setText("<html><img src=\""+imageURL+"/icon_credits.gif\"> &nbsp;"+(int) -(context.getSelectedTower().getTotalPrice() * 0.75)+"</html>"); this.infoDamage.setText("<html><img src=\""+imageURL+"/icon_damage.gif\"> &nbsp;" + context.getSelectedTower().getDamage()+"</html>"); this.infoSpeed.setText("<html><img src=\""+imageURL+"/icon_speed.gif\"> &nbsp;" + _(Constants.Towers.translateSpeed(context.getSelectedTower().getCoolDown()))+"</html>"); this.infoRange.setText("<html><img src=\""+imageURL+"/icon_range.gif\"> &nbsp;" + (int) context.getSelectedTower().getRange()+"</html>"); this.infoSpecial.setText(_(context.getSelectedTower().getType().getSpecial())); // upgrade info panel if (context.getSelectedTower().getType().getNext() != null) { upgradeTower.setText(context.getSelectedTower().getType().getNext().getName()); upgradePrice.setText("<html><img src=\""+imageURL+"/icon_credits.gif\"> &nbsp;" + context.getSelectedTower().getType().getNext().getPrice()); upgradeDamage.setText("<html><img src=\""+imageURL+"/icon_damage.gif\"> &nbsp;" + context.getSelectedTower().getType().getNext().getDamage()); upgradeSpeed.setText("<html><img src=\""+imageURL+"/icon_speed.gif\"> &nbsp;" + _(Constants.Towers.translateSpeed(context.getSelectedTower().getType().getNext().getSpeed()))); upgradeRange.setText("<html><img src=\""+imageURL+"/icon_range.gif\"> &nbsp;"+ (int) context.getSelectedTower().getType().getNext().getRange()); upgradeSpecial.setText(_(context.getSelectedTower().getType().getNext().getSpecial())); } if ((context.getSelectedTower().getType().getNext() != null) && (!context.getSelectedTower().isUpgrading()) && (context.getCredits() >= context.getSelectedTower().getType().getNext().getPrice())) { this.upgradeButton.setEnabled(true); } else { upgradeButton.setEnabled(false); } gamePanel.getBuildTowerInfoPanel().setVisible(false); gamePanel.getNoInfoPanel().setVisible(false); gamePanel.setLastTowerInfoPanel(this); this.setVisible(true); } else if (message.equals("sell")) { gamePanel.getLastTowerInfoPanel().setVisible(false); gamePanel.setLastTowerInfoPanel(gamePanel.getNoInfoPanel()); gamePanel.getNoInfoPanel().setVisible(true); } else if (message.equalsIgnoreCase("upgrade")) { updateButton(); } else if (message.equalsIgnoreCase("strategy")) { FindCreepStrategy fcs; fcs = ((AbstractTower) context.getSelectedTower()).getSelectedStrategy(); weakStrategyButton.getModel().setSelected( fcs instanceof FindWeakestCreep); hardStrategyButton.getModel().setSelected( fcs instanceof FindStrongestCreep); closeStrategyButton.getModel().setSelected( fcs instanceof FindClosestCreep); fastestStrategyButton.getModel().setSelected( fcs instanceof FindFastestCreep); farthestStrategyButton.getModel().setSelected( fcs instanceof FindFarthestCreep); lockCreepButton.getModel().setSelected(fcs.isCreepLock()); } }
9
public FlowBlock getNextFlowBlock(StructuredBlock subBlock) { for (int i = 0; i < caseBlocks.length - 1; i++) { if (subBlock == caseBlocks[i]) { return null; } } return getNextFlowBlock(); }
2
public void shoot() { if(btmr < -10) { int dir; int bx; if(player) if(wrld.p2.x < x) dir = 0; else dir = 1; else if(wrld.p1.x < x) dir = 0; else dir = 1; if(dir == 0) bx = -13; else bx = 13; wrld.bullets.add(new Bullet(x+bx, y, dir)); btmr = 50; } }
5
private void pivot(int p, int q) { // everything but row p and column q for (int i = 0; i <= M; i++) for (int j = 0; j <= M + N; j++) if (i != p && j != q) a[i][j] -= a[p][j] * a[i][q] / a[p][q]; // zero out column q for (int i = 0; i <= M; i++) if (i != p) a[i][q] = 0.0; // scale row p for (int j = 0; j <= M + N; j++) if (j != q) a[p][j] /= a[p][q]; a[p][q] = 1.0; }
8
public static String getScrollBarUIClassName() { // Code switches on the platform and returns the appropriate // platform specific classname or else the default. if (isWindows()) { return "com.organic.maynard.outliner.MetalScrollBarUI"; } else { return "com.organic.maynard.outliner.BasicScrollBarUI"; } }
1
private Instruction readInstruction(java.util.Scanner in) { Instruction inst = Instruction.ERROR; String instString = ""; //Start scanner System.out.print("Please enter a command: "); instString = in.nextLine(); instString = instString.toUpperCase(); if (instString.equals("MAKE A MOVE")) { instString = "MOVE"; } else if (instString.equals("PLAY C4")){ instString = "PLAY_C4"; } else if (instString.equals("PLAY CO")){ instString = "PLAY_CO"; } try { inst = Instruction.valueOf(instString); } catch (IllegalArgumentException e) { inst = Instruction.ERROR; } return inst; }
4
public void validate_update(String dataBaseName, String tableName, ArrayList<Field> entries, Field entry) { boolean flag = true; if (check_dataBase(dataBaseName)) { if (check_table(dataBaseName, tableName)) { for (Field element : entries) { if (!check_type(dataBaseName, tableName, element.getValue(), element.getName())) { flag = false; break; } } if (flag) { if (check_type(dataBaseName, tableName, entry.getValue(), entry.getName())) { DBMS ob = new DBMSImplementer(); ob.update(dataBaseName, tableName, entries, entry); } else { System.out.println("conition does not apply!"); } } else { System.out .println("data type does not math the table's data type"); } } else System.out.println("table does not exist!"); } else System.out.println("database does not exist!"); }
6
public String getSerial (int language) { try { int id = getSerialStringId (); if (id > 0) return dev.getString (id, language); } catch (IOException e) { } return null; }
2
public var_type unaryMinus() throws SyntaxError{ var_type v = new var_type(); if(v_type==keyword.ARRAY){ sntx_err("Math operations on pointers have not been implemented"); } if(isNumber()){ if(v_type == keyword.DOUBLE){ v.v_type = keyword.DOUBLE; v.value = -value.doubleValue(); } else if(v_type == keyword.INT || v_type == keyword.CHAR || v_type == keyword.BOOL || v_type == keyword.SHORT){ v.v_type = keyword.INT; v.value = -value.intValue(); } } v.lvalue = false; v.constant = constant; return v; }
7
public List<Map<String, Object>> findMoreResult(String sql, List<Object> params) throws SQLException { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); int index = 1; pstmt = connection.prepareStatement(sql); if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); } } resultSet = pstmt.executeQuery(); ResultSetMetaData metaData = resultSet.getMetaData(); int cols_len = metaData.getColumnCount(); while (resultSet.next()) { Map<String, Object> map = new HashMap<String, Object>(); for (int i = 0; i < cols_len; i++) { String cols_name = metaData.getColumnName(i + 1); Object cols_value = resultSet.getObject(cols_name); if (cols_value == null) { cols_value = ""; } map.put(cols_name, cols_value); } list.add(map); } return list; }
6
public static boolean isTestPlanEmpty() { boolean isTestPlanEmpty = true; @SuppressWarnings("deprecation") JMeterTreeModel jMeterTreeModel = new JMeterTreeModel(new Object());// Create non-GUI version to avoid headless problems if (JMeter.isNonGUI()) { try { FileServer fileServer = FileServer.getFileServer(); String scriptName = fileServer.getBaseDir() + "/" + fileServer.getScriptName(); FileInputStream reader = new FileInputStream(scriptName); HashTree tree = SaveService.loadTree(reader); JMeterTreeNode root = (JMeterTreeNode) jMeterTreeModel.getRoot(); jMeterTreeModel.addSubTree(tree, root); } catch (FileNotFoundException fnfe) { BmLog.error("Script was not found: " + fnfe); } catch (Exception e) { BmLog.error("TestScript was not loaded: " + e); } } else { jMeterTreeModel = GuiPackage.getInstance().getTreeModel(); } List<JMeterTreeNode> jMeterTreeNodes = jMeterTreeModel.getNodesOfType(AbstractThreadGroup.class); isTestPlanEmpty = jMeterTreeNodes.size() == 0 ? true : false; return isTestPlanEmpty; }
4
public void searchLinkAndAddToList(String str, String site) { String tmp; str = str.replace(" ", ""); int start = str.indexOf("<a"); if(start >= 0){ start = str.indexOf("href=\""); if(start >= 0){ str = str.substring(start+6, str.length()); start = str.indexOf("\""); tmp = str; if(start >= 0){ str = str.substring(0, start); start = str.indexOf("http"); if(start < 0){ str = "http://" + site + str; } if(links.indexOf(str) == -1){ links.add(str); } } searchLinkAndAddToList(tmp, site); } } }
5
public void setCap(int cap) { this.cap = cap; }
0
public boolean setInitializer(Expression expr) { if (constant != null) return constant.equals(expr); /* * This should check for isFinal(), but sadly, sometimes jikes doesn't * make a val$ field final. I don't know when, or why, so I currently * ignore isFinal. */ if (isSynthetic && (fieldName.startsWith("this$") || fieldName .startsWith("val$"))) { if (fieldName.startsWith("val$") && fieldName.length() > 4 && expr instanceof OuterLocalOperator) { LocalInfo li = ((OuterLocalOperator) expr).getLocalInfo(); li.addHint(fieldName.substring(4), type); } analyzedSynthetic(); } else expr.makeInitializer(type); constant = expr; return true; }
7
public static void backupWorld() { if(System.getProperty("os.name").contains("Windows")) { System.err.println("[WARNING] The /backup command is unimplemented under Windows systems."); return; } try { if(!(new File("backups")).isDirectory()) Runtime.getRuntime().exec("mkdir backups"); } catch(Exception e) { e.printStackTrace(); } Cmd.raw("save-all"); Util.sleep(5000); Cmd.raw("save-off"); Util.sleep(1000); boolean hasExited = false; final String cmd = "tar czf backups/" + getBackupName() + " " + Conf.serverConfig.getProperty("level-name", "world") + "/ minecraft_server.jar"; Process tar = null; try { tar = Runtime.getRuntime().exec(cmd); } catch(Exception e) { e.printStackTrace(); } if(tar == null) return; final long startTime = Util.getTime(); while(!hasExited && (Util.getTime() - startTime) < 10000) { try { hasExited = tar.exitValue() != -1; } catch(Exception e) {} } Cmd.raw("save-on"); }
8
public void findVertexCover() { //throw new RuntimeException("You have to implement it yourself..."); //The following code skeleton may be used, but not necessarily. //settings int populationSize = 200; //??? int iterations = 1000; //??? //best chromosome Chromosome bestChromosome = null; //initialisation ArrayList<Chromosome> population = new ArrayList<Chromosome>(); while (population.size() < populationSize) { boolean[] cities = getRandomCities(); if (!isValid(cities)) { cities = repair(cities); } int fitness = getFitness(cities); population.add(new Chromosome(cities, fitness)); } Collections.sort(population); for(int i = 0; i < iterations; i++){ ArrayList<Chromosome> tmp = new ArrayList<Chromosome>(); int size = populationSize/10; for(int j = 0; j < size; j++){ tmp.add(population.get(j)); } Random rand = new Random(); for(int j = 0; j < size*9; j++){ boolean[] origCities = population.get(j).getCities(); boolean[] cities = doMutation(origCities, 5); if (!isValid(cities)) { cities = repair(cities); } int fitness = getFitness(cities); tmp.add(new Chromosome(cities, fitness)); } population = tmp; Collections.sort(population); System.out.println(i + " - " + population.get(0).getFitness()); } bestChromosome = population.get(0); System.out.println(bestChromosome.getFitness()); //display the best solution map.highlightCities(getCityIndices(bestChromosome.getCities()), Color.CYAN); }
6
private void setcmp(Comparator<Buddy> cmp) { bcmp = cmp; String val = ""; if (cmp == alphacmp) val = "alpha"; if (cmp == groupcmp) val = "group"; if (cmp == statuscmp) val = "status"; Utils.setpref("buddysort", val); synchronized (buddies) { Collections.sort(buddies, bcmp); } }
3
private void testAbstractMethods(ByteMatcher matcher) { // test methods from abstract superclass assertEquals("length is one", 1, matcher.length()); assertEquals("matcher for position 0 is this", matcher, matcher.getMatcherForPosition(0)); try { matcher.getMatcherForPosition(-1); fail("expected an IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException expectedIgnore) {} try { matcher.getMatcherForPosition(1); fail("expected an IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException expectedIgnore) {} assertEquals("reversed is identical", matcher, matcher.reverse()); assertEquals("subsequence of 0 is identical", matcher, matcher.subsequence(0)); try { matcher.subsequence(-1); fail("expected an IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException expectedIgnore) {} try { matcher.subsequence(1); fail("expected an IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException expectedIgnore) {} assertEquals("subsequence of 0,1 is identical", matcher, matcher.subsequence(0,1)); try { matcher.subsequence(-1, 1); fail("expected an IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException expectedIgnore) {} try { matcher.subsequence(0, 2); fail("expected an IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException expectedIgnore) {} int count = 0; for (ByteMatcher itself : matcher) { count++; assertEquals("Iterating returns same matcher", matcher, itself); } assertEquals("Count of iterated matchers is one", 1, count); Iterator<ByteMatcher> it = matcher.iterator(); try { it.remove(); fail("Expected UnsupportedOperationException"); } catch (UnsupportedOperationException expectedIgnore) {} it = matcher.iterator(); try { assertTrue(it.hasNext()); it.next(); assertFalse(it.hasNext()); it.next(); fail("Expected NoSuchElementException"); } catch (NoSuchElementException expectedIgnore) {} }
9
@Override public List<Integer> update(Criteria beans, Criteria criteria, GenericUpdateQuery updateGeneric, Connection conn) throws DaoQueryException { List paramList1 = new ArrayList<>(); List paramList2 = new ArrayList<>(); StringBuilder sb = new StringBuilder(UPDATE_QUERY); String queryStr = new QueryMapper() { @Override public String mapQuery() { Appender.append(DAO_DIRECTION_NAME, DB_DIRECTION_NAME, criteria, paramList1, sb, COMMA); Appender.append(DAO_DIRECTION_STATUS, DB_DIRECTION_STATUS, criteria, paramList1, sb, COMMA); Appender.append(DAO_DIRECTION_PICTURE, DB_DIRECTION_PICTURE, criteria, paramList1, sb, COMMA); Appender.append(DAO_DIRECTION_TEXT, DB_DIRECTION_TEXT, criteria, paramList1, sb, COMMA); Appender.append(DAO_ID_TOURTYPE, DB_DIRECTION_ID_TOURTYPE, criteria, paramList1, sb, COMMA); Appender.append(DAO_ID_TRANSMODE, DB_DIRECTION_ID_TRANSMODE, criteria, paramList1, sb, COMMA); Appender.append(DAO_ID_DESCRIPTION, DB_DIRECTION_ID_DESCRIPTION, criteria, paramList1, sb, COMMA); sb.append(WHERE); Appender.append(DAO_ID_DIRECTION, DB_DIRECTION_ID_DIRECTION, beans, paramList2, sb, AND); Appender.append(DAO_DIRECTION_NAME, DB_DIRECTION_NAME, beans, paramList2, sb, AND); Appender.append(DAO_DIRECTION_STATUS, DB_DIRECTION_STATUS, beans, paramList2, sb, AND); Appender.append(DAO_DIRECTION_PICTURE, DB_DIRECTION_PICTURE, beans, paramList2, sb, AND); Appender.append(DAO_DIRECTION_TEXT, DB_DIRECTION_TEXT, beans, paramList2, sb, AND); Appender.append(DAO_ID_TOURTYPE, DB_DIRECTION_ID_TOURTYPE, beans, paramList2, sb, AND); Appender.append(DAO_ID_TRANSMODE, DB_DIRECTION_ID_TRANSMODE, beans, paramList2, sb, AND); Appender.append(DAO_ID_DESCRIPTION, DB_DIRECTION_ID_DESCRIPTION, beans, paramList2, sb, AND); return sb.toString(); } }.mapQuery(); paramList1.addAll(paramList2); try { return updateGeneric.sendQuery(queryStr, paramList1.toArray(), conn); } catch (DaoException ex) { throw new DaoQueryException(ERR_DIRECTION_UPDATE, ex); } }
1
public JsonObject save() { try { JsonValue v = JsonValue.readFrom(text.getText()); if(v.isObject()) { JsonObject o = JsonObject.readFrom(text.getText()); ArrayList<String> names = new ArrayList<String>(); names.addAll(loaded.names()); for(String s: names)loaded.remove(s); for(Member m: o) loaded.add(m.getName(), m.getValue()); } else MessageDialog.showMessageDialog(ModToolkit.getInstance().stage, "The root JSON value must be a JSON object!"); } catch(ParseException e) { MessageDialog.showMessageDialog(ModToolkit.getInstance().stage, "Error parsing JSON: " + Util.newLine + e.getMessage()); } catch(Throwable e) { Util.handleError(e, "An error occurred while saving the JSON", "Failed to format JSON correctly"); } if(jap != null) jap.load(); return loaded; }
6
public void stop() { isRunning = false; }
0
public void setFieldLineIndex(int fieldLineIndex) { this.fieldLineIndex = fieldLineIndex; }
0
@Override public String getGUITreeComponentID() {return this.id;}
0
public CopyMonitorStarter(String quellPfad, List<String> targetPfade, HashMap<String, Boolean> parameters) { this.quellPfad = quellPfad; this.targetPfade = targetPfade; this.parameters = parameters; try { copyMonitor = new CopyMonitor(quellPfad, targetPfade,parameters); logger.info("creating source"); targetMonitors = new ArrayList<TargetFileWatcher>(); for(String targetPfad : targetPfade){ this.targetMonitors.add(new TargetFileWatcher(quellPfad, targetPfad)); } } catch (IOException e) { e.printStackTrace(); logger.error(e.getMessage()); } }
2
public JTextField getOutput() { return output; }
0
public static void reset() { try { prefs.clear(); } catch (BackingStoreException e) { e.printStackTrace(); } }
1
@Override public void createElection(String name, String typeID, User owner) { // Check if there is another election with the same name and typeID // and if yes, return false Collection<Election> col = electionMap.values(); Iterator<Election> it = col.iterator(); while (it.hasNext()) { DnDElection el = (DnDElection) it.next(); if (el.getEID().equals(name) && el.getType() == DnDElectionType.valueOf(typeID)) throw new RuntimeException( "Election with the same name and typeID"); } // create a random id // UUID uuid = UUID.randomUUID(); DnDElection el; try { el = new DnDElection(name, typeID, owner); } catch (IllegalArgumentException e) { throw new RuntimeException("Wrong election type"); } electionMap.put(name, el); // return name; }
4
public boolean onCommand(CommandSender commandSender, Command command, String label, String[] args) { HashMap<String, Integer> commandList = new HashMap<String, Integer>(); commandList.put("buy", 0); commandList.put("donate", 1); commandList.put("purchase", 2); commandList.put("store", 3); commandList.put("shop", 4); commandList.put("ec", 5); commandList.put("buycraft", 6); Boolean status = false; switch(commandList.get(command.getLabel().toLowerCase())) { case 0: case 1: case 2: case 3: case 4: status = BuyCommand.process(commandSender, args); break; case 5: status = EnableChatCommand.process(commandSender, args); break; case 6: status = BuycraftCommand.process(commandSender, args); break; } return status; }
7
private void draw() { if (pane != null) { coords = block.getCoords(); if (pane.insertAt().x != -1) { for (Point p : coords) { pane.cell(maxFall.y + p.y, location.x + p.x).Shadow(); } } for (Point p : coords) { pane.cell(location.y + p.y, location.x + p.x).Block(block.getName()); } } }
4
public void readPropertyFile(File file){ DocumentBuilderFactory factory; DocumentBuilder builder; Document doc; try { System.out.println("学校のニュース取得開始"); factory = DocumentBuilderFactory.newInstance(); builder = factory.newDocumentBuilder(); doc = builder.parse(file); } catch(ParserConfigurationException e) { e.printStackTrace(); return; } catch (IOException e) { e.printStackTrace(); return; } catch (SAXException e) { e.printStackTrace(); return; } // パース開始 NodeList childs = doc.getChildNodes(); for(int i = 0; i < childs.getLength(); i++) { Node n = childs.item(i); Element e = (Element)n; if(e.getNodeType() != Node.ELEMENT_NODE) { continue; } if(!"shed".equals(e.getTagName())) /*<shed>がみつかったら下に*/{ continue; } NodeList paramNode = n.getChildNodes(); for(int j = 0; j < paramNode.getLength(); j++) { Node n2 = (Node)paramNode.item(j); if(n2.getNodeType() != Node.ELEMENT_NODE) { continue; } if("contents".equals(n2.getNodeName())) /*<contents>がみつかったら*/{ BbsInit.contents[kaisu] = n2.getFirstChild().getNodeValue(); System.out.println(BbsInit.contents[kaisu]); kaisu++; } } } }
9
public String typeToString(DataType type){ switch(type){ case FLOAT: return "double"; // insalmo is looking for 'double' not 'float' in Experiment.Setup // eventually, all references to FLOAT here and in the metaprojectdata should be replaced case STRING: return "string"; case INFILENAME: case OUTFILENAME: return "filename"; case BOOL: return "BOOL"; case INTEGER: return "int"; case DATE: return "date"; case DAY: return "day"; } return null; }
8
public double getKiihtyvyys1X() { double res = 0; if(getNappaimenTila(VASEN1)){ res -= KIIHTYVYYS; } if(getNappaimenTila(OIKEA1)){ res += KIIHTYVYYS; } return res; }
2
@SuppressWarnings("unchecked") private List<Object> processDirectives() { yamlVersion = null; tagHandles = new HashMap<String, String>(); while (scanner.checkToken(Token.ID.Directive)) { DirectiveToken token = (DirectiveToken) scanner.getToken(); if (token.getName().equals("YAML")) { if (yamlVersion != null) { throw new ParserException(null, null, "found duplicate YAML directive", token .getStartMark()); } List<Integer> value = (List<Integer>) token.getValue(); Integer major = value.get(0); if (major != 1) { throw new ParserException(null, null, "found incompatible YAML document (version 1.* is required)", token .getStartMark()); } yamlVersion = (List<Integer>) token.getValue(); } else if (token.getName().equals("TAG")) { List<String> value = (List<String>) token.getValue(); String handle = value.get(0); String prefix = value.get(1); if (tagHandles.containsKey(handle)) { throw new ParserException(null, null, "duplicate tag handle " + handle, token .getStartMark()); } tagHandles.put(handle, prefix); } } List<Object> value = new ArrayList<Object>(2); value.add(yamlVersion); if (!tagHandles.isEmpty()) { value.add(new HashMap<String, String>(tagHandles)); } else { value.add(new HashMap<String, String>()); } for (String key : DEFAULT_TAGS.keySet()) { if (!tagHandles.containsKey(key)) { tagHandles.put(key, DEFAULT_TAGS.get(key)); } } return value; }
9
public static BufferedImage loadFace(String spriteFilename) { try { return ImageIO.read(new File("Resources/Faces/" + spriteFilename)); } catch (IOException e) { System.out.println("File not found"); e.printStackTrace(); } return null; }
1
public AudioSample(final File file) throws Exception { try { this.audioInputStream = AudioSystem .getAudioInputStream(new BufferedInputStream( new FileInputStream(file))); this.format = this.audioInputStream.getFormat(); // Support only mono and stereo audio files. if (this.getNumberOfChannels() > 2) { throw new UnsupportedAudioFileException( "Only mono or stereo audio is currently supported."); } // We support 8-bit (PCM), 16-bit, and 24-bit audio. if (this.getBitsPerSample() > 24) { throw new UnsupportedAudioFileException( "Audio recorded higher than 24 bits per sample is not currently supported."); } if(this.getBitsPerSample() == 8) { if(this.getEncoding().equals("ALAW")) { throw new UnsupportedAudioFileException( "A-law enconding is not currently supported."); } if(this.getEncoding().equals("ULAW")) { throw new UnsupportedAudioFileException( "U-law enconding is not currently supported."); } } this.createSampleArrayCollection(); } catch (UnsupportedAudioFileException e) { throw (e); } catch (IOException e) { throw (e); } }
7
public static void aggiungiPedine(int n, int b) { // aggiunge le pedine appena mangiate alla griglia menuItem2.setEnabled(true); for (int i=0, x=0; i<4 && x<b; i++) // aggiunge pedine Bianche for (int j=0; j<3 && x<b; j++, x++) PedinePC[i][j].setIcon(new ImageIcon("images/Pedine/bianca_icon.png")); for (int i=3, x=0; i>=0 && x<n; i--) // aggiunge pedine Nere for (int j=0; j<3 && x<n; j++, x++) PedineUtente[i][j].setIcon(new ImageIcon("images/Pedine/nera_icon.png")); }
8
public static byte[] stringToBytes(String str) { if (str == null) { return null; } char[] chars = str.toCharArray(); int len = chars.length; byte[] buf = new byte[len]; for (int i = 0; i < len; i++) { buf[i] = (byte) chars[i]; } return buf; }
2
private int[] sizeLargestComponent(ArrayList<Node> nw){ Set<Integer> Q = new HashSet<Integer>(); ArrayList<Integer> D = new ArrayList<Integer>(); for(Node N : nw) { Q.add(N.id); } Node N; int n; int q; int r; int maxS = 0; int maxId = -1; while(!Q.isEmpty()) { r = 0; Iterator it = Q.iterator(); q = (Integer)it.next(); it.remove(); D.add(q); while(!D.isEmpty()) { q = D.remove(0); r++; N = nw.get(q); for(int i=0;i<N.getDegree();i++) { n = N.getNeighbour(i).id; if(Q.contains(n)) { Q.remove(n); if(!D.contains(n)) { D.add(n); } } } } if(r > maxS) { maxS = r; maxId = q; } } return new int[]{maxS,maxId}; }
7
public void updateGame(long gameTime, Point mousePosition) { currentLevel.upDate(gameTime); Statistique.update(currentLevel, gameTime); if (currentLevel.isCompleted()) currentLevel = levels.NextLevel(); }
1
public GenericList<E> concat(GenericList<E> that) { GenericList<E> res=this; if(that!=null) { for(int i=0;i<that.size();i++) { res.add(that.list.get(i)); } return res; } else { return res; } }
2
public static void incrementalFsqCrawl(String city, double[] point, String folder, String clientId, String clientSecret, int m) throws IOException{ JsonParser parser = new JsonParser(); // Creating the grid of points around the center of the city. double[][][] grid = createGridAround(point,m); Collection<String> venue_ids = new ArrayList<String>(); String ids_file = Settings.getInstance().getFolder()+ city + File.separator + ".exhaustive_crawl" + File.separator + "venues.ids"; // We get the ids of the venues that have already been crawled, // in order to avoid storing them again. if(new File(ids_file).exists()) { BufferedReader city_file = new BufferedReader(new FileReader(ids_file)); String line = null; while ((line = city_file.readLine()) != null) venue_ids.add(line); city_file.close(); } // Opening the file where the results of the crawl will be written. FileWriter rawVenuesWriter = new FileWriter(folder + city + File.separator + ".exhaustive_crawl" + File.separator + "venues.json",true); FileWriter venueIdsWriter = new FileWriter(ids_file,true); // Iterating over all the points of the grid. for(int x = 0 ; x <grid.length ; ++x){ double[] sw= grid[x][0]; double[] ne= grid[x][1]; String response=null; try { // Retrieves all the Foursquare venues that are located nearby // the bounding box given as a parameter. response = search4SqVenues(sw,ne,clientId,clientSecret); } catch (Exception e) { e.printStackTrace(); continue; } JsonObject jsonResponse; try { jsonResponse= parser.parse(response).getAsJsonObject(); } catch (Exception e) { System.out.println(response); continue; } // Parse the JSON response to extract an array of venues. JsonArray venuesArr = jsonResponse.get("response").getAsJsonObject().get("venues").getAsJsonArray(); for(int i = 0; i < venuesArr.size() ; ++i){ //Since we want popular venues, we heuristically filter venues that have // less than 25 overall checkins. Venue v = new Venue(venuesArr.get(i).toString()); if(v.getCheckincount() < 25 || venue_ids.contains(v.getId())) continue; // Write to the output file. rawVenuesWriter.write(venuesArr.get(i).toString()+"\n"); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } venueIdsWriter.close(); rawVenuesWriter.close(); }
9
public static double getPerfectAim(GunWave wave, State state) { double distance = wave.distanceSq(state.targetPosition); /* * If the enemy is further away then 30 turns there is no way that * perfect targeting could ever hope to work, the upper limit is * likely much much lower. */ if(distance > wave.speed * wave.speed * 30) { return Double.NaN; } FactorRange fwdRange = getRangeMinMax(wave, state, 1); FactorRange revRange = getRangeMinMax(wave, state, -1); if(revRange.getMinimum() > fwdRange.getMaximum() || fwdRange.getMinimum() > revRange.getMaximum()) { return Double.NaN; } return (Math.max(fwdRange.getMinimum(), revRange.getMinimum()) + Math.min(fwdRange.getMaximum(), revRange.getMaximum())) / 2.0; }
3
public void keyPressed(KeyEvent e) { if (!dead) { int key = e.getKeyCode(); if (key == left_key) { t.start(); direction = "LEFT"; dx = -SPEED_PISTOLERO; } else if (key == right_key) { t.start(); direction = "RIGHT"; dx = SPEED_PISTOLERO; } else if (key == up_key) { t.start(); direction = "UP"; dy = -SPEED_PISTOLERO; } else if (key == down_key) { t.start(); direction = "DOWN"; dy = SPEED_PISTOLERO; } else if (key == shoot_key) fire(); else if (key == KeyEvent.VK_ENTER) { if (board.getTimer().isRunning()) board.pause(); else board.restart(); } } }// keyPressed
8
public Causa ingresoImputadoPorTeclado(){ @SuppressWarnings("resource") Scanner scanner = new Scanner (System.in); String texto; int expediente; Long dni; Causa causa = new Causa(); try { System.out.println("Agregar Imputado a Causa"); System.out.println("------------------------"); while (true) { try { System.out.print("Ingrese Numero de Expediente: "); expediente = scanner.nextInt(); causa = this.getCausaByNumero(expediente); if (causa == null) { System.out.println("No existe ninguna Causa con Expediente " + expediente + ".Intente nuevamente"); } else { break; } } catch (RangeException e) { System.out.println(e.getMessage()); } } System.out.println("Datos de la Causa"); System.out.println("-----------------"); System.out.println(causa); scanner = new Scanner (System.in); while (true) { try { System.out.print("Ingrese el DNI del Imputado a agregar a la Causa o presione [ENTER] para continuar: "); texto = scanner.nextLine(); if (texto.length()>0) { dni=Long.parseLong(texto); if (dni>0) causa.addImputado(dni); } break; } catch (NumberFormatException e) { System.out.println("El DNI del imputado debe ser numerico"); } catch (ExcepcionValidacion e) { System.out.println(e.getMessage()); } } return causa; } catch (Exception e) { System.out.printf("ERROR EN EL SISTEMA: %s",e); return null; } }
9
public void testSetIntoPeriod_Object8() throws Exception { MutablePeriod m = new MutablePeriod(); try { StringConverter.INSTANCE.setInto(m, "", null); fail(); } catch (IllegalArgumentException ex) {} try { StringConverter.INSTANCE.setInto(m, "PXY", null); fail(); } catch (IllegalArgumentException ex) {} try { StringConverter.INSTANCE.setInto(m, "PT0SXY", null); fail(); } catch (IllegalArgumentException ex) {} try { StringConverter.INSTANCE.setInto(m, "P2Y4W3DT12H24M48SX", null); fail(); } catch (IllegalArgumentException ex) {} }
4
private static int partion(int[] n, int start, int end) { int tmp = n[start]; while (start < end) { while (n[end] >= tmp && start < end) { end--; } if (start < end) { n[start++] = n[end]; } while (n[start] < tmp && start < end) { start++; } if (start < end) { n[end--] = n[start]; } } n[start] = tmp; return start; }
7
public void visitIntInsn(final int opcode, final int operand) { if (opcode == SIPUSH) { minSize += 3; maxSize += 3; } else { minSize += 2; maxSize += 2; } if (mv != null) { mv.visitIntInsn(opcode, operand); } }
2
@Override protected void calcCoordinates(GraphicForm gForm, Camera camera, PhysObject3D obj) { if(camera.isFixedOrientation() && !getName().equals("Looker")) setName("Looker"); else if(!camera.isFixedOrientation() && !getName().equals("Camera")) setName("Camera"); setTexture(getName() + subName); }
4
public void quickSort(long[] arr, int left, int right) { if (left < right) { int l = left, r = right; long x = arr[left]; while (l < r) { while (l < r && arr[r] >= x) r --; if (l < r) arr[l ++] = arr[r]; while (l < r && arr[l] <= x) l ++; if (l < r) arr[r --] = arr[l]; } arr[l] = x; quickSort(arr, left, l - 1); quickSort(arr, l + 1, right); } }
8
@Override public String buscarDocumentoPorFechaVencimiento(String fechaven1, String fechaven2) { ArrayList<Compra> geResult= new ArrayList<Compra>(); ArrayList<Compra> dbCompras = tablaCompras(); String result=""; Date xfechaven1; Date xfechaven2; Date f; try{ if (fechaven1.equals("") || fechaven2.equals("")){ result="No puede dejar uno de los campos de fecha en blanco"; return result; } else { SimpleDateFormat dformat = new SimpleDateFormat("dd/MM/yyyy"); xfechaven1 = dformat.parse(fechaven1); xfechaven2 = dformat.parse(fechaven2); for (int i = 0; i < dbCompras.size() ; i++){ f=dformat.parse(dbCompras.get(i).getFechaven()); if((f.compareTo(xfechaven1))>=0 && (f.compareTo(xfechaven2))<=0){ geResult.add(dbCompras.get(i)); } } } }catch (NullPointerException e) { result="No hay Compras entre las fechas proporcionadas"; }catch (ParseException e){ result="Las fechas no tienen el formato correcto: "+e.getMessage(); } if (geResult.size()>0){ result=imprimir(geResult); } else { result="No se ha encontrado ningun registro"; } return result; }
8
public void paint(Graphics2D g) { g.setFont(getFont()); String[] lines = null; if (getText().indexOf("\n") > -1) lines = getText().split("\n"); else lines = new String[] {getText()}; if (textUpdated) { maxStrWidth = 0; for (int v = 0; v < lines.length; v++) { int m = g.getFontMetrics().stringWidth(lines[v]); if (m > maxStrWidth) maxStrWidth = m; } if (autoResize) { this.width = 4 + (maxStrWidth); this.height = ((getFont().getSize()+6) * lines.length)+2; createBuffer(lastKnownTransMode); } textUpdated = false; bufferNeedsIntemediatePaint(); } g.setColor(getForegroundColor()); for (int v = 0; v < lines.length; v++) { g.drawString(lines[v], 2, ((v+1)*(getFont().getSize()+2))); } }
6
private void killButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_killButtonActionPerformed try { logger.log(Level.INFO, "Killing process: " + selectedProcess); logger.log(Level.INFO, "ADB Output: " + adbController.executeADBCommand(true, false, deviceManager.getSelectedAndroidDevice(), new String[]{"am", "kill", selectedProcess})); } catch (IOException ex) { logger.log(Level.ERROR, "An error occurred while attempting to kill the selected process: " + ex.toString() + "\n" + "The error stack trace will be printed to the console..."); ex.printStackTrace(System.err); } }//GEN-LAST:event_killButtonActionPerformed
1
protected boolean decodeFrame() throws JavaLayerException { try { AudioDevice out = audio; if (out == null) return false; Header h = bitstream.readFrame(); if (h == null) return false; // sample buffer set when decoder constructed SampleBuffer output = (SampleBuffer) decoder.decodeFrame(h, bitstream); synchronized (this) { out = audio; if(out != null) { out.write(output.getBuffer(), 0, output.getBufferLength()); } } bitstream.closeFrame(); } catch (RuntimeException ex) { throw new JavaLayerException("Exception decoding audio frame", ex); } return true; }
4
private void setFloatValue(final Cursor cursor, final int index, final Field field, final Object object) { final Float value = (!cursor.isNull(index) ? cursor.getFloat(index) : null); Reflection.setFieldValue(field.getName(), object, value); }
1
protected int[] transmit(int[] in) throws Exception { //*deb*/System.out.println("transmit() length: " +in.length); //IO-Warrior 56 needs special handling if (iow.getId() == AbstractIowDevice.IOW56ID) { return transmit56(in); } int length = in.length; int remain = length; int out[] = new int[length]; int pointerInArray = 0; int pointerOutArray = 0; int partLength = 0; int flag = 0; while (remain > 0) { if (length > 6) { partLength = 6; remain = remain - 6; length = length - 6; flag = flags + partLength + 0x40; //with SSactive set } else { partLength = length; remain = remain - length; flag = flags + partLength; //with SSactive not set } int wbuf[] = {9, flag, 0, 0, 0, 0, 0, 0}; for (int t = 0; t < partLength; t++) { wbuf[t + 2] = in[pointerInArray++]; } //send report to spi //*deb*/printReport("out",wbuf); long ret = iow.writeReport(1, wbuf); if (ret != 8) { throw new Exception("SPI write error!"); } //receive report from spi int rbuf[] = (int[]) readQueue.dequeue(); //*deb*/printReport("in ",rbuf); if (rbuf.length == 0) { throw new Exception("SPI read error!"); } int count = rbuf[1]; if (count != partLength) { throw new Exception("SPI read error!"); } for (int t = 0; t < partLength; t++) { out[pointerOutArray++] = rbuf[t + 2]; } } //*deb*/printReport("ret ",out); return out; }
8
* @return the new KB subset collection term * * @throws IOException if a communications error occurs * @throws CycApiException if the Cyc server returns an error */ public CycConstant createKbSubsetCollection(String constantName, String comment) throws IOException, CycApiException { CycConstant kbSubsetCollection = getKnownConstantByName( "KBSubsetCollection"); CycConstant cycConstant = getConstantByName(constantName); if (cycConstant == null) { cycConstant = createNewPermanent(constantName); } assertIsa(cycConstant, kbSubsetCollection); assertComment(cycConstant, comment, baseKB); assertGenls(cycConstant, thing); CycFort variableOrderCollection = getKnownConstantByGuid( "36cf85d0-20a1-11d6-8000-0050dab92c2f"); assertIsa(cycConstant, variableOrderCollection, baseKB); return cycConstant; }
1
public synchronized boolean removeChild(GuiComponent child) { boolean removed = children.remove(child); if (removed) child.deactivate(); return removed; }
1
private String useAbondVariables(String s, int frame) { if (!(model instanceof MolecularModel)) return s; MolecularModel m = (MolecularModel) model; int n = m.bends.size(); if (n <= 0) return s; int lb = s.indexOf("%abond["); int rb = s.indexOf("].", lb); int lb0 = -1; String v; int i; AngularBond bond; while (lb != -1 && rb != -1) { v = s.substring(lb + 7, rb); double x = parseMathExpression(v); if (Double.isNaN(x)) break; i = (int) Math.round(x); if (i < 0 || i >= n) { out(ScriptEvent.FAILED, "Angular bond " + i + " does not exist."); break; } v = escapeMetaCharacters(v); bond = m.bends.get(i); s = replaceAll(s, "%abond\\[" + v + "\\]\\.angle", bond.getAngle(frame)); s = replaceAll(s, "%abond\\[" + v + "\\]\\.strength", bond.getBondStrength()); s = replaceAll(s, "%abond\\[" + v + "\\]\\.bondangle", bond.getBondAngle()); s = replaceAll(s, "%abond\\[" + v + "\\]\\.atom1", bond.atom1.getIndex()); s = replaceAll(s, "%abond\\[" + v + "\\]\\.atom2", bond.atom2.getIndex()); s = replaceAll(s, "%abond\\[" + v + "\\]\\.atom3", bond.atom3.getIndex()); lb0 = lb; lb = s.indexOf("%abond["); if (lb0 == lb) // infinite loop break; rb = s.indexOf("].", lb); } return s; }
8
public void mousePressed(MouseEvent event) { if (event.getSource() instanceof JButton) { JButton btn = (JButton) event.getSource(); Territory territ = map.getTerritory(btn.getName()); boolean all = (event.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK; switch (state) { case PLACE: place(territ); break; case DEPLOY: deploy(territ, all); break; case ATTACK: if (shiftKeyDown) calculate(territ); else attack(territ, all); break; case ADVANCE: advance(territ, all); break; case FORTIFY: fortify(territ, all); break; } } }
7
public int compare(M meeting1, M meeting2) { MeetingImpl mImpl1 = (MeetingImpl) meeting1; MeetingImpl mImpl2 = (MeetingImpl) meeting2; if(mImpl1.meetingDate.before(mImpl2.meetingDate)) { return 1; }else{ return -1; } }
1
public Hand decyrptHand(EncryptedHand hand) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException { Hand ret = new Hand(); for (int i = 0; i < Hand.NUM_CARDS; i++) { EncryptedCard tmp = hand.data.get(i); ret.data.add(decryptCard(tmp)); } return ret; }
1
private void drawByBresenchem(Point startPoint) { List<Point> drawedPoints = new ArrayList<Point>(); startPoint.draw(); drawedPoints.add(startPoint); Point firstPoint = startPoint; Point prePoint = startPoint; Point[] points = new Point[8]; Point bigPoint = new Point(model.getX1(), model.getY1()); bigPoint.dF = Double.MAX_VALUE;// здесь гарантированно большое абсолютное значение Point nextPoint = bigPoint; Point preprePoint = null; do { nextPoint = bigPoint; points[0] = new Point(prePoint.x - 1, prePoint.y - 1); points[1] = new Point(prePoint.x - 1, prePoint.y); points[2] = new Point(prePoint.x - 1, prePoint.y + 1); points[3] = new Point(prePoint.x, prePoint.y - 1); points[4] = new Point(prePoint.x, prePoint.y + 1); points[5] = new Point(prePoint.x + 1, prePoint.y + 1); points[6] = new Point(prePoint.x + 1, prePoint.y - 1); points[7] = new Point(prePoint.x + 1, prePoint.y); for (int i = 0; i < 8; i++) { /*if (!isDrawed(drawedPoints, points[i])) { if (abs(points[i].dF) < abs(nextPoint.dF) && scalar(preprePoint, prePoint, points[i]) >= 0) { nextPoint = points[i]; } } else if (drawedPoints.size() > 2 && (points[i].x == firstPoint.x && points[i].y == firstPoint.y)) { if (abs(points[i].dF) < abs(nextPoint.dF)) { nextPoint = points[i]; } }*/ if (abs(points[i].dF) < abs(nextPoint.dF)){ if (preprePoint == null){ nextPoint = points[i]; } else if (scalar(preprePoint, prePoint, points[i]) >= 0){ nextPoint = points[i]; } } } if (nextPoint.equals(bigPoint)) break; nextPoint.draw(); //drawedPoints.add(nextPoint); preprePoint = new Point(prePoint.x, prePoint.y); prePoint = nextPoint; } while (!(nextPoint.x == firstPoint.x && nextPoint.y == firstPoint.y)); }
7
public String[] getTerminals() { ArrayList list = new ArrayList(); String[] rhsTerminals = getTerminalsOnRHS(); for (int k = 0; k < rhsTerminals.length; k++) { if (!list.contains(rhsTerminals[k])) { list.add(rhsTerminals[k]); } } String[] lhsTerminals = getTerminalsOnLHS(); for (int i = 0; i < lhsTerminals.length; i++) { if (!list.contains(lhsTerminals[i])) { list.add(lhsTerminals[i]); } } return (String[]) list.toArray(new String[0]); }
4
public boolean setBlock(int par1, int par2, int par3, int par4) { if (par1 >= -30000000 && par3 >= -30000000 && par1 < 30000000 && par3 < 30000000) { if (par2 < 0) { return false; } else if (par2 >= 256) { return false; } else { Chunk var5 = this.getChunkFromChunkCoords(par1 >> 4, par3 >> 4); boolean var6 = var5.setBlockID(par1 & 15, par2, par3 & 15, par4); Profiler.startSection("checkLight"); this.updateAllLightTypes(par1, par2, par3); Profiler.endSection(); return var6; } } else { return false; } }
6
FlowBlock getSuccessor(int start, int end) { /* search successor with smallest addr. */ Iterator keys = successors.keySet().iterator(); FlowBlock succ = null; while (keys.hasNext()) { FlowBlock fb = (FlowBlock) keys.next(); if (fb.addr < start || fb.addr >= end || fb == this) continue; if (succ == null || fb.addr < succ.addr) { succ = fb; } } return succ; }
6
@Override public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) { PresentationReconciler reconciler = new PresentationReconciler(); // Default { RGB c = new RGB(0, 0, 0); CoffeescriptScanner scanner = new CoffeescriptScanner(colorManager); scanner.setDefaultReturnToken( new Token(new TextAttribute(colorManager.getColor(c)))); DefaultDamagerRepairer dr = new DefaultDamagerRepairer(scanner); reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE); reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE); } // Comment { RGB c = new RGB( 0x8E, 0x90, 0x8C ); NonRuleBasedDamagerRepairer dr = new NonRuleBasedDamagerRepairer(new TextAttribute(colorManager.getColor(c))); reconciler.setDamager(dr, CoffeescriptPartitionScanner.COMMENT); reconciler.setRepairer(dr, CoffeescriptPartitionScanner.COMMENT); } // String { RGB c = new RGB( 0x71, 0x8C, 0x00 ); NonRuleBasedDamagerRepairer dr = new NonRuleBasedDamagerRepairer(new TextAttribute(colorManager.getColor(c))); reconciler.setDamager(dr, CoffeescriptPartitionScanner.STRING); reconciler.setRepairer(dr, CoffeescriptPartitionScanner.STRING); } return reconciler; }
0
public int partitionInt(int[] data, int length, int start, int end) { // TODO Auto-generated method stub if(data == null || length <=0 || start < 0 || end >= length){ throw new IndexOutOfBoundsException("argument error!"); } Random r = new Random(); //nextInt(0,n+1) create an int in [0, n+1) == [0, n]; int index = r.nextInt(end-start+1)+start; swapInt(data , index , end); int small = start; for(int i = start ; i <= end ; i++){ if(data[i] < data[end]){ if( small != i){ swapInt(data, small , i); } small++; } } swapInt(data , small , end); return small; }
7
public String getDest(){ return this.dest; }
0
private void postEntityFileProcessing(Employee employee) throws IOException { StringWriter stringWriter = null; String newFileName; try { stringWriter = new StringWriter(); xmlManager.marshal(employee, stringWriter); newFileName = StringUtil.concatenateStrings(employee.getEntityFileName(), ValidatorProperties.getInstance() .getProperty(PropertyKeys.PROCESSED_FILE_NAME_SUFFIX.toString())); FileUtil.createFile(newFileName, file.getPath(), stringWriter.toString()); } catch (IOException e) { LOG.error(StringUtil.concatenateStrings("Failed to write to file - ", file.getPath(), CommonUtil.getFileSeparator(), employee.getEntityFileName(), ", content - ", ((stringWriter != null) ? stringWriter.toString() : "")), e); throw e; } }
2
private void checkStraightFlush() { int suit = hand[0].getSuit(); for (int i = 0; i < 5; i++) { Card card = hand[i]; if (card.getSuit() != suit) { break; } if (card.getValue() == (13 - i)) { if (i == 4 && card.getValue() < hand[3].getValue()) { myEvaluation[0] = 9; myEvaluation[1] = hand[0].getValue(); myEvaluation[2] = hand[4].getValue(); myEvaluation[3] = 0; } continue; } else { break; } } }
5
public static boolean isArrayByteBase64( byte[] arrayOctect ) { int length = arrayOctect.length; if (length == 0) { // shouldn't a 0 length array be valid base64 data? // return false; return true; } for (int i=0; i < length; i++) { if ( !Base64.isBase64(arrayOctect[i]) ) return false; } return true; }
3
private void btn_aceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_aceptarActionPerformed if (lab_modo.getText().equals("Alta")){ if (camposCompletos()){ ocultar_Msj(); insertar(); menuDisponible(true); modoConsulta(); updateTabla(); } else{ mostrar_Msj_Error("Por favor, complete todos los campos solicitados"); } } else{ if (lab_modo.getText().equals("Baja")){ if (!field_codigo.getText().equals("")){ if(!existe(Integer.parseInt(field_codigo.getText()))){ mostrar_Msj_Error("Ingrese un codigo que se encuentre registrado en el sistema"); field_codigo.requestFocus(); } else{ ocultar_Msj(); eliminar(); menuDisponible(true); modoConsulta(); vaciarCampos(); updateTabla(); } } else{ mostrar_Msj_Error("Por favor, complete todos los campos solicitados"); } } else{ if (lab_modo.getText().equals("Modificación")){ if (!field_codigo.getText().equals("")){ if(!existe(Integer.parseInt(field_codigo.getText()))){ mostrar_Msj_Error("Ingrese un codigo que se encuentre registrado en el sistema"); field_codigo.requestFocus(); } else{ if (camposCompletos()){ ocultar_Msj(); modificar(); menuDisponible(true); modoConsulta(); updateTabla(); } else{ mostrar_Msj_Error("Por favor, complete todos los campos solicitados"); } } } else{ mostrar_Msj_Error("Por favor, complete todos los campos solicitados"); } } } } }//GEN-LAST:event_btn_aceptarActionPerformed
9
public void addUser(String name, String pass, int accType){ Statement stmt = null; try{ //Connection conn = DriverManager.getConnection(DB_URL, dbUser, dbPass); stmt = conn.createStatement(); if(accType==0){ try{ stmt.executeUpdate("CREATE USER '"+name+"'@'localhost' IDENTIFIED BY '"+pass+"';"); stmt.executeUpdate("GRANT SELECT ON * . * TO '"+name+"'@'localhost' IDENTIFIED BY '"+pass+"' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;"); JOptionPane.showMessageDialog(null,"User '"+name+"' created.","User added",JOptionPane.INFORMATION_MESSAGE); }catch(SQLException ex){ JOptionPane.showMessageDialog(null,"Error adding user. (User may already exit?)","Error",JOptionPane.WARNING_MESSAGE); } }else if(accType==1){ try{ stmt.executeUpdate("CREATE USER '"+name+"'@'localhost' IDENTIFIED BY '"+pass+"';"); stmt.executeUpdate("GRANT ALL PRIVILEGES ON * . * TO '"+name+"'@'localhost' IDENTIFIED BY '"+pass+"' WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;"); JOptionPane.showMessageDialog(null,"Admin '"+name+"' created.","User added",JOptionPane.INFORMATION_MESSAGE); }catch(SQLException ex){ JOptionPane.showMessageDialog(null,"Error adding admin. (Admin may already exist?)","Error",JOptionPane.WARNING_MESSAGE); } } //conn.close(); //stmt.close(); }catch(SQLException ex){ System.err.println(ex); }finally{ if(stmt != null) try { stmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
7
private void initialize() { frame = new JFrame("Chat Client"); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { disconnect(); } }); frame.setBounds(100, 100, 596, 533); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); connectionList = new List(); connectionList.setBounds(448, 67, 124, 335); frame.getContentPane().add(connectionList); chatList = new List(); chatList.setBounds(10, 67, 432, 364); frame.getContentPane().add(chatList); lblOnlineUsers = new JLabel("Offline"); lblOnlineUsers.setHorizontalAlignment(SwingConstants.CENTER); lblOnlineUsers.setBounds(448, 47, 124, 14); frame.getContentPane().add(lblOnlineUsers); JLabel lblChat = new JLabel("Chat"); lblChat.setBounds(10, 47, 46, 14); frame.getContentPane().add(lblChat); JLabel lblIPAddress = new JLabel("Connect to:"); lblIPAddress.setBounds(161, 11, 90, 14); frame.getContentPane().add(lblIPAddress); txtIP = new JTextField(); try { txtIP.setText(InetAddress.getLocalHost().getHostAddress()); } catch (UnknownHostException e1) { txtIP.setText("Unknown IP!?"); } txtIP.setBounds(230, 8, 112, 20); frame.getContentPane().add(txtIP); txtIP.setColumns(10); JLabel lblPort = new JLabel("Port:"); lblPort.setBounds(359, 11, 38, 14); frame.getContentPane().add(lblPort); txtPort = new JTextField(); txtPort.setText("9999"); txtPort.setBounds(393, 8, 57, 20); frame.getContentPane().add(txtPort); txtPort.setColumns(10); btnConnect = new JButton("Connect"); btnConnect.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(checkUsername(txtName.getText())) { try { UDPsocket = new DatagramSocket(); IPaddress = InetAddress.getByName(txtIP.getText()); portNumber = Integer.parseInt(txtPort.getText()); dataBuffer = ("JOIN "+txtName.getText()).getBytes("UTF-8"); sendPacket = new DatagramPacket(dataBuffer, dataBuffer.length, IPaddress, portNumber); UDPsocket.send(sendPacket); addMessage("Connecting to server ..."); startDatagramListener(); } catch (UnknownHostException e) { addMessage("Unable to get IP-Address"+e.getMessage()); } catch (IOException e) { addMessage("Unable to connect"+e.getMessage()); } } else addMessage("please use letters only"); } }); btnConnect.setBounds(460, 7, 112, 23); frame.getContentPane().add(btnConnect); btnDisconnect = new JButton("Disconnect"); btnDisconnect.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { disconnect(); btnConnect.setVisible(true); btnDisconnect.setVisible(false); } }); btnDisconnect.setBounds(460, 7, 112, 23); frame.getContentPane().add(btnDisconnect); txtChat = new JTextField(); txtChat.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String message = ""; if(chboxPriv.isSelected()) { int tries = 0; while(tries<3) { String usernameTo = connectionList.getSelectedItem(); if(!usernameTo.equals(null)) { message = "MSG PRIVATE "+txtName.getText()+" "+usernameTo+" "+txtChat.getText(); addMessage("Private message to "+usernameTo+": "+txtChat.getText()); break; } else tries++; } } else message = "MSG PUBLIC "+txtName.getText()+" "+txtChat.getText(); sendPacket(message); txtChat.setText(""); } }); txtChat.setBounds(10, 443, 562, 20); frame.getContentPane().add(txtChat); txtChat.setColumns(10); JLabel lblName = new JLabel("Name:"); lblName.setBounds(10, 11, 46, 14); frame.getContentPane().add(lblName); txtName = new JTextField(); txtName.setText("Testsubject"); txtName.setBounds(52, 8, 90, 20); frame.getContentPane().add(txtName); txtName.setColumns(10); chboxPriv = new JCheckBox("Private message"); chboxPriv.setBounds(448, 408, 124, 23); frame.getContentPane().add(chboxPriv); menuBar = new JMenuBar(); frame.setJMenuBar(menuBar); mnFile = new JMenu("File"); menuBar.add(mnFile); mntmNewClient = new JMenuItem("New Client"); mnFile.add(mntmNewClient); mntmClose = new JMenuItem("Close"); mnFile.add(mntmClose); mnOption = new JMenu("Option"); menuBar.add(mnOption); mnHelp = new JMenu("Help"); menuBar.add(mnHelp); }
7
public void sendAudioSocks(final SocketChannel chan, final boolean join, final int channel) { Runnable runner = new Runnable() { public void run() { Getoptions opt = new Getoptions(); if(Wuuii.DEBUG) { System.out.println("Send audio byte[] buffer join="+join +" transmission=" + opt.getTransmission()); } //AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100.0F, 16, channel, 4, 44100.0F, false); AudioFormat format = getTransmissionFormat(); DataLine.Info targetInfo = new DataLine.Info(TargetDataLine.class, format, 40960); byte[] audioBuffer = new byte[40960]; int nBufferSize = audioBuffer.length; try { tLine = (TargetDataLine)AudioSystem.getLine(targetInfo); tLine.open(format, 40960); tLine.start(); while(opt.getTransmission()) { tLine.read(audioBuffer, 0, nBufferSize); try { //if(ByteBuffer.wrap(aBuffer) != null && chan.isOpen()) { Wuuii.Spectrum(audioBuffer, format, Wuuii.recvCapture); int len = chan.write(ByteBuffer.wrap(audioBuffer)); if(len == -1) break; } catch (IOException e) { ErrorMessage error = new ErrorMessage("I/O Exception" + e); error.EMessage(); } } if(Wuuii.DEBUG) { opt.prFlush("HANGUP record from server"); } try { chan.close(); } catch (IOException e) { ErrorMessage error = new ErrorMessage("I/O Exception" + e); error.EMessage(); } tLine.drain(); tLine.close(); } catch (LineUnavailableException e) { ErrorMessage error = new ErrorMessage("Line Unavailable: " + e); error.EMessage(); } } }; Thread rec = new Thread(runner); rec.start(); if(join) { try { rec.join(); } catch (InterruptedException e) { e.printStackTrace(); } } }
9
public void setQuestName(String qName) { QuestName = qName; }
0
@Test public void testEquals() { try { System.out.println("equals"); Port anotherPort = new Port(80, 50, 2); Port instance = new Port(80, 50, 2); boolean expResult = true; boolean result = instance.equals(anotherPort); assertEquals(expResult, result); } catch (PortException ex) { Logger.getLogger(PortTest.class.getName()).log(Level.SEVERE, null, ex); } }
1
private void addAll(FactoryOfPlays factory) { for (AbstractPlay play : factory) bestPlays.add(play); }
1
@Override public ChunkGenerator getDefaultWorldGenerator(String worldName, String id) { if(!enabled) getServer().getPluginManager().enablePlugin(this); if(parentGen.equals("")) return new ChunkGen(); Plugin p = getServer().getPluginManager().getPlugin(parentGen); if(p == null) { getLogger().warning("Plugin does not exist for extended world gen: "+parentGen); return new ChunkGen(); } if(!p.isEnabled()) getServer().getPluginManager().enablePlugin(p); return new ChunkGen2(WorldCreator.getGeneratorForName(worldName, parentGen+":"+id, getServer().getConsoleSender())); }
4
public MasterServerImpl(File metaData, TreeMap<String, ReplicaLoc> nameToLocMap) throws IOException { locMap = new ConcurrentHashMap<String, ReplicaLoc[]>(); fileLock = new ConcurrentHashMap<String, Lock>(); txnID = new AtomicInteger(0); timeStamp = new AtomicInteger(0); replicaServerAddresses = new ReplicaLoc[nameToLocMap.size()]; int ii = 0; for (ReplicaLoc loc : nameToLocMap.values()) { replicaServerAddresses[ii++] = loc; } Scanner scanner = new Scanner(metaData); while (scanner.hasNext()) { StringTokenizer tok = new StringTokenizer(scanner.nextLine()); String fName = tok.nextToken(); ReplicaLoc[] fileLocations = new ReplicaLoc[tok.countTokens()]; for (int i = 0; i < fileLocations.length; i++) { fileLocations[i] = nameToLocMap.get(tok.nextToken()); } locMap.put(fName, fileLocations); } scanner.close(); metaDataWriter = new FileWriter(metaData, true); }
3
public DiceImage() { try { for(int i = 0; i < activeDiceImage.length; i++) { activeDiceImage[i] = ImageIO.read(new File(getClass().getResource("resource/" + (i + 1) + ".png").toURI())); inactiveDiceImage[i] = ImageIO.read(new File(getClass().getResource("resource/" + (i + 1) + "g.png").toURI())); } } catch(IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch(URISyntaxException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } current = inactiveDiceImage[0]; addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { setImage(++currentIndex, true); repaint(); } }); }
3
public void clear() { fill(null); }
0
private void addTileIfOutdated(Tile tile, AtomDelta delta) { // Make sure the turf actually exists if(tile != null) { // TODO: discriminate between the different outdated types if(tile.outdated != 0) { delta.updates.add(new FullAtomUpdate(tile)); } for(Atom content : tile.contents) { if(content.outdated != 0) { delta.updates.add(new FullAtomUpdate(content)); } } } }
4
private void toNote() { ItemDefinition item = ItemDefinition.forId(certTemplateId); groundModel = item.groundModel; modelZoom = item.modelZoom; rotationY = item.rotationY; rotationX = item.rotationX; scaleInventory = item.scaleInventory; offsetX = item.offsetX; offsetY = item.offsetY; destColors = item.destColors; srcColors = item.srcColors; ItemDefinition note = ItemDefinition.forId(certId); name = note.name; membersObject = note.membersObject; value = note.value; String s = "a"; char c = note.name.charAt(0); if (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') { s = "an"; } description = ("Swap this note at any bank for " + s + " " + note.name + ".").getBytes(); stackable = true; }
5