method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
6c1c8f7d-1e95-4377-8549-f6ef94f92a0c
2
protected void print() { System.out.println("Print for " + prototype + "------------------"); cfg.visit(new PrintVisitor() { Phi phi = null; public void visitBlock(final Block block) { phi = exprPhiAtBlock(block); super.visitBlock(block); } public void visitLabelStmt(final LabelStmt stmt) { super.visitLabelStmt(stmt); if (stmt.label().startsBlock()) { if (phi != null) { println(phi); phi = null; } } } }); System.out.println("End Print ----------------------------"); }
4db98111-1660-4b0b-807e-435467210fe8
3
private Type parseType() { //System.out.println("parseType"); Type node; switch(showNext().getKind()) { case "ident": node = new NamedType(new Identifier(acceptIt())); break; case "array": node = parseArrayType(); break; case "record": node = parseRecordType(); break; default: node = null; this.console.setText(this.console.getText() + "<br>parsing error for type around l"+showNext().getPos()[0]+"c"+showNext().getPos()[1]); break; } return node; }
5e6d57ec-319b-48c4-91f7-301a2f2243a1
1
public static void insertFonction(String libelle) throws SQLException { String query = ""; try { query = "INSERT INTO FONCTION (FONCLIBELLE) VALUES (?); "; PreparedStatement pStatement = ConnectionBDD.getInstance().getPreparedStatement(query); pStatement.setString(1, libelle.toUpperCase()); pStatement.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(RequetesFonction.class.getName()).log(Level.SEVERE, null, ex); } }
39fe7a8b-ec0c-48f5-aef1-ba1b5c8a8e23
2
public static void selectRightText(OutlinerCellRendererImpl textArea, JoeTree tree, OutlineLayoutManager layout) { Node currentNode = textArea.node; int currentPosition = textArea.getCaretPosition(); if (currentPosition == textArea.getText().length()) { return; } // Update Preferred Caret Position int newCaretPosition = currentPosition + 1; tree.getDocument().setPreferredCaretPosition(newCaretPosition); // Record the CursorPosition only since the EditingNode should not have changed tree.setCursorPosition(newCaretPosition, false); textArea.moveCaretPosition(newCaretPosition); // Redraw and Set Focus if this node is currently offscreen if (!currentNode.isVisible()) { layout.draw(currentNode,OutlineLayoutManager.TEXT); } // Freeze Undo Editing UndoableEdit.freezeUndoEdit(currentNode); }
71ad8518-63e1-4f63-9211-8a00e07d4e6e
8
public static final int getMaxHit(Player player, int weaponId, int attackStyle, boolean ranging, boolean usingSpec, double specMultiplier) { if (!ranging) { int strengthLvl = player.getSkills().getLevel(Skills.STRENGTH); double xpStyle = CombatDefinitions .getXpStyle(weaponId, attackStyle); double styleBonus = xpStyle == Skills.STRENGTH ? 3 : xpStyle == CombatDefinitions.SHARED ? 1 : 0; double otherBonus = 1; if (fullDharokEquipped(player)) { double hp = player.getHitpoints(); double maxhp = player.getMaxHitpoints(); double d = hp / maxhp; otherBonus = 2 - d; } double effectiveStrength = 8 + strengthLvl * player.getPrayer().getStrengthMultiplier() + styleBonus; if (fullVoidEquipped(player, 11665, 11676)) effectiveStrength *= 1.1; double strengthBonus = player.getCombatDefinitions().getBonuses()[CombatDefinitions.STRENGTH_BONUS]; double baseDamage = 5 + effectiveStrength * (1 + (strengthBonus / 64)); return (int) (baseDamage * specMultiplier * otherBonus); } else { double rangedLvl = player.getSkills().getLevel(Skills.RANGE); double styleBonus = attackStyle == 0 ? 3 : attackStyle == 1 ? 0 : 1; double otherBonus = 1; double effectiveStrenght = (rangedLvl * player.getPrayer().getRangeMultiplier() * otherBonus) + styleBonus; if (fullVoidEquipped(player, 11664, 11675)) effectiveStrenght += (player.getSkills().getLevelForXp( Skills.RANGE) / 5) + 1.6; double strengthBonus = player.getCombatDefinitions().getBonuses()[CombatDefinitions.RANGED_STR_BONUS]; double baseDamage = 5 + (((effectiveStrenght + 8) * (strengthBonus + 64)) / 64); return (int) (baseDamage * specMultiplier); } }
f6ef56d3-0480-4604-9438-191fcf81777c
4
public static long appendIncrementalUpdate( Document document, OutputStream out, long documentLength) throws IOException { // Iterate over StateManager entries, writing changed objects // (like Annotation, Page, Annots array) to output stream via // IncrementalUpdater if (logger.isLoggable(Level.FINE)) { if (document.getStateManager().isChanged()) logger.fine("Have changes, will append incremental update"); else logger.fine("No changes, will not append incremental update"); } // If no changes, don't append an incremental update if (!document.getStateManager().isChanged()) return 0L; IncrementalUpdater updater = new IncrementalUpdater( out, documentLength); updater.begin(); Iterator<PObject> changes = document.getStateManager().iteratorSortedByObjectNumber(); while (changes.hasNext()) { PObject pobject = changes.next(); updater.writeObject(pobject.getReference(), pobject.getObject()); } // Write out xref table, based on IncrementalUpdater entries updater.writeXRefTable(); // Write trailer updater.writeTrailer(document.getStateManager().getTrailer()); return updater.getIncrementalUpdateLength(); }
c2df1a13-2eb4-4e9e-8448-96c105019be7
0
public void setId(Integer id) { this.id = id; }
9c0a5fae-7922-494c-82a1-acbb29b36f07
3
/* */ protected RIFCSElement(Node n, String name) /* */ throws RIFCSException /* */ { /* 56 */ if (n == null) /* */ { /* 58 */ throw new RIFCSException("Null Node passed to constructor"); /* */ } /* */ /* 61 */ if ((n instanceof Element)) /* */ { /* 63 */ if (!n.getNodeName().endsWith(name)) /* */ { /* 65 */ throw new RIFCSException("Mismatch tag name. Node tag is: " + n.getNodeName() + ", expected: " + name); /* */ } /* */ } /* */ else /* */ { /* 70 */ throw new RIFCSException("Node of type Element required in constructor"); /* */ } /* */ /* 73 */ this.e = ((Element)n); /* */ }
03d06dd8-e14c-49be-b0e8-c9d28d2921d0
3
@SuppressWarnings("deprecation") @EventHandler public void VillagerSpawn(CreatureSpawnEvent event){ ArrayList<String> firstNames = new ArrayList<String>(); OfflinePlayer[] oln = Bukkit.getOfflinePlayers(); if(event.getEntityType().getName().equalsIgnoreCase("Villager")){ for(OfflinePlayer y : oln){ firstNames.add(y.getName()); } int fnl = firstNames.size(); int rFnl = (int) (Math.random() * fnl ); event.getEntity().setCustomName(firstNames.get(rFnl) ); event.getEntity().setCustomNameVisible(false); }else if(event.getEntityType().getName().equalsIgnoreCase("Zombie")){ } }
d8b4b7f2-0879-440c-96de-60376d7eb7eb
4
public void render(Graphics2D g) { g.drawImage(RL.stone, x, y, width, height, null); if (up) { g.drawImage(RL.stoneVC, x, y - height / 2, 64, 64, null); } if (down) { g.drawImage(RL.stoneVC, x, y + height / 2, 64, 64, null); } if (left) { g.drawImage(RL.stoneHC, x - width / 2, y, 64, 64, null); } if (right) { g.drawImage(RL.stoneHC, x + width / 2, y, 64, 64, null); } }
fe8361ee-418c-4a88-bcc3-4a1adbad1491
9
public void dealerHit() { System.out.println(">Dealer's hidden card was: " + dealerHand.getHand().get(0).toString()); while (dealerHand.getHandValue() < 21) { if (dealerHand.getHandValue() < 17 && !dealerHand.getHValues().contains(11)) { dealerHand.addCard(shoe.dealCard()); System.out.println(">Dealer HIT - Dealer's Hand: " + dealerHand.toString()); } else if (dealerHand.getHandValue() >= 17 && dealerHand.getHandValue() > 21 && dealerHand.getHValues().contains(11)) { dealerHand.getHand().get(dealerHand.getHValues().indexOf(11)) .setAce(); dealerHand.setAceValue(); dealerHand.addCard(shoe.dealCard()); System.out.println(">Dealer HIT - Dealer's Hand: " + dealerHand.toString()); } else if ((dealerHand.getHandValue() >= 17 && !dealerHand .getHValues().contains(11))) { System.out.println(">Dealer stops dealing cards"); break; } } if (dealerHand.getHandValue() > 21) { dealerBust(); } else { dealerStand(); } }
e108d121-8ee7-4a06-9829-4c6f9c06090d
8
private void memory_stage() { InstructionType type = current_instruction.get_type(); int rt; switch (type) { case lw: memory_result = memory_unit.load_word(alu_result); break; case lh: memory_result = memory_unit.load_half_word(alu_result); break; case lhu: memory_result = memory_unit.load_half_word_unsigned(alu_result); break; case lb: memory_result = memory_unit.load_byte(alu_result); break; case lbu: memory_result = memory_unit.load_byte_unsigned(alu_result); break; case sw: rt = register_file.get_register(current_instruction.get_rt()); memory_unit.store_word(alu_result, rt); break; case sh: rt = register_file.get_register(current_instruction.get_rt()); memory_unit.store_half_word(alu_result, rt); break; case sb: rt= register_file.get_register(current_instruction.get_rt()); memory_unit.store_byte(alu_result, rt); break; default: } memory_unit.print(); }
24dbf8af-da27-4251-980a-e4fd10805978
2
private static void fillArray(int[] array, int actualDataSpots){ for (int x = 0; x <= array.length -1; x++){ //fills in starting elements if(x <= actualDataSpots -1){ array[x] = x; } else { //fills the rest with -1 array[x] = -1; } } }
26fe98b2-3adc-47db-852e-673848b34136
5
public static String rTrim(final String value) { if (value == null) { return null; } String trimmed = value; int offset = value.length() - 1; while (offset > -1 && (value.charAt(offset) == ' ' || value.charAt(offset) == '\t')) { offset--; } if (offset < value.length() - 1) { trimmed = value.substring(0, offset + 1); } return trimmed; }
5db2ea52-7cc9-4856-8f12-c9b12768df41
2
public void unpackDat( File datFile, File outFolder ) throws IOException { log.trace("Unpacking dat file " + datFile.getPath() + " into " + outFolder.getPath()); InputStream in = new FileInputStream(datFile); outFolder.mkdirs(); int[] header = readHeader(in); int i = 0; while( i < header.length && header[i++] != 0 ) readFile(in, outFolder); in.close(); }
1387fb0e-5506-4876-a380-52180fb21b33
5
public LineSplitterBrackets(String delimiter, String theBracketLeft, String theBracketRight) { super(delimiter); this.bracketLeft = theBracketLeft; this.bracketRight = theBracketRight; if (bracketLeft.equals(bracketRight)) { bracketFinder = new BracketFinder() { public int getNextClosingBracketPosition(String line, int fromIndex) { return line.indexOf(bracketLeft,fromIndex); } }; } else { bracketFinder = new BracketFinder() { public int getNextClosingBracketPosition(String line, int fromIndex) { int pzu = line.indexOf(bracketRight,fromIndex); if (pzu<0) { return pzu; } int pauf = line.indexOf(bracketLeft,fromIndex); if ((pauf<0) || (pauf>pzu)) { return pzu; } pzu = getNextClosingBracketPosition(line, pauf+1); if (pzu<0) { return pzu; } else { return getNextClosingBracketPosition(line, pzu+1); } } }; } }
115aa413-0428-406b-8ec7-f5641359d38f
4
public OdigoiAdd(int editId) { /* * parathiro gia thn prosthiki i tin epe3ergasia odigou, an to editId einai 0 tote kanei prosthiki alliws epexergasia */ con = new Mysql(); id=editId; if(id==0) // vazei ton katallhlo titlo analoga thn leitourgia pou exei epilex8ei setTitle("Prosthiki Odigou"); else setTitle("Epe3ergasia Odigou"); /* vgazei to para8uro sto kedro tis othonis me diastaseis 300x220 */ Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); this.setBounds(dim.width/2-150, dim.height/2-125, 300, 245); /*--------------*/ this.setResizable(false); getContentPane().setBackground(Color.WHITE); getContentPane().setLayout(null); JLabel onomaLabel = new JLabel("Onoma:"); onomaLabel.setBounds(10, 11, 70, 14); getContentPane().add(onomaLabel); JLabel eponimoLabel = new JLabel("Epwnimo:"); eponimoLabel.setBounds(10, 36, 70, 14); getContentPane().add(eponimoLabel); JLabel usernameLabel = new JLabel("Username:"); usernameLabel.setBounds(10, 61, 70, 14); getContentPane().add(usernameLabel); JLabel kodikosLabel = new JLabel("Password:"); kodikosLabel.setBounds(10, 86, 70, 14); getContentPane().add(kodikosLabel); JLabel kodikosELabel = new JLabel("Epal. Kwdikou:"); kodikosELabel.setBounds(10, 111, 70, 14); getContentPane().add(kodikosELabel); oximaLabel = new JLabel("Oxima:"); oximaLabel.setBounds(10, 136, 90, 14); getContentPane().add(oximaLabel); name = new JTextField(); name.setBounds(101, 8, 125, 20); getContentPane().add(name); name.setColumns(10); surname = new JTextField(); surname.setBounds(101, 33, 125, 20); getContentPane().add(surname); surname.setColumns(10); username = new JTextField(); username.setBounds(101, 58, 125, 20); getContentPane().add(username); username.setColumns(10); pass = new JPasswordField(); pass.setBounds(101, 83, 125, 20); getContentPane().add(pass); pass2 = new JPasswordField(); pass2.setBounds(101, 108, 125, 17); getContentPane().add(pass2); oximataBox = new JComboBox<String>(); oximataBox.setBounds(101, 133, 125, 20); getContentPane().add(oximataBox); addOximata(); JButton saveButton = new JButton("Save"); saveButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { /* * apothikeuei tis times sthn vash afou tis elen3ei prwta */ String nameValue=name.getText(); String surnameValue=surname.getText(); String usernameValue=username.getText(); String passValue=pass.getText(); String pass2Value=pass2.getText(); String oximaValue=oximataBox.getSelectedItem().toString(); String action; if(checkData(nameValue,surnameValue,passValue,pass2Value)){ if(id==0) action="insert"; else action="update"; save(nameValue,surnameValue,usernameValue,passValue,oximaValue,action); } } }); saveButton.setBounds(101, 167, 125, 40); getContentPane().add(saveButton); if(id!=0){ // an exei epilexthei i leitourgia tiw epe3ergasias tote pairnei ta stoixia tou odigou pros epe3ergasia getOdigoForEdit(id); } }
74fa7533-d7df-42ac-9bee-99efaf4b8408
0
@Test public void deleteWorksAtEnd() { initializeWithABC(); l.delete(c); assertEquals(b, l.max()); assertEquals(null, l.succ(b)); }
b5dae4e8-a7a9-48f0-a4a6-e1a19eaf99f2
9
@Override public void run(){ if(state == GameState.Running){ while(true){ robot.update(); if(robot.isJumped()){ currentSprite = characterJumped; } else if (robot.isJumped() == false && robot.isDucked() == false){ currentSprite = anim.getImage(); } ArrayList projectiles = robot.getProjectiles(); for(int i = 0; i < projectiles.size(); i++){ Projectile p = (Projectile) projectiles.get(i); if(p.isVisible() == true){ p.update(); } else { projectiles.remove(i); } } updateTiles(); hb.update(); hb2.update(); bg1.update(); bg2.update(); animate(); repaint(); try{ Thread.sleep(17); } catch (InterruptedException e){ e.printStackTrace(); } if(robot.getCenterY() > 500){ state = GameState.Dead; } } } }
f0e4a1e6-6259-47de-a444-ffedadb9364b
1
private void paintTiles(Graphics g) { for (int i = 0; i < tilearray.size(); i++) { Tile t = (Tile) tilearray.get(i); g.drawImage(t.getTileImage(), t.getTileX(), t.getTileY(), this); } }
3e7b18f5-de8b-44c5-bac9-e9d0d61ff9a3
6
private void writeXML(String xml) { String resourceName = System.getProperty(CONFIG_FILENAME_KEY); if (resourceName == null) { return; } else { URL rUrl = ClassLoader.getSystemResource(resourceName); if (rUrl != null) { File file = new File(rUrl.getFile()); if (file != null && file.canWrite()) { FileWriter fw = null; try { fw = new FileWriter(file); fw.write(xml); fw.close(); } catch (IOException ioe) { //@TODO log it? } finally { try { fw.close(); } catch (IOException ioee) { ; //Nothing to do. } fw = null; file = null; } } } } }
e6e50bec-5126-4455-9883-36833bfb91b7
9
private Map<String, Object> saveMap() { Map<String, Object> map = new HashMap<String, Object>(); map.put("name", name); map.put("main", main); map.put("version", version); map.put("database", database); map.put("order", order.toString()); map.put("default-permission", defaultPerm.toString()); if (commands != null) { map.put("command", commands); } if (depend != null) { map.put("depend", depend); } if (softDepend != null) { map.put("softdepend", softDepend); } if (website != null) { map.put("website", website); } if (description != null) { map.put("description", description); } if (authors.size() == 1) { map.put("author", authors.get(0)); } else if (authors.size() > 1) { map.put("authors", authors); } if (classLoaderOf != null) { map.put("class-loader-of", classLoaderOf); } if (prefix != null) { map.put("prefix", prefix); } return map; }
fac77f7b-53c9-498a-99b3-50ffc5618e36
5
@Override public Integer getIdFromDataBase() throws SQLException { Integer id = null; if(numGroup == null){ return id; } else if(yearSupply == null){ return id; } else if (faculty == null || faculty.getIdFaculty() == null){ return id; } Statement statement = ua.edu.odeku.pet.database.ConnectionDataBase.getStatement(); ResultSet resultSet = statement.executeQuery("Select id_groups from groups where " + "num_group =" + numGroup + " " + "and id_faculty = " + faculty.getIdFaculty() + " " + "and year_supply = " + yearSupply + " ;"); if(resultSet.next()){ id = resultSet.getInt(1); } return id; }
302ff2e4-caae-48fb-919f-1b3846d46882
3
public void setAccountTypes(AccountTypes accountTypes) { this.accountTypes = accountTypes; if (accountTypes != null) { selectedAccountTypes.clear(); for (AccountType type : accountTypes.getBusinessObjects()) { selectedAccountTypes.put(type, Boolean.TRUE); } } boxes.clear(); filter.removeAll(); for (AccountType type : accountTypes.getBusinessObjects()) { JCheckBox checkBox = new JCheckBox(getBundle("BusinessModel").getString(type.getName().toUpperCase())); checkBox.setSelected(true); checkBox.setActionCommand(type.getName()); checkBox.addActionListener(this); boxes.put(type, checkBox); filter.add(checkBox); } }
39bd7bda-19c6-416d-a337-292344a47153
6
public StringBuffer getOOXML() { StringBuffer cooxml = new StringBuffer(); cooxml.append( "<c:view3D>" ); cooxml.append( "\r\n" ); // rotX == anElev if( anElev != 0 ) // default { cooxml.append( "<c:rotX val=\"" + anElev + "\"/>" ); } // hPercent -- a height percent between 5 and 500. // rotY == anRot if( (anRot != 0) || (anElev != 0) ) // default { cooxml.append( "<c:rotY val=\"" + anRot + "\"/>" ); } // depthPercentage -- This element specifies the depth of a 3-D chart as a percentage of the chart width (between 20 and 2000 percent). if( pcDepth != 100 ) { cooxml.append( "<c:depthPercent val=\"" + pcDepth + "\"/>" ); } // rAngAx == !fPerspective if( fPerspective ) { cooxml.append( "<c:rAngAx val=\"1\"/>" ); } // perspective == pcDist if( pcDist != 30 ) // default { cooxml.append( "<c:perspective val=\"" + pcDist + "\"/>" ); } cooxml.append( "</c:view3D>" ); cooxml.append( "\r\n" ); return cooxml; }
1043756e-3122-4a5f-b978-bec2d4d8de2f
8
protected Tuple fetchNext() throws TransactionAbortedException, DbException { /*while (hasMoreChild1Tuples) { while (hasMoreChild2Tuples) { // Loop through every child1 tuple in the cached page for (int i = child1Index; i < child1Max; i++) { Tuple child1Tuple = child1Tuples[i]; // Loop through every child2 tuple in the cached page for (int j = child2Index; j < child2Max; j++) { Tuple child2Tuple = child2Tuples[j]; if (p.filter(child1Tuple, child2Tuple)) { Tuple mergedTuple = new Tuple(getTupleDesc()); int numFieldsFromChild1 = child1Tuple.getTupleDesc().numFields(); for (int k = 0; k < numFieldsFromChild1; k++) { mergedTuple.setField(k, child1Tuple.getField(k)); } for (int k = 0; k < child2Tuple.getTupleDesc().numFields(); k++) { mergedTuple.setField(k + numFieldsFromChild1, child2Tuple.getField(k)); } child1Index = i; child2Index = j + 1; return mergedTuple; } } child2Index = 0; } // If we went through every tuple in the cached child1 page and compared // them with every tuple from the cached child2 page, get next child2 page loadMoreChild2Tuples(); } // If we went through every child2 page for this child1 page, load a new // child1 page and reset the child2 page back to the beginning child2.rewind(); loadMoreChild1Tuples(); loadMoreChild2Tuples(); } // If we went through every tuple in all pages, return null return null;*/ // We'll keep child1Tuple as our 'persistent' tuple from last iteration // If we still have child2 tuples to go through for this child1 tuple while (child1.hasNext() || child1Tuple != null) { if (child1Tuple != null) { // Then go through each child2 tuple until we find one which matches while (child2.hasNext()) { Tuple child2Tuple = child2.next(); if (p.filter(child1Tuple, child2Tuple)) { Tuple mergedTuple = new Tuple(getTupleDesc()); int numFieldsFromChild1 = child1Tuple.getTupleDesc().numFields(); for (int i = 0; i < numFieldsFromChild1; i++) { mergedTuple.setField(i, child1Tuple.getField(i)); } for (int i = 0; i < child2Tuple.getTupleDesc().numFields(); i++) { mergedTuple.setField(i + numFieldsFromChild1, child2Tuple.getField(i)); } return mergedTuple; } } // If we run out of child2 tuples, rewind so that we can check the next child1 tuple child2.rewind(); } if (child1.hasNext()) { child1Tuple = child1.next(); } else { break; } } // Lastly, we're out of tuples for child1 and child2 return null; }
4a3ac643-aa9b-4eff-a341-691a5a675c4b
9
protected void runTestOnData(Instances data) { // count numeric atts int numeric = 0; for (int n = 0; n < data.numAttributes(); n++) { if (data.attribute(n).isNumeric()) numeric++; } // perform tests for (int n = 0; n < data.numInstances(); n++) { try { AlgVector v = new AlgVector(data.instance(n)); // 1. is length correct? assertEquals((n+1) + ": length differs", numeric, v.numElements()); // 2. are values correct? int index = 0; for (int i = 0; i < data.numAttributes(); i++) { if (!data.attribute(i).isNumeric()) continue; assertEquals((n+1) + "/" + (i+1) + ": value differs", data.instance(n).value(i), v.getElement(index)); index++; } // 3. is instance returned correct? Instance inst = v.getAsInstance(data, new Random(1)); for (int i = 0; i < data.numAttributes(); i++) { if (!data.attribute(i).isNumeric()) continue; assertEquals((n+1) + "/" + (i+1) + ": returned value differs", data.instance(n).value(i), inst.value(i)); } } catch (Exception e) { if (!(e instanceof IllegalArgumentException)) fail(e.toString()); } } }
ca4ccd73-40cb-4d0d-b7d9-d482f714351f
8
public void process(ByteBuffer _buffer) { int messageType = _buffer.getInt(); Response response; switch (messageType) { case Response.MSG_CLIENT_REGISTER: _LOGGER.log(Level.FINE, "MSG_CLIENT_REGISTER"); response = registerClient(_buffer.getInt()); response.serialize(_buffer); break; case Response.MSG_CLIENT_DEREGISTER: _LOGGER.log(Level.FINE, "MSG_CLIENT_DEREGISTER"); response = deregisterClient(_buffer.getInt()); response.serialize(_buffer); break; case Response.MSG_QUEUE_CREATE: _LOGGER.log(Level.FINE, "MSG_QUEUE_CREATE"); response = createQueue(_buffer.getInt()); response.serialize(_buffer); break; case Response.MSG_QUEUE_GET: _LOGGER.log(Level.FINE, "MSG_QUEUE_GET"); response = getQueue(_buffer.getInt()); response.serialize(_buffer); break; case Response.MSG_QUEUE_DELETE: _LOGGER.log(Level.FINE, "MSG_QUEUE_DELETE"); response = deleteQueue(_buffer.getInt()); response.serialize(_buffer); break; case Response.MSG_QUEUE_ENQUEUE: _LOGGER.log(Level.FINE, "MSG_QUEUE_ENQUEUE"); response = enqueueMessage(_buffer); response.serialize(_buffer); break; case Response.MSG_QUEUE_DEQUEUE: _LOGGER.log(Level.FINE, "MSG_QUEUE_DEQUEUE"); response = dequeueMessage(_buffer); response.serialize(_buffer); break; case Response.MSG_GET_WAITING_QUEUES: _LOGGER.log(Level.FINE, "MSG_GET_WAITING_QUEUES"); response = getWaitingQueues(_buffer.getInt()); response.serialize(_buffer); break; } _LOGGER.log(Level.FINE, "End of execution engine process"); }
5d21d5f7-6113-44aa-85c9-dd49960b08fd
9
protected static Inet6Address getScopedInetAddress(Inet6Address addr) { if(addr == null) return null; Enumeration<NetworkInterface> en; List<InetAddress> retval=new ArrayList<>(); try { en=NetworkInterface.getNetworkInterfaces(); while(en.hasMoreElements()) { NetworkInterface intf=en.nextElement(); Enumeration<InetAddress> addrs=intf.getInetAddresses(); while(addrs.hasMoreElements()) { InetAddress address=addrs.nextElement(); if(address.isLinkLocalAddress() && address instanceof Inet6Address && address.equals(addr) && ((Inet6Address)address).getScopeId() != 0) { retval.add(address); } } } if(retval.size() == 1) { return (Inet6Address)retval.get(0); } else return null; } catch(SocketException e) { return null; } }
64c9b0ef-73c7-43b1-b1f4-5bbc821a7e82
7
public static commandReturn findCommand(String data){ commandReturn RETURN = new commandReturn(); if(data.indexOf("{COMMAND}") != -1){ String[] commandSplit; String commandNum; String[] commandParams = new String[0]; String commandOther; commandSplit = data.split("::"); commandNum = removeBrackets(commandSplit[1]); if(commandSplit.length > 2){ String params = removeBrackets(commandSplit[2]); if(commandSplit[2].contains("|")) { commandParams = params.split("\\|"); } else{ commandParams = new String[1]; commandParams[0] = params; } if(commandSplit.length > 3){ commandOther = commandSplit[3]; } } //Switch commands here switch (Integer.parseInt(commandNum)){ case 100: RETURN.TYPE = commandType.LOGIN; RETURN.message = commandParams[0]; break; case 101: RETURN.TYPE = commandType.PING; break; case 102: RETURN.TYPE = commandType.SENDTORRENT; break; default: RETURN.TYPE = commandType.MESSAGE; RETURN.message=commandParams[0]; break; } } return RETURN; }
bbcb8161-90ed-4ee2-b368-46ba5c8541c9
9
private static String docidFromURL(URL url) throws HostNoGV, NoQuery, NoDocId, DocIdInvalid { /** Google Video */ String queryURL; int startDocId, endDocId; if ((url.getHost() == null) || (url.getHost().indexOf("video.google.com") == -1)) { throw new HostNoGV(); } if ((queryURL = url.getQuery()) == null) { throw new NoQuery(); } if ((startDocId = queryURL.indexOf("docid=")) == -1) { throw new NoDocId(); } startDocId += "docid=".length(); endDocId = startDocId; if ((endDocId == queryURL.length()) || !((Character.isDigit(queryURL.charAt(endDocId))) || (queryURL.charAt(endDocId) == '-'))) { throw new DocIdInvalid(); } endDocId++; while ((endDocId < queryURL.length()) && (Character.isDigit(queryURL.charAt(endDocId)))) endDocId++; return queryURL.substring(startDocId, endDocId); }
e9cfc8cb-62fb-4bd4-9d15-c2c5ac7fdcc6
9
protected static Ptg calcQuartile( Ptg[] operands ) { Ptg[] aveoperands = new Ptg[1]; aveoperands[0] = operands[0]; Ptg[] allVals = PtgCalculator.getAllComponents( aveoperands ); CompatibleVector t = new CompatibleVector(); double retval = 0; for( Ptg p : allVals ) { try { Double d = new Double( String.valueOf( p.getValue() ) ); t.addOrderedDouble( d ); } catch( NumberFormatException e ) { log.error( "calcQuartile error", e ); } } Double[] dub = new Double[t.size()]; t.toArray( dub ); Integer quart; Object o = operands[1].getValue(); if( o instanceof Integer ) { quart = (Integer) operands[1].getValue(); } else { quart = ((Double) operands[1].getValue()).intValue(); } float quartile = quart.floatValue(); if( quart == 0 ) { // return minimum value return new PtgNumber( dub[0] ); } if( quart == 4 ) { // return maximum value return new PtgNumber( dub[t.size() - 1] ); } if( (quart > 4) || (quart < 0) ) { return new PtgErr( PtgErr.ERROR_NUM ); } // find the kth smallest float kk = quartile / 4; kk = (dub.length - 1) * kk; kk++; // truncate k, but keep the remainder. int k = -1; float remainder = 0; if( (kk % 1) != 0 ) { remainder = kk % 1; String s = String.valueOf( kk ); String ss = s.substring( s.indexOf( "." ), s.length() ); ss = "0" + ss; remainder = new Float( ss ); s = s.substring( 0, s.indexOf( "." ) ); k = Integer.valueOf( String.valueOf( s ) ); } else { k = (int) kk / 1; } if( k >= dub.length ) { return new PtgErr( PtgErr.ERROR_VALUE ); } double firstVal = dub[k - 1]; double secondVal = dub[k]; double output = firstVal + (remainder * (secondVal - firstVal)); PtgNumber pn = new PtgNumber( output ); return pn; }
f4a5c244-78d0-4571-ab7a-a46dcb61aa12
3
public void visit_dup_x1(final Instruction inst) { // 0 1 -> 1 0 1 if (Tree.USE_STACK) { saveStack(); final StackExpr s1 = (StackExpr) stack.pop1(); final StackExpr s0 = (StackExpr) stack.pop1(); final StackExpr[] s = new StackExpr[] { s0, s1 }; manip(s, new int[] { 1, 0, 1 }, StackManipStmt.DUP_X1); } else { final Expr s1 = stack.pop1(); final Expr s0 = stack.pop1(); final LocalExpr t0 = newStackLocal(stack.height(), s0.type()); final LocalExpr t1 = newStackLocal(stack.height() + 1, s1.type()); if (!t0.equalsExpr(s0)) { addStore(t0, s0); } if (!t1.equalsExpr(s1)) { addStore(t1, s1); } Expr copy = (Expr) t1.clone(); copy.setDef(null); stack.push(copy); copy = (Expr) t0.clone(); copy.setDef(null); stack.push(copy); copy = (Expr) t1.clone(); copy.setDef(null); stack.push(copy); } }
619dd280-5105-4b86-9a05-027d98ddf3ae
2
public List<Book> displayAll() { List<Book> bookList = new ArrayList<Book>(); try { // Erforderlicher SQL-Befehl String sqlStatement = "SELECT * FROM bookworm_database.books;"; // SQL-Befehl wird ausgeführt myResultSet = mySQLDatabase.executeSQLQuery(sqlStatement); while (myResultSet.next()) { bookList.add(new Book(myResultSet.getString(1), myResultSet .getString(2), myResultSet.getString(3), myResultSet .getString(4), myResultSet.getString(5), myResultSet .getString(6), myResultSet.getString(7), myResultSet .getString(8), myResultSet.getString(9), myResultSet .getString(10))); } } catch (Exception e) { System.out.println(e.toString()); // Ein Dialogfenster mit entsprechender Meldung soll erzeugt werden String errorText = "Datenbankabfrage konnte nicht durchgeführt werden."; errorMessage.showMessage(errorText); } finally { // offene Verbindungen werden geschlossen mySQLDatabase.closeConnections(); } return bookList; }
bf4e43b9-d8d9-48ee-9aaf-1563e501d88e
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(UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(UI.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 UI().setVisible(true); } }); }
a499825c-b18c-4cb5-8d61-8ac6b9106d59
6
protected int getAddressingMethod(String code) { if (this.register.equalsIgnoreCase("0")) { this.isIndexed = false; } else { this.isIndexed = true; } if (code.indexOf("*") == -1) { this.isIndirect = false; } else { this.isIndirect = true; } if ((this.isIndirect) || (this.isIndexed)) { if (this.isIndexed) { if (this.isIndirect) { return 3; } return 1; } return 2; } return 0; }
b5b2860d-0613-43c6-83e8-11edafc5e658
9
public void affectEntity(EntityLiving par1EntityLiving, EntityLiving par2EntityLiving, int par3, double par4) { int var6; if ((this.id != heal.id || par2EntityLiving.isEntityUndead()) && (this.id != harm.id || !par2EntityLiving.isEntityUndead())) { if (this.id == harm.id && !par2EntityLiving.isEntityUndead() || this.id == heal.id && par2EntityLiving.isEntityUndead()) { var6 = (int)(par4 * (double)(6 << par3) + 0.5D); if (par1EntityLiving == null) { par2EntityLiving.attackEntityFrom(DamageSource.magic, var6); } else { par2EntityLiving.attackEntityFrom(DamageSource.causeIndirectMagicDamage(par2EntityLiving, par1EntityLiving), var6); } } } else { var6 = (int)(par4 * (double)(6 << par3) + 0.5D); par2EntityLiving.heal(var6); } }
a74608c1-b228-48d2-9a28-bd4104f309e8
3
public void addPalavra(String palavra, int numLinha) { int existepalavra = 0; for (Palavra listaPalavra : listaPalavras) { if (listaPalavra.getPalavra().equalsIgnoreCase(palavra)) { listaPalavra.addLinha(numLinha); existepalavra++; } } if(existepalavra == 0) { Palavra novaPalavra = new Palavra(palavra); novaPalavra.addLinha(numLinha); listaPalavras.add(novaPalavra); } }
ebe96ca6-c3c5-4b89-b737-cf92d14ec9c5
4
public static DocumentInfo getDocumentInfo(String pathname) { // Handle an invalid pathname if (pathname == null) { return null; } // Check all the recent files for (int i = 0, limit = frameInfoList.size(); i < limit; i++) { DocumentInfo docInfo = (DocumentInfo) frameInfoList.get(i); if (docInfo == null) { continue; } if (PropertyContainerUtil.propertyEqualsAsString(docInfo, DocumentInfo.KEY_PATH, pathname)) { return docInfo; } } return null; }
3ef9e77f-c0e3-4f3c-bfb1-67f98770c5ed
3
public void addTemplateFields(String initial, String rule, String encoding) throws IOException { LinkedHashMap<String, String> updatingRequestField = requestFields .get(initial); if (updatingRequestField == null) throw new IOException(); if (rule.split("=").length == 1 || encoding.split(":").length == 1) throw new IOException(); updatingRequestField.put(rule, encoding); requestFields.put(initial, updatingRequestField); }
a22e67ec-1117-4837-918f-2e1ab362193b
9
public int[] retornarCoordenadaDe(int idObjeto){ int[] posicion=null; for(int i=0;i<dimension;i++){ for(int j=0;j<dimension;j++){ if(matriz[i][j]==idObjeto){ posicion=new int[2]; posicion[0]=i; posicion[1]=j; return posicion; }else if((idObjeto == ID_ROBOT || idObjeto == ID_SITIO_UNO ) && matriz[i][j]==ID_SITIO_UNO_CON_ROBOT){ posicion=new int[2]; posicion[0]=i; posicion[1]=j; return posicion; }else if((idObjeto == ID_ROBOT || idObjeto == ID_SITIO_DOS ) && matriz[i][j]==ID_SITIO_DOS_CON_ROBOT){ posicion=new int[2]; posicion[0]=i; posicion[1]=j; return posicion; } } } return posicion; }
701004cc-9fdc-4dc3-8d76-e5f3986d19dc
9
public static int determineSeed(Output output, ParameterDatabase parameters, Parameter seedParameter, long currentTime, int offset, boolean auto) { int seed = 1; // have to initialize to make the compiler happy String tmp_s = parameters.getString(seedParameter,null); if (tmp_s==null && !auto) // uh oh { output.fatal("Seed must exist.",seedParameter,null); } else if (V_SEED_TIME.equalsIgnoreCase(tmp_s) || (tmp_s == null && auto)) { if (tmp_s == null && auto) output.warnOnce("Using automatic determination number of threads, but not all seeds are defined.\nThe rest will be defined using the wall clock time."); seed = (int)currentTime; // using low-order bits so it's probably okay if (seed==0) output.fatal("Whoa! This Java version is returning 0 for System.currentTimeMillis(), which ain't right. This means you can't use '"+V_SEED_TIME+"' as a seed ",seedParameter,null); } else { try { seed = parameters.getInt(seedParameter,null); } catch (NumberFormatException e) { output.fatal("Invalid, non-integer seed value ("+seed+")",seedParameter,null); } } return seed + offset; }
0b9edccc-f9da-4c74-b8bf-1c331a035660
2
private static void subarray(int i, int j) { // TODO Auto-generated method stub int l=0,m=0; int k=1,n=1; int whowin = none; for(l = 3*i-2 ;l<3*i+1;l++ ){ n=1; for(m = 3*j-2;m<3*j+1;m++){ currentarray[k][n] = totalarray[l][m]; n++; } k++; } whowin = checkarray(currentarray,cross); whowin = checkarray(currentarray,zero); System.out.print(whowin); bigarraydecision[i][j] = whowin; }
a3335ca5-7803-4f92-91d7-d87f53d6b316
8
@Override public Screen respondToUserInput(KeyEvent key) { switch (key.getKeyCode()) { case KeyEvent.VK_NUMPAD4: player.moveBy(-1,0); break; case KeyEvent.VK_NUMPAD6: player.moveBy(1,0); break; case KeyEvent.VK_NUMPAD8: player.moveBy(0,-1); break; case KeyEvent.VK_NUMPAD2: player.moveBy(0,1); break; case KeyEvent.VK_NUMPAD7: player.moveBy(-1,-1); break; case KeyEvent.VK_NUMPAD9: player.moveBy(1,-1); break; case KeyEvent.VK_NUMPAD1: player.moveBy(-1,1); break; case KeyEvent.VK_NUMPAD3: player.moveBy(1,1); break; } dungeon.update(); return this; }
4c9713f3-b74f-49c0-8444-82bfef9e6d5e
0
public InfoRequest addEmail(String email) { emails.add(new EmailContainer(email)); return this; }
8e18398e-71ab-4435-8437-c42cac1e915c
9
void generate() { if (rootDoc == null || outputdir == null) { return; } PackageDoc[] pds = rootDoc.specifiedPackages(); for (int i = 0; i < pds.length; i++) { // If -nodeprecated option is set and the package is marked as deprecated, // do not convert the package files to HTML. if (!(configuration.nodeprecated && Util.isDeprecated(pds[i]))) convertPackage(pds[i], outputdir); } ClassDoc[] cds = rootDoc.specifiedClasses(); for (int i = 0; i < cds.length; i++) { // If -nodeprecated option is set and the class is marked as deprecated // or the containing package is deprecated, do not convert the // package files to HTML. if (!(configuration.nodeprecated && (Util.isDeprecated(cds[i]) || Util.isDeprecated(cds[i].containingPackage())))) convertClass(cds[i], outputdir); } }
419b4965-e4ab-42fc-b350-ffc3267c19dc
9
private void finalizarLlegada(int input, int output) { TorniqueteDAO dao = new TorniqueteDAO(); boolean verif = dao.registrarActualizar(GUI2.torniquete_id); boolean verifHora = dao.registrarActualizarHora(GUI2.torniquete_id); boolean verifDia = dao.registrarActualizarDia(GUI2.torniquete_id); boolean verifMes = dao.registrarActualizarMes(GUI2.torniquete_id); boolean verifAnio = dao.registrarActualizarAnio(GUI2.torniquete_id); boolean verifTodosDia = dao.registrarActualizarTodosDia(); int entradaRegistrar = 0; int salidaRegistrar = 0; if (entrada.indexOf("S011000000000E") != -1) salidaRegistrar = 1; else if (entrada.indexOf("S010000000000E") != -1) entradaRegistrar = 1; else if (entrada.indexOf("S006") != -1) { entradaRegistrar = input; salidaRegistrar = output; } dao.addContador(GUI2.torniquete_id, entradaRegistrar, salidaRegistrar); if (verif) dao.contar(GUI2.torniquete_id, GUI2.Fecha, entradaRegistrar, salidaRegistrar); else dao.inOut(GUI2.torniquete_id, GUI2.Fecha, entradaRegistrar, salidaRegistrar); if (verifHora) dao.contarHora(GUI2.torniquete_id, GUI2.Fecha.substring(0, GUI2.Fecha.length() - 5) + "00", entradaRegistrar, salidaRegistrar); else dao.inOutHora(GUI2.torniquete_id, GUI2.Fecha.substring(0, GUI2.Fecha.length() - 5) + "00", entradaRegistrar, salidaRegistrar); if (verifDia) dao.contarDia(GUI2.torniquete_id, GUI2.Fecha.substring(0, GUI2.Fecha.length() - 9), entradaRegistrar, salidaRegistrar); else dao.inOutDia(GUI2.torniquete_id, GUI2.Fecha.substring(0, GUI2.Fecha.length() - 9), entradaRegistrar, salidaRegistrar); if (verifMes) dao.contarMes(GUI2.torniquete_id, GUI2.Fecha.substring(0, GUI2.Fecha.length() - 12), entradaRegistrar, salidaRegistrar); else dao.inOutMes(GUI2.torniquete_id, GUI2.Fecha.substring(0, GUI2.Fecha.length() - 12), entradaRegistrar, salidaRegistrar); if (verifAnio) dao.contarAnio(GUI2.torniquete_id, GUI2.Fecha.substring(0, GUI2.Fecha.length() - 15), entradaRegistrar, salidaRegistrar); else dao.inOutAnio(GUI2.torniquete_id, GUI2.Fecha.substring(0, GUI2.Fecha.length() - 15), entradaRegistrar, salidaRegistrar); if (verifTodosDia) dao.contarTodosDias(GUI2.Fecha.substring(0, GUI2.Fecha.length() - 9), entradaRegistrar, salidaRegistrar); else dao.inOutTodosDias(GUI2.Fecha.substring(0, GUI2.Fecha.length() - 9), entradaRegistrar, salidaRegistrar); entrada = ""; dao.desconectar(); }
0cbb2e60-8d0a-44b2-8825-4d35fde2a641
1
public void transform(InputStream xmlSourceStream, InputStream xslSourseStream, OutputStream resultStream) { try { Source xmlSource = new StreamSource(xmlSourceStream); Source xsltSource = new StreamSource(xslSourseStream); TransformerFactory transFact = TransformerFactory.newInstance(); Transformer trans = transFact.newTransformer(xsltSource); trans.transform(xmlSource, new StreamResult(resultStream)); } catch (TransformerException e) { e.printStackTrace(); } }
c611c6d3-d8f0-443a-8f3f-3888023334d5
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."); }
f7d1dfae-6dc0-471b-8235-ce25f18cdc86
7
private int getScore(Point[] points) { int playerone=0; int playertwo=0; for(int i=0;i<points.length;i++) { if(points[i].getState()==Board.PLAYER_ONE) { playerone++; } else if(points[i].getState()==Board.PLAYER_TWO) { playertwo++; } } if(playerone>0 && (playertwo==0)) { //The score is returned as positive for player one and negative for player two (convention) return playerone; } if(playertwo>0 && (playerone==0)) { return -playertwo; } return 0; }
2abcd4b6-0766-41c1-baa8-b690ee52ba68
7
public void run(){ try{ Display.setDisplayMode(new DisplayMode(800,600)); Display.setVSyncEnabled(true); Display.create(); Display.setFullscreen(true); Camera.setCurrentCamera(new Camera(0, 2, 0, 0,0,0)); initGL(); getDelta(); // call once before loop to initialise lastFrame lastFPS = getTime(); // call before loop to initialise fps timer while(!Display.isCloseRequested() && !Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); Camera.Tick(); KeyListener.Tick(); MouseListener.Tick(); KL2.tick(); //Trip Mode! RainbowR +=0.05f; RainbowG +=0.1f; RainbowB +=0.15f; if(RainbowR > 1f){ RainbowR = -1f; } if(RainbowG > 1f){ RainbowG = -1f; } if(RainbowB > 1f){ RainbowB = -1f; } if(KL2.Rainbow == true){ ProjectSyrup.getKirby().setBodyColor(Rendering.RainbowR, Rendering.RainbowG, Rendering.RainbowB); ProjectSyrup.getKirby().setShoeColor(Rendering.RainbowR, Rendering.RainbowG, Rendering.RainbowB); } // -- // renderTick(); updateFPS(); Display.sync(60); Display.update(); } }catch(Exception err){ err.printStackTrace(); System.exit(0); } }
4a611e2c-0d3b-4a2b-ab7a-77084afb671b
9
public void mouseReleased(MouseEvent mouseEvent) { if (treePane.getDragRectangle() != null) { Set<Node> selectedNodes = treePane.getNodesAt((Graphics2D) treePane.getGraphics(), treePane.getDragRectangle().getBounds()); if (!mouseEvent.isShiftDown()) { treePane.clearSelection(); } SelectionMode mode = selectionMode; if (mouseEvent.isAltDown()) { if (mode == SelectionMode.NODE) { mode = SelectionMode.CLADE; } else if (mode == SelectionMode.CLADE) { mode = SelectionMode.NODE; } } for (Node selectedNode : selectedNodes) { switch (mode) { case NODE: treePane.addSelectedNode(selectedNode, true); break; case CLADE: treePane.addSelectedClade(new Node[]{selectedNode, null}, true); break; case TAXA: treePane.addSelectedTaxa(selectedNode); break; default: throw new IllegalArgumentException("Unknown SelectionMode: " + selectionMode.name()); } } } treePane.setDragRectangle(null); }
c10cdc12-d6d8-4008-80b8-6aa4cab1d8a7
3
private static String getDir(String paramString) { if (paramString == null) { return null; } File localFile = new File(paramString); if ((localFile.isDirectory()) && (localFile.canRead())) { return localFile.getAbsolutePath(); } return null; }
09254e0d-33bd-4526-a196-1ca108e3ffe8
7
public static void main(String[] args){ EntityManagerFactory emf; EntityManager em; emf= Persistence.createEntityManagerFactory("colectivos.odb"); em= emf.createEntityManager(); //A CONTINUACION SE CARGAN CIUDADES Ciudad ciu; int i; String[] ciudades = {"Yaguarón", "Paraguarí", "Carapeguá", "Quiindy", "Caapucú", "Villa Florida", "San Miguel", "San Juan", "San Ignacio", "Santa Rosa", "San Patricio", "Santiago", "Ayolas", "General Delgado", "Coronel Bogado", "Carmen del Paraná", "Encarnación", "Hohenau", "Obligado", "María Auxiliadora" }; for(i=0; i < ciudades.length;i++){ em.getTransaction().begin(); ciu= new Ciudad(ciudades[i]); if(i<9){ ciu.setOrden("0"+(i+1)+""); }else{ ciu.setOrden(""+(i+1)+""); } em.persist(ciu); em.getTransaction().commit(); if(i%10==0 ){ System.out.println("mod 10"); em.flush(); em.clear(); } } //A CONTINUACION SE GENERAN TRAYECTOS Trayecto tr; for(i=0; i < 4;i++){ em.getTransaction().begin(); tr= new Trayecto(); em.persist(tr); em.getTransaction().commit(); } //SE ASIGNAN CIUDADES A TRAYECTOS tr= em.find(Trayecto.class, 1); for(i=1; i < 6;i++){ ciu= em.find(Ciudad.class, i); em.getTransaction().begin(); tr.getCiudades().add(ciu); em.getTransaction().commit(); } tr= em.find(Trayecto.class, 2); for(i=6; i < 12;i++){ ciu= em.find(Ciudad.class, i); em.getTransaction().begin(); tr.getCiudades().add(ciu); em.getTransaction().commit(); } tr= em.find(Trayecto.class, 3); for(i=14; i < 21;i++){ ciu= em.find(Ciudad.class, i); em.getTransaction().begin(); tr.getCiudades().add(ciu); em.getTransaction().commit(); } em.close(); emf.close(); }
bfa6a952-2d76-4e38-9dd2-9288679032ad
6
@Override protected boolean process(Token token) { // start tag, end tag, doctype, comment, character, eof switch (token.type) { case StartTag: insert(token.asStartTag()); break; case EndTag: popStackToClose(token.asEndTag()); break; case Comment: insert(token.asComment()); break; case Character: insert(token.asCharacter()); break; case Doctype: insert(token.asDoctype()); break; case EOF: // could put some normalisation here if desired break; default: Validate.fail("Unexpected token type: " + token.type); } return true; }
11fe6838-4adb-4be2-9209-5f5a23a51771
2
public void calculate_pcm_samples(Obuffer buffer) { compute_new_v(); compute_pcm_samples(buffer); actual_write_pos = (actual_write_pos + 1) & 0xf; actual_v = (actual_v == v1) ? v2 : v1; // initialize samples[]: //for (register float *floatp = samples + 32; floatp > samples; ) // *--floatp = 0.0f; // MDM: this may not be necessary. The Layer III decoder always // outputs 32 subband samples, but I haven't checked layer I & II. for (int p=0;p<32;p++) samples[p] = 0.0f; }
050bf1cb-ca85-4a7e-b10a-1b66de7bca23
6
public void drawModel(Graphics2D graphics, Actor actor, Color color) { Model model = actor.getModel(); if (model == null || !model.isValid()) return; Vec3[][] vectors = model.getVectors(); graphics.setColor(color); int gx = actor.getLocation().getGx(); int gy = actor.getLocation().getGy(); for (Vec3[] points : vectors) { Vec3 pa = points[0]; Vec3 pb = points[1]; Vec3 pc = points[2]; Point a = Perspective.trans_tile_cam(getContext().getClient(), gx + (int) pa.x, gy + (int) pc.x, 0 - (int) pb.x); Point b = Perspective.trans_tile_cam(getContext().getClient(), gx + (int) pa.y, gy + (int) pc.y, 0 - (int) pb.y); Point c = Perspective.trans_tile_cam(getContext().getClient(), gx + (int) pa.z, gy + (int) pc.z, 0 - (int) pb.z); if (Perspective.on_screen(a) && Perspective.on_screen(b) && Perspective.on_screen(c)) { graphics.drawPolygon(new Polygon(new int[] { a.x, b.x, c.x }, new int[] { a.y, b.y, c.y }, 3)); } } }
98d8c5b4-caa2-480c-87c8-52d4efc622aa
5
@Override protected void inspectContents(File file, String contents) { StringBuffer buf = new StringBuffer(); // Split it into lines StringSplitter splitter = new StringSplitter(contents, getLineEnding()); // Scan each line int totalMatchesForThisFile = 0; int lineCount = 1; while (splitter.hasMoreElements()) { String line = (String) splitter.nextElement(); boolean keepLooking = true; int indexStart = 0; do { int index = line.indexOf(query, indexStart); if (index == -1) { keepLooking = false; } else { totalMatchesForThisFile++; totalNumberOfMatches++; buf.append(" line: " + lineCount + " position: " + index + getLineEnding()); indexStart = index + query.length(); } } while (keepLooking); lineCount++; } // Output the results if (totalMatchesForThisFile > 0) { if (totalMatchesForThisFile == 1) { System.out.println("Found " + totalMatchesForThisFile + " match in file: " + file.getPath()); } else { System.out.println("Found " + totalMatchesForThisFile + " matches in file: " + file.getPath()); } System.out.print(buf.toString()); System.out.println(""); } }
6e907025-28ad-41b6-9759-8f16d78c6293
4
public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); String[] cards = {"2","3","4","5","6","7","8","9","10","J","Q","K","A"}; String[] faces = {"♣","♦","♥","♠"}; String[] allCards = new String[52]; int caunt = 0; Random random = new Random(51); int randomNum = 0; for (int i = 0; i < cards.length; i++) { for (int j = 0; j < faces.length; j++) { allCards[caunt] = cards[i] + faces[j]; caunt++; } } for (int i = 0; i < n; i++) { for (int j = 0; j < 5; j++) { randomNum = random.nextInt(51); System.out.print(" " + allCards[randomNum]); } System.out.println(); } }
8da78130-b4e9-4d19-93b9-4288ed33ef62
2
public Iterable<String> keysWithPrefix(String prefix) { Queue<String> queue = new Queue<String>(); Node<Value> x = get(root, prefix, 0); if (x == null) return queue; if (x.val != null) queue.enqueue(prefix); collect(x.mid, new StringBuilder(prefix), queue); return queue; }
57870106-236f-49e6-ac07-a801ed27f61d
2
private int setToBeHuffed(){ FactoryOfPlays factory = new FactoryOfPlaysForPlayer(player); if (factory.isEmpty()) return 0; AbstractPlay bestPlay = factory.getBest(); int max = bestPlay.eatNumber(); if (max > 0) player.getBoard().getPiece(bestPlay.getStart()).setHuff(true); return max; }
da806991-10ca-406c-b5d9-75bc32df6706
9
private void pathRek(int x, int y,String path) { if(matrix[y][x]==0) { alignmentPrint(path, y, x); //System.out.println(path); } else { if(y==0) { String temp=path+"I"; pathRek(x-1,y,temp); } if(x==0) { String temp=path+"D"; pathRek(x,y-1,temp); } else { if(matrix[y][x-1]+effort[0]==matrix[y][x]) { String temp=path+"I"; pathRek(x-1,y,temp); } if(matrix[y-1][x]+effort[1]==matrix[y][x]) { String temp=path+"D"; pathRek(x,y-1,temp); } if(matrix[y-1][x-1]+effort[2]==matrix[y][x] && p[y-1]!=t[x-1]) { String temp=path+"R"; pathRek(x-1,y-1,temp); } if(matrix[y-1][x-1]+effort[3]==matrix[y][x] && p[y-1]==t[x-1]) { String temp=path+"M"; pathRek(x-1,y-1,temp); } } } }
80009d83-47e4-441a-8e6b-c696b89eddcb
0
public void setRows(int rows) { this.rows = rows; }
620947bf-2093-47dc-9b13-2b7361316a73
6
public EFontAlign mirror(boolean h, boolean v) { return pos[x == 1 ? 1 : (h ? (x == 0 ? 2 : 0) : x)][y == 1 ? 1 : (v ? (y == 0 ? 2 : 0) : y)]; }
c953dce1-f6ae-4ec9-99d4-3045b0c1164d
1
@RequestMapping(value = "/login", method = RequestMethod.POST) public ModelAndView loginUser(@RequestParam String userId, @RequestParam String password, @RequestParam int department, HttpServletResponse response) { ModelAndView modelAndView = new ModelAndView(); String result = service.login(userId, password, department); modelAndView.addObject("response", result); if (result.equals(ResponseMessages.LOGIN_SUCCESSFUL)) { response.addCookie(new Cookie("System-Cookie", RandomStringUtil .getRandomCookieValue())); Cookie userIdCookie = new Cookie("userid", userId); userIdCookie.setMaxAge(24 * 60 * 60); response.addCookie(userIdCookie); service.postLogin(userId, modelAndView); Employee employee = (Employee) modelAndView.getModelMap().get( "employee_details"); Cookie userNameCookie = new Cookie("user_name", employee.getEmployeeName()); Cookie managerCookie = new Cookie("manager_id", employee.getManagerId()); managerCookie.setMaxAge(24 * 60 * 60); userIdCookie.setMaxAge(24 * 60 * 60); response.addCookie(userNameCookie); response.addCookie(managerCookie); } return modelAndView; }
b57042d7-2940-4965-b213-068d777f35d2
2
public void testPropertyAddNoWrapMinute() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.minuteOfHour().addNoWrapToCopy(9); check(test, 10, 20, 30, 40); check(copy, 10, 29, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(39); check(copy, 10, 59, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(40); check(copy, 11, 0, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(1 * 60 + 45); check(copy, 12, 5, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(13 * 60 + 39); check(copy, 23, 59, 30, 40); try { test.minuteOfHour().addNoWrapToCopy(13 * 60 + 40); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(-9); check(copy, 10, 11, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(-19); check(copy, 10, 1, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(-20); check(copy, 10, 0, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(-21); check(copy, 9, 59, 30, 40); copy = test.minuteOfHour().addNoWrapToCopy(-(10 * 60 + 20)); check(copy, 0, 0, 30, 40); try { test.minuteOfHour().addNoWrapToCopy(-(10 * 60 + 21)); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); }
036003b7-d096-44b1-964d-86a1d812b3ea
7
public void backspace() { TextGrid.DataGridCel cel; // Do nothing if we are at the beginning if (rowOffset + colOffset + currentCol + currentRow == 0) { return; } if ((currentCol + colOffset) == 0 && (currentRow + rowOffset) != 0) { // Get a \n in the previous line (user pressed backspace at the first character of the line) cel = grid.getCel(currentRow + rowOffset - 1, grid.getLineLength(currentRow + rowOffset - 1)); if (currentRow > 0) { // Move cursor upwards currentRow--; } else { // Move up if we are at the top scrollUp(); } // Go at the end of line end(); int hack = colOffset; if (cel == null) { cel = grid.getCel(currentRow + rowOffset, currentCol - 1); } while (cel.getCharacter() != 0x0a) { cel = grid.getCel(currentRow + rowOffset, hack); hack++; } } else { // Get a single character cel = grid.getCel(currentRow + rowOffset, currentCol + colOffset - 1); if (colOffset > 0) { colOffset--; } else { currentCol--; } } // Remove the character grid.removeChar(cel.getBufferIndex()); }
e1dd1278-a05e-4b31-a959-a0cd1fe67114
0
public TransformsType getTransforms() { return transforms; }
752cb0b3-f95e-4d8a-9111-1db904a24366
8
public void creat(List[] input,String strFileName) throws RowsExceededException, WriteException, DocumentException{ try { String newFile = strFileName.substring(0, strFileName.length()-4); System.out.println("newfile"+newFile); WritableWorkbook book = Workbook.createWorkbook(new File(newFile+".xls" )); WritableSheet sheet = book.createSheet("First Page",0 ); WritableFont font1 = new WritableFont(WritableFont.TIMES, 12 ,WritableFont.BOLD); WritableCellFormat format1 = new WritableCellFormat(font1); String[] titles = {"CaseName","TestImportance","ExecutionType","Keywords","Summary","Preconditions","step_number","StepActions","ExpectedResults","Execution"}; for(int i=0;i<titles.length;i++){ Label label_i = new Label(i,0,titles[i],format1); sheet.addCell(label_i); } for(int i=1;i<input.length;i++){ int j=0; int k = 1; System.out.println("i="+i); for(Iterator it = input[i].iterator();it.hasNext();){ Element ele=(Element)it.next(); System.out.println(ele.getText()); j+=1; System.out.println("j="+j); String content1 = filterHtml(ele.getText()); String content2 = content1.replace("&nbsp;", " "); if(i==6||i==7||i==8){ Label label = new Label(i,j,content2); sheet.addCell(label); } else{ int ti[] = new ReadXml().getTime(strFileName); Label label = new Label(i,k,content2); sheet.addCell(label); k = k+ti[j-1]; } } } List<String> li = new ReadXml().getNameAndKey(strFileName); int ti[] = new ReadXml().getTime(strFileName); int k = 1; /* for(int s =0;s<li.;s++){ System.out.println("00000"+li.get(s)); Label label = new Label(0,k,(String)li.get(s)); sheet.addCell(label); System.out.println("-----------"+li.get(s)); System.out.println("********"+ti[s]); k = k+ti[s]; }*/ for (int s =0;s<li.size();s++) { String[] pair = li.get(s).split("::"); String name = pair[0]; String keywords = pair[1]; System.out.println(name); System.out.println("key=" + name + " value=" + keywords); Label label_name = new Label(0,k,name); Label label_keyword = new Label(3,k,keywords); sheet.addCell(label_name); sheet.addCell(label_keyword); k = k+ti[s]; } /* List lis = new ReadXml().getKey(strFileName); k = 1; for(int s =0;s<lis.size();s++){ System.out.println("00000"+lis.get(s)); Label label = new Label(3,k,(String) lis.get(s)); sheet.addCell(label); k = k+ti[s]; }*/ book.write(); book.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
c26a86c8-0e7e-4771-a8cb-4a6cb3f9ccdf
9
public void writeFile(){ try{ PrintWriter output = new PrintWriter(fileName); output.println(scores.size()); output.println(madeMoney); for(PlayerPanel p: scores){ boolean gg[] = p.getGoodG(); output.println(p.getName()); for(int score : p.front9){ output.print(score+"/"); } output.print(p.getOutScore()+"/"); for(int score : p.back9){ output.print(score+"/"); } output.print(p.getInScore()+"/"); output.print(p.getTotalScore()+"/"); output.print(p.getPulled()+"/"); output.println(p.getPlusMinus()); for(int i = 0; i < 4; i++){ if(i == 3){ output.println(gg[i]); }else{ output.print(gg[i]+"/"); } } output.println(p.wasSuperWon()); output.println(p.getInTheMoney()); output.println(p.moneyMade()); for(boolean good : p.frontSkins){ output.print(good+"/"); } for(int i = 0; i < 9; i++){ if(i == 8){ output.println(p.backSkins[i]); }else{ output.print(p.backSkins[i]+"/"); } } output.println(p.getFP()+"/"+p.getSP()+"/"+p.getTP()); } output.println(s); output.println(st); output.println(g); output.println(ss); output.close(); }catch(FileNotFoundException e){ e.printStackTrace(); } }
256b6282-df86-4dd1-b072-6c6e304a9205
5
public Construct readNext() throws SyntaxError { patternSearch: for (LanguagePattern lp : LanguagePattern.searchValues()) { Symbol symbol = lexer.nextToken(); int start = lexer.getIndex(); for (;;) { switch (lp.tryNextToken(symbol)) { case LanguagePattern.PATTERN_ENDED: return lp.fetchProduct(); case LanguagePattern.TOKEN_APROVED: continue; case LanguagePattern.TOKEN_ILLEGAL: lexer.setIndex(start); continue patternSearch; } } } throw new SyntaxError(lexer.nextToken(), this); }
07e12356-3fb6-489e-b33a-b54bc9459683
5
public void renInven() { int index; String oldName, newName; InventoryListObject inventoryListObject; if ( tpContent.getTabCount() > 0 ) { index = tpContent.getSelectedIndex(); oldName = tpContent.getTitleAt( index ); newName = JOptionPane.showInputDialog( Data.getView(), "New Inventory Panel Name", oldName ); if ( newName != null && newName.length() > 0 && !newName.equals( oldName ) ) { inventoryListObject = InventoryObjectDAO.getInventoryListObject( oldName ); if ( inventoryListObject != null ) { inventoryListObject.setListName( newName ); } // if tpContent.setTitleAt( tpContent.getSelectedIndex(), newName ); Data.setInventoryDirty(); checkEnableControls(); } // if } // if } // renInven ----------------------------------------------------------------
ee20c0a8-4c0f-4809-91c6-be175d7ca516
3
public java.lang.Object get(int field$) { switch (field$) { case 0: return to; case 1: return from; case 2: return body; default: throw new org.apache.avro.AvroRuntimeException("Bad index"); } }
9cf94d08-a7e1-4aad-a3f8-288c3df98ff1
2
private void asetaVoittoteksti(String teksti){ char[] voittaja = teksti.toCharArray(); char[] voittoteksti = new char[pelinVoitti.length + voittaja.length]; for (int i=0; i<pelinVoitti.length; i++){ voittoteksti[i]=pelinVoitti[i]; } for (int j=0; j<voittaja.length; j++){ voittoteksti[pelinVoitti.length + j] = voittaja[j]; } pelinVoitti = voittoteksti; }
fbec2da6-a144-4305-a710-60febd9208b5
9
public static Class<?> getClass(Type type) { if (type instanceof Class) { return (Class<?>)type; } if (type instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType)type; return getClass(paramType.getRawType()); } else if (type instanceof WildcardType) { WildcardType wildcardType = (WildcardType)type; if (wildcardType.getLowerBounds() != null && wildcardType.getLowerBounds().length > 0) { return getClass(wildcardType.getLowerBounds()[0]); } if (wildcardType.getUpperBounds() != null && wildcardType.getUpperBounds().length > 0) { return getClass(wildcardType.getUpperBounds()[0]); } } return null; }
e4c1e133-b819-4402-81ca-7c085ef50289
2
public void passaTudoPraWait() { lockS.remove(0); if (waitList.isEmpty()) { ArrayList<String> aux = (ArrayList<String>) lockS.clone(); waitList = aux; } else { for (int i = 0; i < lockS.size(); i++) { waitList.add(lockS.get(i)); } } }
bd178ba5-20db-4689-9ef5-3d7018a1247b
5
@Test public void newBoardTest() throws IOException { Server server = makeServer(); //board1 adds correctly assertTrue(server.newBoard("board1")); assertTrue(server.getBoardsHashtable().containsKey("board1") && server.getBoardsHashtable().size() == 1); //board2 adds correctly assertTrue(server.newBoard("board2")); assertTrue(server.getBoardsHashtable().containsKey("board1") && server.getBoardsHashtable().containsKey("board2") && server.getBoardsHashtable().size() == 2); //board2 will not add again assertTrue(!server.newBoard("board2")); assertTrue(server.getBoardsHashtable().containsKey("board1") && server.getBoardsHashtable().containsKey("board2") && server.getBoardsHashtable().size() == 2); server.close(); }
ce9ddd1f-bff1-4a66-a965-d044c7951328
5
private void solve() { Scanner scanner = new Scanner(System.in); a = scanner.nextInt(); m = scanner.nextInt(); seed = scanner.nextInt(); scanner.nextLine(); String line = scanner.nextLine(); while (line != null) { char[] encryptedText = line.toCharArray(); for (int i = 0; i < encryptedText.length; i++) { boolean isPrinted = false; // try all the characters for (char j = 0x20; j <= 0x7e; j++) { if (encryptedText[i] == encrypt(j)) { seed = tentativeSeed; System.out.print((char) j); isPrinted = true; break; } } if (!isPrinted) System.err.printf("char %c not printed!", encryptedText[i]); } System.out.println(); line = scanner.nextLine(); } }
4940bf60-ad24-4240-89fb-58fda8c6688c
9
public static StatisticalSummaryValues aggregate(Collection<SummaryStatistics> statistics) { if (statistics == null) { return null; } Iterator<SummaryStatistics> iterator = statistics.iterator(); if (!iterator.hasNext()) { return null; } SummaryStatistics current = iterator.next(); long n = current.getN(); double min = current.getMin(); double sum = current.getSum(); double max = current.getMax(); double m2 = current.getSecondMoment(); double mean = current.getMean(); while (iterator.hasNext()) { current = iterator.next(); if (current.getMin() < min || Double.isNaN(min)) { min = current.getMin(); } if (current.getMax() > max || Double.isNaN(max)) { max = current.getMax(); } sum += current.getSum(); final double oldN = n; final double curN = current.getN(); n += curN; final double meanDiff = current.getMean() - mean; mean = sum / n; m2 = m2 + current.getSecondMoment() + meanDiff * meanDiff * oldN * curN / n; } final double variance; if (n == 0) { variance = Double.NaN; } else if (n == 1) { variance = 0d; } else { variance = m2 / (n - 1); } return new StatisticalSummaryValues(mean, variance, n, max, min, sum); }
d6e7afd5-2419-48a6-ba7b-a454da93dd2f
3
public final void removeBlock() { if (outer instanceof SequentialBlock) { if (outer.getSubBlocks()[1] == this) { if (jump != null) outer.getSubBlocks()[0].moveJump(jump); outer.getSubBlocks()[0].replace(outer); } else outer.getSubBlocks()[1].replace(outer); return; } EmptyBlock eb = new EmptyBlock(); eb.moveJump(jump); eb.replace(this); }
413ec564-19ee-4b36-a37a-113203b7745e
0
@Override public List<String> getGroups() { return (List<String>) groups.clone(); }
0c0bd94d-7855-4d83-9d59-f2e0b1a7cbb3
5
@Override protected void initiate_constraint_feature(int label) { m_phi_Z_x = new double[C][CONT_SIZE]; m_b = new double[CONT_SIZE]; m_q = new double[C]; //Arrays.fill(m_b, 5e-2); if(label == 0) { m_phi_Z_x[0][0] = -1; m_phi_Z_x[1][0] = 1; m_phi_Z_x[1][1] = -1; m_phi_Z_x[2][1] = 1; m_phi_Z_x[2][2] = -1; m_phi_Z_x[3][2] = 1; m_phi_Z_x[3][3] = -1; m_phi_Z_x[4][3] = 1; } else if(label == 1) { m_phi_Z_x[0][0] = 1; m_phi_Z_x[1][0] = -1; m_phi_Z_x[1][1] = -1; m_phi_Z_x[2][1] = 1; m_phi_Z_x[2][2] = -1; m_phi_Z_x[3][2] = 1; m_phi_Z_x[3][3] = -1; m_phi_Z_x[4][3] = 1; } else if(label == 2) { m_phi_Z_x[0][0] = 1; m_phi_Z_x[1][0] = -1; m_phi_Z_x[1][1] = 1; m_phi_Z_x[2][1] = -1; m_phi_Z_x[2][2] = -1; m_phi_Z_x[3][2] = 1; m_phi_Z_x[3][3] = -1; m_phi_Z_x[4][3] = 1; } else if(label == 3) { m_phi_Z_x[0][0] = 1; m_phi_Z_x[1][0] = -1; m_phi_Z_x[1][1] = 1; m_phi_Z_x[2][1] = -1; m_phi_Z_x[2][2] = 1; m_phi_Z_x[3][2] = -1; m_phi_Z_x[3][3] = -1; m_phi_Z_x[4][3] = 1; } else if(label == 4) { m_phi_Z_x[0][0] = 1; m_phi_Z_x[1][0] = -1; m_phi_Z_x[1][1] = 1; m_phi_Z_x[2][1] = -1; m_phi_Z_x[2][2] = 1; m_phi_Z_x[3][2] = -1; m_phi_Z_x[3][3] = 1; m_phi_Z_x[4][3] = -1; } }
b7ab4351-850d-4d3a-bf15-75ea8d40f47a
6
public void findSum(TreeNode root,int sum,int curSum,LinkedList<Integer> col){ if(root == null){ return ; } curSum += root.data; col.add(root.data); if(root.left==null&&root.right==null&&curSum == sum){ print(col); } if(root.left!=null) findSum(root.left,sum,curSum,col); if(root.right!=null) findSum(root.right,curSum,sum,col); curSum -= root.data; col.removeLast(); }
9e38d1f1-2afa-4c26-9d7a-8945ce3145f3
4
public void act() { // sends information to expandImage method where it stretches the paddle if(enlarge > -1) { expandImage(getImage().getWidth()+1); // expand by 1 more animation enlarge++; // stop expansion when reached 25 times if(enlarge > 25) { enlarge = -1; } } // sends information to expandImage method where it stretches the paddle else if (shrink > -1) { shrinkImage(getImage().getWidth()-1); // expand by 1 more animation shrink++; // stop expansion when reached 25 times if(shrink > 25) { shrink = -1; } } }
ccc6c95c-ea95-4244-80c3-830e20645700
2
private com.authy.api.User userFromXml(int status, String content) { com.authy.api.User user = new com.authy.api.User(); try { Error error = errorFromXml(status, content); if(error == null) { JAXBContext context = JAXBContext.newInstance(Hash.class); Unmarshaller unmarshaller = context.createUnmarshaller(); StringReader xml = new StringReader(content); Hash hash = (Hash)unmarshaller.unmarshal(new StreamSource(xml)); user = hash.getUser(); } user.setError(error); } catch(JAXBException e) { e.printStackTrace(); } return user; }
7105f2bd-c9b9-42ee-a979-0876e417ec27
9
public void drawUniverseSchematic(){ schematicContainer.getChildren().clear(); // x and y location to draw components, xt is used to reset x back to original value int x, y, xt; // Positions to start drawing x = 50 + (int)mouseInfo.offX(); y = 50 + (int)mouseInfo.offY(); xt = x; //Draw some schematic layout stuff boolean firstFirebox = true; for (Firebox fb : universe.getFireboxList()){ // Draw Firebox shape if (!firstFirebox){ //Draw schematic connector between FB's Line l = new Line(); l.setStrokeWidth(2); l.setStartX(x + 40); l.setStartY(y-20); l.setEndX(x + 40); l.setEndY(y - 1); Circle c = new Circle(); c.setCenterX(x + 40); c.setCenterY(y - 1); c.setRadius(3); c.setFill(Color.BLACK); universeSchematic.getChildren().add(l); universeSchematic.getChildren().add(c); } firstFirebox = false; Rectangle r = new Rectangle(); r.setWidth(80); r.setHeight(30); r.setX(x); r.setY(y); r.setStroke(Color.BLACK); r.getStyleClass().add("universe-green"); Text fireboxText = new Text(); fireboxText.setFill(Color.BLACK); fireboxText.setX(x + 15); fireboxText.setY(y + 20); fireboxText.setText("Firebox " + Integer.toString(fb.getId() + 1)); universeSchematic.getChildren().add(r); universeSchematic.getChildren().add(fireboxText); for (Lunchbox lb : fb.getLunchboxList()) { // Draw Lunchboxes // // Draw lunchbox connecting wire Line l2 = new Line(); l2.setStrokeWidth(2); l2.setStartX(x + 80); l2.setStartY(y + 14); l2.setEndX(x + 90); l2.setEndY(y + 14); //Draw connecting circle Circle c2 = new Circle(); c2.setCenterX(x + 90); c2.setCenterY(y + 14); c2.setRadius(3); c2.setFill(Color.BLACK); universeSchematic.getChildren().add(l2); universeSchematic.getChildren().add(c2); int squibcount = 0; for (Squib s : lb.getSquibList()) { // used to draw each squib in appropriate channel int cX = (s.getChannel() * 10) + x + 83; // Draw the individual squibs in the lunchboxes Rectangle squibRectangle = new Rectangle(); squibRectangle.setX(cX); squibRectangle.setY(y + 7); squibRectangle.setWidth(10); squibRectangle.setHeight(15); squibRectangle.setStroke(Color.BLACK); // TODO: Change color here when simulating firing if squib is dead squibRectangle.getStyleClass().add("universe-green"); Text t = new Text(); t.setFill(Color.BLACK); t.setX(cX + 2); t.setY(y + 19); t.setText(Integer.toString(s.getSquib() + 1)); universeSchematic.getChildren().add(squibRectangle); universeSchematic.getChildren().add(t); //x += 10; squibcount++; } // set squibcount to 0 to draw in all boxes squibcount = 0; // Draw blank squibs to keep alignment easy to maintain while (squibcount < 8){ Rectangle squibRectangle = new Rectangle(); squibRectangle.setX(x + 93); squibRectangle.setY(y + 7); squibRectangle.setWidth(10); squibRectangle.setHeight(15); squibRectangle.setStroke(Color.BLACK); squibRectangle.setFill(Color.TRANSPARENT); universeSchematic.getChildren().add(squibRectangle); x += 10; squibcount++; } // Draw lunchbox label x-x Text id = new Text(); id.setFill(Color.WHITESMOKE); // Some weird off setting to draw the label in the right location, // essentially move cursor back to 0, and build offset from there. id.setX((x-(squibcount*10)) + 85 + squibcount*5); id.setY(y + 35); id.setText((lb.getGrandParent()+1) + "-" + (lb.getId() + 1)); universeSchematic.getChildren().add(id); x += 13; } x = xt; y = y + 52; } schematicContainer.getChildren().add(universeSchematic); // sets the start of a mouse drag schematicContainer.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent t) { if (!clickable) { return; } mouseInfo.start = true; } }); // Setup an event listener to detect when mouse has been dragged schematicContainer.setOnMouseDragged(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent t) { //Point mPoint = MouseInfo.getPointerInfo().getLocation(); if (!clickable) { return; } else if(t.getButton() == MouseButton.SECONDARY) // on right click { if(mouseInfo.start == true) { mouseInfo.setStartX(t.getSceneX()); mouseInfo.setStartY(t.getSceneY()); mouseInfo.start = false; } else { mouseInfo.setEndX(t.getSceneX()); mouseInfo.setEndY(t.getSceneY()); mouseInfo.calcOff(); mouseInfo.setStartX(t.getSceneX()); mouseInfo.setStartY(t.getSceneY()); } universeSchematic.getChildren().clear(); schematicContainer.getChildren().clear(); drawUniverseSchematic(); } } }); }
22fe6400-73bc-4558-99e8-61ee8e340640
2
public final void unpush() { // First, move 'back' one position backwards. if (back_pos > 0) back_pos--; else { back_pos = size - 1; back_chunk = back_chunk.prev; } // Now, move 'end' position backwards. Note that obsolete end chunk // is not used as a spare chunk. The analysis shows that doing so // would require free and atomic operation per chunk deallocated // instead of a simple free. if (end_pos > 0) end_pos--; else { end_pos = size - 1; end_chunk = end_chunk.prev; end_chunk.next = null; } }
3340983d-14e2-44fb-bba5-0026f005251e
9
private TextBlock getCircledCharacter(ILeaf entity, ISkinParam skinParam) { final Stereotype stereotype = entity.getStereotype(); if (stereotype != null && stereotype.getSprite() != null) { return skinParam.getSprite(stereotype.getSprite()).asTextBlock(stereotype.getHtmlColor()); } final UFont font = SkinParamUtils.getFont(getSkinParam(), FontParam.CIRCLED_CHARACTER, null); final HtmlColor classBorder = SkinParamUtils.getColor(getSkinParam(), ColorParam.classBorder, stereotype); if (stereotype != null && stereotype.getCharacter() != 0) { return new CircledCharacter(stereotype.getCharacter(), getSkinParam().getCircledCharacterRadius(), font, stereotype.getHtmlColor(), classBorder, SkinParamUtils.getFontColor(getSkinParam(), FontParam.CIRCLED_CHARACTER, null)); } if (entity.getEntityType() == LeafType.ANNOTATION) { return new CircledCharacter('@', getSkinParam().getCircledCharacterRadius(), font, SkinParamUtils.getColor( getSkinParam(), ColorParam.stereotypeABackground, stereotype), classBorder, SkinParamUtils.getFontColor(getSkinParam(), FontParam.CIRCLED_CHARACTER, null)); } if (entity.getEntityType() == LeafType.ABSTRACT_CLASS) { return new CircledCharacter('A', getSkinParam().getCircledCharacterRadius(), font, SkinParamUtils.getColor( getSkinParam(), ColorParam.stereotypeABackground, stereotype), classBorder, SkinParamUtils.getFontColor(getSkinParam(), FontParam.CIRCLED_CHARACTER, null)); } if (entity.getEntityType() == LeafType.CLASS) { return new CircledCharacter('C', getSkinParam().getCircledCharacterRadius(), font, SkinParamUtils.getColor( getSkinParam(), ColorParam.stereotypeCBackground, stereotype), classBorder, SkinParamUtils.getFontColor(getSkinParam(), FontParam.CIRCLED_CHARACTER, null)); } if (entity.getEntityType() == LeafType.INTERFACE) { return new CircledCharacter('I', getSkinParam().getCircledCharacterRadius(), font, SkinParamUtils.getColor( getSkinParam(), ColorParam.stereotypeIBackground, stereotype), classBorder, SkinParamUtils.getFontColor(getSkinParam(), FontParam.CIRCLED_CHARACTER, null)); } if (entity.getEntityType() == LeafType.ENUM) { return new CircledCharacter('E', getSkinParam().getCircledCharacterRadius(), font, SkinParamUtils.getColor( getSkinParam(), ColorParam.stereotypeEBackground, stereotype), classBorder, SkinParamUtils.getFontColor(getSkinParam(), FontParam.CIRCLED_CHARACTER, null)); } assert false; return null; }
96dd7d9b-e85b-4163-b41a-c6f4ed6ffc42
7
public FilledContainer(String name,String containerType, String baseType , HashMap<String, Double> liquids, double... parameters ) { this.parameters = parameters; this.name = name; this.containerType = containerType; this.baseType = baseType; if( containerType.equalsIgnoreCase("straitght") ) { if ( baseType.equalsIgnoreCase("square") ) { this.container = new SquareStraightContainer(parameters[0]); } if ( baseType.equalsIgnoreCase("rectangle") ) { this.container = new RectangleStraightContainer(parameters[0],parameters[1]); } if ( baseType.equalsIgnoreCase("trapezoid") ) { this.container = new TrapezoidStraightContainer(parameters[0], parameters[1], parameters[2]); } if ( baseType.equalsIgnoreCase("hexagon") ) { this.container = new HexagonStraightContainer(parameters[0]); } if ( baseType.equalsIgnoreCase("circle") ) { this.container = new CircleStraightContainer(parameters[0]); } if ( baseType.equalsIgnoreCase("ellipse") ) { this.container = new EllipseStraightContainer(parameters[0], parameters[1] ); } } this.liquid = new Liquid( name, liquids, container.getVolume() ); }
837a2158-83e1-411f-85c7-8b9a37eff881
1
@Override public boolean event(QEvent e) { if (e.type() == Type.Enter) { over.emit(row, col); } return super.event(e); }
c359feaa-878c-4b6c-a275-3282392e5b7e
1
public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(getLHS()); // buffer.append("->"); buffer.append('\u2192'); String rhs = getRHS(); buffer.append(rhs.length() == 0 ? Universe.curProfile.getEmptyString() : rhs); // buffer.append('\n'); return buffer.toString(); }
07c1055a-d9d8-486e-8dc7-83de9b007173
7
public void communicate(String host, int port) { // Geranate a socket to conect a server. try (Socket socket = new Socket(host, port)) { // reading thread Thread readT = new Thread(new Runnable() { public void run() { try (BufferedReader sbr = new BufferedReader( new InputStreamReader(socket.getInputStream()))) { String str = sbr.readLine(); while (str != null && submiting ) { System.out.println(str); str = sbr.readLine(); } } catch (IOException e) { if (submiting) { System.err.println("Disconnected by server"); e.printStackTrace(System.err); } } } }); readT.start(); // writing try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter spw = new PrintWriter(socket.getOutputStream(), true)) { String str = br.readLine(); while (str != null) {// C-d spw.println(str); str = br.readLine(); } System.out.println("End Submission"); System.out.println("Disconnected by client"); } catch (IOException e) { e.printStackTrace(System.err); } finally { submiting = false; readT.join(); System.exit(0); } } catch (IOException | InterruptedException e) { e.printStackTrace(System.err); } }
c828f54f-e4fa-41ef-9eb7-fba20db806b0
2
public static void main(String[] args) { try { access = CycAccess.getNewCycAccessInteractively(); helloWorldExample(); exampleConnectingToCyc(); exampleContantsManipulations(); exampleNartManipulations(); exampleAssertionManipulations(); exampleSynchronousQueries(); exampleAsynchronousQueries(); exampleInferenceParameters(); exampleGenericLispAPI(); } catch (CycApiException ex) { Logger.getLogger(APIExamples.class.getName()).log(Level.SEVERE, null, ex); } finally { if (access != null) { access.close(); } } System.exit(0); }
e84a8dd6-20ff-4ade-a2bd-a336916b0d38
3
private boolean notDelegated(String name) { if (notDefinedHere.get(name) != null) return true; int n = notDefinedPackages.size(); for (int i = 0; i < n; ++i) if (name.startsWith((String)notDefinedPackages.elementAt(i))) return true; return false; }
e8ec4d3d-2ce9-49e2-849f-7bd4db799f14
1
public String getRequests() { String res = ""; for (Iterator<String> e = requests.iterator(); e.hasNext();) { res += e.next(); } return res; }
4dc23443-9494-4e97-9da0-5146aca78adb
5
private void calculateStudentFines(Book book, User user, int monthBack, int dayBack, int yearBack) { int daysInMonth = 31; int monthsInYear = 12; int daysInYear = 366; double totalDaysOut = 0; int yearDiff = yearBack - book.getYearOut(); int monthDiff = monthBack - book.getMonthOut(); int dayDiff = dayBack - book.getDayOut(); double finesToAdd = 0; if (!(yearDiff == 0)) { totalDaysOut = ((monthsInYear - book.getMonthOut())*daysInMonth) + (daysInMonth - book.getDayOut()) + dayBack + monthBack*daysInMonth + ((yearDiff-1)*daysInYear); } else if (yearDiff == 0 && !(monthDiff == 0)) { totalDaysOut = (daysInMonth - book.getDayOut()) + dayBack + ((monthDiff-1)*daysInMonth); } else if (yearDiff == 0 && monthDiff == 0) { totalDaysOut = dayDiff; } finesToAdd = (totalDaysOut-14)/10; user.setFines(user.getFines() + finesToAdd); }
a7736044-d4f5-4df9-9702-a6bbc2959b2a
8
public Floor(DataBuffer buffer) { while (true) { int attributeId = buffer.getUnsigned(); if (attributeId == 0) { break; } else if (attributeId == 1) { rgbColor = buffer.getTribyte(); rgbToHSL(rgbColor); } else if (attributeId == 2) { textureID = buffer.getUnsigned(); } else if (attributeId == 3) { aBoolean227 = true; } else if (attributeId == 5) { occlude = false; } else if (attributeId == 6) { name = buffer.getString(); } else if (attributeId == 7) { int oldHue2 = hue2; int oldSaturation = saturation; int oldLightness = lightness; int oldHue = hue; rgbToHSL(buffer.getTribyte()); hue2 = oldHue2; saturation = oldSaturation; lightness = oldLightness; hue = oldHue; hueDivisor = oldHue; } else { System.out.println("Error unrecognised config code: " + attributeId); } } }
198bba6e-7d15-49cd-8668-b4d90e2295ca
9
public void sortTheList(String mode) { Vector<Track> sortedList = new Vector<Track>(); int smallest = -1; float smallestValue = 0; while (tracksList.size() > 0) { for (int i = 0; i < tracksList.size(); i++) { float relevantValue = 0; if (mode.equals("bpm")) relevantValue = tracksList.get(i).getBpm(); if (mode.equals("keyFr")) relevantValue = tracksList.get(i).getKeyFr(); if (mode.equals("frPerBpm")) relevantValue = tracksList.get(i).getFrPerBpm(); if (mode.equals("close")) relevantValue = tracksList.get(i).closenessTo(currentTrack()); if (smallestValue >= relevantValue || smallest == -1) { smallestValue = relevantValue; smallest = i; } } sortedList.add(tracksList.remove(smallest)); smallest = -1; } for (int i = 0; i < sortedList.size(); i++) tracksList.add(sortedList.get(i)); parent.cellsManager.updateList(); }
3028f7d2-029a-46d6-955a-8dbcee127e99
7
private void createGrid(int m, int n, boolean edges) { double dy = 20 + 50 / Math.sqrt(m); double dx = 20 + 50 / Math.sqrt(n); System.out.println(dx + " " + dy); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { createVertex(j * dx, i * dy, getNewVertexID()); } } if (edges) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (j != n - 1) { createEdge(vertices.get(i * n + j), vertices.get(i * n + j + 1)); } if (i != m - 1) { createEdge(vertices.get(i * n + j), vertices.get(i * n + j + n)); } } } } type = GraphType.grid; }
f3407163-84aa-4191-aa7e-0e88304eb2d5
0
public String getTitle() { return title; }