method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
e56b1dca-fe14-4701-b2e3-977538848e1d
9
public int getScore(String s, int boardSize) { switch (s.length()) { case 0: case 1: case 2: return 0; case 3: return boardSize <= 4 ? 1 : 0; case 4: return 1; case 5: return 2; case 6: return 3; case 7: return 5; default: return 11; } }
2a87126b-e897-42c6-8659-f09f3ca18a9f
9
@Override protected void Poll() { //if the robot re-oriented itself, cached sine and cosine values need to be re-calculated double rotation = m_robot.GetTransformedData().GetRotation() + m_rotation; if (Math.abs(rotation - m_cacheNetRotation) > PhysicsModel.EPSILON) { m_cacheNetRotation = rotation; m_cacheCos = Math.cos(m_cacheNetRotation); m_cacheSin = Math.sin(m_cacheNetRotation); } //create a ray at the center of the robot PhysicsObject physics = m_robot.GetPhysicsObject(); double x = GetRobot().GetPhysicsObject().GetBounds().GetBoundsType() == BoundsType.Circle ? GetRobot().GetPhysicsObject().GetBounds().GetCollisionCircle().X : GetRobot().GetPhysicsObject().GetBounds().GetCollisionRectangle().GetX() + GetRobot().GetPhysicsObject().GetBounds().GetCollisionRectangle().GetWidth() / 2.0; double y = GetRobot().GetPhysicsObject().GetBounds().GetBoundsType() == BoundsType.Circle ? GetRobot().GetPhysicsObject().GetBounds().GetCollisionCircle().Y : GetRobot().GetPhysicsObject().GetBounds().GetCollisionRectangle().GetY() + GetRobot().GetPhysicsObject().GetBounds().GetCollisionRectangle().GetHeight() / 2.0; Ray ray = new Ray(x, y, m_cacheCos, m_cacheSin); //iterate through all the PhyiscsObjects on the map to find the nearest one double nearestDist = Double.MAX_VALUE, distCache; Iterator<PhysicsObject> objIter = physics.GetPhysicsModel().GetPhysicsObjectIterator(); PhysicsObject current, nearest = null; while (objIter.hasNext()) { current = objIter.next(); if (current == physics || current.GetInteractionType() == InteractionType.Ghost)//the object cannot be the robot, nor can it have InteractionType.Ghost continue; distCache = ray.DistanceTo(current.GetBounds()); if (distCache < nearestDist && distCache >= 0.0) { nearestDist = distCache; nearest = current; } } //if there is something in front of us, store the PhysicsObject's color if (nearest != null) m_data = nearest.GetColor(); else m_data = NO_OBJECT_DETECTED_COLOR;//otherwise store a default error value }
9dfa89d4-9648-40bb-bd3d-0483a4e7485a
4
public static void main(String[] args) { int i; float inputs06[] = { 20, 22, 21, 24, 24, 23, 25, 26, 20, 24, 26, 26, 25, 27, 28, 27, 29, 27, 25, 24 }; float inputs10[] = { 20, 22, 24, 25, 23, 26, 28, 26, 29, 27, 28, 30, 27, 29, 28 }; MovingAverageArray movingAverageArray; MovingAverageQueue movingAverageQueue; System.out.println("Test Moving Average with length 6:"); movingAverageArray = new MovingAverageArray(6); movingAverageQueue = new MovingAverageQueue(6); for (i = 0; i < inputs06.length; ++i) { if (movingAverageArray.movingAverage(inputs06[i]) != movingAverageQueue.movingAverage(inputs06[i])) { System.out.println("Different results at: " + i); } } System.out.println("TestMoving Average length 10:"); movingAverageArray = new MovingAverageArray(10); movingAverageQueue = new MovingAverageQueue(10); for (i = 0; i < inputs10.length; ++i) { if (movingAverageArray.movingAverage(inputs10[i]) != movingAverageQueue.movingAverage(inputs10[i])) { System.out.println("Different results at: " + i); } } }
4b99705e-376a-4cc4-8c3c-c1fdac79019e
1
@Override public void actionPerformed(ActionEvent arg0) { switch(arg0.getActionCommand()) { case ButtonNames.NEWOBJBUTTON: { new ObjCreateDialog(this).setVisible(true); } } }
bfc329ec-1e8e-46a0-8d3e-dfd69db2fcd7
2
private void exitOnGLError(String errorMessage) { int errorValue = GL11.glGetError(); if (errorValue != GL11.GL_NO_ERROR) { String errorString = GLU.gluErrorString(errorValue); System.err.println("ERROR - " + errorMessage + ": " + errorString); if (Display.isCreated()) Display.destroy(); System.exit(-1); } }
264b6728-f35f-4d06-a8d4-5e7fca7aae57
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(JFontSelector.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(JFontSelector.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(JFontSelector.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(JFontSelector.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 JFontSelector().setVisible(true); } }); }
39083967-80d8-4dc6-afcb-969402faecb1
5
private void setToBlack(byte[] buffer, int lineOffset, int bitOffset, int numBits) { int bitNum = (8 * lineOffset) + bitOffset; int lastBit = bitNum + numBits; int byteNum = bitNum >> 3; // Handle bits in first byte int shift = bitNum & 0x7; if (shift > 0) { int maskVal = 1 << (7 - shift); byte val = buffer[byteNum]; while ((maskVal > 0) && (bitNum < lastBit)) { val |= maskVal; maskVal >>= 1; ++bitNum; } buffer[byteNum] = val; } // Fill in 8 bits at a time byteNum = bitNum >> 3; while (bitNum < (lastBit - 7)) { buffer[byteNum++] = (byte) 255; bitNum += 8; } // Fill in remaining bits while (bitNum < lastBit) { byteNum = bitNum >> 3; buffer[byteNum] |= (1 << (7 - (bitNum & 0x7))); ++bitNum; } }
2d1f583b-f18b-4025-a506-c0f676b215b8
0
public void testBlackCount() { List<AnswerCombination> combinations = generateAnswerCombinationList(); assertEquals(0, combinations.get(0).getBlackCount()); assertEquals(1, combinations.get(1).getBlackCount()); assertEquals(2, combinations.get(2).getBlackCount()); assertEquals(3, combinations.get(3).getBlackCount()); assertEquals(4, combinations.get(4).getBlackCount()); assertEquals(2, combinations.get(5).getBlackCount()); assertEquals(2, combinations.get(6).getBlackCount()); assertEquals(2, combinations.get(7).getBlackCount()); assertEquals(3, combinations.get(8).getBlackCount()); assertEquals(4, combinations.get(9).getBlackCount()); assertEquals(5, combinations.get(10).getBlackCount()); assertEquals(0, combinations.get(11).getBlackCount()); }
35a112bb-1d7f-4119-9477-c5f9e91381ed
3
public void setTipo(PTipo node) { if(this._tipo_ != null) { this._tipo_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._tipo_ = node; }
9d50c33b-ee00-4bf2-9ca7-e97daded83e1
3
private void addValueElement( final String element, final String name, final String desc, final String value) { AttributesImpl att = new AttributesImpl(); if (name != null) { att.addAttribute("", "name", "name", "", name); } if (desc != null) { att.addAttribute("", "desc", "desc", "", desc); } if (value != null) { att.addAttribute("", "value", "value", "", SAXClassAdapter.encode(value)); } addElement(element, att); }
1b526962-1fed-4d7c-be85-856683658665
7
public static void rezeptAuswahlKommentar(List<Rezept> rezeptList, Marshaller marshaller , Rezepteseite rezepteseite) throws JAXBException, FileNotFoundException{ int rnr, rnr2; // Rezeptauswahl, anschliessend kommentieren starten // Menüaufbau System.out.println(); System.out.println("Geben sie die Rezeptnummer an"); System.out.println("------------------------------"); System.out.println("Rezeptnummer: "); System.out.println("0 - Übersicht der Rezepte anzeigen"); rnr = in.nextInt(); // Check ob ungültige Eingabe, wenn ja aufforderung zur Wiederholung while( (rnr < 0) || (rnr > rezeptList.size() ) ){ System.out.println(); System.out.printf("Bitte geben sie eine gültige Rezeptnummer an: "); rnr = in.nextInt(); } switch(rnr){ case 0: // Möglichkeit Liste anzuzeigen, anschließende Auswahl rezepteAusgeben(rezeptList); System.out.println(); System.out.printf("Rezeptnummer: "); rnr2 = in.nextInt(); while((rnr2<1) || (rnr2 > rezeptList.size())){ System.out.printf("Bitte gültige Rezeptnummer eingeben: "); rnr2 = in.nextInt(); } // Bei gültiger Nummer kommentieren starten und Marshaller starten List<Kommentar> komment1 = (List<Kommentar>) rezeptList.get(rnr2-1).getKommentare().getKommentar(); kommentieren(komment1, rezeptList, marshaller, rezepteseite); schreiben(marshaller, rezepteseite); break; default: if((rnr-1> rezeptList.size()) || (rnr < 1)){ System.out.printf("Keine gültige Angabe. Das Programm wird beendet."); } // Kommentieren List<Kommentar> komment = (List<Kommentar>) rezeptList.get(rnr-1).getKommentare().getKommentar(); kommentieren(komment, rezeptList, marshaller, rezepteseite); schreiben(marshaller, rezepteseite); break; } }
66dfc57e-9967-45f7-be87-8ed7a55a80f1
3
@BeforeClass public static void setUpBeforeClass() { try { String localTestProperty = System .getProperty(BookStoreConstants.PROPERTY_KEY_LOCAL_TEST); localTest = (localTestProperty != null) ? Boolean .parseBoolean(localTestProperty) : localTest; if (localTest) { CertainBookStore store = new CertainBookStore(); storeManager = store; client = store; } else { storeManager = new ReplicationAwareStockManagerHTTPProxy(); client = new ReplicationAwareBookStoreHTTPProxy(); } storeManager.removeAllBooks(); } catch (Exception e) { e.printStackTrace(); } }
debc5eea-6c95-44e7-a24e-4d910feef4e8
8
public void paint(Graphics g) { // draw main backgdound g.drawImage( Asset.boardlg.getImage() , Asset.boardlg.getPosition().getX(), Asset.boardlg.getPosition().getY(), this); // draw bet backgroud if ( game.getSetting().getGameState() == Setting.GAME_STATE.BET ) drawBet(g); else { // draw action background g.setColor(Color.blue);g.setFont(new Font(Font.MONOSPACED, Font.BOLD, 15)); try{ // read teams's decision place for (int i =0; i < game.getTeamA().getNumOfTank(); i ++){ if (game.getTeamA().getTanks()[i].isAlive()){ int baseX=(game.getTeamA().getTanks()[i].getPosition().getX()-1) *CELL_UNIT; int baseY = (game.getTeamA().getTanks()[i].getPosition().getY()-1) *CELL_UNIT; g.drawImage( Asset.tankA.getImage() ,baseX ,baseY, this); if (game.getTeamA().getTanks()[i].wasAttacked) g.drawImage( Asset.fire.getImage() , baseX,baseY, this); g.drawImage(Asset.statistic.getImage(),baseX+CELL_UNIT*2/3, baseY , this); // draw Statistic g.drawString(game.getTeamA().getTanks()[i].getAmor()+"", baseX+CELL_UNIT*2/3+15, baseY+18 ); g.drawString(game.getTeamA().getTanks()[i].getDamange()+"", baseX+CELL_UNIT*2/3+43, baseY+18 ); g.drawString(game.getTeamA().getTanks()[i].getAttackRange()+"", baseX+CELL_UNIT*2/3+65, baseY+18 ); } else // dead g.drawImage( Asset.dead.getImage() , (game.getTeamA().getTanks()[i].getPosition().getX()-1) *CELL_UNIT, (game.getTeamA().getTanks()[i].getPosition().getY()-1) *CELL_UNIT , this); } // team B for (int i =0; i < game.getTeamB().getNumOfTank(); i ++){ if(game.getTeamB().getTanks()[i].isAlive() ){ int baseX=(game.getTeamB().getTanks()[i].getPosition().getX()-1) *CELL_UNIT; int baseY = (game.getTeamB().getTanks()[i].getPosition().getY()-1) *CELL_UNIT; g.drawImage( Asset.tankB.getImage() ,baseX ,baseY, this); if (game.getTeamB().getTanks()[i].wasAttacked) // draw Statcked g.drawImage( Asset.fire.getImage() ,baseX ,baseY, this); // draw Statistic g.drawImage(Asset.statistic.getImage() ,baseX+CELL_UNIT*2/3 ,baseY, this); g.drawString(game.getTeamB().getTanks()[i].getAmor()+"", baseX+CELL_UNIT*2/3+15, baseY+18 ); g.drawString(game.getTeamB().getTanks()[i].getDamange()+"", baseX+CELL_UNIT*2/3+43, baseY+18 ); g.drawString(game.getTeamB().getTanks()[i].getAttackRange()+"", baseX+CELL_UNIT*2/3+65, baseY+18 ); } else //dead g.drawImage( Asset.dead.getImage() , (game.getTeamB().getTanks()[i].getPosition().getX()-1) *CELL_UNIT, (game.getTeamB().getTanks()[i].getPosition().getY()-1) *CELL_UNIT, this); } } catch(Exception ex) {} } g.finalize(); repaint(); }
e0575b8c-a91b-42d3-a41a-e82d55a44800
3
public void step() { for(int x = 0; x < xSize; x++) { for(int y = 0; y < ySize; y++) { grid[x][y].grow(); // YOU WILL NEED TO IMPLEMENT GROW() YOURSELF. } } Collections.shuffle(agents); for(int a = agents.size()-1; a >= 0; a--) { Agent agent = agents.elementAt(a); agent.act(); // YOU WILL NEED TO COMPLETE ACT() YOURSELF. } }
54d42054-7a71-4ffc-bee7-f25a1ae02102
1
public boolean setUserlistImageFrameWidth(int width) { boolean ret = true; if (width <= 0) { this.userlistImgFrame_Width = UISizeInits.USERLIST_IMAGEFRAME.getWidth(); ret = false; } else { this.userlistImgFrame_Width = width; } setUserlistImageOverlay_Width(this.userlistImgFrame_Width); somethingChanged(); return ret; }
459351b8-b9cd-4f35-8d0d-f88074381f54
3
boolean contains(int x, int y) { return y > y0 && y < (y0 + height) && x > x0 && x < (x0 + width); }
a0c03703-1405-4f76-9ac3-4501772753d2
7
public void sendMessage(ChatMessage msg) { //permet de mettre en forme les messages et de les envoyer try { msg.setSender(username); msg.setPassword(serverKeys.encrypt(clientUI.getPassword()).toString()); msg.setTimeStamp(simpleDate.format(new Date()).toString()); if (msg.getMessage().length() > 1 && msg.getMessage().charAt(0) == '/'){ //module d'évaluation des commandes if (msg.getMessage().length() > 3 && msg.getMessage().substring(0, 3).equals("/to")){ //module d'évalutation pour les MP StringBuilder transform = new StringBuilder(msg.getMessage()); transform = transform.delete(0, 4); //on supprime le mot clé "/to " String name = ""; for (int i = 0; i < transform.length();){ //on extrait le nom d'utilisateur du destinataire du message if(transform.charAt(i) == ' '){ transform = transform.deleteCharAt(i); break; } name += transform.charAt(i); //on le stocke transform = transform.deleteCharAt(i); } msg.setDest(name); //on régle le destinataire dans les paramétres du message msg.setMessage(transform.toString()); msg.setType(ChatMessage.MP); display(msg.getTimeStamp() + " " + msg.getSender() + " : " + msg.getMessage()); } else { display("Cette commande n'est pas reconnue. Commandes existantes : " + comms); return; } } msg.setMessage(serverKeys.encrypt(msg.getMessage()).toString()); sOutput.writeObject(msg); } catch(IOException e) { display("Exception writing to server: " + e); } }//sendMEssage
27f6bf56-c712-4fcb-b078-b2d2e8681143
4
public static void fizzbuzz(Integer n) { for (int i = 1; i <= n; i++) { if (i % 3 == 0) { if (i % 5 == 0) System.out.println("FizzBuzz"); else System.out.println("Fizz"); } else if (i % 5 == 0) System.out.println("Buzz"); else System.out.println(i); } }
497a1945-6aed-4a5f-ae7b-f88b471c3417
3
public String convertFromCell(HSSFCell cell){ Object data = null; int dataType = cell.getCellType(); switch(dataType){ case HSSFCell.CELL_TYPE_NUMERIC: data = cell.getNumericCellValue(); break; case HSSFCell.CELL_TYPE_STRING: data = cell.getStringCellValue(); break; case HSSFCell.CELL_TYPE_BOOLEAN: data = cell.getBooleanCellValue(); break; } return data.toString(); }
93efaa22-826e-4d42-b028-c9f5098ecec4
5
@Override public void mouseReleased(MouseEvent arg0) { if (StorageUnitDisplayPanel.this.displayMode != DisplayMode.FULL) { StorageUnitDisplayPanel.this.fireClick(); return; } int y = arg0.getY(); if (StorageUnitDisplayPanel.this.storageUnit != null) { int height = StorageUnitDisplayPanel.this.getHeight(), max = storageUnit .getStock().getMaxTraysPerStorageUnit(); List<Tray> trays = storageUnit.getTrays(); HashMap<Integer, Tray> traysMap = new HashMap<Integer, Tray>(); for (Tray tray : trays) { traysMap.put(tray.getSlotNumber(), tray); } int j = (int) ((double) y / (height / max)); int i = max - 1 - j; if (traysMap.containsKey(i)) { Tray tray = traysMap.get(i); if (StorageUnitDisplayPanel.hasSelectedTray(tray)) StorageUnitDisplayPanel .removeSelectedTray(tray); else StorageUnitDisplayPanel.addSelectedTray(tray); } } }
87f6c4b7-c847-4f55-961a-7971a4bf7523
8
public void putAll( Map<? extends Double, ? extends V> map ) { Iterator<? extends Entry<? extends Double,? extends V>> it = map.entrySet().iterator(); for ( int i = map.size(); i-- > 0; ) { Entry<? extends Double,? extends V> e = it.next(); this.put( e.getKey(), e.getValue() ); } }
05f842d4-7ac7-4521-b9ab-7e56a6e67084
4
public static void removeCopy(int copyId){ try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try{ conn.setAutoCommit(false); PreparedStatement stmnt = conn.prepareStatement("UPDATE MediaCopies SET lendable = ? " + ", exist = ? " + "WHERE copy_id = ?"); stmnt.setBoolean(1, false); stmnt.setBoolean(2, false); stmnt.setInt(3, copyId); System.out.println(stmnt.toString()); stmnt.execute(); conn.commit(); conn.setAutoCommit(true); }catch(SQLException e){ System.out.println("Remove fail: " + e); } }
bcd22e52-ae80-4c20-990c-24f8c0dffaea
7
private void execSQLWrapper(String query) throws SPARULException { try { execSQL(query); } catch (Exception e) { String expMessage = e.toString(); // This means that VOS is probably down if (expMessage.contains("Broken pipe") || expMessage.contains("Virtuoso Communications Link Failure")) { logger.error("Virtuoso is probably down, exiting...", e); System.exit(1); } //When Virtuoso commits a CHECKPOINT we fail to insert anything //and get a Transaction deadlock exception //here we lock everything and try X attempts every Y seconds if (expMessage.contains("Transaction deadlock")) { synchronized (SPARULVosExecutor.class) { //The checkpoint lasts around 2-3 minutes int attempts = 10; int sleep = 30000; for (int i = 1; i < attempts; i++) { try { logger.warn("Transaction Deadlock, retrying query: " + i + "/" + attempts); execSQL(query); //When no exception return return; } catch (Exception e1) { logger.warn("Transaction Deadlock, retrying query: " + i + "/" + attempts + "(FAILED)"); try { Thread.sleep(sleep); } catch (InterruptedException e2) { //do nothing } } } } } throw new SPARULException(e); } }
bfcac2f9-4bd5-4056-90c4-c1db248ba7c0
2
public void passKeyReleasedInpute(ArrayList<KeyButtons> keyPressed) { switch (whatcha) { case PLAYING: stage.handleReleasedKeys(keyPressed); break; case SELECTSTAGE: stageSelector.handleReleasedKeys(keyPressed); break; } }
7c55f8fc-c0f1-4110-9d9a-66865a999664
1
public static void main(String[] args) { FoneApiClient client = new FoneApiClient( "http://foneapi_server/api/1.0/switch", "****************************", "****************************"); CommandResponse response = client.dial(eDialDestinationType.number, "5551234567", "htt://your_server/location_of_call_answered_event_handler", 0, "htt://your_server/location_of_error_event_handler", 30, "5557654321", "Lester Tester", 0, "verizon", null); if (response.getStatus() != 0) { System.out.println("Call failed with error: " + response.getErrorMsg()); } else { System.out.println("Call id: " + response.getCallId()); } }
ccb3885a-f17e-410a-814f-adf9d4f483ee
4
private void saveSong() { try { FileChooser f = new FileChooser(); f.setInitialDirectory(new File(System.getProperty("user.dir"))); f.setInitialFileName(controller.getNameTextField().getText() + ".txt"); f.getExtensionFilters().addAll( new ExtensionFilter("Text file", "*.txt"), new ExtensionFilter("All files", "*")); File outputFile = f.showSaveDialog(null); if (outputFile == null) return; FileOutputStream f_out = new FileOutputStream(outputFile); StaffSequence out = theStaff.getSequence(); out.setTempo(StateMachine.getTempo()); if (Settings.SAVE_OBJECTS) { saveSongObject(f_out, out); } else { saveSongTxt(f_out, out); } f_out.close(); theStaff.setSequenceFile(outputFile); StateMachine.setSongModified(false); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
acb0c3ed-2409-4e8a-93e6-3806eb19066b
5
public void saveToFile() { File f = location; File dir = f.getParentFile(); if (!dir.isDirectory()) { dir.mkdirs(); } if (f.isFile()) { f.delete(); } try { BufferedWriter output = new BufferedWriter(new FileWriter(f)); output.write("### Savefile used for the application. Version: 2\n"); for (Enum s : curSettings.keySet()) { if (!curSettings.get(s).get().equals("")) { curSettings.get(s).write(output); } else { defaultSettings.get(s).write(output); } } output.close(); } catch (java.io.IOException e) { JOptionPane.showMessageDialog(null, "The application couldn't open the save file output stream. Your settings were not saved."); } }
b8cc806c-ca48-4de2-8bed-2b6574bada13
5
public V get(K key) { int internalKey = generateKey(key); int count = 0; while (array[internalKey] != null && count < size) { if (array[internalKey].getKey().equals(key) && array[internalKey].hashCode() == internalKey) return array[internalKey].getValue(); internalKey++; count++; if (internalKey == size) { internalKey = 0; } } return null; }
57cdda2e-1c1e-431c-826e-36244b3f4afc
0
public boolean contains(String key) { return get(key) != null; }
cd83a802-32a9-4957-9ae8-4bc67b5793e8
4
public boolean isOutOfBounds(int x, int y, int xMin, int yMin, int xMax, int yMax) { if(x <= xMin || x >= xMax+xMin) return true; if(y <= yMin || y >= yMax+yMin) return true; return false; }
376238ee-ae0a-48b7-ae96-c6274f8ce322
7
private JSONWriter append(String string) throws JSONException { if (string == null) { throw new JSONException("Null pointer"); } if (this.mode == 'o' || this.mode == 'a') { try { if (this.comma && this.mode == 'a') { this.writer.write(','); } this.writer.write(string); } catch (IOException e) { throw new JSONException(e); } if (this.mode == 'o') { this.mode = 'k'; } this.comma = true; return this; } throw new JSONException("Value out of sequence."); }
f0b27157-ab60-49a7-b897-9780e219bbdd
6
private static void findPairIntersections() { for (Pair p1 : values) { Card[] c1 = p1.cards; int i1 = p1.ordinal; for (Pair p2 : values) { int i2 = p1.ordinal; Card[] c2 = p2.cards; intersectsPair[i1][i2] = false; if(c1[0] == c2[0]) intersectsPair[i1][i2] = true; if(c1[0] == c2[1]) intersectsPair[i1][i2] = true; if(c1[1] == c2[0]) intersectsPair[i1][i2] = true; if(c1[1] == c2[1]) intersectsPair[i1][i2] = true; } } }
29396d54-69ee-47df-9e4b-f20eda7acde0
7
@Override public int getValues(Component target, int tweenType, float[] returnValues) { switch (tweenType) { case X: returnValues[0] = target.getX(); return 1; case Y: returnValues[0] = target.getY(); return 1; case XY: returnValues[0] = target.getX(); returnValues[1] = target.getY(); return 2; case W: returnValues[0] = target.getWidth(); return 1; case H: returnValues[0] = target.getHeight(); return 1; case WH: returnValues[0] = target.getWidth(); returnValues[1] = target.getHeight(); return 2; case XYWH: returnValues[0] = target.getX(); returnValues[1] = target.getY(); returnValues[2] = target.getWidth(); returnValues[3] = target.getHeight(); return 4; default: return -1; } }
3870a2d2-4751-466f-b4b6-58df7f166f20
7
public void renderMeanForce(Graphics2D g) { if (!showFMean) return; if (aQ == null || aQ.isEmpty()) return; if (outOfView()) return; float x = aQ.getQueue1().getAverage(); float y = aQ.getQueue2().getAverage(); if (Math.abs(x) <= ZERO && Math.abs(y) <= ZERO) return; g.setColor(getView().getBackground()); g.fillOval((int) (rx - 2), (int) (ry - 2), 4, 4); g.setColor(marked ? getView().getMarkColor() : getView().contrastBackground()); g.setStroke(ViewAttribute.THIN); g.drawOval((int) (rx - 3), (int) (ry - 3), 6, 6); drawVector(g, x * getMass() * 120, y * getMass() * 120, getView().getForceFlavor()); }
464887e4-f2ca-4a87-9a0d-2941d3628385
4
public Map<String, String> getDirectoriesAndDestinations() { final File sourceDirectory = new File(source.getDirectory()); // Scan for directories final DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(sourceDirectory); scanner.setIncludes(source.getIncludes().toArray(new String[source.getIncludes().size()])); scanner.setExcludes(source.getExcludes().toArray(new String[source.getExcludes().size()])); // Add default excludes to the list of excludes (see http://plexus.codehaus.org/plexus-utils/apidocs/org/codehaus/plexus/util/AbstractScanner.html#DEFAULTEXCLUDES // or http://plexus.codehaus.org/plexus-utils/apidocs/org/codehaus/plexus/util/AbstractScanner.html#addDefaultExcludes() ) scanner.addDefaultExcludes(); scanner.scan(); final Map<String, String> result = new LinkedHashMap<String, String>(); result.put(FilenameUtils.separatorsToUnix(sourceDirectory.toString()), FilenameUtils.separatorsToUnix(destination.toString())); for (String included : scanner.getIncludedDirectories()) { if (!included.isEmpty()) { final String subdir = StringUtils.difference(sourceDirectory.toString(), included); final File sourceDir = new File(sourceDirectory, included); File destDir = new File(this.destination, subdir); if (this.relativeOutputDirectory != null && !this.relativeOutputDirectory.isEmpty()) { destDir = new File(destDir, this.relativeOutputDirectory); } result.put(FilenameUtils.separatorsToUnix(sourceDir.toString()), FilenameUtils.separatorsToUnix(destDir.toString())); } } return result; }
0a831a63-aeac-48aa-b532-ba5d83b8e96f
2
public void encryptOrDecrypt(String key, int mode, InputStream is,OutputStream os) throws Throwable { DESKeySpec dks = new DESKeySpec(key.getBytes()); SecretKeyFactory skf = SecretKeyFactory.getInstance("DES"); SecretKey desKey = skf.generateSecret(dks); Cipher cipher = Cipher.getInstance("DES"); // DES/ECB/PKCS5Padding for // SunJCE if (mode == Cipher.ENCRYPT_MODE) { cipher.init(Cipher.ENCRYPT_MODE, desKey); CipherInputStream cis = new CipherInputStream(is, cipher); doCopy(cis, os); } else if (mode == Cipher.DECRYPT_MODE) { cipher.init(Cipher.DECRYPT_MODE, desKey); CipherOutputStream cos = new CipherOutputStream(os, cipher); doCopy(is, cos); } }
21b610e0-af33-47de-856a-a62fb98cb11a
8
private void ExecuteInternal() { try { Reset(); if(m_CurrentLM == null) return; long botY = PopScanbeam(); do { InsertLocalMinimaIntoAEL(botY); m_HorizJoins.clear(); ProcessHorizontals(); long topY = PopScanbeam(); ProcessIntersections(botY, topY); ProcessEdgesAtTopOfScanbeam(topY); botY = topY; } while(m_Scanbeam != null || m_CurrentLM != null); // tidy up output polygons and fix orientations where necessary ... for(int i = 0; i < m_PolyOuts.size(); i++) { OutRec outRec = m_PolyOuts.get(i); if(outRec.pts == null) continue; FixupOutPolygon(outRec); if(outRec.pts == null) continue; if((outRec.isHole ^ m_ReverseOutput) == (Area(outRec, m_UseFullRange) > 0)) ReversePolyPtLinks(outRec.pts); } JoinCommonEdges(); if(m_ForceSimple) DoSimplePolygons(); } finally { m_Joins.clear(); m_HorizJoins.clear(); } }
4ea0f391-9039-420b-81dd-b770e903b17c
1
@Override public boolean init(List<String> argumentList, DebuggerVirtualMachine dvm) { if (argumentList.size() > 0) { UserInterface.println("This command takes no arguments."); HelpCommand.displayHelp(this); return false; } return true; }
f94a22f8-dfba-4842-890e-947188d7b34c
1
public static ActionsFunction getActionsFunction() { if (null == _actionsFunction) { _actionsFunction = new SudokuActionsFunction(); } return _actionsFunction; }
ccdf914e-8713-454a-ac35-606755f1fc80
8
protected GameState findSetToTrue(GameState state, Card card) { //Check the hand for(Card c : state.getPlayer(card.getFaction()).getHand()) { if(c.equals(card)) { state.getPlayer(card.getFaction()).removeFromHand(c); c.setTrue(state.getTime()); state.getPlayer(card.getFaction()).addToHand(c); } } //Check the discard for(Card c : state.getPlayer(card.getFaction()).getDiscard()) { if(c.equals(card)) { state.getPlayer(card.getFaction()).removeFromDiscard(c); c.setTrue(state.getTime()); state.getPlayer(card.getFaction()).addToDiscard(c); } } //Check the den for(Card c : state.getPlayer(card.getFaction()).getDen()) { if(c.equals(card)) { state.getPlayer(card.getFaction()).removeFromDen(c); c.setTrue(state.getTime()); state.getPlayer(card.getFaction()).addToDen(c); } } //Check the board for(Card c : state.getBoard().getDeck()) { if(c.equals(card)) { state.getBoard().removeCard(c); c.setTrue(state.getTime()); state.getBoard().addCard(c); } } return state; }
21dec899-1c68-4266-bce8-a328b4b544cd
0
public static Main getInstance() { return instance; }
ff6bfaf0-1d27-4acc-b0d9-b7e15e20f603
8
private void promoteUser(ChangeRolePacket r) { OperationStatusPacket opStat; int flag = OperationStatusPacket.SUCCESS; User sender = null; User affected = null; for (User u : users.keySet()) { if(u.getID() == r.getSenderID()) { sender = u; } else if(u.getID() == r.getUserID()) { affected = u; } if(sender != null && affected != null) break; } // This should *never* happen if(sender == null) return; if(affected != null) { try { // Update the user's role. ChatRoleDAOMySQLImpl.getInstance().updateRole(chatID, r.getUserID(), r.getRole()); affected.setRole(r.getRole()); // If the SQL statement fails, this will never run, so it's safe to do here Packet p = PacketCreator.createUserNotify(affected.getName(), r.getUserID(), r.getChatID(), r.getRole(), UserNotifyPacket.PROMOTED); broadcast(r.getUserID(), p, false, true); } catch (SQLException e) { System.err.println("Chat.promoteUser: SQL exception thrown: " + e.getMessage()); flag = OperationStatusPacket.FAIL; } } else flag = OperationStatusPacket.FAIL; // Send them an OperationStatusPacket no matter what opStat = PacketCreator.createOperationStatus(r.getSenderID(), chatID, flag, OperationStatusPacket.OP_CRUD); ((ServerUser)sender).notifyClient(opStat); }
bfeeaeef-ef69-4d87-9d8d-a932392865c6
9
private void handleKeyboardInput() { final boolean leftPressed = Keyboard.isKeyDown(Keyboard.KEY_LEFT); final boolean rightPressed = Keyboard.isKeyDown(Keyboard.KEY_RIGHT); final boolean returnPressed = Keyboard.isKeyDown(Keyboard.KEY_RETURN); if (!Commons.get().isKeyPressed()) { if (leftPressed || rightPressed) { for (final SELECTION s : SELECTION.values()) { if (!s.equals(currentSelection)) { currentSelection = s; break; } } Commons.get().setKeyPressed(true); Sounds.get().playCursor(); } } else if (!leftPressed && !rightPressed && !returnPressed && !Mouse.isButtonDown(0)) { Commons.get().setKeyPressed(false); } }
82d55083-c531-4e4f-8a34-e03b90eff52d
3
public Inventory solveFractional() { int availableCapacity = capacity; ArrayList<Double> amounts = new ArrayList<Double>(); if (availableCapacity <= 0) { return new Inventory(this, amounts); } for (Item i : items) { if (availableCapacity < i.getWeight()) { amounts.add(((double) availableCapacity) / i.getWeight()); return new Inventory(this, amounts); } availableCapacity -= i.getWeight(); amounts.add(1.0); } return new Inventory(this, amounts); }
691b6168-c2ef-484a-8cc5-e10b9a85bbd8
3
public synchronized void addListener(final CycLeaseManagerListener cycLeaseManagerListener) { //// Preconditions if (cycLeaseManagerListener == null) { throw new InvalidParameterException("cycLeaseManagerListener must not be null"); } if (listeners.contains(cycLeaseManagerListener)) { throw new InvalidParameterException("listener must not be currently registered"); } assert listeners != null : "listeners must not be null"; if (cycAccess.getCycConnection() instanceof CycConnection) { assert cycAccess.getCycLeaseManager().isAlive() : "the CycLeaseManager thread has died because a lease timed-out, errored or was denied"; } // otherwise, this is a SOAP client connection and leasing is never started listeners.add(cycLeaseManagerListener); }
94e81cb8-e9d5-4a92-b2f3-4c7ea6ee1a23
2
public void destroy () { assert (!plugged); if (handle != null) { try { handle.close(); } catch (IOException e) { } handle = null; } }
f5d5dc06-ccdf-4c52-9eb1-ddac7adada60
1
public void render() { gc.art.fill(width, height, 0, 0, 0xFF000000); if (level != null) level.render(gc.art); }
3f654a0d-46a2-473c-9c5e-a37088514e87
9
private void update() { for (turn = 1; turn <= MAXTURNS; turn++) { while(isPaused) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } for (Ant ant : ants) { if (ant.isAlive()) { if (ant.getResting() > 0) { ant.setResting(ant.getResting() - 1); } else { Position p = findAnt(ant.getId()); Cell cell = cells[p.x][p.y]; ant.getStateMachine().step(ant, cell); } } } calcScores(); //update GUI in EDT Runnable updateDisplay = new Runnable() { public void run() { screen.update(); } }; SwingUtilities.invokeLater(updateDisplay); //screen.update(); // dump turn info if (logger != null) { // Choose which turns to log here if (turn < 10000) logger.logTurn(); } // Variable speed try { Thread.sleep(sleepAmount); } catch (InterruptedException e) { // Surely not a problem... e.printStackTrace(); } } }
72d9cfde-aeda-4f48-a835-510e1f9648bf
4
public static void main(String[] args) { String line = ""; String message = ""; int c; try { while ((c = System.in.read()) >= 0) { switch (c) { case '\n': if (line.equals("go")) { PlanetWars pw = new PlanetWars(message); DoTurn(pw); pw.FinishTurn(); message = ""; } else { message += line + "\n"; } line = ""; break; default: line += (char) c; break; } } } catch (Exception e) { } }
064d5914-61e5-4329-b6e6-f5d646035fdb
2
public static byte[] toByteArray(Object o){ try{ ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = null; out = new ObjectOutputStream(bos); out.writeObject(o); byte[] yourBytes = bos.toByteArray(); try{ bos.close(); out.close(); }catch(Exception e){System.out.println("A Memory Leak Has Happened!");e.printStackTrace();} return yourBytes; }catch(Exception e){ return null; } }
43b23311-ae1a-435d-908d-4e3e5886b166
9
public Set<TrapezoidLine> naiveMap(int height, int width) { Set<TrapezoidLine> trapezoidMap = new HashSet<TrapezoidLine>(); // Add the borders of the window as temporary shapes Shape border = new Shape(); Shape border2 = new Shape(); border.getPoints().add(new Point(0, 0)); border.getPoints().add(new Point(width, 0)); border2.getPoints().add(new Point(0, height)); border2.getPoints().add(new Point(width, height)); shapes.add(border); shapes.add(border2); // Step through each shape Iterator<Shape> s = shapes.iterator(); while (s.hasNext()) { Shape sh = s.next(); // Ignore the border shapes so their points do not appear as part of // the trapezoidal map if (sh.equals(border) || sh.equals(border2)) continue; // Step through the points in the current shape Iterator<Point> p = sh.getPoints().iterator(); while (p.hasNext()) { Point pt = p.next(); // Generate two trapezoidal lines for each point (up and down) TrapezoidLine t = new TrapezoidLine(pt, height + 1, true); TrapezoidLine t2 = new TrapezoidLine(pt, height + 1, false); // Debug // System.out.println("Point: ("+pt.x+","+pt.y+")"); // Iterate over all shapes, intersecting the trapezoidal lines // with each of the shapes Iterator<Shape> s2 = shapes.iterator(); while (s2.hasNext()) { Shape sh2 = s2.next(); // if(!sh.equals(sh2)) { // If the intersection yields a positive difference that is // smaller than the previous length, update t if (t.getStart().y - sh2.intersect(t, height + 1) > 0) { t.setLength(Math.min((int) (t.getStart().y - sh2 .intersect(t, height + 1)), t.getLength())); } // if the intersection yields a negative difference that is // absolutely smaller than the previous length, update t2 else if (t2.getStart().y - sh2.intersect(t2, height + 1) < 0) { t2.setLength(Math.min((int) Math.abs(t2.getStart().y - sh2.intersect(t2, height + 1)), t2 .getLength())); } // } } // If the lengths have been updated to a reasonable value, add // them if (t.getLength() < height) { trapezoidMap.add(t); } if (t2.getLength() < height) { trapezoidMap.add(t2); } } } // Remove the borders so they are not displayed shapes.remove(border); shapes.remove(border2); return trapezoidMap; }
dab94ff9-0493-4310-80f3-013f83c4f3f9
9
public void execute(String[] args) throws Exception { processArguments(args); if (objectName == null) throw new CommandException("Missing object name"); MBeanServerConnection server = getMBeanServer(); MBeanInfo mbeanInfo = server.getMBeanInfo(objectName); MBeanAttributeInfo[] attrInfo = mbeanInfo.getAttributes(); MBeanOperationInfo[] opInfo = mbeanInfo.getOperations(); PrintWriter out = context.getWriter(); out.println("Description: "+mbeanInfo.getDescription()); out.println("+++ Attributes:"); int length = attrInfo != null ? attrInfo.length : 0; for(int n = 0; n < length; n ++) { MBeanAttributeInfo info = attrInfo[n]; out.print(" Name: "); out.println(info.getName()); out.print(" Type: "); out.println(info.getType()); String rw = ""; if( info.isReadable() ) rw = "r"; else rw = "-"; if( info.isWritable() ) rw += "w"; else rw += "-"; out.print(" Access: "); out.println(rw); } out.println("+++ Operations:"); length = opInfo != null ? opInfo.length : 0; for(int n = 0; n < length; n ++) { MBeanOperationInfo info = opInfo[n]; out.print(' '); out.print(info.getReturnType()); out.print(' '); out.print(info.getName()); out.print('('); MBeanParameterInfo[] sig = info.getSignature(); for(int s = 0; s < sig.length; s ++) { out.print(sig[s].getType()); out.print(' '); out.print(sig[s].getName()); if( s < sig.length-1 ) out.print(','); } out.println(')'); } closeServer(); }
951bf507-01c7-444a-9251-2ce117506bae
8
public Capabilities getCapabilities() { Capabilities result; Capabilities classes; Iterator iter; Capability capab; if (getFilter() == null) result = super.getCapabilities(); else result = getFilter().getCapabilities(); // only nominal and numeric classes allowed classes = result.getClassCapabilities(); iter = classes.capabilities(); while (iter.hasNext()) { capab = (Capability) iter.next(); if ( (capab != Capability.BINARY_CLASS) && (capab != Capability.NOMINAL_CLASS) && (capab != Capability.NUMERIC_CLASS) && (capab != Capability.DATE_CLASS) ) result.disable(capab); } result.enable(Capability.MISSING_CLASS_VALUES); // set dependencies for (Capability cap: Capability.values()) result.enableDependency(cap); if (result.getMinimumNumberInstances() < 1) result.setMinimumNumberInstances(1); result.setOwner(this); return result; }
b8e4444c-9826-4697-93a9-4e974fdd441f
1
public static CustomButton doPathBrowseButton(final JTextArea textToUpdate) { final JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); final CustomButton a = new CustomButton("browse"); a.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // In response to a button click: int returnVal = fc.showOpenDialog(a); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String path = file.getAbsolutePath(); textToUpdate.append(path); } } }); return a; }
365e3c8e-c3df-4a61-b2ad-3e656d21de79
4
public static int[][] createInverseLookupTable(int[] chars) { int[][] tables = new int[256][]; for (int i = 0; i < 256; i++) { int c = chars[i]; if (c > -1) { int high = (c >>> 8) & 0xFF; int low = c & 0xFF; int[] table = tables[high]; if (table == null) { table = new int[256]; for (int j = 0; j < table.length; j++) table[j] = -1; tables[high] = table; } table[low] = i; } } return tables; }
2af55af4-d646-4034-b986-42a91dc6bd82
9
public void start() { running = true; t = new Thread(new Runnable() { @Override public void run() { try { serverSocket = new ServerSocket(10188); } catch (IOException e) { System.err.println("Could not listen on port: 10188 (is it in use?."); e.printStackTrace(); } try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("--- Server connection failed ---"); } if (clientSocket == null) return; PrintWriter out = null; try { out = new PrintWriter(clientSocket.getOutputStream(), true); } catch (IOException e) { e.printStackTrace(); } BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(clientSocket .getInputStream())); } catch (IOException e) { e.printStackTrace(); } String input; String output; ServerProtocol cp = new ServerProtocol(); output = cp.processInput(null); out.println(output); try { pr = new PrintWriter(clientSocket.getOutputStream(), true); } catch (IOException e1) { e1.printStackTrace(); } while (running) { try { while ((input = in.readLine()) != null) { cp.processInput(input); } } catch (Exception e) { e.printStackTrace(); } } } }, "ConnectionThread-Server"); t.start(); }
3956475c-8ad3-4194-9867-49a26a5b348e
4
public void encode_ascii(String encoded_string) throws IOException { File op = new File("output.txt"); n=0; BufferedWriter bw = new BufferedWriter(new FileWriter(op)); String temp=String.valueOf(encoded_string.charAt(0)); for(int i=1;i<encoded_string.length();i++) if(i%8==0){ //System.out.println(temp); bw.write((char)(Integer.parseInt(temp, 2))); temp=String.valueOf(encoded_string.charAt(i)); } else temp+=String.valueOf(encoded_string.charAt(i)); //System.out.println(temp); if(temp.length()==8) bw.write((char)(Integer.parseInt(temp, 2))); else{ /*bw.write('X'); bw.write(temp); */ n=8-temp.length(); while(temp.length()!=8) temp="0"+temp; bw.write((char)(Integer.parseInt(temp, 2))); } bw.close(); }
0683dad2-5bcb-4a42-9257-f2ce6dc70e47
5
@Override public void execute(MapleClient c, MessageCallback mc, String[] splitted) { if (splitted[0].equals("startProfiling")) { CPUSampler sampler = CPUSampler.getInstance(); sampler.addIncluded("net.sf.odinms"); sampler.start(); } else if (splitted[0].equals("stopProfiling")) { CPUSampler sampler = CPUSampler.getInstance(); try { String filename = "odinprofile.txt"; if (splitted.length > 1) { filename = splitted[1]; } File file = new File(filename); if (file.exists()) { mc.dropMessage("The entered filename already exists, choose a different one"); return; } sampler.stop(); FileWriter fw = new FileWriter(file); sampler.save(fw, 1, 10); fw.close(); } catch (IOException e) { log.error("THROW", e); } sampler.reset(); } }
b45ab579-7c9c-4468-9d46-4356fef07bec
4
public void setPlayers(ArrayList<Player> players, boolean resetGame) { if (players.size() <= 0) { players.add(new HumanPlayer()); players.get(0).setName("Nope. Nope. Nope."); } if (resetGame || players.size() != this.players.size()) { this.players = players; gameComponent.setPlayers(players); resetGame(); } else { for (int i = 0; i < players.size(); i++) { players.get(i).setCards(this.players.get(i).getCards()); } int currentPlayerIndex = this.players.indexOf(currentPlayer); this.players = players; gameComponent.setPlayers(players); setCurrentPlayer(currentPlayerIndex); } }
018b2370-b3c5-4d5c-9289-d289d41ab5f0
1
private void declarationList() { while (have(NonTerminal.DECLARATION_LIST)) { declaration(); } }
b4d25668-3f30-4138-9013-44cc43e31e64
0
public static Element createProductionElement(Document document, Production production) { Element pe = createElement(document, PRODUCTION_NAME, null, null); pe.appendChild(createElement(document, PRODUCTION_LEFT_NAME, null, production.getLHS())); pe.appendChild(createElement(document, PRODUCTION_RIGHT_NAME, null, production.getRHS())); return pe; }
1ce42d0c-906d-4517-a90f-4bb74e9c98f6
6
private void testConflict(final ChangedFile c) { if (this.checkedInFiles.isEmpty()) { readCache(); } final String filename; { final int offset = c.s.lastIndexOf('/'); if (offset < 0) { filename = c.s; } else { filename = c.s.substring(offset + 1); } } final String filenameRemove = this.checkedInFiles.remove(c.s); final Collection<String> filenames = this.checkedInFiles.values(); if (filenames.contains(filename)) { int files = 0; for (final Map.Entry<String, String> e : this.checkedInFiles .entrySet()) { if (e.getValue().equals(filename)) { c.conflictFiles.add(e.getKey()); ++files; } } c.conflict = files; } if (filenameRemove != null) { this.checkedInFiles.put(c.s, filenameRemove); } }
390e90c5-0e76-4468-9539-6a1c638e1b36
9
public static void main(final String[] args) { try { // load mysql jdbc driver Class.forName("com.mysql.jdbc.Driver"); // Setup the connection with the DB Importer.connect = DriverManager.getConnection("jdbc:mysql://localhost/" + props.getString(Importer.MOVIEDB_KEY) + "?user=" + props.getString(Importer.DBUSER_KEY) + "&password=" + props.getString(Importer.DBPASS_KEY)); } catch (final ClassNotFoundException e) { LOG.info("mysql driver not found"); e.printStackTrace(); } catch (final SQLException e2) { LOG.info("Connection could not established."); e2.printStackTrace(); } BufferedReader br = null; try { LOG.info(props.getString(Importer.EXPORT_FILE_KEY)); final File file = new File(props.getString(Importer.EXPORT_FILE_KEY)); br = new BufferedReader(new FileReader(file)); // count for successful inserts int successCount = 0; int successCountWithWarnings = 0; int errorCount = 0; int alreadyInDBCount = 0; while (br.ready()) { // remove some characters and parentFolders String movieName = br.readLine(); movieName = movieName.replace("./", ""); movieName = movieName.substring(movieName.indexOf("/") + 1, movieName.length()); LOG.info("Processing movie \"" + movieName + "\"..."); // Remove unwanted space from moviename by trimming it and // replace whitespaces with "+" final String movieNameForURL = movieName.trim().replace(" ", "+"); final Document doc = Importer.searchForMovies(movieNameForURL); final Map<String, String> resultMap = Importer.checkResultList(doc, movieName); resultMap.put(TITLE, movieName); if (!Importer.checkWhetherMovieIsAlreadyInDatabase(resultMap.get(TITLE))) { if (resultMap.containsKey(Importer.ERROR)) { errorCount++; Importer.LOG.info("ERROR: " + resultMap.get(Importer.ERROR)); } else { // load movie details with given ID Importer.loadMovieDetails(resultMap); // save details in database Importer.saveDetailsInDatabase(resultMap); if (resultMap.containsKey(Importer.WARNING)) { successCountWithWarnings++; Importer.LOG.info("WARNING: " + resultMap.get(Importer.WARNING)); } successCount++; Importer.LOG.info("... load data for \"" + movieName + "\" was successful"); } } else { alreadyInDBCount++; LOG.info("... the movie is already in database, no need to import it."); } } LOG.info("-----------------------------------------------------------------------------------"); LOG.info("| Summary:"); LOG.info("| successful movie inserts: " + successCount); LOG.info("| successful movie with warnings: " + successCountWithWarnings); LOG.info("| error count: " + errorCount); LOG.info("| already in db: " + alreadyInDBCount); LOG.info("-----------------------------------------------------------------------------------"); } catch (final IOException e) { e.printStackTrace(); } finally { try { if (br != null) { br.close(); } } catch (final IOException e) { e.printStackTrace(); } } }
8019c3c4-4ce6-46bd-9715-4fc0769df35b
6
private LinkedList<Actor> removeDuplicateActors(LinkedList<Actor> actors) { if (((actors.get(2).getName().equals(actors.get(1).getName())) && (actors .get(2).getBirthday().equals(actors.get(1).getBirthday()))) || ((actors.get(2).getName().equals(actors.get(0).getName())) && (actors .get(2).getBirthday().equals(actors.get(0) .getBirthday())))) { actors.remove(actors.get(2)); } if ((actors.get(1).getName().equals(actors.get(0).getName())) && (actors.get(1).getBirthday().equals(actors.get(0) .getBirthday()))) { actors.remove(actors.get(1)); } return actors; }
b36cd7ac-ed07-4afc-8a5a-d9f30a6ca2a3
6
@Override public void mouseClicked(final MouseEvent e) { this.e = e; player.setActivityTimer(1000); //if(player.getActivityTimer()==0){ new Thread(new Runnable(){ @Override public void run() { ToiletOverlay overlay = (ToiletOverlay)((JLabel) e.getSource()).getParent(); overlay.progress.setVisible(true); overlay.progressText.setVisible(true); overlay.close.setVisible(false); while(player.getActivityTimer()>0) { // System.out.println("Event"+player.getActivityTimer()); switch(player.getActivityTimer()*5/1000) { case 3: overlay.progress.setIcon(new ImageIcon(overlay.graphicManager.progress1.getImage())); break; case 2: overlay.progress.setIcon(new ImageIcon(overlay.graphicManager.progress2.getImage())); break; case 1: overlay.progress.setIcon(new ImageIcon(overlay.graphicManager.progress3.getImage())); break; case 0: overlay.progress.setIcon(new ImageIcon(overlay.graphicManager.progress4.getImage())); } try { Thread.sleep(40); } catch (InterruptedException e1) {} } DiscoObject.setStatusES(player, action); ((JLabel) e.getSource()).getParent().setVisible(false); ((JLabel) e.getSource()).getParent().setEnabled(false); disableActions(); player.setActivity(0); System.out.println(player.getActivityTimer()); // Reset player.setVisible(true); overlay.progress.setIcon(new ImageIcon(overlay.graphicManager.progress0.getImage())); overlay.progress.setVisible(false); overlay.progressText.setVisible(false); overlay.close.setVisible(true); ((JLabel) e.getSource()).setIcon(i); } }).start();; }
38caccd3-0e6f-4b3b-9540-14a260eb74dc
3
@Test public void testInsertAndDeleteOfArrays() throws Exception { PersistenceManager pm = new PersistenceManager(driver,database,login,password); for(int x = 0;x<10;x++) { //insert 10 objects for(int t = 0;t<10;t++) { ObjectArrayContainingObject aco = new ObjectArrayContainingObject(); aco.setData(new Object[]{x*10.0+t,2.0,3.0}); pm.saveObject(aco); } assertEquals(x*5+10,pm.getCount(ObjectArrayContainingObject.class, new All())); //delete 5 objects for(int t = 0;t<5;t++) { ObjectArrayContainingObject match = new ObjectArrayContainingObject(); match.setData(new Object[]{x*10.0+t}); pm.deleteObjects(ObjectArrayContainingObject.class, new Equal(match)); } assertEquals((x+1)*5,pm.getCount(ObjectArrayContainingObject.class, new All())); } //delete all objects pm.deleteObjects(ObjectArrayContainingObject.class, new All()); assertEquals(0, pm.getCount(ObjectArrayContainingObject.class, new All())); pm.close(); }
c337ccbd-3b5f-4cc4-9b7d-aba02117d4df
7
public static void main(String[] args){ //Local var declaration Scanner sc = new Scanner(System.in); String src,dst; if(args.length < 2){ //User inout interface System.out.println("=============================================="); System.out.println("= Copy File ="); System.out.println("=============================================="); System.out.print("Please select your source file : "); src = PATH+sc.next(); if((new File(src)).exists()){ try{ System.out.print("Please select your destination file : "); dst = PATH+sc.next(); byte[] buffer = readFile(src); for(int i=0;i<buffer.length;i++){ System.out.printf("0x%02X ",buffer[i]); if((i+1)%15==0) System.out.printf("\n"); } System.out.println(""); writeFile(buffer,dst); System.out.println("File has been copy to "+dst); }catch(IOException ex){ ex.printStackTrace(); } }else{ System.out.println("The source file is not exists."); } }else{ src = args[0]; dst = args[1]; if((new File(src)).exists()){ try{ byte[] buffer = readFile(src); writeFile(buffer, dst); System.out.println("The file has been copied to \""+dst+"\""); }catch(IOException ex){ ex.printStackTrace(); } }else{ System.err.println("The file is not exists"); } } }
b0a5e5b9-57fd-4f4d-9ab3-63b9b0405ef7
9
public void mouseReleased(MouseEvent e) { removeMouseMotionListener(this); if (creationLien && enabled) { creationLien = false; ZElement cibleLien = chercheElement(e.getX(), e.getY()); if (cibleLien != null) { lienTemp.setElement(cibleLien, Constantes.MCDENTITE2); x2 = e.getX(); y2 = e.getY(); } if (peutCreerLien(lienTemp.getElement(Constantes.MCDENTITE1), lienTemp .getElement(Constantes.MCDENTITE2))){ addLien(lienTemp); } else lienTemp.clearElement(); repaint(); } else if (enabled) { elementPress = null; if (arriveeCadreSelection != null) { selectionCourante.addAll(selectionTemporaire); selectionTemporaire.clear(); departCadreSelection = null; arriveeCadreSelection = null; } repaint(); } if (actionListener != null) actionListener.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "")); /* Correction Bug Graphique */ if (getPreferredSize().height > getSize().height || getPreferredSize().width > getSize().width /* * || getPreferredSize().height < getSize().height || * getPreferredSize().width < getSize().width */) this.setSize(getPreferredSize()); }
3b15f4e9-33ae-4d2a-aa76-c2b5b0a3a996
6
private static void initializePhiGrid() { // Defines the phis across the grid scalePhisHere = new ArrayList<ArrayList<Double>> (); int numGridLines = getNumGridlines(); double scaleNormalizer = Math.pow(2, Settings.startLevel/2.0); double i1 = Settings.getMinimumRange(); // Loop across the gridlines for (int x1Ind = 0; x1Ind < numGridLines; x1Ind++) { ArrayList<Double> thesePhis = new ArrayList<Double> (); i1 += Settings.discretization; int[] i1RelevantIndices = findRelevantKIndices(i1, Settings.startLevel); int k1Max = i1RelevantIndices[1]; int k1Min = i1RelevantIndices[0]; // Cycle through relevant X1 translates for the line for (int k1Ind = k1Min; k1Ind < k1Max; k1Ind++) { double k1 = Transform.scalingTranslates.get(k1Ind); double Xi1 = Math.pow(2, Settings.startLevel) * i1 - k1; double phi1Here = Wavelet.getPhiAt(Xi1) * scaleNormalizer; thesePhis.add(phi1Here); } scalePhisHere.add(thesePhis); } if (Settings.waveletFlag) { wavePhisHere = new ArrayList<ArrayList<ArrayList<Double>>> (); wavePsisHere = new ArrayList<ArrayList<ArrayList<Double>>> (); // Loop through resolutions for (double j = Settings.startLevel; j <= Settings.stopLevel; j++){ int waveInd = (int) Math.floor(j - Settings.startLevel); double waveNormalizer = Math.pow(2, j/2.0); ArrayList<ArrayList<Double>> jPhis = new ArrayList<ArrayList<Double>> (); ArrayList<ArrayList<Double>> jPsis = new ArrayList<ArrayList<Double>> (); // Loop through grid i1 = Settings.getMinimumRange(); for (int x1Ind = 0; x1Ind < numGridLines; x1Ind++) { ArrayList<Double> thesePhis = new ArrayList<Double> (); ArrayList<Double> thesePsis = new ArrayList<Double> (); i1 += Settings.discretization; int[] i1RelevantIndices = findRelevantKIndices(i1, j); int k1Max = i1RelevantIndices[1]; int k1Min = i1RelevantIndices[0]; // Cycle through relevant X1 translates for the line for (int k1Ind = k1Min; k1Ind < k1Max; k1Ind++) { double k1 = Transform.waveletTranslates.get(waveInd).get(k1Ind); double Xi1 = Math.pow(2, j) * i1 - k1; double phi1Here = Wavelet.getPhiAt(Xi1) * waveNormalizer; thesePhis.add(phi1Here); double psi1Here = Wavelet.getPsiAt(Xi1) * waveNormalizer; thesePsis.add(psi1Here); } // End cycling through relevant x1 translates jPhis.add(thesePhis); jPsis.add(thesePsis); } // End cycling through x1 grid wavePhisHere.add(jPhis); wavePsisHere.add(jPsis); } // End looping across resolutions } // End defining wavelet phis and psis }
6604f07f-7544-4c5d-9672-8bd6af26e1ab
6
public String toString() { int i, spaces; boolean longParam = false; StringBuilder buf = new StringBuilder(100); buf.append(" "); buf.append(arg); spaces = 20 - arg.length(); if (spaces <= 0) { spaces = 35 - arg.length(); longParam = true; } for (i = 0; i < spaces; i++) buf.append(" "); // Check for defaultValue of null if (defaultValue == null) { buf.append("null"); // append the string null if (longParam) { spaces = 21 - defaultValue.length(); } else spaces = 36; // which is 40 - length of the string "null" } else { buf.append(defaultValue); if (longParam) { spaces = 25 - defaultValue.length(); } else spaces = 40 - defaultValue.length(); } for (i = 0; i < spaces; i++) buf.append(" "); buf.append(description); buf.append('\n'); return buf.toString(); }
71e56333-3957-4a13-b5e6-ee8fd7185bb8
1
public void removeAllListeners() { Object[] listenerArray = listeners.getListenerList(); for (int i = 0, size = listenerArray.length; i < size; i += 2) { listeners.remove((Class)listenerArray[i], (EventListener)listenerArray[i+1]); } }
f9f7c949-042a-44ee-b3a1-ba682b45c604
7
public boolean isFine( String n, int w, int h ) { if ( !n.equals( name ) ) return false; switch ( compare ) { case 0: return ( w == width && h == height ); case 1: return ( w <= width && h <= height ); case 2: return ( w >= width && h >= height ); default: // -1 = no specs return true; } }
d6853ed1-85c4-4a73-87c6-3d41bb69b84e
0
public void removeClassPath(String path) { int index = paths.indexOf(path); paths.remove(index); }
3230d010-2f95-4892-9e11-969481110b62
1
public static void readXML() throws Exception { puzzleHighscores = new Vector<SlidingPuzzleHighscore>(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new File("highscore.xml")); Element rootElement = doc.getDocumentElement(); System.out.println("root element: " + rootElement.getNodeName()); NodeList list = rootElement.getElementsByTagName("user"); for (int i = 0; i < list.getLength(); i++) { Node userNode = list.item(i); new SlidingPuzzleHighscore(userNode.getAttributes() .getNamedItem("name").getNodeValue(), userNode .getAttributes().getNamedItem("score").getNodeValue()); } }
7ee93633-f62f-44e3-bd65-674abb4b0fe7
0
private JobConf jobConf(HadoopContext hadoopContext) { JobConf jobconf = new JobConf(); jobconf.setJobName("stackoverflow"); jobconf.setUser("hduser"); jobconf.setMapperClass(StackoverflowCommentsToCsv.Map.class); jobconf.setNumReduceTasks(0); jobconf.setOutputValueClass(IntWritable.class); jobconf.setOutputKeyClass(Text.class); jobconf.set("fs.defaultFS", hadoopContext.getHdfs()); jobconf.setWorkingDirectory(new Path(hadoopContext.getHome())); return jobconf; }
e8a8550f-8102-4acb-b76d-7e38fb7cf9ff
7
public void play() throws PlayWaveException{ //FileInputStream inputStream; try { waveStream = new FileInputStream(filename); } catch (FileNotFoundException e) { return; } AudioInputStream audioInputStream = null; try { audioInputStream = AudioSystem.getAudioInputStream(this.waveStream); } catch (UnsupportedAudioFileException e1) { throw new PlayWaveException(e1); } catch (IOException e1) { throw new PlayWaveException(e1); } // Obtain the information about the AudioInputStream AudioFormat audioFormat = audioInputStream.getFormat(); System.out.println(audioFormat); Info info = new Info(SourceDataLine.class, audioFormat); // opens the audio channel SourceDataLine dataLine = null; try { dataLine = (SourceDataLine) AudioSystem.getLine(info); dataLine.open(audioFormat, this.EXTERNAL_BUFFER_SIZE); } catch (LineUnavailableException e1) { throw new PlayWaveException(e1); } // Starts the music :P dataLine.start(); int readBytes = 0; byte[] audioBuffer = new byte[this.EXTERNAL_BUFFER_SIZE]; try { while (readBytes != -1) { readBytes = audioInputStream.read(audioBuffer, 0, audioBuffer.length); if (readBytes >= 0){ dataLine.write(audioBuffer, 0, readBytes); System.out.println("Soundbytes Read ="+readBytes); } } } catch (IOException e1) { throw new PlayWaveException(e1); } finally { // plays what's left and and closes the audioChannel dataLine.drain(); dataLine.close(); } }
8e575c65-be43-4334-b9cd-01e823daae42
3
public void saveChunk(World var1, Chunk var2) throws IOException { var1.checkSessionLock(); File var3 = this.chunkFileForXZ(var2.xPosition, var2.zPosition); if(var3.exists()) { WorldInfo var4 = var1.getWorldInfo(); var4.setSizeOnDisk(var4.getSizeOnDisk() - var3.length()); } try { File var10 = new File(this.saveDir, "tmp_chunk.dat"); FileOutputStream var5 = new FileOutputStream(var10); NBTTagCompound var6 = new NBTTagCompound(); NBTTagCompound var7 = new NBTTagCompound(); var6.setTag("Level", var7); storeChunkInCompound(var2, var1, var7); CompressedStreamTools.writeGzippedCompoundToOutputStream(var6, var5); var5.close(); if(var3.exists()) { var3.delete(); } var10.renameTo(var3); WorldInfo var8 = var1.getWorldInfo(); var8.setSizeOnDisk(var8.getSizeOnDisk() + var3.length()); } catch (Exception var9) { var9.printStackTrace(); } }
07c8f7e7-05cb-4379-83b1-5ac241c79268
7
public static boolean validate(String name, String pass, PersonBean bean) { boolean status = false; PreparedStatement pst = null; ResultSet rs = null; Connection conn=null; try { conn=ConnectionPool.getConnectionFromPool(); pst = conn .prepareStatement("select * from person where userid=? and password=SHA1(?)"); pst.setString(1, name); pst.setString(2, pass); rs = pst.executeQuery(); status = rs.next(); if(status){ bean.setFname(rs.getString("FNAME")); bean.setLname(rs.getString("LNAME")); bean.setType(rs.getString("TYPE")); bean.setAddress(rs.getString("ADDRESS")); bean.setId(rs.getInt("ID")); bean.setUserid(rs.getString("USERID")); } } catch (Exception e) { System.out.println(e); } finally { if(conn!=null){ ConnectionPool.addConnectionBackToPool(conn); } if (pst != null) { try { pst.close(); } catch (SQLException e) { e.printStackTrace(); } } if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } return status; }
07a5329f-f9dc-4060-b6af-286c7d716100
3
@Override public void keyPressed(KeyEvent e) { //Implement send on enter press if (e.getKeyCode() == KeyEvent.VK_ENTER && !txtField.getText().equals("")) { send(); } //Implement message last sent text field population //can be used to re-send last message with a spelling correction if (e.getKeyCode() == KeyEvent.VK_UP) { txtField.setText(lastMessage); } }
fb3e4c66-e333-4eef-8e9a-344d8ae64e35
6
static private void insertGetString (ClassWriter cw, String classNameInternal, ArrayList<Field> fields) { int maxStack = 6; MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "getString", "(Ljava/lang/Object;I)Ljava/lang/String;", null, null); mv.visitCode(); mv.visitVarInsn(ILOAD, 2); if (!fields.isEmpty()) { maxStack--; Label[] labels = new Label[fields.size()]; Label labelForInvalidTypes = new Label(); boolean hasAnyBadTypeLabel = false; for (int i = 0, n = labels.length; i < n; i++) { if (fields.get(i).getType().equals(String.class)) labels[i] = new Label(); else { labels[i] = labelForInvalidTypes; hasAnyBadTypeLabel = true; } } Label defaultLabel = new Label(); mv.visitTableSwitchInsn(0, labels.length - 1, defaultLabel, labels); for (int i = 0, n = labels.length; i < n; i++) { if (!labels[i].equals(labelForInvalidTypes)) { mv.visitLabel(labels[i]); mv.visitFrame(F_SAME, 0, null, 0, null); mv.visitVarInsn(ALOAD, 1); mv.visitTypeInsn(CHECKCAST, classNameInternal); mv.visitFieldInsn(GETFIELD, classNameInternal, fields.get(i).getName(), "Ljava/lang/String;"); mv.visitInsn(ARETURN); } } // Rest of fields: different type if (hasAnyBadTypeLabel) { mv.visitLabel(labelForInvalidTypes); mv.visitFrame(F_SAME, 0, null, 0, null); insertThrowExceptionForFieldType(mv, "String"); } // Default: field not found mv.visitLabel(defaultLabel); mv.visitFrame(F_SAME, 0, null, 0, null); } insertThrowExceptionForFieldNotFound(mv); mv.visitMaxs(maxStack, 3); mv.visitEnd(); }
be2fdaa5-8fb2-43f8-ae68-51e0841fde18
9
final void method2136(int i, int i_0_, byte i_1_) { anInt6224++; if (aClass61_6222 != null) { if (i_1_ >= -42) method2149(-65); ((Class286) this).aHa_Sub2_3684.method3738(-15039, 1); if ((i & 0x80) != 0) ((Class286) this).aHa_Sub2_3684.method3771((byte) -122, null); else if ((0x1 & i_0_) != 1) { if (!((Class83) aClass83_6227).aBoolean1442) ((Class286) this).aHa_Sub2_3684.method3771 ((byte) -84, ((Class83) aClass83_6227).aClass258_Sub3Array1444[0]); else ((Class286) this).aHa_Sub2_3684.method3771 ((byte) -97, ((Class83) aClass83_6227).aClass258_Sub1_1440); OpenGL.glProgramLocalParameter4fARB(34336, 65, 0.0F, 0.0F, 0.0F, 1.0F); } else if (!((Class83) aClass83_6227).aBoolean1442) { int i_2_ = (((OpenGlToolkit) ((Class286) this).aHa_Sub2_3684).anInt7735 % 4000 * 16 / 4000); ((Class286) this).aHa_Sub2_3684.method3771 ((byte) -88, ((Class83) aClass83_6227).aClass258_Sub3Array1444[i_2_]); OpenGL.glProgramLocalParameter4fARB(34336, 65, 0.0F, 0.0F, 0.0F, 1.0F); } else { ((Class286) this).aHa_Sub2_3684.method3771 ((byte) -83, ((Class83) aClass83_6227).aClass258_Sub1_1440); OpenGL.glProgramLocalParameter4fARB(34336, 65, aFloat6225, 0.0F, 0.0F, 1.0F); } ((Class286) this).aHa_Sub2_3684.method3738(-15039, 0); if ((0x40 & i) != 0) OpenGL.glProgramLocalParameter4fARB(34336, 66, 1.0F, 1.0F, 1.0F, 1.0F); else { Class348_Sub42_Sub1.aFloatArray9491[2] = (((OpenGlToolkit) ((Class286) this).aHa_Sub2_3684).aFloat7823 * (((OpenGlToolkit) ((Class286) this).aHa_Sub2_3684) .aFloat7768)); Class348_Sub42_Sub1.aFloatArray9491[0] = (((OpenGlToolkit) ((Class286) this).aHa_Sub2_3684).aFloat7781 * (((OpenGlToolkit) ((Class286) this).aHa_Sub2_3684) .aFloat7768)); Class348_Sub42_Sub1.aFloatArray9491[1] = (((OpenGlToolkit) ((Class286) this).aHa_Sub2_3684).aFloat7768 * (((OpenGlToolkit) ((Class286) this).aHa_Sub2_3684) .aFloat7816)); OpenGL.glProgramLocalParameter4fvARB(34336, 66, (Class348_Sub42_Sub1 .aFloatArray9491), 0); } int i_3_ = i & 0x3; if (i_3_ == 2) OpenGL.glProgramLocalParameter4fARB(34336, 64, 0.05F, 1.0F, 1.0F, 1.0F); else if (i_3_ == 3) OpenGL.glProgramLocalParameter4fARB(34336, 64, 0.1F, 1.0F, 1.0F, 1.0F); else OpenGL.glProgramLocalParameter4fARB(34336, 64, 0.025F, 1.0F, 1.0F, 1.0F); } }
5cc2eeac-67e7-4994-910f-4f7e3bcfd28b
6
@EventHandler public void CreeperNightVision(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getCreeperConfig().getDouble("Creeper.NightVision.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if ( plugin.getCreeperConfig().getBoolean("Creeper.NightVision.Enabled", true) && damager instanceof Creeper && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, plugin.getCreeperConfig().getInt("Creeper.NightVision.Time"), plugin.getCreeperConfig().getInt("Creeper.NightVision.Power"))); } }
3a304b86-2df6-4337-b87a-c8535d0eadc5
4
@Test @DatabaseSetup(value="classpath:databaseEntries.xml", type=DatabaseOperation.CLEAN_INSERT) public void testListLecturers() { List<LecturerImpl> lect_list = lecturerJdbcDaoSupportObject.listLecturers(); assertEquals(2, lect_list.size()); for(LecturerImpl l : lect_list){ String fn = l.getFirstName(); String ln = l.getLastName(); boolean isDonna = fn.equals("Donna") && ln.equals("OShea"); boolean isTed = fn.equals("Ted") && ln.equals("Scully"); assertTrue( isDonna || isTed ); } }
7b29c74c-3360-4dab-88c3-ed9defea511f
8
public void calc() { if(operator== "+") { firstNum += secondNum; System.out.println("firstNum plus secondNum is: " + firstNum); } if(operator == "-"){ firstNum -= secondNum; System.out.println("firstNum minus secondNum is: " + firstNum);} if(operator == "*") { firstNum *= secondNum; System.out.println("firstNum times secondNum is: " + firstNum);} if((operator == "/") && secondNum != 0.0){ System.out.println("firstNum div by secondNum is: " + firstNum); firstNum /= secondNum;} if((operator == "/") && secondNum == 0.0){ display.setText("ERROR"); System.out.println(display.getText()); firstNum = 0.0; secondNum = 0.0; operators = true; doClear = true; } if (!(display.getText().equals("ERROR"))) { operators = true; decPoint = false; display.setText(String.valueOf(firstNum)); secondNum = firstNum; System.out.println("SecondNum is: " + firstNum); } }
a327c1a6-ca7a-45cc-8494-f16f9bbb80cc
5
private void err(String prefix, String message, Throwable throwable) { String log = buildMessage(prefix, message); System.err.println(log); if (outputStream != null) { try { outputStream.write((log + "\r\n").getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (throwable != null) { for (StackTraceElement stackTraceElement : throwable.getStackTrace()) { try { outputStream.write((" at " + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName() + "(" + stackTraceElement.getFileName() + ":" + stackTraceElement.getLineNumber() + ")" + "\r\n").getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
ddcec104-9c5a-43d6-94b1-d4573843c805
8
public static Object asType(Object typeKey, Object value) { if (value==null) { return null; } if (typeKey==null) { return value; } // Check if the provided value is already of the target type if (typeKey instanceof Class && ((Class)typeKey)!=Object.class) { if (((Class)typeKey).isInstance(value)) { return value; } } // Find the type conversion object TypeConversion conversion; if (value instanceof ConvertibleType) { conversion=((ConvertibleType)value).getTypeConversion(typeKey); } else { conversion=typeConversions.get(typeKey); } // Convert the value if (conversion!=null) { if (value instanceof Listener) { ((Listener)value).beforeConversion(typeKey); return ((Listener)value).afterConversion(typeKey, conversion.convertValue(value)); } else { return conversion.convertValue(value); } } else { throw new IllegalArgumentException("Could not find type "+ "conversion for type \""+typeKey+"\" (value = \""+value+"\""); } }
6e45e40a-a3e9-49ea-a44b-e66f3a8ec1e6
4
public TreeColumn overColumn(int x) { if (x >= 0 && !mColumns.isEmpty()) { int divider = getColumnDividerWidth(); int count = mColumns.size() - 1; int pos = 0; for (int i = 0; i < count; i++) { TreeColumn column = mColumns.get(i); pos += column.getWidth() + divider; if (x < pos) { return column; } } return mColumns.get(count); } return null; }
345a0d10-d373-4b69-bd2d-5cc55eb2ae5f
9
private int computeEdgeParameters(DynamicGraph dynamicGraph, List<Date> sortedDates) { AttributeModel attributeModel = Lookup.getDefault().lookup(AttributeController.class).getModel(); AttributeColumn overlapColumn = attributeModel.getEdgeTable().addColumn("overlapd", AttributeType.DYNAMIC_DOUBLE); int overlapColumnIndex = overlapColumn.getIndex(); AttributeColumn embeddednessnColumn = attributeModel.getEdgeTable().addColumn("embeddednessd", AttributeType.DYNAMIC_INT); int embeddednessnColumnIndex = embeddednessnColumn.getIndex(); double startDateLong = sortedDates.get(0).getTime(); int previousCreated = 0; int theSame = 0; int rounds = 0; for (int i = 0; i < sortedDates.size(); i++) { double endDateLong = Double.POSITIVE_INFINITY; if (i + 1 < sortedDates.size()) { endDateLong = sortedDates.get(i + 1).getTime(); } Graph subGraph = dynamicGraph.getSnapshotGraph(startDateLong, endDateLong); ClusteringCoefficient clusteringMetric = new ClusteringCoefficient(); OverlapMetric overlapMetric = new OverlapMetric(); overlapMetric.execute(subGraph.getGraphModel(), attributeModel); clusteringMetric.execute(subGraph.getGraphModel(), attributeModel); Iterator<Edge> iterator = subGraph.getEdges().iterator(); AttributeColumn neighborhoodOverlapColumn = attributeModel.getEdgeTable().getColumn("neighborhoodOverlap"); int neighborhoodOverlapColumnIndex = neighborhoodOverlapColumn.getIndex(); AttributeColumn embeddednessColumn = attributeModel.getEdgeTable().getColumn("embeddedness"); int embeddednessColumnIndex = embeddednessColumn.getIndex(); int j = 0; Edge edg = null; while (iterator.hasNext()) { j++; Edge edge = iterator.next(); if (edg == null) { edg = edge; } Double overlapCoefficient = (Double) edge.getAttributes().getValue(neighborhoodOverlapColumnIndex); Integer embeddedness = (Integer) edge.getAttributes().getValue(embeddednessColumnIndex); DynamicDouble overlapCoefficientD = (DynamicDouble) edge.getAttributes().getValue(overlapColumnIndex); if (overlapCoefficientD == null) { overlapCoefficientD = new DynamicDouble(new Interval<Double>(startDateLong, endDateLong, overlapCoefficient)); } else { overlapCoefficientD = new DynamicDouble(overlapCoefficientD, new Interval<Double>(startDateLong, endDateLong, overlapCoefficient)); } edge.getAttributes().setValue(overlapColumnIndex, overlapCoefficientD); DynamicInteger embeddednessD = (DynamicInteger) edge.getAttributes().getValue(embeddednessnColumnIndex); if (embeddednessD == null) { embeddednessD = new DynamicInteger(new Interval<Integer>(startDateLong, endDateLong, embeddedness)); } else { embeddednessD = new DynamicInteger(embeddednessD, new Interval<Integer>(startDateLong, endDateLong, embeddedness)); } edge.getAttributes().setValue(embeddednessnColumnIndex, embeddednessD); if (edg.getEdgeData().getId().equals(edge.getEdgeData().getId())) { System.out.println(overlapCoefficient + " created overlapCoefficientD " + embeddedness + " created embeddednessD"); } } rounds++; System.out.println(j + " created edge"); if (j == previousCreated) { theSame++; if (theSame > 5) { System.out.println("No new data, skipping"); return rounds; } } else { theSame = 0; } previousCreated = j; } return rounds; }
0f567a74-aa42-40ec-8351-9bda419f783d
6
@Override public void propertyChange(PropertyChangeEvent evt) { if (programExit) if (evt.getPropertyName().equals("state")&& (evt.getNewValue()).toString().equals("DONE")){ System.exit(0); } if (makeNewDocument) if (evt.getPropertyName().equals("state")&& (evt.getNewValue()).toString().equals("DONE")){ initNewDocument(); } }
259f6cf3-22f5-4814-8c90-232d368b29d8
7
public void drawPoint(Chimera3DLVertex vertex[]) { Chimera3DMatrix mat = matrixWorld.mod(matrixCamera).mod(matrixProjection).mod(matrixViewPort); Chimera3DVector dest = new Chimera3DVector(); for(int i = 0; i < vertex.length; ++i) { mat.transformVectorPosition(dest, vertex[i].pos); if (dest.z >= 0.0 && dest.z < 1.0) { if (dest.y >= 0.0 && dest.y < height) { if (dest.x >= 0.0 && dest.x < width) { backBuffer.setColor(new Color(vertex[i].color)); backBuffer.fillRect((int)dest.x, (int)dest.y, 2, 2); } } } } }
f1802a68-ece6-47c7-9e02-0e50cbc9ccc7
1
*/ public void convertDragRowsToSelf(List<Row> list) { Row[] rows = mModel.getDragRows(); rows[0].getOwner().removeRows(rows); for (Row element : rows) { mModel.collectRowsAndSetOwner(list, element, false); } }
d12fe1c9-c714-4033-9725-cf005428c998
6
private void generateField() { field = new MinefieldCell[rows][cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) field[i][j] = new MinefieldCell(); for (int i = 0; i < mines; i++) { int row = (int) (Math.random() * rows); int col = (int) (Math.random() * cols); while (field[row][col].hasMine()) { row = (int) (Math.random() * rows); col = (int) (Math.random() * cols); } field[row][col].setMine(true); } for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) field[i][j].setAdjacentMines(countAdjacentMines(i, j)); }
7b1d81ba-f1f3-4e18-bf2a-0e74401bffde
3
public static boolean checkUpdatesMain() { //Nastavi številko za najnovejšo verzijo iz strežnika double version=0; try { URL url=new URL("http://"+Main.ip+"/d0941e68da8f38151ff86a61fc59f7c5cf9fcaa2/computer/mainVersion.html"); BufferedReader in=new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); String ln; String out=""; while ((ln=in.readLine())!=null) out+=ln; in.close(); version=Float.parseFloat(out); } catch (Exception e) {e.printStackTrace();} //Zaradi problemov pri shranjevanju decimalnih številk v binarni sistem, //jih zaokroži na 1 decimalno mesto. version=(float)Math.round(version*10.0)/10.0; //Če je najnovejša verzija programa večja od trenutne verzija, //vrni "true", drugače pa vrni "false" if (version>Main.currentVersion) return true; else return false; }
bcaf8385-a8ba-46cf-ae24-bb827c16f428
9
@Override public MinesweeperTile[] getSurroundingTiles() { ArrayList<MinesweeperTile> surrondingList = new ArrayList<MinesweeperTile>(8); for (int x = xPos - 1 ; x <= xPos + 1; x++) { for (int y = yPos - 1 ; y <= yPos + 1; y++) { if (x >= 0 && y >= 0 && x < board.amountOfTiles.width && y < board.amountOfTiles.height && !(xPos == x && yPos == y)) surrondingList.add(board.theGame[x][y]); } } MinesweeperTile[] tiles = new MinesweeperTile[surrondingList.size()]; int tileIndex = 0; for (MinesweeperTile tile : surrondingList){ tiles[tileIndex++] = tile; } return tiles; }
5dab5f0a-ad46-410b-9d0d-ff47eef39acb
9
public static void Update(){ room.Update(); boolean change_room = false; //OFFSCREEN LEFT if (room.player.x+room.player.rb/2 < 0){ change_room = true; room.player.x = room.MAP_WIDTH*Tile.WIDTH - 16; int x = (int)coordinates.getX(); x--; if (x < 0) x = world_width-1; coordinates.setLocation(x, coordinates.getY()); } //OFFSCREEN RIGHT else if (room.player.x+room.player.rb/2 >= room.MAP_WIDTH*Tile.WIDTH){ change_room = true; room.player.x = 0; int x = (int)coordinates.getX(); x++; if (x >= world_width) x = 0; coordinates.setLocation(x, coordinates.getY()); } //OFFSCREEN TOP else if (room.player.y+room.player.bb/2 < 0){ change_room = true; room.player.y = room.MAP_HEIGHT*Tile.HEIGHT - 16; int y = (int)coordinates.getY(); y--; if (y < 0) y = world_height-1; coordinates.setLocation(coordinates.getX(), y); } //OFFSCREEN BOTTOM else if (room.player.y+room.player.bb/2 >= room.MAP_HEIGHT*Tile.HEIGHT){ change_room = true; room.player.y = 0; int y = (int)coordinates.getY(); y++; if (y >= world_height) y = 0; coordinates.setLocation(coordinates.getX(), y); } if (change_room){ Player player = room.player; room = rooms.get((int)coordinates.getY()).get((int)coordinates.getX()); room.player.facing = player.facing; room.player.whatdidisay = player.whatdidisay; room.player.voice = player.voice; room.player.x = player.x; room.player.y = player.y; room.player.Update(room); } }
4d249c98-1c77-406c-b8d6-be2bdc213a73
2
public void update(){ for(int i = 0; i < particles.size(); i++){ Particle p = particles.get(i); p.update(); if (p.isDead()){ particles.remove(i); i--; } } }
7f70c502-8564-401f-b27c-0544a2d0a4c4
6
public void toggleSquare(int x, int y) { //first check we are are allowed to make a move if (!checkValidMove(x, y)) return; Square square = board.getSquare(x, y); if (square.isRevealed()) { //do nothing return; } if (square.isFlagged()) minesUnflagged++; //toggle flag and notify listener switch(square.toggleState()) { case flagged: listener.squareFlagged(x, y); minesUnflagged--; break; case unmarked: listener.squareUnmarked(x, y); break; case questioned: listener.squareQuestioned(x, y); break; default: break; } listener.totalFlagsChanged(minesUnflagged); }
1c5d5944-26ca-4630-98e9-7e43c3df3cbf
5
private void scheduleSchemaForProcessing(URL schemaLocation) { if (cache.hasSchema(schemaLocation)) { return; //schema has already been compiled before, or on another thread } for (ProcessingEntry it : schemasToCompile) { if (it.schemaLocation.toString().equals(schemaLocation.toString())) { return; //schema is already scheduled for compilation } } try { JsonParser parser = jsonFactory.createJsonParser(schemaLocation); try { JsonNode rawSchema = parser.readValueAsTree(); schemasToCompile.add(new ProcessingEntry(schemaLocation, rawSchema)); } finally { parser.close(); } } catch (JsonParseException jpe) { throw new IllegalArgumentException("The schema at location " + schemaLocation.toString() + " contains invalid JSON", jpe); } catch (IOException ioe) { throw new IllegalArgumentException("Could not retrieve schema from " + schemaLocation.toString(), ioe); } }
ee14a905-5e66-458b-8c30-33c45bae0748
3
public Menu() { // Elements of the bar: JMenu menuFile = new JMenu("File"); add(menuFile); JMenu menuHelp = new JMenu("Help"); add(menuHelp); // Elements of File: JMenuItem fileConnect = new JMenuItem("Connect"); fileConnect.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int connectToPortInputBox = 0; String connectToIPInputBox = (String) JOptionPane.showInputDialog("Insert Your Mate's IP:"); try { connectToPortInputBox= Integer.parseInt((String) JOptionPane.showInputDialog("Insert Your Mate's Port:")); if(connectToPortInputBox > 65535 || connectToPortInputBox < 49152) sc.chatLogWrite("Plese provide a number greather then 65535 and lesser then 49152"); } catch(NumberFormatException exc) { sc.chatLogWrite("Attenzione: Inserisci un indirizzo di porta numerico."); } SimpleChat.getInstance().connect(connectToIPInputBox, connectToPortInputBox); } }); fileDisconnect = new JMenuItem("Disconnect"); fileDisconnect.setEnabled(false); fileDisconnect.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { sc.sendSCMessage("01-CLOSE_REQ"); sc.closeConnection(); } }); JMenuItem fileExit = new JMenuItem("Exit"); fileExit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { sc.closeConnection(); sc.removeUPnPMapping(); System.exit(0); } }); menuFile.add(fileConnect); menuFile.add(fileDisconnect); menuFile.add(fileExit); // Elements of Help: JMenuItem helpHelp = new JMenuItem("Help"); helpHelp.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { new HelpFrame(); } }); JMenuItem helpAbout = new JMenuItem("About"); menuHelp.add(helpHelp); menuHelp.add(helpAbout); }
cadc00ee-7a2c-4061-9df8-80b78757fdc0
1
private static boolean method517(char arg0) { return !Censor.isLetter(arg0) && !Censor.isDigit(arg0); }