method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
3c96ee2c-eb72-411c-b081-1f70d16d2a58
4
public String toString() { String output = "webOS " + version + "\n"; if(wallpaper!=null) { output += "\tWallpaper: " + wallpaper.getPath() + "\n"; } output += "\tFiles:\n"; for(int i=0; i<files.size(); i++) { output += "\t\t" + files.get(i) + "\n"; } output += "\tIcons:\n"; for(int i=0; i<icons.size(); i++) { output += "\t\t" + icons.get(i) + "\n"; } output += "\tPatches:\n"; for(int i=0; i<patches.size(); i++) { output += "\t\t" + patches.get(i) + "\n"; } return output; }
45065062-f3ac-4bd8-8c42-3fd365521dbe
2
public static void deleteSkin(String filename) { Path skinPath; if (!filename.endsWith(Constants.SKINFILE_SUFFIX)) { skinPath = Constants.PROGRAM_SKINS_PATH.resolve(filename + Constants.SKINFILE_SUFFIX); } else { skinPath = Constants.PROGRAM_SKINS_PATH.resolve(filename); } if (model.deleteSkin(skinPath)) { chooser.updateList(); } else { showProblemMessage("Main.deleteSkin: Skin was not deleted!"); } }
f555bb43-7c44-4e87-a862-dcaf922dd6b2
2
private void viewManagementPlan() { //save original order of Stakeholders OriginalStakeholders.clear(); for(Stakeholder s : Stakeholders) { OriginalStakeholders.add(s); } //sort Stakeholders by Influence value Collections.sort(Stakeholders, new Comparator<Stakeholder>(){ public int compare(Stakeholder s1, Stakeholder s2) { return Double.compare(s2.getInfluence(), s1.getInfluence());}}); managementPlanUpdate(); //make table headers clickable if (mouseListenerExists == false) { managementPlanTable.getTableHeader().addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ManagementPlanColumnMouseClicked(evt);}}); mouseListenerExists = true; } }
6cc75193-f16e-402b-bf2c-bac8eab8c661
1
private void updateDisplay() { need = getWhatNeedsDone(); boolean done = need.length == 0; convertAction.setEnabled(!done); doAllAction.setEnabled(!done); highlightAction.setEnabled(!done); exportAction.setEnabled(done); if (done) directionLabel .setText("Conversion done. Press \"Export\" to use."); else directionLabel.setText(need.length + " production(s) must be converted."); }
eb6bfd1b-4b3f-4466-b87a-a1e66a23b196
2
public E pred(E e) { DoublyLinkedNode node = search(e); if (node != null) { if (node.getPred() != null) { final E returnValue = (E) node.getPred().getKey(); return returnValue; } } return null; }
b0589dae-37a9-4a29-9672-d6a471d057ca
5
public static void MutePlayer( String sender, String target, boolean command ) throws SQLException { BSPlayer p = PlayerManager.getPlayer( sender ); if ( !PlayerManager.playerExists( target ) ) { p.sendMessage( Messages.PLAYER_DOES_NOT_EXIST ); return; } BSPlayer t = PlayerManager.getSimilarPlayer( target ); if ( t != null ) { target = t.getName(); } if ( command ) { command = !PlayerManager.isPlayerMuted( target ); } else { if ( !PlayerManager.isPlayerMuted( target ) ) { p.sendMessage( Messages.PLAYER_NOT_MUTE ); return; } } PlayerManager.mutePlayer( target ); if ( command ) { p.sendMessage( Messages.PLAYER_MUTED.replace( "{player}", target ) ); return; } else { p.sendMessage( Messages.PLAYER_UNMUTED.replace( "{player}", target ) ); } }
1a05b9d2-5df6-4b39-9134-673d25560a55
2
public ImageIcon[][] getColorGrid() { Piece piece; ImageIcon[][] tab = new ImageIcon[plateau.getTailleX()][plateau.getTailleY()]; for (int i = 0; i < plateau.getTailleX(); i++) { for (int j = 0; j < plateau.getTailleY(); j++) { piece=new Piece(plateau.getPlateau()[i][j]); tab[i][j] =piece.getFrame(); } } return tab; }
e09fd6a9-5535-4248-a6ba-38dbe85ae8a5
4
private Type zeroExtend(Type type) { if (type == Type.SHORT || type == Type.BYTE || type == Type.CHAR || type == Type.BOOLEAN) return Type.INTEGER; return type; }
3507c6f4-70dd-4069-9a05-8404acfb1697
7
@Override public void actionPerformed(ActionEvent e) { //Set ip address if (e.getSource() == ipSetButton) { serverAddress = new InetSocketAddress(ipField.getText().trim(), defaultPort); local.println("IP Address set to: " + serverAddress); log.setCaretPosition(log.getDocument().getLength()); } //Start sending random fruit if (e.getSource() == startButton) { local.println("Sending random fruit..."); log.setCaretPosition(log.getDocument().getLength()); if (generator == null) { generator = new RandomFruitGenerator(serverAddress, local); } generator.start(); } //Pause sending random fruit if (e.getSource() == pauseButton) { if (generator != null) { generator.pause(); local.println("Paused"); log.setCaretPosition(log.getDocument().getLength()); } } //Stop sending random fruit if (e.getSource() == stopButton) { if (generator != null) { generator.stop(); local.println("Stopping fruit sending thread"); log.setCaretPosition(log.getDocument().getLength()); } generator = null; } log.setCaretPosition(log.getDocument().getLength()); }
95e8cfe9-0b5e-418a-a94c-13dc0adfb39c
6
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Variable)) { return false; } Variable other = (Variable) obj; if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; }
34495bf7-17d3-4b8f-a500-3b5a008cb44a
1
public String toString() { return actions.toString() + (loop ? " loop " : ""); }
69ff67db-6efe-40bc-80d4-5aee31010826
4
@Override public void onDeleteFile(String arg0, DokanFileInfo arg1) throws DokanOperationException { try { if (DEBUG) System.out.println("DeleteFile: " + arg0); fileSystem.deleteFile(mapWinToUnixPath(arg0)); } catch (AccessDeniedException e) { throw new DokanOperationException(net.decasdev.dokan.WinError.ERROR_ACCESS_DENIED); } catch (PathNotFoundException e) { throw new DokanOperationException(net.decasdev.dokan.WinError.ERROR_PATH_NOT_FOUND); } catch (Exception e) { e.printStackTrace(); } }
cd7e730d-76ae-4e49-b66c-36dc64ed96c0
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(Calculadora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Calculadora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Calculadora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Calculadora.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 Calculadora().setVisible(true); } }); }
26eccb52-a2f0-4fb1-8bf3-28be8410a7b7
2
public Integer readUnicodeChar() throws IOException { int off = 0; int len = readInt(); byte[] s = new byte[len]; while (off < len) { off += read(s, off, len - off); } String charString = new String(s, "UTF-8"); int retval = (int) charString.charAt(0); // NOTE: When we upgrade to java 1.5 change the above line to // int retval = charString.codePointAt(0); if (trace == API_TRACE_DETAILED) { debugNote("readUnicodeChar: 0x" + Integer.toHexString(retval)); } return new Integer(retval); }
3f978f33-e840-4a82-a71e-154fd0d98cce
6
void appendChild(XML xml) { if (xml.isAttribute()) { if (attributes == null) attributes = new TreeMap<String, XML>(); attributes.put(xml.getNodeName(), xml); } else { if (nodeValue != null) throw new IllegalStateException("only leaf node can contain text"); if (elements == null) { elements = new TreeMap<String, XML>(); elementsOrder = new ArrayList<XML>(); } elementsOrder.add(xml); String qname = xml.getNodeName(); XML child = elements.get(qname); if (child == null) { elements.put(qname, xml); } else if (child.getNodeType() == NodeType.ELEMENT_LIST) { ((XMLList) child).appendToList(xml); } else { XMLList xmllist = new XMLList(); xmllist.appendToList(child); xmllist.appendToList(xml); elements.put(qname, xmllist); } } }
2bbd47f6-6f96-46f6-acef-97bb5d2e3f72
2
@Override public void mark(int boardPosition, Cell[] cellBoard, int rows, int columns) throws IllegalMark { //Find the row. int boardPositionRow = boardPosition / columns; //Find the column. int boardPositionColumn = boardPosition % columns; //Position to mark. int positionToMark = boardPosition; for(int currentRow = boardPositionRow,currentColumn = boardPositionColumn; currentRow < rows && currentColumn < columns; currentRow++,currentColumn++){ positionToMark = columns * currentRow + currentColumn; mark(boardPosition, positionToMark,cellBoard); } }
bc019621-2817-4cbb-9b23-5690f6bdd04c
7
public String prefCon() { nameList t=null; if(getScreen() == 1 || getScreen()==3 || getScreen()==4) { if(baseCon != null) t = baseCon.getSelected(); else if(remCon != null) t = remCon.getSelected(); if(t == null) return ";"; else if(t.getDeleted()) return ";"; else return t.getName()+";"; } return""; }
efc987b5-8e1e-4749-ad81-4c2928c0b19d
2
static boolean palindromenTest(String reeks) { boolean palindroom = true; int j = reeks.length() - 1; for(int i = 0; i <= j; i++, j--) { if(reeks.charAt(i) != reeks.charAt(j)) palindroom = false; } return palindroom; }
41529280-2f86-4582-8e25-e40bce0e58bb
8
public String spellCheckConfusionMatrices(String wrong, DataSet testSet) { String correct; double probability = 0.0; //System.out.println("Calculating probabilites with all possible words..."); double max = 0.0; // Set<String> candidates = new HashSet<String>(); String candidate = ""; //iterate over all correct words in test set for (int i = 0 ; i < testSet.correctWords.size() ; i++) { correct = testSet.correctWords.get(i); //get the ith correct word //probability = bigrams.getProbability(correct); probability = bigWordCounts.getProbability(correct); //find probability of the correct word itself int result[] = errorMatrices.findError(wrong, correct); //detect the type of error and the characters involved in the error //System.out.println("type of error: "+result[0]); switch(result[0]) { case ErrorMatrices.NO_ERROR: probability = 1; //p=1 since we have found a dictionary word case ErrorMatrices.INSERTION: //System.out.println("Candidate Word: "+correct); //System.out.println("p(c): "+probability); probability *= errorMatrices.getIProbability(result[1], result[2]); //so far probability contained P(C), now we mult it by P(W/C) wrt insertion //System.out.println("p(w/c): "+errorMatrices.getIProbability(result[1], result[2])); //System.out.println("p(c/w): "+probability); break; case ErrorMatrices.DELETION: //System.out.println("Candidate Word: "+correct); //System.out.println("p(c): "+probability); probability *= errorMatrices.getDProbability(result[1], result[2]); //System.out.println("p(w/c): "+errorMatrices.getDProbability(result[1], result[2])); //System.out.println("p(c/w): "+probability); break; case ErrorMatrices.SUBSTITUTION: //System.out.println("Candidate Word: "+correct); //System.out.println("p(c): "+probability); probability *= errorMatrices.getSProbability(result[1], result[2]); //System.out.println("p(w/c): "+errorMatrices.getSProbability(result[1], result[2])); //System.out.println("p(c/w): "+probability); break; case ErrorMatrices.TRANSPOSITION: //System.out.println("Candidate Word: "+correct); //System.out.println("p(c): "+probability); probability *= errorMatrices.getXProbability(result[1], result[2]); //System.out.println("p(w/c): "+errorMatrices.getXProbability(result[1], result[2])); //System.out.println("p(c/w): "+probability); break; case ErrorMatrices.UNKNOWN_ERROR: probability = 0; //not a single error hence should not be part of candidate set break; } //at this point correct is a candidate word and probability is P(C/W) if ( max < probability ) //word with probability > max found { max = probability; //candidates.clear(); //candidates.add(correct); candidate = correct; } /* else if ( max == probability ) { if(max != 0.0) candidates.add(correct); } */ else //probability < max so can't be a candidate { /*do nothing*/ } } System.out.println("\nmax probability: "+max); System.out.println("-----------------\nCorrect Word:\n------------------"); /* Iterator<String> iterator = candidates.iterator(); while(iterator.hasNext()) { String candidateWord = iterator.next(); System.out.println(candidateWord); } */ System.out.println(candidate); System.out.println("------------------"); return candidate; }
80049b42-cb88-467e-8779-7816b4259205
8
public void service() throws IOException { //由serverSocketChannel向selector注册接受连接就绪事件,如果就绪,则将SelectionKey对象加入到Selected-keys集合中 serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); while(selector.select()>0){ Set readyKeys = selector.selectedKeys(); Iterator it = readyKeys.iterator(); while (it.hasNext()) { SelectionKey selectionKey = null; selectionKey = (SelectionKey) it.next(); it.remove(); if (selectionKey.isAcceptable()){ } if (selectionKey.isReadable()){ } if(selectionKey.isWritable()){ ByteBuffer bf = (ByteBuffer) selectionKey.attachment(); SocketChannel sc = (SocketChannel) selectionKey.channel(); bf.flip(); //将position位置设置为0 CharBuffer cb = charSet.decode(bf); String data = cb.toString(); if (data.indexOf("\r\n")==-1) return; String outputData = data.substring(0,data.indexOf("\n")+1); ByteBuffer outputBuffer = charSet.encode("echo"+outputData); while(outputBuffer.hasRemaining()){ sc.write(outputBuffer); } ByteBuffer temp = charSet.encode(outputData); bf.position(temp.limit()); bf.compact(); //删除已经处理的字符串 if (outputData.equals("bye\r\n")){ selectionKey.cancel(); sc.close(); System.out.println("关闭与客户端的连接"); } } } } }
8a2040d3-5fbc-4298-a67e-6865cf327abd
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(LoopTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(LoopTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(LoopTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(LoopTest.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 LoopTest().setVisible(true); } }); }
93ac0552-e692-416d-bfb1-96aded86bf0c
0
@Override public int compare(TVC o1, TVC o2) { return o2.compareTo(o1); }
05281750-3f4b-40f9-bb8c-dc339f38319e
4
public boolean onHandshakeRecieved(WebSocket conn, String handshake, byte[] reply) throws IOException, NoSuchAlgorithmException { // TODO: Do some parsing of the returned handshake, and close connection // (return false) if we recieved anything unexpected. if(this.draft == WebSocketDraft.DRAFT76) { if (reply == null) { return false; } byte[] challenge = new byte[] { (byte)( this.number1 >> 24 ), (byte)( (this.number1 << 8) >> 24 ), (byte)( (this.number1 << 16) >> 24 ), (byte)( (this.number1 << 24) >> 24 ), (byte)( this.number2 >> 24 ), (byte)( (this.number2 << 8) >> 24 ), (byte)( (this.number2 << 16) >> 24 ), (byte)( (this.number2 << 24) >> 24 ), this.key3[0], this.key3[1], this.key3[2], this.key3[3], this.key3[4], this.key3[5], this.key3[6], this.key3[7] }; MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] expected = md5.digest(challenge); for (int i = 0; i < reply.length; i++) { if (expected[i] != reply[i]) { //return false; } } } return true; }
5c08503f-cc6a-4f8f-b34b-48780052d846
9
public static void readConstantsFromFile() { DataInputStream constantsStream; FileConnection constantsFile; byte[] buffer = new byte[255]; String content = ""; try { // Read everything from the file into one string. constantsFile = (FileConnection)Connector.open("file:///" + CONSTANTS_FILE_PATH, Connector.READ); constantsStream = constantsFile.openDataInputStream(); while (constantsStream.read(buffer) != -1) { content += new String(buffer); } constantsStream.close(); constantsFile.close(); // Extract each line separately. String[] lines = Util.split(content, "\n"); for (int i = 0; i < lines.length; i++) { // Extract the key and value. String[] line = Util.split(lines[i], "="); if (line.length != 2) { System.out.println("Error: invalid constants file line: " + (lines[i].length() == 0 ? "(empty line)" : lines[i])); continue; } boolean found = false; // Search through the constants until we find one with the same name. for (int j = 0; j < constants.size(); j++) { Constant constant = (Constant)constants.elementAt(j); if (constant.getName().compareTo(line[0]) == 0) { System.out.println("Setting " + constant.getName() + " to " + Double.parseDouble(line[1])); constant.setVal(Double.parseDouble(line[1])); found = true; break; } } if (!found) System.out.println("Error: the constant doesn't exist: " + lines[i]); } } catch (IOException e) { System.out.println("Constants.txt not found. Not overriding constants."); } catch (Exception e) { e.printStackTrace(); } }
92b4cd81-3b7a-4246-a6b2-9c6e3f866e9f
2
public long getLong(String key) { Object value = get(key); try { return value instanceof Number ? ((Number) value).longValue() : Long.parseLong((String) value); } catch (Exception exception) { return 0; } }
de781ad7-71d7-4579-9876-eb9d0b2fc39b
3
protected void drawShadow(mxGraphicsCanvas2D canvas, mxCellState state, double rotation, boolean flipH, boolean flipV, mxRectangle bounds, double alpha, boolean filled) { // Requires background in generic shape for shadow, looks like only one // fillAndStroke is allowed per current path, try working around that // Computes rotated shadow offset double rad = rotation * Math.PI / 180; double cos = Math.cos(-rad); double sin = Math.sin(-rad); mxPoint offset = mxUtils.getRotatedPoint(new mxPoint(mxConstants.SHADOW_OFFSETX, mxConstants.SHADOW_OFFSETY), cos, sin); if (flipH) { offset.setX(offset.getX() * -1); } if (flipV) { offset.setY(offset.getY() * -1); } // TODO: Use save/restore instead of negative offset to restore (requires fix for HTML canvas) canvas.translate(offset.getX(), offset.getY()); // Returns true if a shadow has been painted (path has been created) if (drawShape(canvas, state, bounds, true)) { canvas.setAlpha(mxConstants.STENCIL_SHADOW_OPACITY * alpha); // TODO: Implement new shadow //canvas.shadow(mxConstants.STENCIL_SHADOWCOLOR, filled); } canvas.translate(-offset.getX(), -offset.getY()); }
241d0ddd-aea4-4758-a0e9-96d27069efbb
2
public Block block() { Node p = this; while (p != null) { if (p instanceof Tree) { return ((Tree) p).block(); } p = p.parent; } throw new RuntimeException(this + " is not in a block"); }
096c22ee-3c3b-45da-93a3-8a6979ac60ac
4
public Password(String pass) { try { this.setKey(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } try { this.setupCipher(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } this.encrypt(pass); }
b4c9fa81-a672-4968-acc8-4edcfc360e3d
7
public ParsingResult parse(List<String> strings) { List<double[]> matrix = new ArrayList<double[]>(); strings = InputExtensions.trimAll(strings); int start = strings.lastIndexOf("OUTC|" + section); if (start == -1) { throw new RuntimeException("Corrupted ChIPMunk output detected."); } for (int lineNumber = start; lineNumber < strings.size(); ++lineNumber) { if (StringExtensions.startWith(strings.get(lineNumber), matrix_start)) { int lengthOfMotif = strings.get(lineNumber).split("\\s+").length; for (int positionIndex = 0; positionIndex < lengthOfMotif; ++positionIndex) { matrix.add(new double[alphabet_size]); } for (int letterIndex = 0; letterIndex < alphabet_size; ++letterIndex) { String[] weights = strings.get(letterIndex + lineNumber).split("\\|")[1].split("\\s+"); for (int positionIndex = 0; positionIndex < lengthOfMotif; ++positionIndex) { matrix.get(positionIndex)[letterIndex] = Double.parseDouble(weights[positionIndex]); } } break; } } if (matrix.size() == 0) { throw new RuntimeException("Corrupted ChIPMunk output detected."); } return new ParsingResult(matrix, null); }
1058222e-94cd-422a-8dd6-1a5a4e2fffe3
2
public static int rate(Point location) { WorldHash hash = GlobalGame.worldHash; Entity ent = hash.getEntity(location); if (ent != null) { if (!ent.is_passable) { playerTarget = ent; return Priority.MEDIUM.val(); } } return Priority.NONE.val(); }
b1411729-347f-467b-add7-36cdfed14fd1
6
public static void main(String[] args) { System.out.println("*******1st Example******"); int[] a = new int[5];// default initialization (all 0) for (int i : a) System.out.println(i);// print the array System.out.println("*******2nd Example******"); int[] b = new int[5];// initialize array for (int i = 0; i < b.length; i++) // use for loop to set values b[i] = i * i; for (int i : b) System.out.println(i);// print the array System.out.println("*******3rd Example******"); int[] c = new int[5];// initialize array c[0] = 0; c[1] = 1; c[2] = 2; c[3] = 3; c[4] = 4; for (int i : c) System.out.println(i);// print the array System.out.println("*******4th Example******"); int[] d = { 0, 1, 2, 3, 4 }; for (int i : d) System.out.println(i);// print the array System.out.println("*******5th Example******"); for (int i = 0; i < d.length; i++) // use normal for loop to print the array d System.out.println(d[i]); }
7ffa691b-94d7-4929-a783-ddf6fea8c273
2
public void drawTree(Graphics g) { g.setColor(Color.red); int halfWidth = cellWidth / 2; if (showTree) { for (Edge e : this.maze.mst) { g.drawLine(e.from.x * cellWidth - halfWidth, e.from.y * cellWidth - halfWidth, e.to.x * cellWidth - halfWidth, e.to.y * cellWidth - halfWidth); } } }
2d5b5ca0-ec57-40d6-b09c-bac03a60ae07
8
@Override public void run() { int frames = 0; long previousTime = System.nanoTime(); double ns = 1000000000.0 / 60.0; double delta = 0; int updates = 0; long timer = System.currentTimeMillis(); requestFocus(); //this is awesome! while (running) { long currentTime = System.nanoTime(); delta += (currentTime - previousTime) / ns; previousTime = currentTime; if (delta >= 1) { tick(); updates++; delta--; } frames++; if (menu) { if (add) { renderAddress(); } else { renderMenu(); } } else { if (pause) { renderPause(); } else { if (win) { renderWin(); } else if (loose) { renderLoose(); } else { render(); } } } while (System.currentTimeMillis() - timer > 1000) { timer += 1000; fps = frames; frames = 0; updates = 0; } } }
5e6589d0-7f90-40fc-901b-b6cc578c00d7
5
public static String parse(String startMonth, String startYear, String endMonth, String endYear, String isCurrent, String datePattern) throws ParseException { boolean current = Boolean.parseBoolean(isCurrent); SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy"); String startDateString; String endDateString; if (startMonth != null && startYear != null) { Date startDate = sdf.parse(startMonth + "/" + startYear); startDateString = new SimpleDateFormat(datePattern).format(startDate); } else { startDateString = "Unknown"; } if (current) { endDateString = "Present"; } else { if (endMonth != null && endYear != null) { Date endDate = sdf.parse(endMonth + "/" + endYear); endDateString = new SimpleDateFormat(datePattern).format(endDate); } else { endDateString = "Unknown"; } } return startDateString + "-" + endDateString; }
13584eb7-7aaa-4757-959c-9686e42cd957
2
public String getBookSource1to66(int book, int chapter) { StringBuilder sb = new StringBuilder(); String filename = "unv_" + TITLE_SHORT_EN_1TO66[book] + "_" + chapter + ".html"; Path file = Paths.get(CBOL_HOME + filename); Charset charset = Charset.forName("UTF-8"); try (BufferedReader reader = Files.newBufferedReader(file, charset)) { String line = null; while ((line = reader.readLine()) != null) { sb.append(line); // System.out.println(line); } } catch (IOException x) { System.err.format("IOException: %s%n", x); } return sb.toString(); }
751928d7-3503-48da-a9a9-d8ae71214fba
1
public Jump removeJumps(FlowBlock dest) { if (dest != END_OF_METHOD) dest.predecessors.remove(this); return ((SuccessorInfo) successors.remove(dest)).jumps; }
d4f43b2e-d02d-43b0-afbe-7474a8078264
5
public int getLastBlockChange(int x, int y) { if(chunkID < 0) { x = 15-x; } if(x < 0 || x >= blocks.length || y < 0 || y >= blocks[0].length) return 0; return blockChanges[x][y]; }
b1b2f719-588f-4ef2-859d-41948fd0cec8
4
private void addOthers(int xGap, int yGap) { if (xGap < 20) xGap = 20; if (yGap < 20) yGap = 20; for (int x = 0; x < panel.getWidth(); x += xGap) { for (int y = 0; y < panel.getHeight(); y += yGap) { add(new Point(x, y)); } } }
48e3643b-4f1a-441f-94a6-38b9e0cf25be
8
protected Vector<Integer> fillChoices(Room R) { final Vector<Integer> choices=new Vector<Integer>(); for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--) { final Room room=R.getRoomInDir(d); final Exit exit=R.getExitInDir(d); final Exit opExit=R.getReverseExit(d); if((room!=null) &&((room.domainType()&Room.INDOORS)==0) &&(room.domainType()!=Room.DOMAIN_OUTDOORS_AIR) &&((exit!=null)&&(exit.isOpen())) &&(opExit!=null)&&(opExit.isOpen())) choices.addElement(Integer.valueOf(d)); } return choices; }
fc52ef1c-44a2-4da7-bd5e-150ec13e0339
6
public void addClasa(Clasa cl, Node node) { NodeList childNodes = node.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node cNode = childNodes.item(i); if (cNode instanceof Element) { String content = cNode.getLastChild().getTextContent().trim(); switch (cNode.getNodeName()) { case "idClasa": cl.setIdClasa(content); break; case "listaMaterii": addListaMaterii(cl, cNode); break; case "listaElevi": addListaElevi(cl, cNode); break; case "catalog": formCatalog(cl, cNode); break; default: break; } } } }
a920e51c-4d7b-4eb3-a4d0-142889288f29
8
static void doRun(Action action){ try { Var.pushThreadBindings(RT.map(RT.AGENT, action.agent)); nested.set(PersistentVector.EMPTY); Throwable error = null; try { Object oldval = action.agent.state; Object newval = action.fn.applyTo(RT.cons(action.agent.state, action.args)); action.agent.setState(newval); action.agent.notifyWatches(oldval,newval); } catch(Throwable e) { error = e; } if(error == null) { releasePendingSends(); } else { nested.set(PersistentVector.EMPTY); if(action.agent.errorHandler != null) { try { action.agent.errorHandler.invoke(action.agent, error); } catch(Throwable e) {} // ignore errorHandler errors } if(action.agent.errorMode == CONTINUE) { error = null; } } boolean popped = false; ActionQueue next = null; while(!popped) { ActionQueue prior = action.agent.aq.get(); next = new ActionQueue(prior.q.pop(), error); popped = action.agent.aq.compareAndSet(prior, next); } if(error == null && next.q.count() > 0) ((Action) next.q.peek()).execute(); } finally { nested.set(null); Var.popThreadBindings(); } }
2b164c93-0b77-49b8-8156-1c28d638356d
8
public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) return l2; if (l2 == null) return l1; ListNode mergedHead = null; if (l1.val > l2.val) { mergedHead = l2; l2 = l2.next; } else { mergedHead = l1; l1 = l1.next; } ListNode current = mergedHead; while (l1 != null && l2 != null) { if (l1.val > l2.val) { current.next = l2; l2 = l2.next; } else { current.next = l1; l1 = l1.next; } current = current.next; } if (l1 == null) { current.next = l2; } if (l2 == null) { current.next = l1; } return mergedHead; }
2d3b4616-30d6-4898-a6ca-3b7d32da751b
9
private static void improved_range_search_binary(finger_print fp, double dis, Data data) { //System.out.println(fp.id); ArrayList<Integer> lst1 = new ArrayList<Integer>(); HashMap<Integer, Integer> potent = new HashMap<Integer, Integer>(); ArrayList<Integer> lst2 = new ArrayList<Integer>(); // to be commented // for (int i : data.data_set.keySet()) { // if (fp.getDistance(data.data_set.get(i)) < dis) { // lst2.add(i); // //System.out.print(" " + fp.getDistance(data.data_set.get(i))); // } // } // System.out.println(lst2); // int s=lst2.size(); // lst2.clear(); int q_feat = fp.feature_size; /** binary **/ int feat_count = 0; double min_fts = 0; boolean add = true; int f = 0; int gen=0; Collections.sort(fp.feat_present, finger_print.comp); // uncomment fsort //System.out.println(); for (Integer fid : fp.feat_present) { add = true; if (finger_print.mn_ft_allpts_infeat.containsKey(fid)) { //System.out.println("No fo0 points in feature "+fid+" "+finger_print.invert_index.get(fid).keySet().size()* finger_print.mn_ft_allpts_infeat.get(fid)); double temp = 0, max_sim = 0; /** binary **/ temp = Math.min(min_fts, finger_print.mn_ft_allpts_infeat.get(fid)); max_sim = (feat_count + 1.0) / (q_feat - (1 + feat_count) + temp); /****/ //System.out.println(dis); if (max_sim < 1 - dis) { //System.out.println("Rejected "+fid + " "+finger_print.invert_index.get(fid).containsKey(553)+" feature no "+gen+" "+fp.getDistance(data.data_set.get(553))); //f++; min_fts = temp; // System.out.println(( feat_neglect.size()+1.0) / (q_feat // -1 - feat_neglect.size() + Math.max(max, // finger_print.mn_ft_allpts_infeat.get(fid)))); add = false; //System.out.println("Feature no : "+ fid+ ); feat_count++; } if (add) { if (finger_print.invert_index.containsKey(fid)) { for (Integer id : finger_print.invert_index.get(fid) .keySet()) { if (!potent.containsKey(id)) { potent.put(id, 1); lst1.add(id); } } } } } } //System.out.println("percent pruned "+1.0*f/fp.feat_present.size()); //System.out.println("Features pruned "+feat_count); //System.out.println("rehected no of feats " + f); for (int i = 0; i < lst1.size(); i++) { int j = lst1.get(i); if (fp.getDistance(data.data_set.get(j)) < dis) { lst2.add(j); //System.out.print(" "+ fp.getDistance(data.data_set.get(lst1.get(i)))); // System.out.println("Point "+j); } } // if(lst2.size()!=s){ // System.out.println("NNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOO"); // } //System.out.println(lst2); //System.out.println("Candidate point list size "+lst1.size()); //System.out.println(); }
f6200034-a31b-45a3-8cce-b987ecb1e402
9
public void processBatch(MappedStatement ms, Statement stmt, List<Object> parameters) { ResultSet rs = null; try { rs = stmt.getGeneratedKeys(); final Configuration configuration = ms.getConfiguration(); final TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry(); final String[] keyProperties = ms.getKeyProperties(); final ResultSetMetaData rsmd = rs.getMetaData(); TypeHandler<?>[] typeHandlers = null; if (keyProperties != null && rsmd.getColumnCount() >= keyProperties.length) { for (Object parameter : parameters) { if (!rs.next()) break; // there should be one row for each statement (also one for each parameter) final MetaObject metaParam = configuration.newMetaObject(parameter); if (typeHandlers == null) typeHandlers = getTypeHandlers(typeHandlerRegistry, metaParam, keyProperties); populateKeys(rs, metaParam, keyProperties, typeHandlers); } } } catch (Exception e) { throw new ExecutorException("Error getting generated key or setting result to parameter object. Cause: " + e, e); } finally { if (rs != null) { try { rs.close(); } catch (Exception e) { // ignore } } } }
4ead11ed-7c03-4366-8fee-2aef2ea15c7d
3
public synchronized AudioDevice createAudioDevice() throws JavaLayerException { if (!tested) { testAudioDevice(); tested = true; } try { return createAudioDeviceImpl(); } catch (Exception ex) { throw new JavaLayerException("unable to create JavaSound device: "+ex); } catch (LinkageError ex) { throw new JavaLayerException("unable to create JavaSound device: "+ex); } }
715072ce-0ea0-41fe-991f-a3f747f4f5c9
5
public boolean clickInRegion(int x1, int x2, int y1, int y2) { if (getScale() != 1) { x2 = (int) ((x2 - x1) * getScale()); x1 *= getScale(); x2 += x1; y2 = (int) ((y2 - y1) * getScale()); y1 *= getScale(); y2 += y1; x1 += Main.scaledX; x2 += Main.scaledX; y1 += Main.scaledY; y2 += Main.scaledY; } if (clickX >= x1 && clickX <= x2 && clickY >= y1 && clickY <= y2) { return true; } return false; }
f026c5f9-8d0f-460d-83d3-dffd578f20e9
9
public static char[] UsarComodin() throws Exception { //Buffer del diccionario que se esta usando BufferedReader Frd = new BufferedReader(new FileReader("archivos/diccionarios/"+Idioma()+".txt")); String PDiccionario; char[] nulo = "n".toCharArray(); int contador = 0; int[] repetidas = new int[Utilidades.Letras.length]; //leemos el diccionario hasta el final while((PDiccionario=Frd.readLine()) != null){ char[] diccio = PDiccionario.toCharArray(); for (int i = 0; i < diccio.length; i++) { for (int j = 0; j < Letras.length; j++) { if(diccio[i] == Letras[j]) { repetidas[j]++; } } } for (int i = 0; i < repetidas.length; i++) { if(repetidas[i] == 1) { contador++; } } if (contador == diccio.length) { if(!Palabra.leerPalabraUsada(diccio)) { if(Palabra.ComprobarPaPn(Juego.PActual, diccio)) { return diccio; } } } contador = 0; } Frd.close(); return nulo; }
e1f63977-e11b-40f9-b4df-17371d666a01
0
private static void buildAndRunGui(final Alloy alloy, final String[] hn) { SwingUtilities.invokeLater(new Runnable() { // (dispatch thread code) @Override public void run() { Display display = new Display(alloy, hn, "Assignment 3: Alloy Simulation"); display.setVisible(true); display.draw(); } }); // (/dispatch thread code) }
ed8d5755-4118-4645-baf6-44cac10b1e11
6
public void changeProfessor() { int actualRound = Sims_1._maingame.round; if (actualRound == 4) { lectorChanged4 = true; //shows that professor was changed on the beginning of the 2.Semester (4.Round) Sims_1._maingame.professor = (int) Math.round(Math.random() * 100 + 1); } else if (actualRound == 7) { lectorChanged7 = true; Sims_1._maingame.professor = (int) Math.round(Math.random() * 100 + 1); } else if (actualRound == 10) { lectorChanged10 = true; Sims_1._maingame.professor = (int) Math.round(Math.random() * 100 + 1); } else if (actualRound == 13) { lectorChanged13 = true; Sims_1._maingame.professor = (int) Math.round(Math.random() * 100 + 1); } else if (actualRound == 16) { lectorChanged16 = true; Sims_1._maingame.professor = (int) Math.round(Math.random() * 100 + 1); } //setting new professor icon //temp is a temporar variable needed for comparison int temp; //fix by Dawid while ((temp = (int) Math.round(Math.random() * 2)) == Sims_1._maingame.professorIconNum); // String temp=Sims_1._maingame.professorIconPath[((int) Math.round(Math.random()*2 ))]; // // //elimination of setting the same professor picture as before // while (Sims_1._maingame.professorIcon.equals(temp)){ // temp=Sims_1._maingame.professorIconPath[((int) Math.round(Math.random()*2 ))]; // } Sims_1._maingame.professorIconNum = temp; Sims_1._maingame.professorIcon = Sims_1._maingame.professorIconPath[temp]; //loading new icon on the button this.professorButton.setIcon(new ImageIcon(getClass().getResource(Sims_1._maingame.professorIcon))); this.professorButton.updateUI(); // System.out.println("Dozent wurde gewechselt. Neuer Dozentenwert: " + Sims_1._maingame.professor); professorCounter.setText("0x"); //label update professorCounter.repaint(); }
c90e7f8c-a5a8-40ec-ad07-147d131659d3
8
public Set<Node> getNodesAt(Graphics2D g2, Rectangle rect) { Set<Node> nodes = new HashSet<Node>(); for (Node node : tree.getExternalNodes()) { Shape taxonLabelBound = tipLabelBounds.get(node); if (taxonLabelBound != null && g2.hit(rect, taxonLabelBound, false)) { nodes.add(node); } } for (Node node : tree.getNodes()) { Shape branchPath = transform.createTransformedShape(treeLayoutCache.getBranchPath(node)); if (branchPath != null && g2.hit(rect, branchPath, true)) { nodes.add(node); } Shape collapsedShape = transform.createTransformedShape(treeLayoutCache.getCollapsedShape(node)); if (collapsedShape != null && g2.hit(rect, collapsedShape, false)) { nodes.add(node); } } return nodes; }
c82be578-eed8-4c03-b345-3abf59c750df
7
private void eating1310(int j) throws NoInputException { if (f < 5) { die3000(j); return; } do { print("Do you want to eat <b>(1)</b> poorly, <b>(2)</b> moderately or <b>(3)</b> well ?"); e = skb.inputInt(screen); if (e < 1 || e > 3) { print("Enter 1, 2, or 3, please."); break; } final int ee = (int) (4 + 2.5 * e); if (e == 1 && ee > f) { f = 0; return; } if (ee > f) { print("You don't have enough to eat that well."); break; } f -= ee; return; } while (true); }
9dcedf2b-3778-4898-b2d0-1006a9eda1f0
6
private static boolean isChildrenTree(TreeNode parent, TreeNode children) { // TODO Auto-generated method stub if(parent == null && children == null){ return true; } else if(parent == null){ return false; } else if(children == null){ return false; }else{ if(parent.data == children.data){ return isChildrenTree(parent.left,children.left) && isChildrenTree(parent.right,children.right); }else{ return false; } } }
26ec2714-654d-4fcb-bfde-8bd817d2faf9
2
public static Point pointAt( Point start, Point dir, double dist ) { if( dir.x == 0 && dir.y == 0 ){ return start; } double dirDist = Math.sqrt( dist2( 0, 0, dir.x, dir.y )); double factor = dist / dirDist; return new Point( round( start.x + factor * dir.x ), round( start.y + factor * dir.y ) ); }
3b44711e-7204-434b-b944-1443f72028be
3
public String showDiff(String s1, String s2) { StringBuilder diff = new StringBuilder(); String lines1[] = s1.split("\n"); String lines2[] = s2.split("\n"); diff.append("Number of lines: " + lines1.length + " vs " + lines2.length + "\n"); int min = Math.min(lines1.length, lines2.length); int countLinesDiff = 0; for (int i = 0; i < min; i++) { if (!lines1[i].equals(lines2[i])) { countLinesDiff++; // Show difference between lines diff.append(String.format("%10d\t|%s|\n", (i + 1), lines1[i])); diff.append(String.format(" \t|%s|\n", lines2[i])); diff.append(String.format(" \t|%s|\n\n", showDiffLine(lines1[i], lines2[i]))); } if (countLinesDiff > MAX_LINES_DIFF) break; } return diff.toString(); }
ddcf5698-beaa-4b0d-8beb-4929674ce3a3
2
public static String[] removeEmptyStrings(String[] data) { ArrayList<String> result = new ArrayList<String>(); for (int i = 0; i < data.length; i++) if (!data[i].equals("")) result.add(data[i]); String[] res = new String[result.size()]; result.toArray(res); return res; }
b568176f-c27e-483c-a52e-e2f102565462
2
public static int compare(long lhs, long rhs) { return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1); }
ae762428-3894-4af1-9542-90514ed098a1
8
public void doStep() { int i; for (i = 0; i != getPostCount(); i++) { Pin p = pins[i]; if (p.output && pins[9].value) { p.value = volts[i] > 2.5; } if (!p.output) { p.value = volts[i] > 2.5; } } execute(); for (i = 0; i != getPostCount(); i++) { Pin p = pins[i]; if (p.output && !pins[9].value) { sim.updateVoltageSource(0, nodes[i], p.voltSource, p.value ? 5 : 0); } } }
be60fb60-7751-4382-82e8-fb14c0f3bee2
8
private static boolean validateMove(PGNMove move) { String strippedMove = move.getMove(); if (move.isCastle()) { return true; } else if (move.isEndGameMarked()) { return true; } else if (strippedMove.length() == MOVE_TYPE_1_LENGTH) { return strippedMove.matches(MOVE_TYPE_1_RE); } else if (strippedMove.length() == MOVE_TYPE_2_LENGTH) { return strippedMove.matches(MOVE_TYPE_2_RE) || strippedMove.matches(MOVE_TYPE_5_RE); } else if (strippedMove.length() == MOVE_TYPE_3_LENGTH) { return strippedMove.matches(MOVE_TYPE_3_RE) || strippedMove.matches(MOVE_TYPE_6_RE); } else if (strippedMove.length() == MOVE_TYPE_4_LENGTH) { return strippedMove.matches(MOVE_TYPE_4_RE); } return false; }
246569cd-27ca-4fa3-b17f-c4f4109a7b77
5
private boolean insertTime(Time newTime) { boolean saved = false; try { Connection conn = Dao.getConnection(); // Check that the fields are not null and that the duration is greater than 1 minute. if (newTime.isFullFilled() && newTime.getDuration() >= MINIMUM_TIME_DURATION) { int insertTime = timeDao.insertTime(conn, newTime); if (insertTime > 0) saved = true; } else { checkTimeFields(newTime); } } catch (SQLException ex) { ErrorMessages.sqlExceptionError("insertTime()", ex); } catch (ClassNotFoundException ex) { ErrorMessages.classNotFoundError("insertTime()", ex); } return saved; }
6f8106b5-f789-45c2-9ad7-97642451c2fc
8
private Component cycle(Component currentComponent, int delta) { int index = -1; loop : for (int i = 0; i < m_Components.length; i++) { Component component = m_Components[i]; for (Component c = currentComponent; c != null; c = c.getParent()) { if (component == c) { index = i; break loop; } } } // try to find enabled component in "delta" direction int initialIndex = index; while (true) { int newIndex = indexCycle(index, delta); if (newIndex == initialIndex) { break; } index = newIndex; // Component component = m_Components[newIndex]; if (component.isEnabled() && component.isVisible() && component.isFocusable()) { return component; } } // not found return currentComponent; }
4c0915ec-23ae-434c-a692-236002213944
5
public static boolean deleteDirectory( File dir ) { if( dir.isDirectory() ) { String[] children = dir.list(); for( int i = 0; i < children.length; i++ ) { if( children[ i ] == "." || children[ i ] == ".." ) continue; boolean ok = deleteDirectory( new File( dir, children[ i ] ) ); if( !ok ) return( false ); } } return( dir.delete() ); }
af3e7f4f-7c03-4db9-a203-4d46f5dbdbf1
5
public void draw(Graphics g){ for (int i = 0; i < 13; i++) { stripes[i].draw(g); } this.union.draw(g); for (int i = 0 ; i < this.wstars.length; i++){ for (int j = 0; j< 6; j++){ if (i%2 ==0){ this.wstars[i][j].draw(g); }else { if (j<5){ this.wstars[i][j].draw(g); } } } } }
d3aafad2-06b0-4cc9-ab08-d8d4f6321d57
7
public static void main(String[] args) { assert (args.length >= 3): "Must pass at least 3 arguments!"; String method = args[0]; // method is always the first argument String input = args[args.length-2]; // input is always 2nd last argument String output = args[args.length-1]; // output is always last argument Picture image = Utils.loadPicture(input); Process proc = new Process(image); switch (method) { case "invert": proc.invert(); break; case "grayscale": proc.grayscale(); break; case "rotate": int theta = Integer.parseInt(args[1]); proc.rotate(theta); break; case "flip": proc.flip(args[1]); break; case "blur": proc.blur(); break; case "blend": Picture otherImage = Utils.loadPicture(args[1]); proc.blend(otherImage); break; case "electricField": proc.electricField(Integer.parseInt(args[1]), Integer.parseInt(args[2]), Integer.parseInt(args[3])); } Utils.savePicture(proc.getPicture(), output); }
a4e8e4d3-a564-4fc3-be1f-9a418b2a1e90
8
protected CoverTreeNode batch_insert(Integer p, int max_scale, // current // scale/level int top_scale, // max scale/level for this dataset Stack<DistanceNode> point_set, // set of points that are nearer to p // [will also contain returned unused // points] Stack<DistanceNode> consumed_set) // to return the set of points that have // been used to calc. max_dist to a // descendent // Stack<Stack<DistanceNode>> stack) //may not be needed { if (point_set.length == 0) { CoverTreeNode leaf = new_leaf(p); leaf.nodeid = m_NumNodes; m_NumNodes++; // incrementing node count m_NumLeaves++; // incrementing leaves count return leaf; } else { double max_dist = max_set(point_set); // O(|point_set|) the max dist // in point_set to point "p". int next_scale = Math.min(max_scale - 1, get_scale(max_dist)); if (next_scale == Integer.MIN_VALUE) { // We have points with distance // 0. if max_dist is 0. Stack<CoverTreeNode> children = new Stack<CoverTreeNode>(); CoverTreeNode leaf = new_leaf(p); leaf.nodeid = m_NumNodes; children.push(leaf); m_NumLeaves++; m_NumNodes++; // incrementing node and leaf count while (point_set.length > 0) { DistanceNode tmpnode = point_set.pop(); leaf = new_leaf(tmpnode.idx); leaf.nodeid = m_NumNodes; children.push(leaf); m_NumLeaves++; m_NumNodes++; // incrementing node and leaf count consumed_set.push(tmpnode); } CoverTreeNode n = new_node(p); // make a new node out of p and assign // it the children. n.nodeid = m_NumNodes; m_NumNodes++; // incrementing node count n.scale = 100; // A magic number meant to be larger than all scales. n.max_dist = 0; // since all points have distance 0 to p n.num_children = children.length; n.children = children; return n; } else { Stack<DistanceNode> far = new Stack<DistanceNode>(); split(point_set, far, max_scale); // O(|point_set|) CoverTreeNode child = batch_insert(p, next_scale, top_scale, point_set, consumed_set); if (point_set.length == 0) { // not creating any node in this // recursive call // push(stack,point_set); point_set.replaceAllBy(far); // point_set=far; return child; } else { CoverTreeNode n = new_node(p); n.nodeid = m_NumNodes; m_NumNodes++; // incrementing node count Stack<CoverTreeNode> children = new Stack<CoverTreeNode>(); children.push(child); while (point_set.length != 0) { // O(|point_set| * num_children) Stack<DistanceNode> new_point_set = new Stack<DistanceNode>(); Stack<DistanceNode> new_consumed_set = new Stack<DistanceNode>(); DistanceNode tmpnode = point_set.pop(); double new_dist = tmpnode.dist.last(); consumed_set.push(tmpnode); // putting points closer to new_point into new_point_set (and // removing them from point_set) dist_split(point_set, new_point_set, tmpnode, max_scale); // O(|point_saet|) // putting points closer to new_point into new_point_set (and // removing them from far) dist_split(far, new_point_set, tmpnode, max_scale); // O(|far|) CoverTreeNode new_child = batch_insert(tmpnode.idx, next_scale, top_scale, new_point_set, new_consumed_set); new_child.parent_dist = new_dist; children.push(new_child); // putting the unused points from new_point_set back into // point_set and far double fmax = dist_of_scale(max_scale); tmpnode = null; for (int i = 0; i < new_point_set.length; i++) { // O(|new_point_set|) tmpnode = new_point_set.element(i); tmpnode.dist.pop(); if (tmpnode.dist.last() <= fmax) point_set.push(tmpnode); else far.push(tmpnode); } // putting the points consumed while recursing for new_point // into consumed_set tmpnode = null; for (int i = 0; i < new_consumed_set.length; i++) { // O(|new_point_set|) tmpnode = new_consumed_set.element(i); tmpnode.dist.pop(); consumed_set.push(tmpnode); } }// end while(point_size.size!=0) point_set.replaceAllBy(far); // point_set=far; n.scale = top_scale - max_scale; n.max_dist = max_set(consumed_set); n.num_children = children.length; n.children = children; return n; }// end else if(pointset!=0) }// end else if(next_scale != -214.... }// end else if(pointset!=0) }
115c883e-480f-4480-8ea8-29a2995c37bd
5
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FeatureNode other = (FeatureNode)obj; if (index != other.index) return false; if (Double.doubleToLongBits(value) != Double.doubleToLongBits(other.value)) return false; return true; }
a559ce61-23d4-4d74-8ef6-5d8689ad7c5a
0
@Override public void keyTyped(KeyEvent arg0) { // TODO Auto-generated method stub }
d8eed5f4-f315-454a-8bdf-4c68a16372ae
2
public void addCharacter(Character c){ if (hasCharacter()){ throw new UnsupportedOperationException("Can't add character to tile - there already is one"); } if (c instanceof Player){ setRoomAsVisited(); } character = c; setChanged(); notifyObservers(); }
f7684726-acfa-4900-b8c0-6d8b97da000a
3
@Override public boolean wipeTable(String table) throws MalformedURLException, InstantiationException, IllegalAccessException { //Connection connection = null; Statement statement = null; String query = null; try { if (!this.checkTable(table)) { this.writeError("Error wiping table: \"" + table + "\" does not exist.", true); return false; } //connection = getConnection(); this.connection = this.getConnection(); statement = this.connection.createStatement(); query = "DELETE FROM " + table + ";"; statement.executeUpdate(query); return true; } catch (SQLException e) { if (!e.toString().contains("not return ResultSet")) return false; } return false; }
46021f02-72d8-4b46-9f54-90124a9ddf97
7
private void setupMouseListener( final IMouseListener mouseListener ) { addMouseMotionListener( new MouseMotionAdapter() { public void mouseDragged( MouseEvent e ) { Point p = e.getPoint(); onFakeMove( p ); } public void mouseMoved( MouseEvent e ) { Point p = e.getPoint(); mouseListener.onMove( p.x, p.y ); } public void onFakeMove( Point p ) { mouseListener.onMove( p.x, p.y ); } } ); addMouseListener( new MouseAdapter() { public void mousePressed( MouseEvent e ) { if ( e.getButton() == 1 ) { mouseListener.onLeftDown( e.getPoint().x, e.getPoint().y ); } else if ( e.getButton() == 2 ) { mouseListener.onMiddleDown( e.getPoint().x, e.getPoint().y ); } else if ( e.getButton() == 3 ) { mouseListener.onRightDown( e.getPoint().x, e.getPoint().y ); } } public void mouseReleased( MouseEvent e ) { if ( e.getButton() == 1 ) { mouseListener.onLeftUp( e.getPoint().x, e.getPoint().y ); } else if ( e.getButton() == 2 ) { mouseListener.onMiddleUp( e.getPoint().x, e.getPoint().y ); } else if ( e.getButton() == 3 ) { mouseListener.onRightUp( e.getPoint().x, e.getPoint().y ); } } } ); addMouseWheelListener( new MouseWheelListener() { public void mouseWheelMoved( MouseWheelEvent e ) { if ( e.getWheelRotation() > 0 ) { // scroll down mouseListener.onScrollDown( e.getPoint().x, e.getPoint().y ); } else { mouseListener.onScrollUp( e.getPoint().x, e.getPoint().y ); } } } ); }
09835893-00d8-4650-93fb-e80f03a450a3
0
private void openBotFolderActionPerformed(ActionEvent e) { // TODO add your code here }
ef2ad181-2e04-4acc-a21c-c28abe2e78ab
7
public List<Employee> getEmployeeInJoiningDateRange(String startDate, String endDate) { if (startDate == null || endDate == null) throw new IllegalArgumentException(); DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); List<Employee> employeesInDate = new ArrayList<Employee>(); try { Date start = df.parse(startDate); Date end = df.parse(endDate); List<TreeNode> nodes = getEmployees(); for (TreeNode n: nodes) { Employee e = n.getEmployee(); Date joinDate = df.parse(e.getDateOfJoining()); if (start.compareTo(joinDate) <=0 && end.compareTo(joinDate) >= 0) employeesInDate.add(e); } } catch (ParseException e) { throw new CompanyHierarchyException("Date parsing failed!"); } if (employeesInDate.isEmpty()) return null; return employeesInDate; }
8770cdcc-f708-4756-ab99-8610d4f3def6
4
public static double[][] add(double A[][], double B[][]){ if(A.length != B.length || A[0].length != B[0].length) return null; double T[][] = new double[A.length][A[0].length]; for(int i = 0; i<T.length; i++){ for(int j = 0; j<T[0].length; j++){ T[i][j] = A[i][j]+B[i][j]; } } return T; } //end add method
2b80eddd-1e00-494b-bd61-0fb1e11a5cce
3
private void bl(String label) { if (verbose) System.out.println("(Branch? " + (acc < 0 ? "YES" : "NO") + ")"); if (acc < 0) index = branches.get(label) - 1; }
1efce14d-b7de-44cb-acf1-b92db8a1697f
9
private static String RemoveSpecialCharacters(String str) { char[] buffer = new char[str.length()]; int idx = 0; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c == '.') || (c == '_')) { buffer[idx] = c; idx++; } } return new String(buffer, 0, idx); }
d3a57477-867a-448e-a907-c242f4f4bb6c
9
@Override public String getParent(FakeFile fake) { String path = fake.getPath(); int length = path.length(), firstInPath = 0; if (getSeparatorChar() == '\\' && length > 2 && path.charAt(1) == ':') { firstInPath = 2; } int index = path.lastIndexOf(getSeparatorChar()); if (index == -1 && firstInPath > 0) { index = 2; } if (index == -1 || path.charAt(length - 1) == getSeparatorChar()) { return null; } if (path.indexOf(getSeparatorChar()) == index && path.charAt(firstInPath) == getSeparatorChar()) { return path.substring(0, index + 1); } return path.substring(0, index); }
3326e62a-fe7a-43ab-965b-ff7c03882a70
2
public void addNotify() { super.addNotify(); // Create BackBuffer... createBufferStrategy( 2 ); buffer = getBufferStrategy(); // Create off-screen drawing surface bi = gc.createCompatibleImage( WIDTH, HEIGHT ); if (animator == null) { try { animator = new Thread(this, "GameLoop"); animator.start(); } catch (Exception e) { System.out.println(e.getMessage()); } } }
b2adf1a8-319e-4e15-bf58-5f6983656fe8
0
private void fireDisconnectEvent(DisconnectEvent evt) { fireClientDisconnectEvent(evt); }
6e4e1d15-426a-4e47-a1a6-2b996df66ba8
2
public String[] getTerminalsOnLHS() { ArrayList list = new ArrayList(); for (int i = 0; i < myLHS.length(); i++) { char c = myLHS.charAt(i); if (ProductionChecker.isTerminal(c)) list.add(myLHS.substring(i, i + 1)); } return (String[]) list.toArray(new String[0]); }
6ce5f2b6-84f7-4d2b-81b5-b52485c07931
2
public int geti(int i){ int k=i; int j; for(j =-1; k!=0 ; ){ j++; if ( !r[j] ) k--; } r[j]=true; return j+1; }
a327845d-ddf4-47f4-b6d0-5d4e70b73c6a
0
@Override public void setGUITreeComponentID(String id) {this.id = id;}
dc50d6fe-1864-4ef5-bf55-ae3cdeeab140
9
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ServletPrinter sp = null; PreparedStatement stmt = null; Connection conn = null; String nickname, password, storyId, parent, userIdstring, subject, body; String comment_table; int page = 0, nbOfStories = 0, userId; int updateResult; sp = new ServletPrinter(response, "StoreComment"); nickname = request.getParameter("nickname"); password = request.getParameter("password"); storyId = request.getParameter("storyId"); parent = request.getParameter("parent"); subject = request.getParameter("subject"); body = request.getParameter("body"); comment_table = request.getParameter("comment_table"); if (nickname == null) { nickname = request.getParameter("nickname"); } if (password == null) { password = request.getParameter("password"); } if (storyId == null) { sp.printHTML("StoreComment, You must provide a story identifier!<br>"); return; } if (parent == null) { sp .printHTML("StoreComment, You must provide a follow up identifier!<br>"); return; } if (subject == null) { sp.printHTML("StoreComment, You must provide a comment subject!<br>"); return; } if (body == null) { sp .printHTML("StoreComment, <h3>You must provide a comment body!<br></h3>"); return; } if (comment_table == null) { sp.printHTML("Viewing comment, You must provide a comment table!<br>"); return; } sp.printHTMLheader("RUBBoS: Comment submission result"); sp.printHTML("<center><h2>Comment submission result:</h2></center><p>\n"); conn = getConnection(); // Authenticate the user userIdstring = sp.authenticate(nickname, password, conn); userId = (Integer.valueOf(userIdstring)).intValue(); if (userId == 0) sp.printHTML("Comment posted by the 'Anonymous Coward'<br>\n"); else sp.printHTML("Comment posted by user #" + userId + "<br>\n"); // Add comment to database try { stmt = conn.prepareStatement("INSERT INTO " + comment_table + " VALUES (NULL, " + userId + ", " + storyId + ", " + parent + ", 0, 0, NOW(), \"" + subject + "\", \"" + body + "\")"); updateResult = stmt.executeUpdate(); stmt.close(); stmt = conn.prepareStatement("UPDATE " + comment_table + " SET childs=childs+1 WHERE id=" + parent); updateResult = stmt.executeUpdate(); } catch (Exception e) { closeConnection(stmt, conn); sp.printHTML("Exception getting categories: " + e + "<br>"); return; } closeConnection(stmt, conn); sp.printHTML("Your comment has been successfully stored in the " + comment_table + " database table<br>\n"); sp.printHTMLfooter(); }
b3647a53-3474-4222-8600-19ae95eac6b0
0
@Override public void setReceiveQuery(IReceiveQuery receiveQuery) { this.receiveQuery = receiveQuery; }
b1348d4a-d623-4aca-b339-669e08a7dfff
3
private int getRand(String[] nr) { int ret = -1; int tries = 3; int rand = LangCoach.RANDOM.nextInt(nr.length + 1); for (int i = 0; i < tries; i ++) { if (rand == nr.length) break; if (nr[rand].equals("-")) { rand = LangCoach.RANDOM.nextInt(nr.length); continue; } ret = rand; } return ret; }
f6d722f1-24f9-48e7-adb4-764bcbe33979
0
public PolicyType createPolicyType() { return new PolicyType(); }
2abb4987-0a85-4a23-af38-2e7d2e6be70a
7
protected void connect() { try { boolean received = false; for (int rounds = 0; !received && rounds < MAX_ROUNDS; ++rounds) { int transaction_id = random.nextInt(); DatagramPacket sentPacket = url.makePacket(getRawConnectMessage(transaction_id).array()); try { this.socket.send(sentPacket); } catch (IOException e) { e.printStackTrace(); } DatagramPacket packet = url.makePacket(new byte[256]); try { this.socket.setSoTimeout((int) (15000 * Math.pow(2, rounds))); this.socket.receive(packet); ByteBuffer buffer = ByteBuffer.wrap(packet.getData()); int action = buffer.getInt(); int received_tid = buffer.getInt(); long received_cid = buffer.getLong(); if (action == ACTION_ID_CONNECT && received_tid == transaction_id) { this.connection_time = System.currentTimeMillis(); this.connection_id = received_cid; received = true; } } catch (IOException e) { e.printStackTrace(); } } } catch (UnknownHostException ex) { ex.printStackTrace(); } }
a965316e-282a-4923-a839-227048a49476
8
private void generate(){ Queue<Integer> q = new Queue<Integer>(); for (int v = 0; v < g.V(); v++) numOfPaths[v] = -1; numOfPaths[base] = 1; q.enqueue(base); levels[base] = 0; while (!q.isEmpty()) { int v = q.dequeue(); for (int w : g.adj(v)) { if (numOfPaths[w] != -1) { if(levels[w] < levels[v]) numOfPaths[v] += numOfPaths[w]; } if(numOfPaths[w] == -1) { q.enqueue(w); levels[w] = levels[v]+1; numOfPaths[w] = 0; } } if(numOfPaths[v] > mostPaths) { mostPaths = numOfPaths[v]; mostPathsVertex = v; } if(v == base) numOfPaths[v] = 1; } }
3d011a9b-5f36-4d71-aeb8-f5c23c3aaa35
4
@Override public void actionPerformed(ActionEvent e) { String action = e.getActionCommand(); if (opdrCreatieView.getCategorie().getSelectedItem().toString() == "Opsomming") { opdrCreatieView.getOpsommingPanel().setVisible(true); opdrCreatieView.getMeerKeuzePanel().setVisible(false); opdrCreatieView.getReproductiePanel().setVisible(false); } if (opdrCreatieView.getCategorie().getSelectedItem().toString() == "Meerkeuze") { opdrCreatieView.getOpsommingPanel().setVisible(false); opdrCreatieView.getMeerKeuzePanel().setVisible(true); opdrCreatieView.getReproductiePanel().setVisible(false); } if (opdrCreatieView.getCategorie().getSelectedItem().toString() == "Reproductie") { opdrCreatieView.getOpsommingPanel().setVisible(false); opdrCreatieView.getMeerKeuzePanel().setVisible(false); opdrCreatieView.getReproductiePanel().setVisible(true); } if (action.equals("Toevoegen")) { createOpdracht(); facade.getPersistable().slaOpdrachtOp(opdrachtCatalogus, opdracht); opdrCreatieView.getAntwoordHintT().setText(""); opdrCreatieView.getAntwoordT().setText(""); opdrCreatieView.getVraagT().setText(""); opdrCreatieView.getAlleKeuzesT().setText(""); opdrCreatieView.getMaxAntwoordTijdC().setSelectedIndex(0); opdrCreatieView.getMaxAantalPogingenC().setSelectedIndex(0); } }
388700bd-0db9-45d0-9daa-e33ca0647a2d
1
@SuppressWarnings("unchecked") public static void main(String[] args) throws ScriptException { ScriptEngineManager manager = new ScriptEngineManager(); List<ScriptEngineFactory> factories = manager.getEngineFactories(); for (ScriptEngineFactory f : factories) { System.out.println("egine name:" + f.getEngineName()); System.out.println("engine version:" + f.getEngineVersion()); System.out.println("language name:" + f.getLanguageName()); System.out.println("language version:" + f.getLanguageVersion()); System.out.println("names:" + f.getNames()); System.out.println("mime:" + f.getMimeTypes()); System.out.println("extension:" + f.getExtensions()); System.out.println("-----------------------------------------------"); } ScriptEngine engine = manager.getEngineByName("js"); engine.put("a", 4); engine.put("b", 6); Object maxNum = engine.eval("function max_num(a,b){return (a>b)?a:b;}max_num(a,b);"); System.out.println("max_num:" + maxNum + ", (class = " + maxNum.getClass() + ")"); @SuppressWarnings("rawtypes") Map m = new HashMap(); m.put("c", 10); engine.put("m", m); maxNum =engine.eval("var x= max_num(a,m.get('c'));"); System.out.println("max_num:" + engine.get("x")); }
9cf9eafb-d44b-45c2-80cd-200cb9184a6d
7
private void setConsoleCaretPosition() { int caretLocation = inputControl.getInputRangeStart(); if (!ignoreInput) { if (caretLocation > -1) consolePane.setCaretPosition(caretLocation); else consolePane.setCaretPosition(consoleStyledDocument.getLength()); if (inputCarryOver && inputControl.hasStoredInput()) inputControl.restoreInput(); if (alwaysKeepScrollBarMaxed || !alwaysKeepScrollBarMaxed && isScrollBarAtMax) setScrollBarMax(); } else { consolePane.setCaretPosition(0); } }
621c7e83-2a2d-4112-9725-56cfdddae206
4
@Override public int hashCode() { int hc = 0; for (Field f : Database.getDBFields(getClass())) try { if (f.get(this) != null) hc += f.get(this).hashCode(); } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } return hc; }
e66835fc-9a62-4fc5-a367-dd619e104931
8
public String eval(final String messageTemplate, final Object problem) { try { final JexlContext ctx = JexlHelper.createContext(); final Map<String, Object> values = new TreeMap<String, Object>(); values.put("problem", problem); ctx.setVars(values); final StringBuilder results = new StringBuilder( messageTemplate.length()); int state = STATE_OUT_OF_EXPRESSION; int expStartIndex = 0; /* * So you may have guessed that writing compilers is not my strong * suit. Okay so this isn't exactly the fastest or most attractive * code in the world, but it solved the problem in a hurry and * didn't require much of a state machine. If you think my code * sucks, at least I got it working in 30 minutes. If you think you * can do better please send me a patch. */ for (int i = 0, length = messageTemplate.length(); i < length; ++i) { final char current = messageTemplate.charAt(i); char nextChar = 0x0000; if (i + 1 < length) { nextChar = messageTemplate.charAt(i + 1); } switch (state) { case STATE_IN_EXPRESSION: if (nextChar == '}') { final String found = messageTemplate.substring( expStartIndex, ++i); final Expression jexlExp = ExpressionFactory .createExpression(found); final Object result = jexlExp.evaluate(ctx); results.append(result); state = STATE_OUT_OF_EXPRESSION; } break; default: // Start expression if (current == '$' && nextChar == '{') { // skip $ and { ++i; expStartIndex = ++i; state = STATE_IN_EXPRESSION; } else { results.append(current); } break; } } /* * append the entire escape just incase they left it open, so * ${problem.value gets printed in the results if there is no * closing brace; */ if (state == STATE_IN_EXPRESSION) { final String openExpression = messageTemplate.substring( expStartIndex - 2, messageTemplate.length()); throw new InterpolationException(openExpression); } return results.toString(); } catch (final Throwable t) { throw new InterpolationException(t); } }
c3fd7874-fa4f-4978-b1a7-e82d1c52fc74
5
public void destroy(String id) throws NonexistentEntityException, RollbackFailureException, Exception { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Depto depto; try { depto = em.getReference(Depto.class, id); depto.getDepDepartamento(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException("The depto with id " + id + " no longer exists.", enfe); } Area areaareidArea = depto.getAreaareidArea(); if (areaareidArea != null) { areaareidArea.getDeptoCollection().remove(depto); areaareidArea = em.merge(areaareidArea); } em.remove(depto); em.getTransaction().commit(); } catch (Exception ex) { try { em.getTransaction().rollback(); } catch (Exception re) { throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re); } throw ex; } finally { if (em != null) { em.close(); } } }
95fa3278-e4f1-4b52-ab3e-90ed4c444ac1
6
private void field_codigoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_field_codigoFocusLost if (field_codigo.isEditable() && (lab_modo.getText().equals("Alta"))){ if ((evt.getOppositeComponent()!=null)&&(!evt.getOppositeComponent().equals(btn_cancelar))){ if (!field_codigo.getText().equals("")){ if (!existe(field_codigo.getText())){ btn_aceptar.setEnabled(true); this.ocultar_Msj(); } else{ field_codigo.requestFocus(); this.mostrar_Msj_Error("El código del Cliente ya se encuentra registrado."); } } else{ field_codigo.requestFocus(); this.mostrar_Msj_Error("Debe ingresar un codigo de Cliente."); } } } }//GEN-LAST:event_field_codigoFocusLost
4bdf8e20-0f71-46e2-a570-63f0e9f72c8f
7
private static boolean isInteger(String s) { if (s == null || s.length() == 0) { return false; } char c = s.charAt(0); if (s.length() == 1) { return c >= '0' && c <= '9'; } return (c == '-' || c >= '0' && c <= '9') && onlyDigits(s.substring(1)); }
980bb9d9-2ffa-4cb2-bb95-71a92e4f7867
0
public String getFechaRecogida() { return fechaRecogida; }
254fb968-15e6-4bc8-86fe-bbca7b0e55c4
6
public void checkForHardLinks() { List<SceneNode> sectors = getAllRegionsAsList(masterSector); int shouldBeSix = Direction.values().length; for (SceneNode s1 : sectors) { if ( !( s1 instanceof Sector ) ) { continue; } for ( int c = 0; c < shouldBeSix; ++c ) { ((Sector)s1).links[ c ] = null; } for (SceneNode s2 : sectors) { if (s2 == s1) continue; if ( !( s2 instanceof Sector )) { continue; } checkLinksForSectors((Sector) s1, (Sector) s2); } } }
ceed46fd-0173-4e58-a8ad-9267be2e74a3
4
public double rawPersonMean(int index){ if(!this.dataPreprocessed)this.preprocessData(); if(index<1 || index>this.nPersons)throw new IllegalArgumentException("The person index, " + index + ", must lie between 1 and the number of persons," + this.nPersons + ", inclusive"); if(!this.variancesCalculated)this.meansAndVariances(); return this.rawPersonMeans[index-1]; }
71648c4e-6dbd-494b-b5b0-c509b066f36b
6
public BagAttribute(URI type, Collection bag) { super(type); if (type == null) throw new IllegalArgumentException("Bags require a non-null " + "type be provided"); // see if the bag is empty/null if ((bag == null) || (bag.size() == 0)) { // empty bag this.bag = new ArrayList(); } else { // go through the collection to make sure it's a valid bag Iterator it = bag.iterator(); while (it.hasNext()) { AttributeValue attr = (AttributeValue)(it.next()); // a bag cannot contain other bags, so make sure that each // value isn't actually another bag if (attr.isBag()) throw new IllegalArgumentException("bags cannot contain " + "other bags"); // make sure that they're all the same type if (! type.equals(attr.getType())) throw new IllegalArgumentException("Bag items must all be of " + "the same type"); } // if we get here, then they're all the same type this.bag = bag; } }
2893acad-d3f5-4d6b-a412-e0dd54f5a239
1
public void addPathFromRoot(List<String> pathFromRoot){ String[] newPathFromRoot = new String[pathFromRoot.size()]; int i=0; for (String idRef: pathFromRoot) { newPathFromRoot[i] = idRef; i++; } pathsFromRoot.add(newPathFromRoot); }
57536b78-6c78-4607-8522-2cf4ef18e9b0
1
public void addItem(final StockItem stockItem) { try { StockItem item = getItemById(stockItem.getId()); item.setQuantity(item.getQuantity() + stockItem.getQuantity()); log.debug("Found existing item " + stockItem.getName() + " increased quantity by " + stockItem.getQuantity()); } catch (NoSuchElementException e) { rows.add(stockItem); log.debug("Added " + stockItem.getName() + " quantity of " + stockItem.getQuantity()); } fireTableDataChanged(); }