method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
39666cce-7908-491c-b4de-55e733c78f61
7
public void paivita(Object uusi, int rivi, int sarake) { Elokuva elokuva = elokuvat.get(rivi); if (sarake == 1) elokuva.setNimi((String) uusi); else if (sarake == 2) elokuva.setOhjaaja((String) uusi); else if (sarake == 3) elokuva.setNayttelijat((String) uusi); else if (sarake == 4) elokuva.setLajityyppi((String) uusi); else if (sarake == 5) elokuva.setJulkaisuvuosi((String) uusi); else if (sarake == 6) elokuva.setPituus((String) uusi); else if (sarake == 7) elokuva.setJuoni((String) uusi); elokuvat.remove(rivi); elokuvat.add(rivi, elokuva); tallenna(); }
ae5f4b27-144c-47ec-be54-30826a941233
4
public Game() { grid = new Tile[GRID_WIDTH][GRID_HEIGHT]; currentPiece = generatePiece(); for (int i = 0; i < 4; i++) currentPiece = new Piece().changeX(currentPiece, 1); nextPiece = generatePiece(); for (int i = 0; i < 4; i++) nextPiece = new Piece().changeX(nextPiece, 1); //insert(nextPiece, 7, 7); state = PLACEMENT; generator = new Random(); for (int i = 0; i < grid.length; i++) for (int j = 0; j < grid[i].length; j++) { grid[i][j] = new Tile(); grid[i][j].setActive(false); } linesToClear = LINES_TO_CLEAR; }
a80a7463-1faa-431d-bfd8-2605b445f509
7
public synchronized void startGame(List<String> wordList) { if (wordList.isEmpty()) { // TODO: do something.... end game? } gameEnded = false; currentScore = 100; while (countClients() < GamePlay.NUM_PLAYERS) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } Random random = new Random(); int wordIndex = random.nextInt(wordList.size()); word = wordList.get(wordIndex); wordList.remove(wordIndex); System.out.println("Next word is " + word); int i = 0; for (Player p : players) { p.setDrawing((i++) == roundRobin); p.startGame(word); if (p.isDrawing()) { this.drawer = p; } } System.out.println("Drawer: " + this.drawer.getPlayerName()); startTimer(); roundRobin = (roundRobin + 1) % NUM_PLAYERS; while (!gameEnded) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } }
c5ad8e6a-2a30-4c9d-851a-7ec84399bfde
2
@Override public void Parse(Session Session, EventRequest Request) { if (!Session.GrabActor().InRoom()) { return; } Session.GrabResponse().Initialize(ComposerLibrary.LeavingRoom); Session.GrabResponse().AppendBoolean(false); Session.SendResponse(); if (Session.GrabActor().CurrentRoom.GrabParty().size() == 1) { Grizzly.GrabHabboHotel().GrabRoomHandler().RemoveRoom(Session.GrabActor().CurrentRoom.ID, false); } Session.GrabActor().CurrentRoom.RemoveUser(Session); System.gc(); }
5a5dab4c-a09f-4507-8e90-625e86da9105
8
final public void VarDecl() throws ParseException { /*@bgen(jjtree) VarDecl */ SimpleNode jjtn000 = new SimpleNode(JJTVARDECL); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token value; try { jj_consume_token(VAR_TAG); value = jj_consume_token(VAR_LOCAL); jjtn000.numVar =value.toString(); jj_consume_token(EQUAL); Aritm(); jj_consume_token(SEMMICOLON); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } }
ad73d327-4ff1-4dad-921c-148a3030cffb
9
@Override public void doTask() { if(!dead) { // Log.debug("Moving Man"); this.direction = ai.getNextDirection(); if (direction.equals(Direction.TOP)) { if (!collisions.contains(Direction.TOP)) { super.setRealY(super.getRealY() - super.speed); } } if (direction.equals(Direction.BOTTOM)) { if (!collisions.contains(Direction.BOTTOM)) { super.setRealY(super.getRealY() + super.speed); } } if (direction.equals(Direction.LEFT)) { if (!collisions.contains(Direction.LEFT)) { super.setRealX(super.getRealX() - super.speed); } } if (direction.equals(Direction.RIGHT)) { if (!collisions.contains(Direction.RIGHT)) { super.setRealX(super.getRealX() + super.speed); } } } }
6f367ac2-18d4-435c-8cb8-42700a719f9a
4
public User getUserById(long userId) throws DataAccessException { Connection connection = getConnection(); try { PreparedStatement ps = connection.prepareStatement( "SELECT * FROM grad_users WHERE user_id=?"); PreparedStatement ps2 = connection.prepareStatement( "SELECT * FROM grad_phase WHERE user_id=? ORDER BY phase_time"); ps.setLong(1, userId); ps2.setLong(1, userId); ResultSet rs = ps.executeQuery(); ResultSet rs2 = ps2.executeQuery(); if (!rs.next()) { return null; } long id = rs.getLong("user_id"); String name = rs.getString("user_name"); String pass = rs.getString("user_pass"); User user = new User(); user.setId(id); user.setUsername(name); user.setPassword(pass); LinkedList<Long> list = new LinkedList<Long>(); for (int i = 0; rs2.next(); i++){ long time = rs2.getLong("phase_time"); if(i == 0) { list.add(time); } else { list.add(time - list.peekLast()); } } Schedule schedule = new Schedule(); schedule.setDeltaTimeTable(list); user.setSchedule(schedule); return user; } catch(SQLException ex) { logger.log(Level.SEVERE, ex.getMessage(), ex); throw new DataAccessException(ex); } }
c2b3fdfb-7ff5-4017-b0a6-2b565b59afb0
6
private void viewHistory() { System.out.println("View interpretation history ..."); // get list of grouping effective time: ArrayList<DataTimestamp> timestamps = this.loader.getGroupingEffectiveTimestamps(); // insert a "Baseline" timestamp timestamps.add(timestamps.size(), new DataTimestamp(this.src.srdsSrcID)); // create a an input dialog for users to select a timestamp: DataTimestamp ts = (DataTimestamp) JOptionPane.showInputDialog( frame, "Please select a timestamp:", "Interpretation Timestamp", JOptionPane.QUESTION_MESSAGE, null, timestamps.toArray(), this.selectedTimestamp); // exit if no source id was selected: if (ts == null) return; // [TEST] print user's selection: System.out.println("User selected: " + ts); // make it NULL if latest ts is selected: if (ts == timestamps.get(0)){ ts = null; } // check if a new timestamp was selected: if (this.selectedTimestamp == ts || (this.selectedTimestamp != null && ts != null && this.selectedTimestamp.equals(ts))) { return; } // set selected timestamp: this.selectedTimestamp = ts; // Clear this horizon from FESVo: // ------------------------------ this.loader.clearFeaturesCache(); // set requested timestamp: this.loader.setFeaturesTimestamp(ts); // [TEST] print System.out.println("Features were removed from FESVo"); // Rebuild texture buffer (reload & rendering): // -------------------------------------------- // reload and render latest horizons: this.renderer.reloadHorizons(); }//viewHistory
59420490-8137-4872-aed1-386729c90138
9
private void assertReaderClosed(IndexReader reader, boolean checkSubReaders, boolean checkNormsClosed) { assertEquals(0, reader.getRefCount()); if (checkNormsClosed && reader instanceof SegmentReader) { assertTrue(((SegmentReader) reader).normsClosed()); } if (checkSubReaders) { if (reader instanceof DirectoryReader) { IndexReader[] subReaders = reader.getSequentialSubReaders(); for (int i = 0; i < subReaders.length; i++) { assertReaderClosed(subReaders[i], checkSubReaders, checkNormsClosed); } } if (reader instanceof MultiReader) { IndexReader[] subReaders = reader.getSequentialSubReaders(); for (int i = 0; i < subReaders.length; i++) { assertReaderClosed(subReaders[i], checkSubReaders, checkNormsClosed); } } if (reader instanceof ParallelReader) { IndexReader[] subReaders = ((ParallelReader) reader).getSubReaders(); for (int i = 0; i < subReaders.length; i++) { assertReaderClosed(subReaders[i], checkSubReaders, checkNormsClosed); } } } }
c59da3cb-15b4-4527-b568-f9adcee2cf51
8
public void refreshMonLocs() { // if (this.useDelay) // this.flushNewInf(this.mySim.curTime); if (this.numMonitors == 0 || this.trackLocations.size() == 0) return; else if (this.weightByPop) this.refreshMonLocsWeightByPop(); else if (this.actualInfCount) this.refreshMonLocsActInfCount(); else if (this.monAtRisk) this.refreshMonLocsAtRiskRand(); else if (this.useMonAgent) this.refreshMonLocsUseMonAgent(); else if (this.monUniformRand) this.refreshMonLocsUniform(); else if (this.sepPopSickMons) this.refreshMonLocsSepPopSickmons(); else this.refreshMonLocsUseAllMons(); }
5624bd46-8694-43ad-b161-983d40cb5335
5
private final void printMessageFunc(final String title, final String message, @SuppressWarnings("hiding") final String text) { if (Thread.currentThread() == this.master) { synchronized (Button.class) { this.pressed = Button.ABORT; Button.class.notifyAll(); } } if (title == null) { Debug.print("\n%s", message); } else { Debug.print("#%s#\n%s", title, message); } this.mainFrame.getContentPane().removeAll(); this.text.setEditable(false); this.text.setText(message); final JPanel panel = new JPanel(); final JScrollPane scrollPane = new JScrollPane(panel); panel.setLayout(new BorderLayout()); panel.add(this.text); this.mainFrame.add(scrollPane); if (text != null) { if (title != null) { this.wait.setText(title); } else { this.wait.setText(""); } panel.add(this.wait, BorderLayout.NORTH); this.mainFrame.add(Button.OK.getButton(), BorderLayout.SOUTH); this.mainFrame.pack(); final int height = scrollPane.getHeight(); if (height > 800) { final Dimension d = scrollPane.getSize(); d.height = 800 - Button.OK.getButton().getHeight(); scrollPane.setPreferredSize(d); this.mainFrame.pack(); } waitForButton(text); } else { this.mainFrame.pack(); synchronized (this) { revalidate(true, false); } } }
e95d6d45-210f-48c3-9d56-b76b67928f96
9
public static void initializeRuntime() { String bootPath = System.getProperty("sun.boot.class.path"); String pathSeparator = System.getProperty("path.separator"); if ((bootPath == null) || (pathSeparator == null)) { StandardLog .warning("Cannot initialize boot path through system properties"); return; } initialize(bootPath, pathSeparator); String javaHome = System.getProperty("java.home"); String fileSeparator = System.getProperty("file.separator"); if ((javaHome == null) || (fileSeparator == null)) { StandardLog .warning("Cannot initialize extension library through system properties"); return; } File extDir = new File(javaHome + fileSeparator + "lib" + fileSeparator + "ext"); if (!extDir.getClass().getName().equals("java.io.File")) { StandardLog .warning("Extension classes initialization not supported for J2ME build"); return; } if (extDir.isDirectory()) { File[] files = extDir.listFiles(); for (int i = 0; i < files.length; i++) { String path = files[i].getPath(); if (path.endsWith(".jar") || path.endsWith(".zip")) { initializeJar(path); } } } else { StandardLog.warning(extDir + " is not a directory"); } }
3643c741-660a-4f5d-90d4-2cf0c6d1a5e1
0
public PrioritizedTaskProducer(Queue<Runnable> q, ExecutorService e) { queue = q; exec = e; }
24084eba-2473-46f7-8b87-3e4595d62d34
1
public HMWord(String word) { this.setWord(word); length = word.length(); setWrongLetters(new ArrayList<Character>()); setPlaceholder(new ArrayList<Character>()); for (int i = 0; i < length; i++) { getPlaceholder().add(UNDERSCORE); } }
b6fe678f-2c92-46a5-898c-f39e86b94f87
5
@Override public boolean match(ValueExpression te, Map<String, ValueExpression> map) { if (!(te instanceof TupleExpression)) { return false; } TupleExpression tuple = (TupleExpression)te; if (!(tuple.getTupleType().equals(getTupleType()))) { return false; } else { if (elements.size() == tuple.getElements().size()) { for (int i=0; i < elements.size(); i++) { ValueExpression myElement = elements.get(i); ValueExpression otherElement = tuple.getElements().get(i); if (!myElement.match(otherElement, map)) { return false; } } return true; } else { return false; } } }
5f588925-a3b2-4910-8cef-57a582042f92
4
@Override public C next() { if (lastNode!=null && (index < lastNode.keysSize)) { lastValue = lastNode.getKey(index++); return lastValue; } while (toVisit.size()>0) { // Go thru the current nodes BTree.Node<C> n = toVisit.pop(); // Add non-null children for (int i=0; i<n.childrenSize; i++) { toVisit.add(n.getChild(i)); } // Update last node (used in remove method) index = 0; lastNode = n; lastValue = lastNode.getKey(index++); return lastValue; } return null; }
4b70b3bf-3382-4484-892e-75ed0fef2886
4
public boolean isInBound ( int x, int y) { if(x<0||x>=boardSize||y<0||y>=boardSize) return false; return true; }
738e8965-8c1e-4d7c-b414-f7693647a03d
5
static void readBTX(File f) throws Throwable { BTXParser v = new BTXParser(f); l: while (true) { switch (v.next()) { case ATTRIBUTE : BTXAttribute at = v.getEventData().getAttribute(); at.getName(); at.asString(); break; case END_OBJECT : break; default : case EOF : break l; case START_OBJECT : @SuppressWarnings("unused") // We still need to access the name to have apples to apples with xml String objName = v.getEventData().objName; break; } } v.close(); }
ec1a9044-7566-4ab7-aa7d-b737f57e811f
5
private void asetaTKuva() { if (noppa == 2 || noppa == 3){ ImageIcon nyrkki = new ImageIcon(new ImageIcon(getClass().getResource("/nyrkky.jpg")).getImage()); setIcon(nyrkki); } else if (noppa == 4){ ImageIcon jousi = new ImageIcon(new ImageIcon(getClass().getResource("/bow.jpg")).getImage()); setIcon(jousi); } else if (noppa == 5){ ImageIcon miekka = new ImageIcon(new ImageIcon(getClass().getResource("/sord.jpg")).getImage()); setIcon(miekka); } else if (noppa == 6){ ImageIcon tulipallo = new ImageIcon(new ImageIcon(getClass().getResource("/greatballsoffire.jpg")).getImage()); setIcon(tulipallo); } }
6d38a073-d9a0-41bf-a08e-f7d6bb9fcec9
7
public boolean HandleRequest( HTTPRequest request, StringWriter out ) { if ( !request.method.equals( "GET" ) && !request.method.equals( "POST" ) ) return false; String command = ""; if ( request.parameters.containsKey( "command" ) ) { command = request.parameters.get( "command" ).trim(); } else if ( request.data instanceof JSONObject ) { JSONObject json = (JSONObject)request.data; try { command = (String)json.get( "command" ); } catch ( Exception e ) { // Silently fail. } } String output = ""; int response_code = 200; if(!(command.equals(""))){ output = executeConsoleCommand( command ); } if (output.equals("")) { response_code = 404; output = "Error: Invalid parameters"; } HTTPResponseHeaderHelper.outputHeaders( response_code, out ); out.write(output); return true; }
a73d326e-31a0-4905-9dcf-6b8109cfdd6a
2
private boolean isLeaf() { if (internal_node) return false; if (objects.size() < max_objects_per_leaf) return true; grow_leaves(); return false; }
69c8186d-84a6-4e94-bda7-8c712569e006
1
public Collection<GroupSettings> getGroups(boolean includeManual) { if(includeManual) return Collections.unmodifiableList(mAllGroups); else return Collections.unmodifiableList(mAutoGroups); }
73a289b7-b2ee-4f9a-bb92-5fde821ecb1a
6
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Client other = (Client) obj; if (this.idClient != other.idClient) { return false; } if (!Objects.equals(this.nom, other.nom)) { return false; } if (!Objects.equals(this.prenom, other.prenom)) { return false; } if (this.CIN != other.CIN) { return false; } return true; }
26b374d7-1401-4cb9-92e1-e02900742dbe
2
public synchronized static void print(String name) { for (int i = 0; i < 20; i++) { System.out.printf("%s %s\n", name, i); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }
9d59fec6-9c07-4c9a-901e-f6bb86c6baa3
0
public void mouseClicked(MouseEvent e) { }
56fe6e49-f50f-4b1a-822b-633ae52d30ee
4
private int computeGlobalSize() { int size = (allocator.getRegNumber() + 2) * 4; // useless, just to make // code logic simple int maxReg = 0; for (int reg : regMap.values()) { if (maxReg < reg) { maxReg = reg; } } if (maxReg > allocator.getRegNumber() + 2) { size = maxReg * 4; } for (Variable var : root.getLocalVarTable()) { size += var.computeSize(); } return size; }
42c947a4-1e9b-4a27-b00e-528c230344f5
8
@Override public void computeFontSize(List<TagCloudElement> elements) { if (elements.size() > 0) { Double minCount = null; Double maxCount = null; for (TagCloudElement tce : elements) { double n = tce.getWeight(); if ((minCount == null) || (minCount > n)) { minCount = n; } if ((maxCount == null) || (maxCount < n)) { maxCount = n; } } double maxScaled = scaleCount(maxCount); double minScaled = scaleCount(minCount); double diff = (maxScaled - minScaled) / (double)this.numSizes; for (TagCloudElement tce : elements) { int index = (int)Math.floor((scaleCount(tce.getWeight()) - minScaled) / diff); if (Math.abs(tce.getWeight() - maxCount) < PRECISION) { index = this.numSizes - 1; } tce.setFontSize(this.prefix + index); } } }
98c9fe5c-1c0f-4f02-bef3-63dfb8ce8fbe
9
void hitmiss(int xe, int ye, int [][] pixel2, int [][]pixel, int [] lut){ int x, y; // considers the pixels outside image to be 0 (not set) for (x=1; x<xe-1; x++) { for (y=1; y<ye-1; y++) { pixel[x][y]+= lut[( pixel2[x-1][y-1] + pixel2[x ][y-1] * 2 + pixel2[x+1][y-1] * 4 + pixel2[x-1][y ] * 8 + pixel2[x ][y ] * 16 + pixel2[x+1][y ] * 32 + pixel2[x-1][y+1] * 64 + pixel2[x ][y+1] * 128 + pixel2[x+1][y+1] * 256)]; } } y=0; for (x=1; x<xe-1; x++) { //upper row pixel[x][y]+= lut[( pixel2[x-1][y ] * 8 + pixel2[x ][y ] * 16 + pixel2[x+1][y ] * 32 + pixel2[x-1][y+1] * 64 + pixel2[x ][y+1] * 128 + pixel2[x+1][y+1] * 256)]; } y=ye-1; for (x=1; x<xe-1; x++) { //lower row pixel[x][y]+= lut[( pixel2[x-1][y-1] + pixel2[x ][y-1] * 2 + pixel2[x+1][y-1] * 4 + pixel2[x-1][y ] * 8 + pixel2[x ][y ] * 16 + pixel2[x+1][y ] * 32)]; } x=0; for (y=1; y<ye-1; y++) { //left column pixel[x][y]+= lut[( pixel2[x ][y-1] * 2 + pixel2[x+1][y-1] * 4 + pixel2[x ][y ] * 16 + pixel2[x+1][y ] * 32 + pixel2[x ][y+1] * 128 + pixel2[x+1][y+1] * 256)]; } x=xe-1; for (y=1; y<ye-1; y++) { //right column pixel[x][y]+= lut[( pixel2[x-1][y-1] + pixel2[x ][y-1] * 2 + pixel2[x-1][y ] * 8 + pixel2[x ][y ] * 16 + pixel2[x-1][y+1] * 64 + pixel2[x ][y+1] * 128)]; } x=0; //upper left corner y=0; pixel[x][y]+= lut[(pixel2[x][y] * 16 + pixel2[x+1][y] * 32 + pixel2[x][y+1] * 128 + pixel2[x+1][y+1] * 256)]; x=xe-1; //upper right corner //y=0; pixel[x][y]+= lut[(pixel2[x-1][y] * 8 + pixel2[x][y] * 16 + pixel2[x-1][y+1] * 64 + pixel2[x][y+1] * 128)]; x=0; //lower left corner y=ye-1; pixel[x][y]+= lut[(pixel2[x][y-1] * 2 + pixel2[x+1][y-1] * 4 + pixel2[x][y] * 16 + pixel2[x+1][y] * 32)]; x=xe-1; //lower right corner y=ye-1; pixel[x][y]+= lut[(pixel2[x-1][y-1] + pixel2[x][y-1] * 2 + pixel2[x-1][y] * 8 + pixel2[x ][y] * 16)]; for (x=0; x<xe; x++) { for (y=0; y<ye; y++){ pixel2[x][y]= ((pixel2[x][y]-pixel[x][y])>0?1:0); } } }
e219f7ee-13fe-44b0-9366-a5b303c0db78
6
private int method42(int i, int j, int k) { int l = k >> 7; int i1 = j >> 7; if(l < 0 || i1 < 0 || l > 103 || i1 > 103) return 0; int j1 = i; if(j1 < 3 && (byteGroundArray[1][l][i1] & 2) == 2) j1++; int k1 = k & 0x7f; int l1 = j & 0x7f; int i2 = intGroundArray[j1][l][i1] * (128 - k1) + intGroundArray[j1][l + 1][i1] * k1 >> 7; int j2 = intGroundArray[j1][l][i1 + 1] * (128 - k1) + intGroundArray[j1][l + 1][i1 + 1] * k1 >> 7; return i2 * (128 - l1) + j2 * l1 >> 7; }
1e1d8e30-5a63-403a-b73a-109fd1657c90
1
protected void carregaTabelaEnderecos(List<Endereco> lista){ this.modeloTabelaEndereco = new DefaultTableModel(); this.modeloTabelaEndereco.addColumn("Rua"); this.modeloTabelaEndereco.addColumn("Bairro"); this.modeloTabelaEndereco.addColumn("Cep"); this.modeloTabelaEndereco.addColumn("Número"); this.modeloTabelaEndereco.addColumn("Cidade"); this.modeloTabelaEndereco.addColumn("Estado"); for(Endereco e : lista){ Vector v = new Vector(); v.add(0,e.getRua()); v.add(1,e.getBairro()); v.add(2,e.getCep()); v.add(3,e.getNumero()); v.add(4,e.getCidade()); v.add(5,e.getEstado()); modeloTabelaEndereco.addRow(v); } this.tblEnderecos.setModel(modeloTabelaEndereco); this.tblEnderecos.repaint(); }
7aa406db-d8da-4cd8-be0e-17dab83fbe32
2
private boolean impliedBy(int and, int xor) { for (int i = 0; i < andMasks.length; i++) { if (implies(and, xor, andMasks[i], xorMasks[i])) return true; } return false; }
88bbab56-a099-4ba7-a4b7-3553587fc6c5
1
public static void load() { File file = new File("./Player.xml"); if(file.exists()){ playerData = JAXB.unmarshal(file, PlayerData.class); } else { playerData = JAXB.unmarshal(PlayerData.class.getResourceAsStream("/data/Player.xml"), PlayerData.class); } }
dd50b733-1cb7-4988-880d-d74fef82769d
1
public static void display(long array[]){ for(long arr : array){ System.out.print(arr+" "); } System.out.println(); }
dd8c59d0-6014-40be-acfe-93127c2a21b1
0
public int getCoordonneeX() { return x; }
5d6f1c59-284b-49b5-b57f-6d58b8511eba
2
private void gererLesEvenementsUtilisateurs() { while (Mouse.next()) { this.camera.onMouseEvent(); } while (Keyboard.next()) { this.sphere.onKeyEvent(); } }
2183284d-668a-4ef8-8320-54813a2b4bb4
4
private void assertTagValue(Document doc, String tagName, String tagValue) throws XPathExpressionException { NodeList list; if (tagName.startsWith("/")) { XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); XPathExpression expr = xpath.compile(tagName); list = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); } else { list = doc.getElementsByTagName(tagName); if (list.getLength() == 0) { fail("Tag '" + tagName + "' not found in document"); } } for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if (node.getTextContent().equals(tagValue)) { return; } } fail("There is no tag '" + tagName + "' with value '" + tagValue + "'"); }
c10cc800-5d79-42bb-94aa-58989d33d923
0
public List<String> getPrefNames() { return prefNameCombo.getItems(); }
fe746ca9-19e1-46a5-aae5-230b7fa2731f
2
private OutputChannels(int channels) { outputChannels = channels; if (channels<0 || channels>3) throw new IllegalArgumentException("channels"); }
393f11d6-0517-450a-bb29-8ff118cdcd17
6
public boolean playerWon(int p){ // If sentinel won if(winner == 1) { // Check whether player was on team sentinel for(int s:sentinel) { if(s == p) return true; } } // If scourge won if(winner == -1) { // Check whether player was on team scourge for(int s:scourge) { if(s == p) return true; } } // If no one won, or the player was not found on the winning team // the result is false. return false; }
d0016f4c-820b-4e66-9ccf-2988bfde8a2f
4
public static List<Point2D> ConnectionPoint (ABObject o1, ABObject o2) { List<Point2D> connection_p = new ArrayList<Point2D>(); if (o1.id != o2.id) { List<Point2D> pointsO1 = MathFunctions.getObjectContourPoints(o1); List<Point2D> pointsO2 = MathFunctions.getObjectContourPoints(o2); //System.out.println("Object " + o1.id + " size : " + pointsO1.size()); //System.out.println("Object " + o2.id + " size : " + pointsO2.size()); double error_distance = 2.0; for (int i = 0; i < pointsO1.size(); i++) { Point2D p1 = pointsO1.get(i); for (int j = 0; j < pointsO2.size(); j++) { Point2D p2 = pointsO2.get(j); double distance = Distance2Points(p1, p2); //System.out.println("Distance between " + p1 + ", " + p2 + " = " + distance); if (distance < error_distance) { /*System.out.println("Distance between " + "(" + p1.x + ", " + p1.y + ")" + "(" + p2.x + ", " + p2.y + ")" + " = " + distance);*/ connection_p.add(p1); connection_p.add(p2); } } } } return connection_p; }
d5e6652d-6b4f-4506-9864-e4b644346b37
7
public void hataHesapla(double ideal[]) { int i, j; final int arakatmanİndeksi = girisSayisi; final int cikisİndeksi = girisSayisi + arakatmanSayisi; for (i = girisSayisi; i < neuronSayisi; i++) { hata[i] = 0; } for (i = cikisİndeksi; i < neuronSayisi; i++) { hata[i] = ideal[i - cikisİndeksi] - seviyeCikislari[i]; globalHata += hata[i] * hata[i]; hataDelta[i] = hata[i] * seviyeCikislari[i] * (1 - seviyeCikislari[i]); } int winx = girisSayisi * arakatmanSayisi; for (i = cikisİndeksi; i < neuronSayisi; i++) { for (j = arakatmanİndeksi; j < cikisİndeksi; j++) { birikimliDelta[winx] += hataDelta[i] * seviyeCikislari[j]; hata[j] += matris[winx] * hataDelta[i]; winx++; } birikimliEsikDegerDelta[i] += hataDelta[i]; } for (i = arakatmanİndeksi; i < cikisİndeksi; i++) { hataDelta[i] = hata[i] * seviyeCikislari[i] * (1 - seviyeCikislari[i]); } winx = 0; for (i = arakatmanİndeksi; i < cikisİndeksi; i++) { for (j = 0; j < arakatmanİndeksi; j++) { birikimliDelta[winx] += hataDelta[i] * seviyeCikislari[j]; hata[j] += matris[winx] * hataDelta[i]; winx++; } birikimliEsikDegerDelta[i] += hataDelta[i]; } }
313bffde-3cba-4b54-8450-5b1fd67da33e
3
public void gameLoop() { long startTime = System.currentTimeMillis(); long currTime = startTime; while (isRunning) { long elapsedTime = System.currentTimeMillis() - currTime; currTime += elapsedTime; // update if (startTime + 3000 < currTime) update(elapsedTime); // draw the screen Graphics2D g = screen.getGraphics(); draw(g); g.dispose(); screen.update(); // take a nap try { Thread.sleep(20); } catch (InterruptedException ex) { } } }
eda8fe0c-c464-4185-9a82-692c2e8d3b1f
9
public static void display(JPanel p, String font) { // loops for the length of how many non-repeating words there are rect = new ArrayList<Rectangle>(); System.out.println("hi hi hi world!! " + wordsList.size()); p.setOpaque(true); p.setBackground(Color.white); for(int q = 0; q < wordsList.size(); q++) { red = r.nextInt(256); green = r.nextInt(256); blue = r.nextInt(256); System.out.println("hi hi hi " + q); // default multiplier int multi = 14; System.out.println("1"); // default bounds values int x = 0; System.out.println("2"); int y = 0; System.out.println("3"); int height, width; System.out.println("4"); // array list of the times each word occurs ArrayList<Integer> timesList = new ArrayList<Integer>(Arrays.asList(times)); System.out.println("5"); // creates a new integer to hold the position of the word that corresponds to its correct frequency // because there isn't a way to sort the word array based on the integer array int wordsListPosition = Arrays.asList(timesOld).indexOf(times[q]); System.out.println("6"); // number of words that only occur once int singleFreq = Collections.frequency(timesList, new Integer(1)); System.out.println("7"); // corrects the multiplier based upon how many total words there are to be displayed or if the single word count // is greater than 100 if((wordsList.size() >= 500) && (wordsList.size() < 1000) || (singleFreq > 100)) { System.out.println("8"); multi = 8; } if((wordsList.size() > 1000)) { System.out.println("9"); multi = 6; } System.out.println("10"); // the font size is equal to the frequency at q position in the array multiplied by the multiplier fontSize = times[q] * multi; System.out.println("11"); // new color from random values Color background = new Color(red, green, blue); System.out.println("12"); // new JLabel created from the word at the corresponding position based upon the times array JLabel word = new JLabel(wordsList.get(wordsListPosition)); System.out.println("13"); // sets font color word.setForeground(background); System.out.println("14"); // sets font, style, and size word.setFont(new Font(font, Font.PLAIN, fontSize)); System.out.println("15"); // creates new FontMetrics object to determine the bounds of the word FontMetrics fm = word.getFontMetrics(word.getFont()); System.out.println("16"); // gets the height of the word height = fm.getHeight(); System.out.println("17"); // gets the width of the word width = fm.stringWidth(wordsList.get(wordsListPosition)); System.out.println("18"); // if an exception has already been found, resize the rest of the words if((cont == 1) || (wordsList.size() >= 200)) { System.out.println("19"); // creates a rectangle for the word that has been rescaled Rectangle rescaled = WordCloud.rescaleFont(p, fontSize, wordsListPosition, word, font); System.out.println("20"); // new height, width, x value, and y value for the word height = (int)rescaled.getHeight(); System.out.println("21"); width = (int)rescaled.getWidth(); System.out.println("22"); x = (int)rescaled.getX(); System.out.println("23"); y = (int)rescaled.getY(); System.out.println("24"); // new rectangle created from the new "rescaled" parameters Rectangle correctRect = WordCloud.checkRect(q, x, y, width, height); System.out.println("25"); // new height, width, x value, and y value for the word height = (int)correctRect.getHeight(); System.out.println("26"); width = (int)correctRect.getWidth(); System.out.println("27"); x = (int)correctRect.getX(); System.out.println("28"); y = (int)correctRect.getY(); System.out.println("29"); // sets the bounds for the JLabel word.setBounds(x, y, width, height); System.out.println("30"); // turns the frequency of the just displayed word to zero so it can't be found again if there are multiples // words with the same frequency. zero is used because each word occurs at least once. timesOld[wordsListPosition] = 0; System.out.println("31"); // displays the word p.add(word); System.out.println("32"); } // if an exception hasn't been found yet continue System.out.println("20"); if(cont == 0) { // tries for an IllegalArgumentException try { // generates random coordinates within the bounds of the GUI x = r.nextInt(746-width); y = r.nextInt(484-height); Rectangle correctRect = WordCloud.checkRect(q, x, y, width, height); height = (int)correctRect.getHeight(); width = (int)correctRect.getWidth(); x = (int)correctRect.getX(); y = (int)correctRect.getY(); word.setBounds(x, y, width, height); timesOld[wordsListPosition] = 0; p.add(word); } // catches an IllegalArgumentException, in this program a "n is not a positive integer" is thrown when // the font size is too large catch(IllegalArgumentException e) { Rectangle rescaled = WordCloud.rescaleFont(p, fontSize, wordsListPosition, word, font); height = (int)rescaled.getHeight(); width = (int)rescaled.getWidth(); x = (int)rescaled.getX(); y = (int)rescaled.getY(); Rectangle correctRect = WordCloud.checkRect(q, x, y, width, height); height = (int)correctRect.getHeight(); width = (int)correctRect.getWidth(); x = (int)correctRect.getX(); y = (int)correctRect.getY(); word.setBounds(x, y, width, height); timesOld[wordsListPosition] = 0; p.add(word); } } } }
15eb710d-4555-4c31-a9df-b01cd6758548
9
static public boolean checkInstallation(JavaPlugin plugin, Properties config, Logger log) { boolean ret = true; String pluginName = plugin.getDescription().getName(); byte buffer[] = new byte[512]; Iterator<Entry<Object, Object>> it = config.entrySet().iterator(); while (it.hasNext()) { Entry<Object, Object> entry = it.next(); if (!(entry.getKey() instanceof String) || !(entry.getValue() instanceof String)) { continue; } String path = (String) entry.getKey(); String url = (String) entry.getValue(); File file = new File(path); if (!file.exists()) { // make folders file.getParentFile().mkdirs(); DataInputStream dis = null; DataOutputStream dos = null; try { // get the url URL fileToGet = new URL(url); //net input dis = new DataInputStream(fileToGet.openStream()); //file output dos = new DataOutputStream(new FileOutputStream(file)); int size; while ((size = dis.read(buffer)) > 0) { dos.write(buffer, 0, size); } log.info(pluginName + " : Downloaded default file " + path); } catch (IOException ex) { log.warning(pluginName + " : could not download " + path); ret = false; } finally { try { if (dis != null) { dis.close(); } if (dos != null) { dos.close(); } } catch (IOException ex) { log.warning(pluginName + " : could not close streams for " + path); } } } } return ret; }
b50c41ab-f0b4-4b2a-b086-d0fa185eaf6c
5
public boolean isFull(Comparable[] flatTree) { boolean answer = true; for (int i = 1; i < flatTree.length; i++) // go through everything in the flattree { Comparable left = getLeftKid(i,flatTree); // get the left child of the current item Comparable right = getRightKid(i,flatTree); // get the right child of the current item if ((left == null && right != null) || (left != null && right == null)) // for it to be a full tree, each spot needs to have 0 { // or no kids, if either spot has only ONE kid, then this will fail answer = false; // one has only ONE kid, so set it to false } } return answer; //return the answer }
60334a1f-619e-4266-ae42-0b90800643fd
7
private void flipColors(Node h) { // h must have opposite color of its two children assert (h != null) && (h.left != null) && (h.right != null); assert (!isRed(h) && isRed(h.left) && isRed(h.right)) || (isRed(h) && !isRed(h.left) && !isRed(h.right)); h.color = !h.color; h.left.color = !h.left.color; h.right.color = !h.right.color; }
001bb03c-c318-418b-8775-6700471dfc6b
5
public void writeKnownAttributes(GrowableConstantPool gcp, DataOutputStream output) throws IOException { if (bytecode != null) { output.writeShort(gcp.putUTF8("Code")); output.writeInt(bytecode.getSize()); bytecode.write(gcp, output); } if (exceptions != null) { int count = exceptions.length; output.writeShort(gcp.putUTF8("Exceptions")); output.writeInt(2 + count * 2); output.writeShort(count); for (int i = 0; i < count; i++) output.writeShort(gcp.putClassName(exceptions[i])); } if (syntheticFlag) { output.writeShort(gcp.putUTF8("Synthetic")); output.writeInt(0); } if (deprecatedFlag) { output.writeShort(gcp.putUTF8("Deprecated")); output.writeInt(0); } }
5c105290-6049-4b72-bf58-68303a3cdbe3
8
public synchronized void buyBooks(Set<BookCopy> bookCopiesToBuy) throws BookStoreException { if (bookCopiesToBuy == null) { throw new BookStoreException(BookStoreConstants.NULL_INPUT); } // Check that all ISBNs that we buy are there first. int ISBN; BookStoreBook book; Boolean saleMiss = false; for (BookCopy bookCopyToBuy : bookCopiesToBuy) { ISBN = bookCopyToBuy.getISBN(); if (bookCopyToBuy.getNumCopies() < 0) throw new BookStoreException(BookStoreConstants.NUM_COPIES + bookCopyToBuy.getNumCopies() + BookStoreConstants.INVALID); if (BookStoreUtility.isInvalidISBN(ISBN)) throw new BookStoreException(BookStoreConstants.ISBN + ISBN + BookStoreConstants.INVALID); if (!bookMap.containsKey(ISBN)) throw new BookStoreException(BookStoreConstants.ISBN + ISBN + BookStoreConstants.NOT_AVAILABLE); book = bookMap.get(ISBN); if (!book.areCopiesInStore(bookCopyToBuy.getNumCopies())) { book.addSaleMiss(); // If we cannot sell the copies of the book // its a miss saleMiss = true; } } // We throw exception now since we want to see how many books in the // order incurred misses which is used by books in demand if (saleMiss) throw new BookStoreException(BookStoreConstants.BOOK + BookStoreConstants.NOT_AVAILABLE); // Then make purchase for (BookCopy bookCopyToBuy : bookCopiesToBuy) { book = bookMap.get(bookCopyToBuy.getISBN()); book.buyCopies(bookCopyToBuy.getNumCopies()); } return; }
7dcee073-88b2-4078-9d29-d78cc7fc0c1d
4
@Override public void stop() { switch( channelType ) { case SoundSystemConfig.TYPE_NORMAL: if( clip != null ) { clip.stop(); clip.setFramePosition(0); } break; case SoundSystemConfig.TYPE_STREAMING: if( sourceDataLine != null ) sourceDataLine.stop(); break; default: break; } }
d3d46d77-573d-42fc-bed5-3fa91eaf12d1
1
public void copyField( Level level ) { for ( int i = 0; i < level.field.length; i++ ) { System.arraycopy( level.field[i], 0, field[i], 0, level.field[0].length ); } }
054779e8-4773-462f-b89e-6e9bc2daab90
5
public LinkedList<File> getPatches() { LinkedList<File> patches = new LinkedList<File>(); if(carrierString!=null) { if(carrierString.length()>0) { patches.add(findReplace(extractFromJar(CARRIER_PATCH), "/*Edit Here*/", "+\t\t\tthis.carrierText = \"" + carrierString + "\";\n")); } } if(textColour!=null) { if(textColour!=Color.WHITE) { String colHex = getHexVal(); patches.add(findReplace(extractFromJar(TEXTCOLOUR_PATCH), "/*Edit Here*/", "+\t\tcolor: " + colHex + ";\n")); } } if(opacity!=100) { String opacVal = (((double)opacity)/100) + ""; patches.add(findReplace(extractFromJar(OPACITY_PATCH), "/*Edit Here*/", "+\topacity: " + opacVal + ";\n")); } return patches; }
cc0dd065-1949-43a9-b7d0-0df939904029
1
private void init() { _view.cmb_status.setModel(new javax.swing.DefaultComboBoxModel(fa.Ticket_ComboBox(4).toArray( new Object[fa.Ticket_ComboBox(4).size()]))); _view.cmb_category.setModel(new javax.swing.DefaultComboBoxModel(fa.Ticket_ComboBox(3).toArray( new Object[fa.Ticket_ComboBox(3).size()]))); _view.cmb_eID.setModel(new javax.swing.DefaultComboBoxModel(fa.Ticket_ComboBox(2).toArray( new Object[fa.Ticket_ComboBox(2).size()]))); _view.cmb_cID.setModel(new javax.swing.DefaultComboBoxModel(fa.Ticket_ComboBox(1).toArray( new Object[fa.Ticket_ComboBox(1).size()]))); ArrayList <String> list = fa.showProductName(); model = new DefaultListModel(); for (int i=0; i <= list.size()-1; i++) { model.addElement((String)list.get(i)); } _view.ls_products.setModel(model); }
9c74f63d-4255-45bd-9f39-4e055c48e111
4
private void readGroups( Element groupsElement ) { NodeList nl = groupsElement.getChildNodes(); for ( int i=0;i<nl.getLength();i++ ) { org.w3c.dom.Node node = nl.item( i ); if ( node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE ) { String nodeName = node.getNodeName(); if ( nodeName != null && nodeName.equals(GROUP) ) { Element e = (Element)node; String groupName = e.getAttribute( NAME ); String parentStr = e.getAttribute( PARENT ); short parent = Short.parseShort( parentStr ); Group g = new Group( parent, groupName ); groups.add( g ); } } } }
8553ad48-c1ec-4f6e-9b4e-26b567c64a2b
2
public void filter(byte[] samples, int offset, int length) { for (int i=offset; i<offset+length; i+=2) { // update the sample short oldSample = getSample(samples, i); short newSample = (short)(oldSample + decay * delayBuffer[delayBufferPos]); setSample(samples, i, newSample); // update the delay buffer delayBuffer[delayBufferPos] = newSample; delayBufferPos++; if (delayBufferPos == delayBuffer.length) { delayBufferPos = 0; } } }
7451891c-f55e-4b7b-b678-97ca450bd8d4
8
public static void main(String[] args) { if (args.length < 2) { System.out.println("Please indicate the number of planes and the length of a time unit (in milliseconds) as command line arguments (in that order)."); return; } int num_aircraft; int time_unit; Lock lock; try { num_aircraft = Integer.parseInt(args[0]); time_unit = Integer.parseInt(args[1]); if ((args.length > 2) && (args[2].equals("C"))) { lock = new LockC(); } else { lock = new LockB(num_aircraft); } } catch (NumberFormatException e) { System.out.println("Please enter only numbers for the number of planes and the time unit."); return; } Random rand = new Random(); Aircraft.set_time_unit(time_unit); Aircraft.set_lock(lock); Aircraft.set_random(rand); //create a thread for each Aircraft, which will have an id from 0 to num-aircraft - 1 and a //random number of touch-and-goes Thread threads[] = new Thread[num_aircraft]; for (int i = 0; i < num_aircraft; i++) { threads[i] = new Thread(new Aircraft(i, rand.nextInt(MAX_TOUCH_GO))); } //Let the aircraft class know that the simulation is beginning //and then start all of the threads/planes Aircraft.begin_simulation(); for (int i = 0; i < num_aircraft; i++) { threads[i].start(); } try { //wait on all of the planes to finish their training flights for (int i = 0; i < num_aircraft; i++) { threads[i].join(); } } catch (InterruptedException e) { System.out.println("Error: main interrupted."); } }
64400854-7a57-49ce-a277-31e5c5844ae3
1
public static NormalDistributedStochasticLotsizingProblem generate( int quarterPeriodLength, int numberOfQuarterPeriods, double baseLevelMean, double amplitudeMean, double cv, double setupCost, double inventoryHoldingCost, float alpha, AbstractNormalLikeOrdersGenerator orderGenerator){ //calculate sin step double sinStep = (Math.PI/2)/quarterPeriodLength; NormalDistributedLotSizingPeriod[] periods = new NormalDistributedLotSizingPeriod[quarterPeriodLength*numberOfQuarterPeriods]; for (int i = 0; i < periods.length; i++){ double mean = baseLevelMean+(Math.sin(i*sinStep)*amplitudeMean); periods[i] = new NormalDistributedLotSizingPeriod(setupCost, inventoryHoldingCost, orderGenerator.getOrderDistributions(mean, mean*cv)); } return new NormalDistributedStochasticLotsizingProblem("Generated: SinodialSeasonNormalDistributedProblemGenerator (1)", periods, alpha); }
b1e860f2-a0ac-4eff-bb4f-fee1fc7198cf
1
public synchronized ClassInfo loadClass(String className) throws ClassNotFoundException { // Lots of interesting stuff to do here. For the moment, just // load the class from the ClassInfoLoader and add it to the // hierarchy. className = className.replace('.', '/').intern(); // Check the cache of ClassInfos ClassInfo info = (ClassInfo) classInfos.get(className); if (info == null) { BloatContext.db("BloatContext: Loading class " + className); info = loader.loadClass(className); hierarchy.addClassNamed(className); BloatContext.db("loadClass: " + className + " -> " + info); classInfos.put(className, info); } return (info); }
a6ac5c6c-7f09-42e1-a377-8f450fdd934e
3
public int inserir(Manutencao m){ Connection conn = null; PreparedStatement pstm = null; int retorno = -1; try{ conn = ConnectionFactory.getConnection(); pstm = conn.prepareStatement(INSERT, Statement.RETURN_GENERATED_KEYS); pstm.setString(1, m.getMotivo()); pstm.setString(2, m.getTipo()); pstm.setDate(3, m.getData()); pstm.execute(); try(ResultSet rs = pstm.getGeneratedKeys()){ if(rs.next()){ retorno = rs.getInt(1); } } }catch(Exception e){ JOptionPane.showMessageDialog(null,"Erro ao adicionar um cadastro "+ e); }finally{ try{ ConnectionFactory.closeConnection(conn, pstm); }catch (Exception e){ JOptionPane.showMessageDialog(null,"Erro ao desconectar com o banco " + e); } } return retorno; }
d2e64d8b-9478-43ab-b83a-127912a264ec
5
public void actionPerformed(ActionEvent evt) { String response; try { Object source = evt.getSource(); //finds the source of the objects that triggers the event int indexPosition = (Integer) ((JComponent) evt.getSource()).getClientProperty("index"); //variable that represents the buttons 'index' (0-8) out.println("MOVE: " + indexPosition); response = in.readLine(); System.out.println(response); if (response.startsWith("LEGAL_MOVE")) { ((AbstractButton) source).setText("X"); //Sets the user selected button as an 'X' response = in.readLine(); setOpponentsMove(response); } // Check for win/loss out.println("CHECK_STATUS"); response = in.readLine(); System.out.println(response); if (response.startsWith("WON")) { endOfGame("You win!!"); } else if (response.startsWith("LOST")) { endOfGame("Sorry you lose."); } else if (response.startsWith("DRAW")) { endOfGame("Cat's game... it's a draw!"); } } catch (IOException e) { e.printStackTrace(); } }
fcb755cb-e73a-4283-9e97-dce34d0b8f01
9
private float getValue(char letter) { switch (letter) { case 'I': return I; case 'V': return V; case 'X': return X; case 'L': return L; case 'C': return C; case 'D': return D; case 'M': return M; case 'S': return S; case '*': return star; } return -1; }
bbe366a2-7ab6-4425-a1d9-05a444b6472a
4
@Test public void testMoveForward() { Random rand = Mockito.mock(Random.class); // On s'assure que le terrain et toujours franchissable. Mockito.when(rand.nextInt(Land.CountLand())).thenReturn(0); Robot r = new Robot(); r.land(new Coordinates(0,0), new LandSensor(rand)); try { Assert.assertEquals(0, r.getXposition()); Assert.assertEquals(0, r.getYposition()); r.moveForward(); Assert.assertEquals(0, r.getXposition()); Assert.assertEquals(1, r.getYposition()); r.turnRight(); r.moveForward(); Assert.assertEquals(1, r.getXposition()); Assert.assertEquals(1, r.getYposition()); r.turnRight(); r.moveForward(); Assert.assertEquals(1, r.getXposition()); Assert.assertEquals(0, r.getYposition()); r.turnRight(); r.moveForward(); Assert.assertEquals(0, r.getXposition()); Assert.assertEquals(0, r.getYposition()); } catch (UnlandedRobotException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (InsufficientChargeException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (LandSensorDefaillance landSensorDefaillance) { landSensorDefaillance.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (InaccessibleCoordinate inaccessibleCoordinate) { inaccessibleCoordinate.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } }
3213005f-7be9-4603-87b2-d9be54f1de8c
9
public static void main(String[] args) throws IOException { // 1. Reading input by lines: BufferedReader in = new BufferedReader(new FileReader("mao.txt")); String s, s2 = new String(); while ((s = in.readLine()) != null) s2 += s + "\n"; in.close(); // 1b. Reading standard input: BufferedReader stdin = new BufferedReader(new InputStreamReader( System.in)); System.out.print("Enter a line:"); System.out.println(stdin.readLine()); // 2. Input from memory StringReader in2 = new StringReader(s2); int c; while ((c = in2.read()) != -1)//add by andy, c is the character code System.out.print((char) c); // 3. Formatted memory input try { //DataInputStream, which is a byteoriented //I/O class (rather than char oriented). DataInputStream in3 = new DataInputStream(new ByteArrayInputStream( s2.getBytes())); while (true) System.out.print((char) in3.readByte()); } catch (EOFException e) { System.err.println("End of stream"); } // 4. File output try { BufferedReader in4 = new BufferedReader(new StringReader(s2)); PrintWriter out1 = new PrintWriter(new BufferedWriter( new FileWriter("IODemo.out"))); int lineCount = 1; while ((s = in4.readLine()) != null) out1.println(lineCount++ + ": " + s); out1.close(); } catch (EOFException e) { System.err.println("End of stream"); } // 5. Storing & recovering data try { DataOutputStream out2 = new DataOutputStream( new BufferedOutputStream(new FileOutputStream("Data.txt"))); out2.writeDouble(3.14159); out2.writeUTF("That was pi"); out2.writeDouble(1.41413); out2.writeUTF("Square root of 2"); out2.close(); DataInputStream in5 = new DataInputStream(new BufferedInputStream( new FileInputStream("Data.txt"))); // Must use DataInputStream for data: System.out.println(in5.readDouble()); // Only readUTF() will recover the // Java-UTF String properly: System.out.println(in5.readUTF()); // Read the following double and String: System.out.println(in5.readDouble()); System.out.println(in5.readUTF()); } catch (EOFException e) { throw new RuntimeException(e); } // 6. Reading/writing random access files RandomAccessFile rf = new RandomAccessFile("rtest.dat", "rw"); for (int i = 0; i < 10; i++) rf.writeDouble(i * 1.414); rf.close(); rf = new RandomAccessFile("rtest.dat", "rw"); rf.seek(5 * 8); rf.writeDouble(47.0001); rf.close(); rf = new RandomAccessFile("rtest.dat", "r"); for (int i = 0; i < 10; i++) System.out.println("Value " + i + ": " + rf.readDouble()); rf.close(); monitor.expect("mao.txt"); }
d8648e5d-9637-47f8-ba9e-4c788a84b931
6
public void addMessageListener(int type, MessageEventListener messageEventListener) { try { switch(type) { case 0: this.stdmessageEventManager.addEventListener(messageEventListener); break; case 1: this.authmessageEventManager.addEventListener(messageEventListener); break; case 2: this.usermessageEventManager.addEventListener(messageEventListener); break; case 3: this.channelmessageEventManager.addEventListener(messageEventListener); break; case 4: this.severmessageEventManager.addEventListener(messageEventListener); break; } } catch (Exception e) { System.out.println("Could not attach listener - " + e.getMessage()); } }
b822c1af-56fc-4f14-be3f-d3e33ea8e807
1
public void setState1(State state1) throws IllegalArgumentException{ if(state1 != null) this.state1 = state1; else throw new IllegalArgumentException(); }
c6a9f54b-ca05-40f9-af6f-223b1d0619ca
2
@BeforeClass public static void setUpClass() { clock_ = new LamportClock(); timestampList_ = new ArrayList<Long>(); thread1_ = new Thread(new Runnable() { @Override public void run() { for (int i = 1; i <= events1_; i++) { clock_.clockedEvent((long) i); synchronized (lock_) { timestampList_.add(clock_.getTimestamp()); } } } }); thread2_ = new Thread(new Runnable() { @Override public void run() { for (int i = 1; i <= events2_; i++) { clock_.clockedEvent((long) i); synchronized (lock_) { timestampList_.add(clock_.getTimestamp()); } } } }); }
4c7e4790-7f84-4a83-8c61-cc5dc1589637
3
public long skip( long n ) throws IOException { if( this.isClosed ) throw new IOException( "This stream was already closed. Cannot skip input." ); if( this.emptyStopMarkSet() ) return this.in.skip( n ); // First call? if( this.currentStreams[0] == null ) initStreamStack(); return this.currentStreams[ 0 ].skip( n ); /*long skipped = this.in.skip( n ); // Buffer data becomes invalid when skipping! this.buffer.clear(); return skipped; */ }
aa49e470-b025-4115-8e30-3693ca0090c6
0
public Taso getTaso() { return taso; }
6d7fcfb8-3a12-4fab-9158-33cc071b7cc1
4
public boolean implementedBy(ClassInfo clazz) { while (clazz != this && clazz != null) { ClassInfo[] ifaces = clazz.getInterfaces(); for (int i = 0; i < ifaces.length; i++) { if (implementedBy(ifaces[i])) return true; } clazz = clazz.getSuperclass(); } return clazz == this; }
42c4a065-1624-46ca-aadc-d9b21fb225fe
5
protected String getList() { StringBuilder fileList = new StringBuilder(); File[] files = new File( configPath ).listFiles(); fileList.append( " " ); for ( int i = 0; i < files.length; i++ ) { if ( files[i].getName().contains( ".txt" ) ) { fileList.append( files[i].getName() ); if ( i < ( files.length - 1 ) ) { fileList.append( ", " ); } if ( i % 5 == 0 && i != 0 ) { fileList.append( "\n " ); } } } return fileList.toString(); }
bf8c4fa6-2d34-4271-9f0e-3e9ba792be6e
4
public static int ppt2pdf(String srcPath, String destPath) { File file = new File(srcPath); if (file.exists()) { ComThread.InitMTA(); ActiveXComponent ppt = null; try { ppt = new ActiveXComponent("Powerpoint.Application"); ppt.setProperty("Visible", new Variant(true)); Dispatch presentations = ppt.getProperty("Presentations") .toDispatch(); log.info("使用MS Powerpoint打开文档..." + srcPath); Dispatch presentation = Dispatch.call(presentations, "Open", new Variant(srcPath), new Variant(PPTREADONLYMODE)) .toDispatch(); log.info("转换文档到PDF..." + destPath); File toFile = new File(destPath); if (toFile.exists()) { toFile.delete(); } Dispatch.call(presentation, "SaveAs", new Variant(destPath), new Variant(PPTFORMATPDF)); Dispatch.call(presentation, "Close"); log.info("转换完成"); return TRANSFERSUCCESS; } catch (Exception e) { log.info("调用MS Powerpoint转换失败:" + e.getMessage()); } finally { if (ppt != null) { log.info("退出Powerpoint"); ppt.invoke("Quit"); } ComThread.Release(); } } log.info("文档不存在..."); return TRANSFERFAILURE; }
ed7b2f70-5444-4f0a-9cc6-40de17050c66
2
public boolean deleteKey(String key) { try { if (METHOD_DELETE_KEY == null) { METHOD_DELETE_KEY = getMethod(mRoot.getClass(), "WindowsRegDeleteKey", int.class, byte[].class); } return ((Integer) METHOD_DELETE_KEY.invoke(mRoot, new Object[] { mRootKey, toCstr(key) })).intValue() == 0; } catch (Exception exception) { Log.error(exception); } return false; }
70b0ee01-778f-4280-8fe9-0c73926680ad
8
private boolean verifyValidExport() { for (Link link : story.getAllLinks()) { // Check if there are any links with no media item if (link.getMediaItems().isEmpty()) { JOptionPane.showMessageDialog(null, "There are Links with no Media items. Add some media items or delete these links.", "No media items", JOptionPane.ERROR_MESSAGE); return false; } for (final MediaItem mediaItem : link.getMediaItems()) { // Check for corrupt items if (mediaItem.isCorrupt()) { JOptionPane.showMessageDialog(null, "There are one or more corrupt files in this project. \nSelect these files before the export can proceed.", "Corrupt file(s) found", JOptionPane.WARNING_MESSAGE); // Browse for any corrupt file JFileChooser corruptFileChooser = new JFileChooser(); corruptFileChooser.setFileFilter(new ExtensionFileFilter( new String[]{".RTF", ".TXT", ".HTM", ".HTML", ".JPG", ".JPEG", ".PNG", ".BMP", ".M4V", ".MOV", ".MP4"}, "All supported files")); corruptFileChooser.setAcceptAllFileFilterUsed(false); corruptFileChooser.setDialogTitle("Find the corrupt file"); corruptFileChooser.setFileFilter(new FileFilter() { @Override public boolean accept(File corruptFile) { if (corruptFile.isDirectory()) { return true; } else if (mediaItem.getFileName().equals(corruptFile.getName())) { return true; } return false; } @Override public String getDescription() { return mediaItem.getFileName(); } }); int corruptDialog = corruptFileChooser.showOpenDialog(this); // Catch actions of the File Chooser Dialog Window if (corruptDialog == JFileChooser.APPROVE_OPTION) { File corruptFile = corruptFileChooser.getSelectedFile(); mediaItem.setAbsolutePath(corruptFile.getPath().substring(0, corruptFile.getPath().length() - corruptFile.getName().length())); mediaItem.setCorrupt(false); } else if (corruptDialog == JFileChooser.CANCEL_OPTION) { return false; } } } } return true; }
5beda620-925c-43b9-93db-3395849a6614
1
protected DatabaseHandler() { try { //contructor method to initiate (combo)DataSource for pooled connections on spawning an object. //initiateDataSource(); initiateDataSource(); } catch (SQLException ex) { throw new RuntimeException("Something went wrong while initializing the DataSource", ex); } nodesDownloadedPct = 0; edgesDownloadedPct = 0; streetsDownloadedPct = 0; }
6d918ca8-5893-4747-8983-912259975b01
2
public void testTrackRead() { try { buildEmptyTrackForTest(); Record r = GetRecords.create().getRecords("fake-empty-tracks-testing").get(0); for (int i = 1; i <= r.getNumberOfFormatTracks(); i++) { assert (r.getFormTrackArtist(i).length() > 0); System.err.println("HERE = " + r.getFormTrackTitle(i)); assert (r.getFormTrackTitle(i).length() > 0); } } catch (SQLException e) { e.printStackTrace(); assert (false); } }
cc4a2816-3cf8-4c23-8407-43b40f0eeb59
8
public static double[][] readMatrix(Path path, HamaConfiguration conf, int rows, int columns, int blockSize) { int finalRows = getBlockMultiple(rows, blockSize); int finalCols = getBlockMultiple(columns, blockSize); double[][] matrix = new double[finalRows][finalCols]; SequenceFile.Reader reader = null; try { FileSystem fs = FileSystem.get(conf); reader = new SequenceFile.Reader(fs, path, conf); VectorWritable row = new VectorWritable(); IntWritable i = new IntWritable(); while (reader.next(i, row) && i.get()<rows) { DoubleVector v = row.getVector(); for (int j = 0; j < columns; j++) { matrix[i.get()][j] = v.get(j); } } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } for (int k = rows; k < finalRows; k++) { for (int p = columns; p < finalCols; p++) { matrix[k][p] = 0; } } return matrix; }
0398f7fa-515d-4015-96e9-8a820fcc3499
1
public final TMState createBlock(Point point) { int i = 0; while (getStateWithID(i) != null) i++; OpenAction read = new OpenAction(); OpenAction.setOpenOrRead(true); JButton button = new JButton(read); button.doClick(); OpenAction.setOpenOrRead(false); return getAutomatonFromFile(i, point); }
bcd39265-0c01-4287-b106-e92b8d2e4bc6
7
public Integer insert(MovimientosBeans movi) throws DAOException { PreparedStatement pst = null; ResultSet generatedKeys = null; try { pst = con.prepareStatement(sql.getString("INSERT_MOVIMIENTOS"), Statement.RETURN_GENERATED_KEYS); //INSERT INTO MOVIMIENTOS (IDTIPO_MOVIMIENTO, IDUSUARIOS, IDUNICO_MOVIMIENTOS, IDUNICO_PRODUCTOS, DATE, PALLETS_IDPALLET) VALUES (?,?,?,?,?,?,?) pst.setInt(1, movi.getIdTipoMovimiento()); pst.setInt(2, movi.getIdUsuario()); pst.setInt(3, movi.getIdUnicoMovimientos()); pst.setInt(4, movi.getIdUnicoProductos()); pst.setDate(5, (java.sql.Date) movi.getDate()); pst.setInt(6, movi.getPalletsIdPallet()); if (pst.executeUpdate() != 1) throw new DAOException("No se pudo insertar la solicitud"); generatedKeys = pst.getGeneratedKeys(); generatedKeys.first(); ResultSetMetaData rsmd = generatedKeys.getMetaData(); if (rsmd.getColumnCount() > 1) { throw new DAOException("Se genero mas de una llave"); } //con.commit(); return generatedKeys.getInt(1); } catch (SQLException e) { e.printStackTrace(); throw new DAOException(e.getMessage()); } catch (Exception e) { throw new DAOException(e.getMessage()); } finally { try { if (pst != null) pst.close(); if (generatedKeys != null) generatedKeys.close(); } catch (SQLException e) { e.printStackTrace(); } } }
a2f11ce7-cc31-496d-ab39-03f9072977f4
4
public void get(int key) { HashPrinter.tryGet(key); /** Run along the array */ int runner = 0; int hash = (key % TABLE_INITIAL_SIZE); while (table[hash] != null && runner < TABLE_INITIAL_SIZE) { if (table[hash].getKey() == key) { break; } runner++; hash = ((key + runner) % TABLE_INITIAL_SIZE); } if (runner >= TABLE_INITIAL_SIZE) { HashPrinter.notFound(key); } else { HashPrinter.found(table, key, hash); } }
da6a7b72-c8e2-4b41-bf16-03e25b3e5106
1
@Override public boolean canImport(TransferSupport support) { return (support.getComponent() instanceof JList) && support.isDataFlavorSupported(RosterTransferComponent.ROSTER_COMPONENT_DATA_FLAVOR); }
958b9bf8-c2e4-451a-8384-21502fa991b1
9
private static ArrayList<ResidualEdge> minCostFlowWithPrimalDualSub( ArrayList<ResidualEdge>[] edges, int[] lastShortestDists, int s, int t) { int n = edges.length; ResidualEdge[] prevE = new ResidualEdge[n]; int[] prevV = new int[n]; int[] dist = new int[n]; Arrays.fill(prevV, -1); Arrays.fill(dist, INF); dist[s] = 0; prevV[s] = -2; // make sure source is not rediscovered PriorityQueue<EdgeState> queue = new PriorityQueue<EdgeState>(); queue.add(new EdgeState(0, s)); while (!queue.isEmpty()) { EdgeState state = queue.poll(); int v = state.n; if (dist[v] < state.cost) continue; for (ResidualEdge e : edges[v]) { if (e.residual > 0 && dist[e.to] > dist[v] + e.cost + lastShortestDists[v] - lastShortestDists[e.to]) { dist[e.to] = dist[v] + e.cost + lastShortestDists[v] - lastShortestDists[e.to]; prevE[e.to] = e; prevV[e.to] = v; queue.add(new EdgeState(dist[e.to], e.to)); } } } if (prevE[t] == null) return null; for (int v = 0; v < n; v++) { lastShortestDists[v] += dist[v]; } ArrayList<ResidualEdge> path = new ArrayList<ResidualEdge>(); ResidualEdge e; for (int v = t;; v = prevV[v]) { e = prevE[v]; if (e == null) break; path.add(e); } return path; }
c9e6dfb9-15b7-4721-9ef1-b49b50cf96b2
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(PasswordGenerator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(PasswordGenerator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(PasswordGenerator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(PasswordGenerator.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 PasswordGenerator().setVisible(true); } }); }
4fd3a3c6-341e-457d-a4db-8b150f048f3e
2
public Bag getDiscsByType(DiscType discType) { LOGGER.log(Level.INFO, "Getting all discs of type " + discType); Bag discBag = new Bag(); for (int i = 0; i < discs.size(); i++) { if (discs.get(i).getDiscType() == discType) { discBag.addDisc(discs.get(i)); } } LOGGER.log(Level.INFO, "Found " + discBag.size() + " discs found of type " + discType); return discBag; }
9c3f565b-43c7-4df2-b613-107e4bc5b423
5
private static int procmemsize(long rnum, String path) { System.gc(); long musage = memusagerss(); double stime = Utility.time(); long count = -1; if (path == null) { int bnum = rnum < Integer.MAX_VALUE ? (int)rnum : Integer.MAX_VALUE; Map<String, String> map = new HashMap<String, String>(bnum, 100); for (long i = 0; i < rnum; i++) { String key = String.format("%08d", i); String value = String.format("%08d", i); map.put(key, value); } count = map.size(); } else { DB db = new DB(); if (db.open(path, DB.OWRITER | DB.OCREATE | DB.OTRUNCATE)) { for (long i = 0; i < rnum; i++) { String key = String.format("%08d", i); String value = String.format("%08d", i); db.set(key, value); } count = db.count(); db.close(); } } printf("count: %d\n", count); double etime = Utility.time(); printf("time: %.3f\n", etime - stime); System.gc(); printf("usage: %.3f MB\n", (memusagerss() - musage) / 1024.0 / 1024.0); return 0; }
6b1e0882-4796-4cef-9d0f-eab2093621b0
5
@Override public void update(Observable o, Object arg) { searchNumber.setText(arg+""); if (board.getValidAnswer()){ switch(movePlayer){ case moveByA: pointsPlayerA++; log.finer("Player A was right!"); break; case moveByB: pointsPlayerB++; log.finer("Player B was right!"); break; } lValidNumber.setIcon(new ImageIcon("richtig.png")); } else{ switch(movePlayer){ case moveByA: pointsPlayerB++; log.finer("Player A was wrong!"); break; case moveByB: pointsPlayerA++; log.finer("Player B was wrong!"); break; } lValidNumber.setIcon(new ImageIcon("falsch.png")); } movePlayer = -1; lPlayerPoints.setText("Player A: " + pointsPlayerA + " | Player B: " + pointsPlayerB); }
669b945e-465d-4508-919b-51753b8ecf39
1
public void rotCW() { if (!pause) { plateau.updatePosition(0, 1); updateObservers(); } }
99518101-fd60-42ff-bd4f-415c71216374
5
public LinkedHashMap<Integer, Persona> cargarPersonaTexto(String nombreFichero) { LinkedHashMap<Integer, Persona> personas = new LinkedHashMap<>(); Persona p; FileInputStream fis = null; ObjectInputStream ois = null; try { fis = new FileInputStream(nombreFichero); ois = new ObjectInputStream(fis); //Si el archivo está ocupado también devuelve 0 while (fis.available() > 0) { p = (Persona) ois.readObject(); personas.put(p.getId(), p); } } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(null, "Aún no existe un archivo, para crearlo \n añada personas y guardelas"); } catch (IOException | ClassNotFoundException ex) { Logger.getLogger(FicherosDatos.class.getName()).log(Level.SEVERE, null, ex); } finally { if (fis != null) { try { fis.close(); ois.close(); } catch (IOException ex) { Logger.getLogger(FicherosDatos.class.getName()).log(Level.SEVERE, null, ex); } } } return personas; }
5d63a179-a1b5-4c6b-8264-0fff9502b330
9
public static double documentRankIDFWeighted(List<String> document, List<String> query, IDFMatrix iDF) { if(document.isEmpty() && query.isEmpty()) return 1; if(document.isEmpty() && !query.isEmpty()) return 0; if(query.isEmpty() && !document.isEmpty()) return 0; FrequencyMatrix documentFrequencyMatrix = new FrequencyMatrix(document); FrequencyMatrix queryFrequencyMatrix = new FrequencyMatrix(query); double denominator; double numerator = 0; double aMagnitudeTotal = 0; double bMagnitudeTotal = 0; for(String word : document) { numerator += documentFrequencyMatrix.getFreq(word) * queryFrequencyMatrix.getFreq(word) * Math.pow(iDF.getIDF(word),2); aMagnitudeTotal += Math.pow(documentFrequencyMatrix.getFreq(word) * iDF.getIDF(word), 2); } for(String word : query) bMagnitudeTotal += Math.pow(queryFrequencyMatrix.getFreq(word) * iDF.getIDF(word), 2); denominator = Math.sqrt(aMagnitudeTotal) * Math.sqrt(bMagnitudeTotal); Double sim = numerator / denominator; if(denominator == 0) return 0; return sim; }
9865203b-5d4c-4f20-9640-f71e3b4ea3d2
3
public static long bstExperiment(BSTInterface<Long> tree) { int choice; Long number; startTime = (new Date()).getTime(); for(int i = 0; i < NUMBER_OF_CHOICES; i++) { choice = choices[i]; number = numbers[choice]; if(!tree.contains(number)) { System.out.println("Not found"); break; } else if(tree.contains(123L)) { System.out.println("123L found"); break; } } return (new Date()).getTime() - startTime; }
92bf61e1-a6d7-44f7-89c2-84d1fcaa3aa4
0
public final void addDragListeners(final Node n) { n.setOnMousePressed(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent me) { startDragX = me.getSceneX(); startDragY = me.getSceneY(); root.setStyle("-fx-opacity:.7;"); } }); n.setOnMouseReleased(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent me) { root.setStyle("-fx-opacity:1;"); } }); n.setOnMouseDragged(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent me) { stage.setX(me.getScreenX() - startDragX); stage.setY(me.getScreenY() - startDragY); } }); }
31da6fe1-a9b1-4b00-86c3-ce2ebbe3a307
3
@Override public String compress(String xml) { if(!enabled || xml == null || xml.length() == 0) { return xml; } //preserved block containers List<String> cdataBlocks = new ArrayList<String>(); //preserve blocks xml = preserveBlocks(xml, cdataBlocks); //process pure xml xml = processXml(xml); //return preserved blocks xml = returnBlocks(xml, cdataBlocks); return xml.trim(); }
6ad910b8-1fd8-4dad-8f05-d5f505fe7a0c
1
static void printNumbers(int n){ if(n <= 0){ return; } System.out.println(n); printNumbers(n-2); printNumbers(n-3); System.out.println(n); }
3ca9e8c0-86f6-4fb7-883e-28ba487d1872
7
public Map<Vertex, Integer> calculate(WeightedNonDirectedGraphImpl<Integer> graph, Vertex<Integer> start) { processedVertices = new HashSet<Vertex<Integer>>(); unsettledVertices = new HashSet<Vertex<Integer>>(); distances = new HashMap<Vertex, Integer>(graph.numVertices()); for (Vertex vertex : graph.getVertices()) { distances.put(vertex, Integer.MAX_VALUE); } distances.put(start, 0); unsettledVertices.add(start); while (!unsettledVertices.isEmpty()) { Vertex<Integer> next = getClosest(unsettledVertices); unsettledVertices.remove(next); Integer distance = distances.get(next); if (distance == Integer.MAX_VALUE) { System.out.println("Execution stopped vertices are non connected"); break; } for (Edge<Integer> neighbor : next.getEdges()) { Vertex neighborVertex; if (neighbor.getVertex1().equals(next)) { neighborVertex = neighbor.getVertex2(); } else { neighborVertex = neighbor.getVertex1(); } if (processedVertices.contains(neighborVertex)) { continue; } int newDistance = distance + neighbor.getWeight(); if (newDistance < distances.get(neighborVertex)) { distances.put(neighborVertex, newDistance); unsettledVertices.add(neighborVertex); } } processedVertices.add(next); } return distances; }
24143e5e-131c-4bd8-8cf9-6686c7a969e3
7
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); HttpSession session=request.getSession(true); String poruka=""; String ime=request.getParameter("ime"); String lozinka=request.getParameter("lozinka"); session.setAttribute("poruka",poruka); Connection con=(Connection)Konekcija.konekcija(); Statement st=null; ResultSet rs=null; try{ st=con.createStatement(); rs=st.executeQuery("select * from korisnik where korisnickoIme='"+ime+"' and lozinka='"+lozinka+"'"); if(!rs.next()){ RequestDispatcher dis=request.getRequestDispatcher("greska.jsp"); dis.forward(request, response); }else { int zahtev=rs.getInt(9); String kor=rs.getString(2); if(zahtev==0){ session.setAttribute("ime", kor); String vrstaKorisnika=rs.getString(8); if(vrstaKorisnika.equalsIgnoreCase("administrator")){ RequestDispatcher dis1=request.getRequestDispatcher("logovanjeAdministratora.jsp"); dis1.forward(request, response); }else if(vrstaKorisnika.equalsIgnoreCase("seflabaratorije")){ RequestDispatcher dis2=request.getRequestDispatcher("logovanjeSefaLabaratorije.jsp"); dis2.forward(request, response); }else if(vrstaKorisnika.equalsIgnoreCase("sefmagacina")){ RequestDispatcher dis3=request.getRequestDispatcher("logovanjeSefaMagacina.jsp"); dis3.forward(request, response); } }else{ RequestDispatcher dis1=request.getRequestDispatcher("Nalog.jsp"); dis1.forward(request, response); } }} catch(SQLException e){} finally{ if(con!=null)con.close();; out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
a28765b4-6f62-4c16-a112-cd56d352575e
5
public static void print_help_if_requested(List<String> argv, String doc) { if (argv.isEmpty() || ArrayExtensions.contain(argv, "-h") || ArrayExtensions.contain(argv, "--h") || ArrayExtensions.contain(argv, "-help") || ArrayExtensions.contain(argv, "--help")) { System.err.println(doc); System.exit(1); } }
14e84396-10a1-41a8-8485-54d1d37af3ad
4
private void scruffPolyline(Element element) { StringBuilder modified = new StringBuilder(); List<Point2D> points = Point2D.parsePoints(element.getAttribute("points")); for(int i=0, n=points.size()-1; i<n; i++) { Point2D pn0Orig = points.get(i); Point2D pn0 = pn0Orig; Point2D pn1 = points.get(i+1); double hMax = 0.02*pn0Orig.lengthTo(pn1); modified.append(pn0.asString()).append(' '); double distance; while((distance = pn0.lengthTo(pn1))>20) { double radius = distance * 0.02; if(radius>5) radius = 5; Point2D interm; // prevent a too big distorsion by cumulating displacement in the same direction do { interm = pn0.split(pn1, distance*random.nextDouble()).angularMove( radius, 2 * Math.PI * random.nextDouble()); } while(pointToLineDistance(pn0Orig, pn1, interm)>hMax); modified.append(interm.asString()).append(' '); pn0 = interm; } } // append last point modified.append(points.get(points.size() - 1).asString()); element.setAttribute("points", modified.toString()); }
1894c4cf-3e99-48db-96a1-01f502fc55b3
0
public void setPostalCode(String postalCode) { Address.setPostalCode(postalCode); }
5188783d-04ef-460a-bd5a-e87e2c00956f
1
@Override public final void update(Graphics g) { if (graphics == null) { graphics = g; } shouldClearScreen = true; raiseWelcomeScreen(); }
277281e0-3a19-4c44-9751-2f8c825dca01
5
public int[] getIntsArray() { if (this.getTypeByte() == Encoder.TAG_NULL) return null; Decoder dec; try { dec = this.getContent(); } catch (ASN1DecoderFail e) { e.printStackTrace(); return null; } ArrayList<BigInteger> ints = new ArrayList<BigInteger>(); for(;;){ Decoder val = dec.getFirstObject(true); if(val==null) break; ints.add(val.getInteger()); } int result[] = new int[ints.size()]; for(int k = 0; k<ints.size(); k++) { result[k] = ints.get(k).intValue(); } return result; }
d237b0bd-4ff0-4929-a7fb-3c765fb95bdd
1
public void generateWeapon(int ALG_TYPE, int roundNumber) { Weapon w; cw = CalculateWeapon.makeCalc(ALG_TYPE, roundNumber); w = cw.calculateWeapon(); super.setWeapon(w); if (ALG_TYPE == 1) { setPredictedWeapon(null); } else { setPredictedWeapon(w); } }
13c3fba8-abcf-4f8c-8e96-205219657c16
1
public void keyup(KeyEvent ev) { setmods(ev); if (keygrab == null) root.keyup(ev); else keygrab.keyup(ev); }