text
stringlengths
14
410k
label
int32
0
9
private static Pair<Boolean, Integer> huntDown(ChemistryUnit in, ChemistryUnit inExpression, ChemistryUnit outExpression){ if(inExpression != null && in.equals(inExpression)){ return Pair.make(true, 1); } else if(outExpression != null && in.equals(outExpression)){ return Pair.make(false, 1); } else if(in.getType() == ChemistryUnit.TYPE_BASE){ return Pair.make(false, -1); } for(Map.Entry<ChemistryUnit, Integer> cu : in.getSubUnits().entrySet()){ Pair<Boolean, Integer> pair = huntDown(cu.getKey(), inExpression, outExpression); if(pair.getValueTwo().equals(-1)){ continue; } else{ return Pair.make(pair.getValueOne(), pair.getValueTwo() * cu.getValue()); } } return Pair.make(false, -1); }
7
public void run() { AudioFormat format =new AudioFormat(8000,16,2,true,true);//AudioFormat(float sampleRate, int sampleSizeInBits, int channels, boolean signed, boolean bigEndian BufferedInputStream playbackInputStream; try { playbackInputStream=new BufferedInputStream(new AudioInputStream(s.getInputStream(),format,2147483647)); } catch (IOException ex) { return; } DataLine.Info info = new DataLine.Info(SourceDataLine.class,format); try { line = (SourceDataLine) AudioSystem.getLine(info); line.open(format, bufSize); } catch (LineUnavailableException ex) { return; } byte[] data = new byte[1024]; int numBytesRead = 0; line.start(); while (thread != null) { try{ numBytesRead = playbackInputStream.read(data); line.write(data, 0,numBytesRead); } catch (IOException e) { break; } } if (thread != null) { line.drain(); } line.stop(); line.close(); line = null; }
5
@AfterGroups("Insertion") @Test(groups = "Random BST") public void testRandomBSTSearch() throws KeyNotFoundException, EmptyCollectionException { Integer count = 0; Reporter.log("[ ** Random BST Search ** ]\n"); try { timeKeeper = System.currentTimeMillis(); for (Integer i = 0; i < seed; i++) { randomBST.search(i); } Reporter.log("Search -- Passed : " + (System.currentTimeMillis() - timeKeeper) + " ms\n"); timeKeeper = System.currentTimeMillis(); for (Integer i = -seed; i < 0; i++) { try { randomBST.search(i); } catch (KeyNotFoundException e) { count++; } } if (count == seed) { Reporter.log("False search -- Passed : " + (System.currentTimeMillis() - timeKeeper) + " ms\n"); } else { throw new KeyNotFoundException(); } } catch (KeyNotFoundException e) { Reporter.log("Searching -- Failed!!!\n"); throw e; } }
5
@Override public void update(long deltaMs) { super.update(deltaMs); for(ShopItemButton sib : itemSlots) { sib.update(deltaMs); } }
1
public static ListNode reverseBetween(ListNode head, int m, int n) { ListNode newHead = new ListNode(0); if(head == null) { return head; } if(head.next == null) { return head; } if(m==n) { return head; } ListNode currentNode = head; ListNode start = null; ListNode last = null; ListNode lasthead = newHead; int count = 1; while(currentNode != null) { ListNode tmp = currentNode.next; if(count == m) { last = currentNode; start = currentNode; } else if(start != null && count != n) { currentNode.next = last; last = currentNode; } else if(count == n){ lasthead.next = currentNode; start.next = currentNode.next; currentNode.next = last; if(m == 1) { return newHead.next; }else { return head; } } else { lasthead = currentNode; } count++; currentNode = tmp; } return head; }
9
private void renderTex(float fadeVal) { // //You draw a diamond-shaped area around the four points- final float w = xdim(), h = ydim(), x = xpos(), y = ypos() ; GL11.glBegin(GL11.GL_QUADS) ; if (fadeVal == -1) GL11.glTexCoord2f(0, 0) ; else GL11.glTexCoord3f(0, 0, fadeVal) ; GL11.glVertex2f(x, y + (h / 2)) ; if (fadeVal == -1) GL11.glTexCoord2f(0, 1) ; else GL11.glTexCoord3f(0, 1, fadeVal) ; GL11.glVertex2f(x + (w / 2), y + h) ; if (fadeVal == -1) GL11.glTexCoord2f(1, 1) ; else GL11.glTexCoord3f(1, 1, fadeVal) ; GL11.glVertex2f(x + w, y + (h / 2)) ; if (fadeVal == -1) GL11.glTexCoord2f(1, 0) ; else GL11.glTexCoord3f(1, 0, fadeVal) ; GL11.glVertex2f(x + (w / 2), y) ; GL11.glEnd() ; }
4
* @return String */ public static String stringTrim(String string) { { int start = 0; int last = string.length() - 1; int end = last; while ((start <= end) && (Stella.$CHARACTER_TYPE_TABLE$[(int) (string.charAt(start))] == Stella.KWD_WHITE_SPACE)) { start = start + 1; } while ((end > start) && (Stella.$CHARACTER_TYPE_TABLE$[(int) (string.charAt(end))] == Stella.KWD_WHITE_SPACE)) { end = end - 1; } if ((start > 0) || (end < last)) { return (Native.string_subsequence(string, start, end + 1)); } else { return (string); } } }
6
public void crossover() { // Chromosome lengths int chr_length_1 = chromosome1.getBrainStates().length; int chr_length_2 = chromosome2.getBrainStates().length; // Longest length int shortest = (chr_length_1 < chr_length_2) ? chr_length_1 : chr_length_2; // Determine crossover point int cr_point = random.nextInt(shortest); // Lengths will invert BrainState[] _bs1 = new BrainState[chr_length_2]; BrainState[] _bs2 = new BrainState[chr_length_1]; // Pull out the original set of BrainStates BrainState[] bs1 = chromosome1.getBrainStates(); BrainState[] bs2 = chromosome2.getBrainStates(); // Create new chromosome1 for (int i = 0; i < _bs1.length; i++) { if (i < cr_point) { _bs1[i] = bs1[i].clone(); } else { _bs1[i] = bs2[i].clone(); } } // Create new chromosome2 for (int i = 0; i < _bs2.length; i++) { if (i < cr_point) { _bs2[i] = bs2[i].clone(); } else { _bs2[i] = bs1[i].clone(); } } // Update the inter-BrainState pointers to match their index values _bs1 = AntBrainGenerator.cleanStates(_bs1); _bs2 = AntBrainGenerator.cleanStates(_bs2); // Update the chromosomes chromosome1 = new AntBrain(_bs1,AntColour.RED); chromosome2 = new AntBrain(_bs2,AntColour.RED); }
5
public Matrix solve(Matrix B) { if (B.getRowDimension() != m) { throw new IllegalArgumentException("Matrix row dimensions must agree."); } if (!this.isNonsingular()) { throw new RuntimeException("Matrix is singular."); } // Copy right hand side with pivoting int nx = B.getColumnDimension(); Matrix Xmat = B.getMatrix(piv,0,nx-1); double[][] X = Xmat.getArray(); // Solve L*Y = B(piv,:) for (int k = 0; k < n; k++) { for (int i = k+1; i < n; i++) { for (int j = 0; j < nx; j++) { X[i][j] -= X[k][j]*LU[i][k]; } } } // Solve U*X = Y; for (int k = n-1; k >= 0; k--) { for (int j = 0; j < nx; j++) { X[k][j] /= LU[k][k]; } for (int i = 0; i < k; i++) { for (int j = 0; j < nx; j++) { X[i][j] -= X[k][j]*LU[i][k]; } } } return Xmat; }
9
public void confirmMessage() { if(pendingMessage == null) { throw new IllegalStateException("Message was confirmed although messageBuffer was not waiting for a confirmation."); } else { pendingMessage = null; deliveredPackages++; if(messageBuffer.isEmpty()) { long interval = System.currentTimeMillis() - startTime; Debugger.println("throughput", "Delivered " + deliveredPackages +" packages in " + interval/1000 + "."+ interval%1000 +" seconds."); deliveredPackages = 0; } } }
2
private int ten(String num) { switch(num) { case "twenty": return 20; case "thirty": return 30; case "forty": return 40; case "fifty": return 50; case "sixty": return 60; case "seventy": return 70; case "eighty": return 80; case "ninety": return 90; } return 0; }
8
public Encargo getEncargo() { return encargo; }
0
public synchronized void stop() { running = false; }
0
@EventHandler(priority=EventPriority.MONITOR) void onPlayerLogin(PlayerJoinEvent e) { String group = mPlugin.getPermissionsManager() .getPrimaryGroup((String) null, e.getPlayer().getName()); if(group == null) return; mData.put(e.getPlayer().getName(), group); if(mPlugin.syncPlayerGroups(mData)){ mData.clear(); } }
2
public Table parseTable(String statement) { String[] statementSplit = statement.split("\""); Table table = new Table(); table.setName(statementSplit[1]); for (String line : statement.split("\r\n")) { line = line.trim(); String keyField = line.split(" ")[0]; String[] splitValues = line.split("\""); if (splitValues.length > 0) { try { if (keyField.equals("DUMP-NAME")) { table.setDump(splitValues[1]); } if (keyField.equals("LABEL")) { table.setLabel(splitValues[1]); } if (keyField.equals("DESCRIPTION")) { table.setDescription(splitValues[1]); } if (keyField.equals("AREA")) { table.setArea(splitValues[1]); } if (keyField.equals("TABLE-TRIGGER")) { DatabaseTrigger trigger = new DatabaseTrigger(); trigger.setType(splitValues[1]); trigger.setProcedure(splitValues[3]); table.getTriggers().add(trigger); } } catch (Exception e) { } } } return table; }
8
private void setNextDestination() { lastDest ++; if(lastDest == 70) { lastDest = 0; destInverted = !destInverted; } if(lastDest == 35) { currentX = !currentX; } int xDiff = destInverted ? 5 : -5; int yDiff = destInverted ? 5 : -5; if(currentX) yDiff = 0; else xDiff = 0; //this.destination = entity.position.copy(); this.destination.add(new Vector2(xDiff, yDiff)); }
5
public void setNode(Node node) { this.node = node; }
0
private void load(final List<String> clientSuites, final List<String> serverSuites) throws IOException { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream( Constants.SUITES_FILE))); String line = null; while ((line = in.readLine()) != null) { line = line.trim(); if (line.charAt(0) == '#') continue; final String[] tok = line.split("=", 2); final String algorith = tok[0].trim().toUpperCase(); final String usage = tok[1].trim().toUpperCase(); if (usage.indexOf('C') != -1) { if (!clientSuites.contains(algorith)) clientSuites.add(algorith); } if (usage.indexOf('S') != -1) { if (!serverSuites.contains(algorith)) serverSuites.add(algorith); } } } finally { try { if (in != null) in.close(); } catch (Exception ign) { } } }
8
void hide() { lblDate.getScene().getWindow().hide(); }
0
public void SaveNews(News[] news){ try{ File xmlFile = new File(xmlFileName); DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder xmlBulder = dFactory.newDocumentBuilder(); Document doc; doc = xmlBulder.newDocument(); Node wrap = doc.createElement("items"); String[] tagName = new String[]{"id","title","anounce","date","fulltext","rubric"}; SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss"); for(int i=0; i<news.length; i++){ Node item = doc.createElement("item"); for(int j=0; j<tagName.length; j++){ Node node = doc.createElement(tagName[j]); String cont=""; if(tagName[j].equals("id")){ cont = news[i].getId(); }else if(tagName[j].equals("title")){ cont = news[i].getTitle(); }else if(tagName[j].equals("anounce")){ cont = news[i].getAnounce(); }else if(tagName[j].equals("date")){ cont = sdf.format(news[i].getDate()); }else if(tagName[j].equals("fulltext")){ cont = news[i].getFulltext(); }else if(tagName[j].equals("rubric")){ cont = news[i].getRubric(); } node.setTextContent(cont); item.appendChild(node); } wrap.appendChild(item); } doc.appendChild(wrap); //save document: TransformerFactory TF = TransformerFactory.newInstance(); Transformer transformer = TF.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(xmlFile); transformer.transform(source, result); }catch(Exception e){ e.printStackTrace(); } }
9
protected void save() { try { File fFile = new File("test.jpeg"); this.setCursor(new Cursor(Cursor.WAIT_CURSOR)); JFileChooser fc = new JFileChooser(); // Start in current directory fc.setCurrentDirectory(new File(".")); // Set to a default name for save. fc.setSelectedFile(fFile); // Open chooser dialog int result = fc.showSaveDialog(this); if (result == JFileChooser.CANCEL_OPTION) { } else if (result == JFileChooser.APPROVE_OPTION) { fFile = fc.getSelectedFile(); if (fFile.exists()) { int response = JOptionPane.showConfirmDialog(null, "Overwrite existing file?", "Confirm Overwrite", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (response == JOptionPane.CANCEL_OPTION) { } } // save buffered image Image img = createImage(getWidth(), getHeight()); Graphics g = img.getGraphics(); paint(g); ImageIO.write(toBufferedImage(img), "jpeg", fFile); JOptionPane.showMessageDialog(null, "Image saved to " + fFile.toString()); g.dispose(); } this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } catch (Exception ex) { ex.printStackTrace(); } }
5
public SkillsMain getSkill1() { return skill1; }
0
public void actionPerformed(ActionEvent actionEvent) { if (actionEvent.getActionCommand().equals("Cut")) { if (tf != null) { tf.cut(); } else { ta.cut(); } } if (actionEvent.getActionCommand().equals("Copy")) { if (tf != null) { tf.copy(); } else { ta.copy(); } } if (actionEvent.getActionCommand().equals("Paste")) { if (tf != null) { tf.paste(); } else { ta.paste(); } } }
6
public Texture getSlickTexture(String resourceName) throws FailedTextureException { Texture tex = (Texture) table.get(resourceName); if (tex != null) { return tex; } try { tex = org.newdawn.slick.opengl.TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream(resourceName)); } catch(IOException e) { System.err.println("Could not load texture " + resourceName); } catch(RuntimeException re) { System.err.println("Could not load texture " + resourceName + ". Loading Error texture."); throw new FailedTextureException(); } table.put(resourceName,tex); return tex; }
3
private void RemoverEquipa_ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RemoverEquipa_ButtonActionPerformed try { if (EquipaSelecionada_Label.getText().equals("nenhuma")) { JOptionPane.showMessageDialog(null, "Não está nenhuma equipa seleccionada! Tem que seleccionar uma equipa!", "Alerta!", JOptionPane.WARNING_MESSAGE); } else { String equipaSelec = EquipaSelecionada_Label.getText(); EquipaSelecionada_Label.setText("nenhuma"); a.RemoveEquipa(Escola_ComboBox1.getSelectedItem().toString(), Escola_ComboBox1.getSelectedItem().toString() + "-" + equipaSelec); Equipa_ComboBox2.removeAllItems(); Escola escola = a.getDAOEscola().get(Escola_ComboBox1.getSelectedItem().toString()); if (escola != null) { for (Equipa equipa : escola.getEquipas(escola)) { Equipa_ComboBox2.addItem(equipa.getNome()); } } for (Component component : DadosJogador_Panel.getComponents()) { component.setEnabled(false); } DadosJogador_Panel.setEnabled(false); } } catch (HeadlessException ex) { JOptionPane.showMessageDialog(null, ex.getMessage(), "Erro!", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_RemoverEquipa_ButtonActionPerformed
5
public static String sortedWord(String s) { int size = StringDemo.wordCount(s); String s1[] = new String[size]; String temp; for (int i = 0; i < size; i++) { if (i == (size - 1)) { s1[i] = s.substring(0); } else { s1[i] = s.substring(0, s.indexOf(' ')); s = s.substring(s.indexOf(' ') + 1); } } for (int i = 0; i < size; i++) { for (int j = i; j < size; j++) { if (s1[i].compareToIgnoreCase(s1[j]) > 0) { temp = s1[i]; s1[i] = s1[j]; s1[j] = temp; } } } s = s1[0]; for (int i = 1; i < size; i++) { s = s + " " + s1[i]; } return s; }
6
@Override public void process(GameContext context) { if (name.length() >= 15) { client.receivedChatMessage("That's a terribly long name. Choose a shorter name."); } else if (client.getName() == null) { if (name.toLowerCase().equals("boss") || name.toLowerCase().equals("dragon") || name.startsWith("#")) { this.client.receivedChatMessage("Another player has already taken that name!"); return; } for (ClientContext cli : client.serverContext.listPlayers()) { if (cli != null && cli.getName() != null && name.toLowerCase().equals(cli.getName().toLowerCase())) { this.client.receivedChatMessage("Another player has already taken that name!"); return; } } client.setName(name); client.receivedChatMessage("Hello, " + name + "!"); } else { client.receivedChatMessage("You already set your name!"); } }
9
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); try{ String s = request.getParameter("n"); DataModel dataModel = new DataModel(s); dataModel.setAll(); response.getWriter().println(dataModel.inputName); response.getWriter().println(dataModel.wikiName); response.getWriter().println(dataModel.shift); response.getWriter().println(dataModel.mf); response.getWriter().println(dataModel.cursive_syllabary); response.getWriter().println(dataModel.record_str); response.getWriter().println(dataModel.content_str); }catch(NullPointerException e){ response.getWriter().println("input string is null."); } response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); response.getWriter().println("serverID:" + serverID); response.getWriter().println("otherServerID:" + otherServerID); response.getWriter().println("maintenance:" + maintenance_str); String input = request.getParameter("sflag"); if (input != null) { if (input.equals("true_change")) { if (setMaintenance("true")) response.getWriter() .println( "server status has been changed to \"maintenance\"."); } else if (input.equals("false_change")) { response.getWriter().println( "server status has been changed to \"normal\"."); setMaintenance("false"); } } DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Entity serv = null; try { serv = datastore.get(KeyFactory.createKey("server_status", "this")); } catch (EntityNotFoundException e) { serv = new Entity("server_status", "this"); serv.setProperty("maintenance_str", "false"); if(false)datastore.put(serv); } try { response.getWriter().println("<br />"); String log[] = ((Text) serv.getProperty("log")).getValue().split( ","); for (String s : log) response.getWriter().println( "<a href=\"" + s + "&debag=true\">" + s + "</a><br />"); } catch (Throwable t) { } }
9
public boolean setDirection(String directionArg){ if(directionArg.equals("up") || directionArg.equals("down") || directionArg.equals("left-up") || directionArg.equals("left-down") || directionArg.equals("right-up") || directionArg.equals("right-down")){ direction = directionArg; return true; } else { return false; } }
6
public int rate(String from, String to) { if(from.equals(to)) return 1; Integer rate = rates.get(new Pair(from, to)); return rate.intValue(); }
1
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(IndemniteEtudiant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(IndemniteEtudiant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(IndemniteEtudiant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(IndemniteEtudiant.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 IndemniteEtudiant().setVisible(true); } }); }
6
public Vector2f findNearestIntesection(Vector2f a, Vector2f b, Vector2f posRel) { if(b != null && (a == null || a.sub(posRel).length() > b.sub(posRel).length())) { return b; } return a; }
3
public static String transactionIsolationToString(int txisolation) { switch(txisolation) { case Connection.TRANSACTION_NONE: // transactions not supported. return "TRANSACTION_NONE"; case Connection.TRANSACTION_READ_UNCOMMITTED: // All three phenomena can occur return "TRANSACTION_NONE"; case Connection.TRANSACTION_READ_COMMITTED: // Dirty reads are prevented; non-repeatable reads and // phantom reads can occur. return "TRANSACTION_READ_COMMITTED"; case Connection.TRANSACTION_REPEATABLE_READ: // Dirty reads and non-repeatable reads are prevented; // phantom reads can occur. return "TRANSACTION_REPEATABLE_READ"; case Connection.TRANSACTION_SERIALIZABLE: // All three phenomena prvented; slowest! return "TRANSACTION_SERIALIZABLE"; default: throw new IllegalArgumentException( txisolation + " not a valid TX_ISOLATION"); } }
5
public static void addRepresentationCaddie (String numS, String dateRep, String zone, String nofp) throws BDException { String requete = null; PreparedStatement pstmt = null; Statement stmt = null; ResultSet rs = null; Connection conn = null; try { conn = BDConnexion.getConnexion(); BDRequetesTest.testRepresentation(conn, numS, dateRep); stmt = conn.createStatement(); rs =stmt.executeQuery("select idr from lecaddie where numS="+numS+" and dateRep = to_date('"+dateRep+"','dd/mm/yyyy hh24:mi') and numZ="+zone); if (rs.next()){ setQtCaddie(rs.getInt(1)+"", '+'); return; } stmt = conn.createStatement(); rs = stmt.executeQuery("select max(idr) from lecaddie"); int id; if (!rs.next()) id=1; else id=rs.getInt(1)+1; requete = "insert into LeCaddie values (?,?,?,?,?)"; pstmt = conn.prepareStatement(requete); pstmt.setInt(1, id); pstmt.setInt(2, Integer.valueOf(numS)); pstmt.setTimestamp(3, new Timestamp((new SimpleDateFormat("dd/MM/yyyy HH:mm")).parse(dateRep).getTime())); pstmt.setInt(4, Integer.valueOf(zone)); pstmt.setInt(5, Integer.valueOf(nofp)); int nb_insert = pstmt.executeUpdate(); conn.commit(); if(nb_insert != 1) throw new BDException("Problème dans l'ajout d'une représentation dans le caddie"); stmt.executeUpdate("update config set date_cad = CURRENT_DATE"); } catch (SQLException e) { throw new BDException("Problème dans l'ajout d'une représentation dans le caddie (Code Oracle : "+e.getErrorCode()+")"); } catch (ParseException e) {} finally { BDConnexion.FermerTout(conn, stmt, rs); BDConnexion.FermerTout(null, pstmt, null); } }
5
@Override public void keyReleased(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_UP: getAisha().stopUp(); break; case KeyEvent.VK_DOWN: getAisha().stopDown(); break; case KeyEvent.VK_LEFT: getAisha().stopLeft(); break; case KeyEvent.VK_RIGHT: getAisha().stopRight(); break; case KeyEvent.VK_Z: break; } }
5
public void body() { LinkedList resList; // waiting to get list of resources. Since GridSim package uses // multi-threaded environment, your request might arrive earlier // before one or more grid resource entities manage to register // themselves to GridInformationService (GIS) entity. // Therefore, it's better to wait in the first place while (true) { // need to pause for a while to wait GridResources finish // registering to GIS super.gridSimHold(2*SEC); // wait for 2 seconds resList = getGridResourceList(); if (resList.size() > 0) { break; } else { System.out.println(super.get_name() + ": Waiting to get list of resources ..."); } } // list of resource IDs that can support Advanced Reservation (AR) ArrayList resARList = new ArrayList(); // list of resource names that can support AR ArrayList resNameList = new ArrayList(); int totalPE = 0; int i = 0; Integer intObj = null; // resource ID String name; // resource name // a loop that gets a list of resources that can support AR for (i = 0; i < resList.size(); i++) { intObj = (Integer) resList.get(i); // double check whether a resource supports AR or not. // In this example, all resources support AR. if (GridSim.resourceSupportAR(intObj) == true) { // gets the name of a resource name = GridSim.getEntityName( intObj.intValue() ); // gets the total number of PEs owned by a resource totalPE = super.getNumPE(intObj); // adds the resource ID, name and its total PE into // their respective lists. resARList.add(intObj); resNameList.add(name); } } //---------------------------------------------------- // sends one or more reservations to a gridresource entity sendReservation(resARList, resNameList); try { // then get the results or Gridlets back int size = list_.size() - failReservation_; for (i = 0; i < size; i++) { Gridlet gl = super.gridletReceive(); this.receiveList_.add(gl); } } catch (Exception e) { e.printStackTrace(); } // shut down all the entities shutdownGridStatisticsEntity(); terminateIOEntities(); shutdownUserEntity(); System.out.println(super.get_name() + ":%%%% Exiting body() with " + "number of failed reservation is " + failReservation_); }
6
public static void main(String[] args) throws IOException { //make a TCP server socket final ServerSocket TCP_Socket = new ServerSocket(7007); //make UDP server socket final DatagramSocket UDP_Socket = new DatagramSocket(7007); //thread to handle TCP specific connections Thread tcpListenThread = new Thread(new Runnable() { @Override public void run() { while (listening) { // creates a new TcpSendThread when a new tcp connection is received try { new TcpSendThread(TCP_Socket.accept()).start(); } catch (IOException e) { e.printStackTrace(); } } } }); //thread to handle UDP specific requests Thread udpListenThread = new Thread(new Runnable() { @Override public void run() { new UdpSendThread(UDP_Socket).start(); } }); //start the 2 listening threads for UDP + TCP tcpListenThread.start(); udpListenThread.start(); }
2
@Override public void characters(char ch[], int start, int length) throws SAXException { super.characters(ch, start, length); }
0
private void renderIntersections(Graphics2D g2) { Viewport gameViewport = ((pathXMiniGame)game).getGameViewport(); Iterator<Intersection> it = data.intersectionsIterator(); while (it.hasNext()) { Intersection intersection = it.next(); // ONLY RENDER IT THIS WAY IF IT'S NOT THE START OR DESTINATION // AND IT IS IN THE VIEWPORT if ((!data.isStartingLocation(intersection)) && (!data.isDestination(intersection)) && gameViewport.isCircleBoundingBoxInsideViewport(intersection.x, intersection.y, INTERSECTION_RADIUS)) { // FIRST FILL if (intersection.isOpen()) { g2.setColor(OPEN_INT_COLOR); } else { g2.setColor(CLOSED_INT_COLOR); } recyclableCircle.x = intersection.x - gameViewport.getViewportX() - INTERSECTION_RADIUS; recyclableCircle.y = intersection.y - gameViewport.getViewportY() - INTERSECTION_RADIUS; g2.fill(recyclableCircle); // AND NOW THE OUTLINE if (data.isSelectedIntersection(intersection)) { g2.setColor(HIGHLIGHTED_COLOR); } else { g2.setColor(INT_OUTLINE_COLOR); } Stroke s = recyclableStrokes.get(INT_STROKE); g2.setStroke(s); g2.draw(recyclableCircle); } } // AND NOW RENDER THE START AND DESTINATION LOCATIONS Image startImage = data.getStartingLocationImage(); Intersection startInt = data.getStartingLocation(); renderIntersectionImage(g2, startImage, startInt); Image destImage = data.getDesinationImage(); Intersection destInt = data.getDestination(); renderIntersectionImage(g2, destImage, destInt); }
6
public CommandWords() { validCommands = new HashMap<String, CommandWord>(); for(CommandWord command : CommandWord.values()) { if(command != CommandWord.UNKNOWN) { validCommands.put(command.toString(), command); } } }
2
public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); this.setBorderPainted(false); String name="/images/"; String text = ""; switch (type){ case AQUILLA: name+="aquilla_bg.png"; port=25565; text="Aquilla";break; } if(!online.equals("")){ g2.drawImage(new ImageIcon(Utils.getLocalImage(name,this)).getImage(), 0, 0, null); g2.drawImage(new ImageIcon(Utils.getLocalImage("/images/aquilla_progress.png",this)).getImage(), 3, 3,progressWidth, 48, null); }else{ g2.drawImage(new ImageIcon(Utils.getLocalImage("/images/offline_bg.png",this)).getImage(), 0, 0, null); } try { Font font = Font.createFont(Font.TRUETYPE_FONT,this.getClass().getResourceAsStream("/font/Nautilus.ttf")); font = font.deriveFont(25.0f); g2.setColor(Color.decode("#007180")); g2.setFont(font); FontMetrics fontMetrics = g.getFontMetrics(font); int textWidth = fontMetrics.charsWidth(text.toCharArray(),0,text.length()); g2.drawString(text,354/2-textWidth/2+1,29+1); g2.setColor(Color.WHITE); g2.drawString(text,354/2-textWidth/2,29); font=font.deriveFont(12.0f); if(!online.equals("")){ g2.setFont(font); g2.setColor(Color.decode("#007180")); g2.drawString(online,354/2-fontMetrics.charsWidth(online.toCharArray(),0,online.length())/2+15+1,43+1); g2.setColor(Color.WHITE); g2.drawString(online,354/2-fontMetrics.charsWidth(online.toCharArray(),0,online.length())/2+15,43); } else{ g2.setFont(font); g2.setColor(Color.decode("#007180")); g2.drawString("Offline",354/2-fontMetrics.charsWidth("Offline".toCharArray(),0,"Offline".length())/2+25+1,43+1); g2.setColor(Color.WHITE); g2.drawString("Offline",354/2-fontMetrics.charsWidth("Offline".toCharArray(),0,"Offline".length())/2+25,43); } } catch (FontFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } g2.setColor(Color.WHITE); }
5
public void loadElements(VisibleElements type) { this.visibleElements = type; // ZOrder index int index = 0; // Remove all drawed elements. draw.removeAll(); List<GenericTreeNode<LayoutParserTreeElement>> list = this.layoutParser.XMLTree .build(GenericTreeTraversalOrderEnum.PRE_ORDER); // Go through all elements. for (int i = 0; i < list.size(); i++) { LayoutParserTreeElement e = list.get(i).getData(); // Check if element is of selected type. if (e.elementType == type.toType()) { GElement panel = new GElement(list.get(i)); // Set height and width so that the element is visible.. int width = e.right - e.left > 1 ? e.right - e.left : 3; int height = e.bottom - e.top > 1 ? e.bottom - e.top : 3; // Check direction. if (this.layoutParser.direction == Direction.DESCENDING) { panel.setBounds(e.left, e.top, width, height); } else { int m_height = this.image.getHeight(this); panel.setBounds(e.left, m_height - e.bottom, width, height); } if (this.visCombo.getSelectedItem().toString() .compareTo(ElementsVisibility.S_IMAGE.toString()) == 0) { panel.setTextArea(width, height, false); } else { if (panel.element.getData().elementType == type.toType()) { panel.setTextArea(width, height, true); } else { panel.setTextArea(width, height, false); } } // Create the popup menu for the current panel GPopup popupMenu = new GPopup(); /* * Action listener pentru popupMenu Primeste ca parametru * ElementJPanel pentru a extrage LayoutParserTreeElement */ ActionListener actionListener = new PopupItemListener(panel, this); // Face analiza OCR. JMenuItem ocrItem = new JMenuItem( ElementActions.S_OCR.toString()); ocrItem.addActionListener(actionListener); popupMenu.add(ocrItem); // Sparge blocul de text orizontal. JMenuItem splitItemH = new JMenuItem( ElementActions.S_BREAK_H.toString()); splitItemH.addActionListener(actionListener); splitItemH.addMouseListener(new PopupItemMouseListener(panel, draw)); popupMenu.add(splitItemH); // Sparge blocul de text veritcal. JMenuItem splitItemV = new JMenuItem( ElementActions.S_BREAK_V.toString()); splitItemV.addActionListener(actionListener); splitItemV.addMouseListener(new PopupItemMouseListener(panel, draw)); popupMenu.add(splitItemV); // Marcheaza blocul de text ca fiind numar pagina. if (panel.element.getData().elementType.toString().compareTo( "TextBlock") == 0) { JMenuItem paginaItem = new JMenuItem( ElementActions.S_PAGE.toString()); paginaItem.addActionListener(actionListener); popupMenu.add(paginaItem); } // Marcheaza blocul de text ca fiind numar pagina. JMenuItem deleteItem = new JMenuItem( ElementActions.S_DELETE.toString()); deleteItem.addActionListener(actionListener); popupMenu.add(deleteItem); // Vezi textul. JMenuItem textItem = new JMenuItem( ElementActions.S_TEXT.toString()); textItem.addActionListener(actionListener); popupMenu.add(textItem); // Bring to front. JMenuItem frontItem = new JMenuItem( ElementActions.S_FRONT.toString()); frontItem.addActionListener(actionListener); popupMenu.add(frontItem); // Sent to Back. JMenuItem backItem = new JMenuItem( ElementActions.S_BACK.toString()); backItem.addActionListener(actionListener); popupMenu.add(backItem); // Redimensioneaza JMenuItem redimItem = new JMenuItem( ElementActions.S_RESIZE.toString()); redimItem.addActionListener(actionListener); popupMenu.add(redimItem); // Set popup menu. panel.setPopup(popupMenu); // Draw panel. draw.add(panel); // Set zOrder for a component draw.setComponentZOrder(panel, index++); } } }
8
public static Date getTriggerTime(Boolean morning) { int hour; if(morning) { hour = 7; } else { hour = 13; } Date currentTime = new Date(); Calendar cal = new GregorianCalendar(); cal.setTime(currentTime); cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, 0); if(cal.getTime().before(currentTime)) { cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) + 1); } return cal.getTime(); }
2
public static int compareTo(byte[] lhs, byte[] rhs) { if (lhs == rhs) { return 0; } if (lhs == null) { return -1; } if (rhs == null) { return +1; } if (lhs.length != rhs.length) { return ((lhs.length < rhs.length) ? -1 : +1); } for (int i = 0; i < lhs.length; i++) { if (lhs[i] < rhs[i]) { return -1; } else if (lhs[i] > rhs[i]) { return 1; } } return 0; }
8
public int countOpenChains() { int chainCount = 0; for(int i = 0; i < height; i++) { for(int j = 0; j < width; j++) { int vertex = j + i * width; List<List<Integer>> chains = getAllChains(vertex); for(int chainIndex = 0; chainIndex < chains.size(); chainIndex++) { if(chains.get(chainIndex).size() >= 3) { chainCount++; } } } } clearGraphMarks(); return chainCount; }
4
File[] getRoots() { /* * On JDK 1.22 only... */ // return File.listRoots(); /* * On JDK 1.1.7 and beyond... * -- PORTABILITY ISSUES HERE -- */ if (System.getProperty ("os.name").indexOf ("Windows") != -1) { Vector /* of File */ list = new Vector(); list.add(new File(DRIVE_A)); list.add(new File(DRIVE_B)); for (char i = 'c'; i <= 'z'; ++i) { File drive = new File(i + ":" + File.separator); if (drive.isDirectory() && drive.exists()) { list.add(drive); if (initial && i == 'c') { currentDirectory = drive; initial = false; } } } File[] roots = (File[]) list.toArray(new File[list.size()]); sortFiles(roots); return roots; } File root = new File(File.separator); if (initial) { currentDirectory = root; initial = false; } return new File[] { root }; }
7
public boolean similar(Object other) { if (!(other instanceof JSONArray)) { return false; } int len = this.length(); if (len != ((JSONArray)other).length()) { return false; } for (int i = 0; i < len; i += 1) { Object valueThis = this.get(i); Object valueOther = ((JSONArray)other).get(i); if (valueThis instanceof JSONObject) { if (!((JSONObject)valueThis).similar(valueOther)) { return false; } } else if (valueThis instanceof JSONArray) { if (!((JSONArray)valueThis).similar(valueOther)) { return false; } } else if (!valueThis.equals(valueOther)) { return false; } } return true; }
8
public Graph() { }
0
@Override public boolean tick(Tickable ticking, int tickID) { if(tickID==Tickable.TICKID_MOB) { if((affected!=null) &&(affected instanceof MOB) &&(invoker!=null)) { final MOB mob=(MOB)affected; if(((mob.amFollowing()==null) ||(mob.amDead()) ||(!mob.isInCombat()) ||(mob.location()!=invoker.location()))) unInvoke(); } } return super.tick(ticking,tickID); }
8
public static void e117(long n) { if(counts[(int)n] != 0) count += counts[(int)n]; else if(n <= 4) switch((int)n){ case 1 : count += 1; break; case 2 : count += 2; break; case 3 : count += 4; break; case 4 : count += 8; break; } else { e117(n-1); e117(n-2); e117(n-3); e117(n-4); } }
6
public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[][] grid = new int[n][n]; for (int y = 0; y < n; y++) for (int z = 0; z < n; z++) { grid[y][z] = in.nextInt(); if (z > 0) grid[y][z] += grid[y][z - 1]; // pre-processing } int maxSubRect = -127 * 100 * 100; // lowest possible value for this problem int subRect = 0; for (int l = 0; l < n; l++) for (int r = l; r < n; r++) { subRect = 0; for (int row = 0; row < n; row++) { // Max 1D Range Sum on columns of this row i if (l > 0) subRect += grid[row][r] - grid[row][l - 1]; else subRect += grid[row][r]; // Kadane's algorithm on rows if (subRect < 0) subRect = 0; maxSubRect = Math.max(maxSubRect, subRect); } } System.out.println(maxSubRect); }
8
public boolean equals(Object obj) { if (obj == this) return true; if (obj == null) return false; if (obj.getClass() != this.getClass()) return false; Picture that = (Picture) obj; if (this.width() != that.width()) return false; if (this.height() != that.height()) return false; for (int x = 0; x < width(); x++) for (int y = 0; y < height(); y++) if (!this.get(x, y).equals(that.get(x, y))) return false; return true; }
8
private void Accept(Socket connection) throws IOException { DataInputStream reader = new DataInputStream(connection.getInputStream()); byte firstsend = reader.readByte(); switch (firstsend) { case 0: //Minecraft player new Player(connection, this, firstsend, server); break; case (byte)'G': //A browser or website is using GET new Browser(connection, this, firstsend); break; case 2: //SMP Player Packet p = this.getPacket(firstsend); if (p == null) connection.close(); IOClient ic = new IOClient(connection, this); //ic.Listen(); p.Handle(new byte[0], server, ic); break; } }
4
@Override public void move() { Grid<Actor> grid = getGrid(); if(grid == null) return; Location loc = getLocation(); Location next = loc.getAdjacentLocation(getDirection()); if (grid.isValid(next)) moveTo(next); else removeSelfFromGrid(); Uranium uranium = new Uranium(super.getColor()); uranium.putSelfInGrid(grid, loc); }
2
@Override public TexInfo getTexInfo(int metadata){ switch(metadata){ default: case 0: return normal; case 1: return striped; } }
2
private void jBDescartesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBDescartesActionPerformed if(!bicho || (bicho && combatido && !muerto)){ if(tesorosVisiblesSeleccionados.isEmpty() && tesorosOcultosSeleccionados.isEmpty()) dialogo = new Dialogo(this,true, "¡Muy bien! Pero... exactamente, ¿qué quieres descartar?"); else{ juego.descartarTesorosOcultos(tesorosOcultosSeleccionados); juego.descartarTesorosVisibles(tesorosVisiblesSeleccionados); actualizarJugador(); actualizarMarcador(); } }else{ if(bicho){ if(!combatido) dialogo = new Dialogo(this,true, "¿Acaso no has visto que hay un monstruo muy bonico esperando? Ve y lucha contra él"); else{ if(muerto) dialogo = new Dialogo(this,true, "Puede que no te hayas dado cuenta, pero... ¡Estás muerto!"); } } } }//GEN-LAST:event_jBDescartesActionPerformed
9
public int read(InputStream outputStream) throws IOException { long l = 0; int in = 0; for( int i = 0; i < 8; i++ ) { in = outputStream.read(); if( in < 0 ) return in; l = (l << 8) | (in & 0xff); } nmer = l; return in; }
2
@Override public void actionPerformed(ActionEvent e) { if ("Timer".equals(e.getActionCommand())) {doTimerActions();} if ("Display Log".equals(e.getActionCommand())) {displayLog();} if ("Display Help".equals(e.getActionCommand())) {displayHelp();} if ("Display About".equals(e.getActionCommand())) {displayAbout();} if ("New File".equals(e.getActionCommand())) {doSomething1();} if ("Open File".equals(e.getActionCommand())) { doSomething2(); } if ("Load Data From File".equals(e.getActionCommand())){ loadDataFromFile(); } if ("Save Data To File".equals(e.getActionCommand())){ saveDataToFile(); } }//end of Controller::actionPerformed
8
public static void deleteObject(RestS3Service ss, S3Bucket sb, String key) { try { ss.deleteObject(sb, key); } catch (S3ServiceException e) { e.printStackTrace(); } }
1
public static void main(String[] args) { /** * Creating an array of Shapes with random number of cells; */ Shape[] shapes = new Shape[getRandomNumber(1, 100)]; /** * Filling an array cells with random Shapes. */ for (Shape shape : shapes){ shape = getRandomShape(); shape.drawTheShape(); } }
1
public void fireSelectEvent(final SelectEvent EVENT) { final EventHandler<SelectEvent> HANDLER; final EventType TYPE = EVENT.getEventType(); if (SelectEvent.SELECT == TYPE) { HANDLER = getOnSelect(); } else if (SelectEvent.DESELECT == TYPE) { HANDLER = getOnDeselect(); } else { HANDLER = null; } if (HANDLER != null) { HANDLER.handle(EVENT); } }
3
public void putAll( Map<? extends K, ? extends Byte> map ) { Iterator<? extends Entry<? extends K,? extends Byte>> it = map.entrySet().iterator(); for ( int i = map.size(); i-- > 0; ) { Entry<? extends K,? extends Byte> e = it.next(); this.put( e.getKey(), e.getValue() ); } }
8
public void actualizarQuantum(Proceso p) { Boolean asigno = false; int prioridadEstatica = p.getPrioridadEstatica(); int quantum = p.getQuantum(); int tcpu = p.getTiemposCPU(); p.setQuantum(--quantum); // Disminuye num de Ticks que necesita para terminar ejecucion p.setTiemposCPU(--tcpu); p.decrementarTiempoDurmiendo(); if (quantum <= 0) { /** * Se coloca el proceso actual en null para buscar un nuevo proceso * que use el cpu */ cpu.setProcesoActual(null); cpu.getRunqueue().setProcesoActual(null); // Si todavia le queda trabajo al proceso if (tcpu > 0) { quantum = (140 - prioridadEstatica) * (prioridadEstatica < 120 ? 20 : 5); p.setQuantum(java.lang.Math.min(quantum, tcpu)); p.setEsPrimerQuantum(false); /** * Tanto en los procesos de tiempo real como los normales se usa * la politica de RoundRobin */ if (p.esTiempoReal()) { // Se inserta a activos: cpu.getRunqueue().getActivos().insertarProceso(p); } else { this.actualizarPrioridadDinamica(p); if (cpu.getRunqueue().getTiempoPrimerExpirado() == 0) { cpu.getRunqueue().setTiempoPrimerExpirado(reloj.getNumTicks()); } // Se inserta en la cola de expirados cpu.getRunqueue().insertarProcesoExpirado(p); } /** * Si el proceso aun tiene tiempo de para hacer entrada y salida * se despacha el dispositivo */ } else if (p.getTiemposIO() != 0 && p.getTiemposIO() != -1) { dispositivoIO.insertarColaBloqueados(p); } else { insertarListaFinalizados(p); } // Se pasa a buscar un nuevo proceso activo para el CPU asigno = this.asignarCPU(); } }
7
public List<Short> getShortList(String path) { List<?> list = getList(path); if (list == null) { return new ArrayList<Short>(0); } List<Short> result = new ArrayList<Short>(); for (Object object : list) { if (object instanceof Short) { result.add((Short) object); } else if (object instanceof String) { try { result.add(Short.valueOf((String) object)); } catch (Exception ex) { } } else if (object instanceof Character) { result.add((short) ((Character) object).charValue()); } else if (object instanceof Number) { result.add(((Number) object).shortValue()); } } return result; }
8
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed // TODO add your handling code here: Validaciones v = new Validaciones(); if (jCheckBox1.isSelected()){ jLabel4.setVisible(false); Cargar_Tabla("SELECT * FROM "+nombre_tabla); } if (jCheckBox2.isSelected()){ if (!"".equals(jTextField1.getText())){ if (v.isInt(jTextField1.getText())){ jLabel4.setVisible(false); Cargar_Tabla("SELECT * FROM "+nombre_tabla+" WHERE "+campo_clave+" = "+jTextField1.getText()); } else{ jLabel4.setVisible(true); jTextField1.requestFocus(); jTextField1.selectAll(); jLabel4.setText("Ingrese un valor numerico."); } } else{ jLabel4.setVisible(true); jTextField1.requestFocus(); jLabel4.setText("Ingrese un valor numerico."); } } if (jCheckBox3.isSelected()){ if (!"".equals(jTextField1.getText()) || !"".equals(jTextField2.getText())){ if (v.isInt(jTextField1.getText()) && v.isInt(jTextField2.getText())){ jLabel4.setVisible(false); Cargar_Tabla("SELECT * FROM "+nombre_tabla+" WHERE "+campo_clave+" >= "+jTextField1.getText()+" AND "+campo_clave+" <= "+jTextField2.getText()); } else{ jLabel4.setVisible(true); jTextField1.requestFocus(); jLabel4.setText("Ingrese valores numericos."); } } else{ jLabel4.setVisible(true); jTextField1.requestFocus(); jLabel4.setText("Ingrese valores numericos."); } } }//GEN-LAST:event_jButton4ActionPerformed
9
private void processMessage(String s){ String[] tokens = s.split(" "); for(int i = 0; i < tokens.length; i++){ //System.out.println(tokens[i]); } if (tokens[0] != null && tokens[0].contains("GET")){ PageServer ps = new PageServer(); sendMessage(ps.getPage(tokens[1].substring(1))); } }
3
public static void main(String[] tArgs) throws IOException { File f = null; JFrame frame = new JFrame(); if(tArgs.length>0&&tArgs[0] != null) { f = new File(tArgs[0]).getAbsoluteFile(); } else { f = FileChooser.chooseFile(frame, "Load", JFileChooser.FILES_ONLY); } FileWriter FW = new FileWriter(); if(f == null) { return; } if(!f.exists()) { try { //noinspection ResultOfMethodCallIgnored f.createNewFile(); } catch(IOException e) { e.printStackTrace(); } } try { FW.readFromFile(f); } catch(IOException e) { e.printStackTrace(); } FileWriterGUI FWG = new FileWriterGUI(); FWG.setFileWriter(FW); FWG.updateStructure(); frame.add(FWG); frame.pack(); frame.setVisible(true); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); }
6
public static boolean isActive(JComponent c) { if (c == null) { return false; } boolean active = true; if (c instanceof JInternalFrame) { active = ((JInternalFrame) c).isSelected(); } if (active) { Container parent = c.getParent(); while (parent != null) { if (parent instanceof JInternalFrame) { active = ((JInternalFrame) parent).isSelected(); break; } parent = parent.getParent(); } } if (active) { active = isFrameActive(c); } return active; }
6
public static void home(Node currentNode, JoeTree tree, OutlineLayoutManager layout) { // Record the EditingNode, Mark and CursorPosition tree.setCursorMarkPosition(0); tree.setCursorPosition(0, false); tree.getDocument().setPreferredCaretPosition(0); // Redraw and Set Focus layout.draw(currentNode, OutlineLayoutManager.TEXT); }
0
public void eliminarBD() { File basedatos= new File(this.ruta); if(basedatos.exists())basedatos.delete(); }
1
public static boolean correctISBNFormat(String isbn) { String regex = "\\d+"; if (isbn.length() == 10) return isbn.matches(regex); if (isbn.length() == 14) { String i[] = isbn.split("\\-"); if (i[0].length() != 3) return false; return i[0].matches(regex) && correctISBNFormat(i[1]); } return false; }
4
public boolean update(float tslf, LinkedList<Bullet> bullets) { if(path.size() > 0) { float absx = path.get(path.size() - 1).getX() * Texture.tilesize + Texture.tilesize / 2 - (xpos + look.getWidth() / 2); float absy = path.get(path.size() - 1).getY() * Texture.tilesize + Texture.tilesize / 2 - (ypos + look.getHeight() / 2); rotation = Math.atan2(absy, absx); xspeed = (float) (Math.cos(rotation) * SPEED); yspeed = (float) (Math.sin(rotation) * SPEED); } else { xspeed = 0; yspeed = 0; } xpos += xspeed * tslf; ypos += yspeed * tslf; if(path.size() > 0 && path.get(path.size() -1).getX() == getTilePosX() && path.get(path.size() -1).getY() == getTilePosY()) path.remove(path.size() - 1); for(int i = 0; i < bullets.size(); i++) { if(Collision.circleToCircle(bullets.get(i).getX(), bullets.get(i).getY(), 2, xpos + size, ypos + size, size)) { bullets.remove(i); return true; } } return false; }
6
@Override public void actionPerformed(ActionEvent e) { Random r = new Random(); int d = r.nextInt() % 5; switch (d) { case 0: break; case 1: // move right if (dx < 0) { dx = -dx; // if moving left, move right } break; case 2: //move left if (dx > 0) { dx = -dx; // if moving right, move left } break; case 3: // move up if (dy > 0) { dy = -dy; // if moving down, move up } break; case 4: // move down if (dy < 0) { dy = -dy; // if moving up, move down } break; } }
9
public ChangePwdServlet() { super(); // TODO Auto-generated constructor stub }
0
public boolean ajout(Personne pers){ boolean exists = false; if (!this.estVide()) { int i = 0; while (i<contacts.size() && !exists) { if (contacts.get(i) instanceof Particulier && pers instanceof Particulier) { Particulier part = (Particulier) pers; Particulier part1 = (Particulier) contacts.get(i); exists = part1.equals(part); } if (contacts.get(i) instanceof Professionnel && pers instanceof Professionnel) { Professionnel pro = (Professionnel) pers; Professionnel pro1 = (Professionnel) contacts.get(i); exists = pro1.equals(pro); } i++; } } if (!exists) { this.contacts.add(pers); Collections.sort(this.contacts); this.dernier++; } return !exists; }
8
private void debug() { if ( Input.getKey( Input.KEY_F5 ) ) glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); else if ( Input.getKey( Input.KEY_F6 ) ) glPolygonMode( GL_FRONT_AND_BACK, GL_POINT ); else glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); }
2
public void actionPerformed(ActionEvent event){ //set string equal to nothing in it. String string = ""; //so basically we do here is we look to see if anyone typed //Anything into any of these text boxes and hits enter, we want to //set string equal to field (whatever one you entered in), and what you entered. //get action command returns strings of whatever is typed in that is associated with //this action. //event.getSource just finds the location of where the action happened. if(event.getSource() == text1) string = String.format("field 1: %s", event.getActionCommand()); else if(event.getSource() == text2) string = String.format("field 2: %s", event.getActionCommand()); else if(event.getSource() == text3) string = String.format("field 3: %s", event.getActionCommand()); else if(event.getSource() == passwordField) string = String.format("password field is: %s", event.getActionCommand()); //prints everything after action is completed. //first argument is the positioning, and second is what you want it to print. JOptionPane.showMessageDialog(null, string); }
4
public void update(double mod){ for (int i = 0; i < points.size(); i++){ if (!points.get(i).isFrozen()){ points.get(i).setY(points.get(i).getY()+mod*speed); //freeze point if it reaches the bottom if (points.get(i).getY() > maxHeight){ points.get(i).freeze(); points.get(i).setY(maxHeight); } //check other points for (int j = 0; j < points.size(); j++){ if (j != i){ //don't check current point //if (isCollision(points.get(i),radius,points.get(j),radius) && points.get(j).isFrozen()){ // points.get(i).freeze(); //} if (j < points.size()-1){ if (isCollision( points.get(j).getX(),points.get(j).getY(), points.get(j+1).getX(), points.get(j+1).getY(), points.get(i).getX(), points.get(i).getY(), radius) && points.get(j).isFrozen() && points.get(j+1).isFrozen()){ points.get(i).freeze(); } } } } } } }
9
private void setupRepeatRun(BigInteger numPrunedConfsToAllow, int numRotForResNonPruned[], int numLevels, int numMutable){ BigInteger totalNumConfsUnpruned = new BigInteger("0"); Iterator<RotInfo<Boolean>> elimRotIter = eliminatedRotAtRes.iterator(); Iterator<RotInfo<Boolean>> prunedStericIter = prunedIsSteric.iterator(); while(elimRotIter.hasNext()){ //for (int i=0; i<eliminatedRotAtRes.length; i++){ RotInfo<Boolean> elimRotInfo = elimRotIter.next(); RotInfo<Boolean> prunedStericInfo = prunedStericIter.next(); //check to make sure we are always checking same index assert (elimRotInfo.curPos == prunedStericInfo.curPos && elimRotInfo.curAA == prunedStericInfo.curAA && elimRotInfo.curRot == prunedStericInfo.curRot) : "ElimRot and PrunedSteric indexes don't match"; if ((elimRotInfo.state)&&(!prunedStericInfo.state)){ //pruned non-steric rotamer //if ((eliminatedRotAtRes[i])&&(!prunedIsSteric[i])){ //pruned non-steric rotamer int curLevel = elimRotInfo.curPos;//(int)Math.floor(i/numTotalRotamers); //the residue number for the cur rot index //TODO: fix that all positions are assumed to have "numTotalRotamers" number of rotamers /*if (curLevel>=numInAS) //ligand level (the ligand may have more than numTotalRotamers rotamers) curLevel = numInAS; //the residue number for the cur rot index*/ numRotForResNonPruned[curLevel]++; eliminatedRotAtRes.set(elimRotInfo,false); BigInteger numConfsAtLevelUnpruned = new BigInteger("1"); //count the unpruned confs by unpruning the cur rot index for (int j=0; j<numLevels; j++){ if (j!=curLevel){ numConfsAtLevelUnpruned = numConfsAtLevelUnpruned.multiply(BigInteger.valueOf(numRotForResNonPruned[j])); } } totalNumConfsUnpruned = totalNumConfsUnpruned.add(numConfsAtLevelUnpruned); if (totalNumConfsUnpruned.compareTo(numPrunedConfsToAllow)>=0) // num pruned confs reduced by the necessary number break; }
8
public boolean handleInput(String line) { // start new Game if (line.matches("start[0-9]+")) { String param = line; param = param.replaceAll("start", ""); int cash = Integer.parseInt(param); controller.start(cash); } else if (line.equalsIgnoreCase("stand")) { controller.stand(); } else if (line.equalsIgnoreCase("hit")) { controller.hit(); } else if (line.equalsIgnoreCase("double")) { controller.doubleDown(); } else if (line.equalsIgnoreCase("split")) { controller.split(); } else if (line.equalsIgnoreCase("stat")) { out.print(controller.getStatistic()); } else if (line.equalsIgnoreCase("exit")) { return false; } else if (line.matches("bet[0-9]+")) { String param = line; param = param.replaceAll("bet", ""); int cash = Integer.parseInt(param); controller.bet(cash); } else if (line.contains("set:")) { String param = line; param = param.replaceAll("set", ""); controller.setHand(param); } return true; }
9
public static void main(String[] args)throws Exception{ if(args.length < 1){ System.out.println("Usage: java ThreadRequest <u=url> <t=threads> <r=runs> <f=foundReturnMessage> <s=sleep>"); return; } for(int i=0;i<args.length;i++){ if(args[i].startsWith("u=")){ spec = args[i].substring(2); }else if(args[i].startsWith("t=")){ threads = Integer.parseInt(args[i].substring(2)); }else if(args[i].startsWith("r=")){ runs = Integer.parseInt(args[i].substring(2)); }else if(args[i].startsWith("f=")){ strFoundReturnMessage = args[i].substring(2); }else if(args[i].startsWith("s=")){ sleep = Long.parseLong(args[i].substring(2)); } } start = System.currentTimeMillis(); File headersFile = new File("headers.ini"); if(headersFile.exists()){ InputStream headersInputStream = new FileInputStream(headersFile); headersProps.load(headersInputStream); headersInputStream.close(); } ts = new ThreadRequest[threads]; for(int i=0;i<threads;i++){ ts[i] = new ThreadRequest(); ts[i].start(); } Daemon d = new Daemon(); d.start(); }
9
public Color unique(Object o) { if (!uniqueColors.containsKey(o)) { Random rand = new Random(); Color bestColor = null; double bestDelta = -1; for(int x = 0; x < 10; x++) { Color unique = colorFromHash(rand.nextInt()); int delta = 0; for(Color other : uniqueColors.values()) { delta += colorDelta(unique, other); } if (delta > bestDelta) { bestDelta = delta; bestColor = unique; } } uniqueColors.put(o, bestColor); } return uniqueColors.get(o); }
4
private static Path processPoly(Element element, StringTokenizer tokens) throws ParsingException { int count = 0; ArrayList pts = new ArrayList(); boolean moved = false; boolean reasonToBePath = false; Path path = null; while (tokens.hasMoreTokens()) { try { String nextToken = tokens.nextToken(); if (nextToken.equals("L")) { float x = Float.parseFloat(tokens.nextToken()); float y = Float.parseFloat(tokens.nextToken()); path.lineTo(x,y); continue; } if (nextToken.equals("z")) { path.close(); continue; } if (nextToken.equals("M")) { if (!moved) { moved = true; float x = Float.parseFloat(tokens.nextToken()); float y = Float.parseFloat(tokens.nextToken()); path = new Path(x,y); continue; } reasonToBePath = true; float x = Float.parseFloat(tokens.nextToken()); float y = Float.parseFloat(tokens.nextToken()); path.startHole(x,y); continue; } if (nextToken.equals("C")) { reasonToBePath = true; float cx1 = Float.parseFloat(tokens.nextToken()); float cy1 = Float.parseFloat(tokens.nextToken()); float cx2 = Float.parseFloat(tokens.nextToken()); float cy2 = Float.parseFloat(tokens.nextToken()); float x = Float.parseFloat(tokens.nextToken()); float y = Float.parseFloat(tokens.nextToken()); path.curveTo(x,y,cx1,cy1,cx2,cy2); continue; } } catch (NumberFormatException e) { throw new ParsingException(element.getAttribute("id"), "Invalid token in points list", e); } } if (!reasonToBePath) { return null; } return path; }
8
public void render(Graphics2D g) { Graphics2D g2d = (Graphics2D) finalBoard.getGraphics(); g2d.drawImage(gameBoard, 0, 0, null); for (int row = 0; row < ROWS; row++) { for (int col = 0; col < ROWS; col++) { Tile current = board[row][col]; if (current == null) continue; current.render(g2d); } } g.drawImage(finalBoard, x, y, null); g2d.dispose(); g.setColor(Color.lightGray); g.setColor(new Color(0xFF0000)); g.setFont(new Font("Arial", Font.BOLD, 16)); String howTo1 = "HOW TO PLAY: Use your arrow keys to move the tiles. When"; String howTo2 = "two tiles with the same number touch, they merge into one!"; g.drawString(howTo1, 40, Game.HEIGHT - 40); g.drawString(howTo2, 40, Game.HEIGHT - 10); g.drawString("Move the Tiles to Match the Picture!", 50, 130); g.fillRect(380, 100, 120, 40); g.fillRect(380, 100, 120, 40); g.setColor(new Color(0xF9F6F2)); g.setFont(new Font("Arial", Font.BOLD, 18)); g.drawString("New Game", 392, 127); g.setColor(new Color(0xFF0000)); g.setFont(new Font("Arial", Font.BOLD, 43)); g.drawString("Rubik's Race", 50, 80); g.setColor(new Color(0xBBADA0)); g.fillRect(330, 32, 90, 50); g.fillRect(424, 32, 90, 50); g.setColor(new Color(0xEEE4DA)); g.setFont(new Font("Arial", Font.BOLD, 13)); g.drawString("SCORE", 353, 50); g.drawString("BEST", 450, 50); g.setColor(new Color(0xFFFFFF)); g.setFont(new Font("Arial", Font.BOLD, 17)); g.setStroke(new BasicStroke(3)); g.setColor(new Color(0xBF00FD)); g.drawRect(192, 442, Tile.WIDTH * 3 + 5, 6 + Tile.HEIGHT * 3); /* * g.setFont(scoreFont); g.drawString("" + score, 30, 40); * g.setColor(Color.red); g.drawString("Best: "+highScore, * Game.WIDTH-DrawUtils.getMessageWidth("Best: "+highScore, scoreFont, * g)-20, 40); * g.drawString("Fastest: "+formatTime(fastestMS),Game.WIDTH- * DrawUtils.getMessageWidth("Fastest: "+formatTime(fastestMS), * scoreFont, g)-20,90); g.setColor(Color.black); * g.drawString("Time: "+fromattedTime, 30, 90); */ }
3
public static String decrypt3DES(byte[] message, String encrKey) { try { final MessageDigest md = MessageDigest.getInstance("md5"); final byte[] digestOfPassword = md.digest(encrKey.getBytes("utf-8")); final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); for (int j = 0, k = 16; j < 8;) keyBytes[k++] = keyBytes[j++]; final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(new byte[8]); final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); decipher.init(Cipher.DECRYPT_MODE, key, iv); final byte[] plainText = decipher.doFinal(message); return StringTools.getString(plainText); } catch (Exception ex) { System.out.println("Bad key"); return null; } }
2
private ApplyDeletesResult closeSegmentStates(IndexWriter.ReaderPool pool, SegmentState[] segStates, boolean success, long gen) throws IOException { int numReaders = segStates.length; Throwable firstExc = null; List<SegmentCommitInfo> allDeleted = null; long totDelCount = 0; for (int j=0;j<numReaders;j++) { SegmentState segState = segStates[j]; if (success) { totDelCount += segState.rld.getPendingDeleteCount() - segState.startDelCount; segState.reader.getSegmentInfo().setBufferedDeletesGen(gen); int fullDelCount = segState.rld.info.getDelCount() + segState.rld.getPendingDeleteCount(); assert fullDelCount <= segState.rld.info.info.maxDoc(); if (fullDelCount == segState.rld.info.info.maxDoc()) { if (allDeleted == null) { allDeleted = new ArrayList<>(); } allDeleted.add(segState.reader.getSegmentInfo()); } } try { segStates[j].finish(pool); } catch (Throwable th) { if (firstExc != null) { firstExc = th; } } } if (success) { // Does nothing if firstExc is null: IOUtils.reThrow(firstExc); } if (infoStream.isEnabled("BD")) { infoStream.message("BD", "applyDeletes: " + totDelCount + " new deleted documents"); } return new ApplyDeletesResult(totDelCount > 0, gen, allDeleted); }
8
public static void main(String args[]) throws Throwable { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); for (int t = 0, T = parseInt(in.readLine().trim()); t++ < T;) { StringTokenizer st = new StringTokenizer(in.readLine()); int C = parseInt(st.nextToken()), V = parseInt(st.nextToken()); int[][] votes = new int[V][C]; int[][] candidates = new int[C][2]; for (int i = 0; i < V; i++) { st = new StringTokenizer(in.readLine()); for (int j = 0; j < C; j++) votes[i][j] = parseInt(st.nextToken()); candidates[votes[i][0] - 1][0]++; candidates[votes[i][0] - 1][1] = votes[i][0] - 1; } Arrays.sort(candidates, new Comparator<int[]>() { public int compare(int[] o1, int[] o2) { return o1[0] != o2[0] ? o2[0] - o1[0] : o2[1] - o1[1]; } }); if (candidates[0][0] > votes.length / 2) sb.append(candidates[0][1] + 1).append(" 1"); else { candidates[0][0] = 0; candidates[1][0] = 0; for (int i = 0; i < V; i++) if (pos(votes[i], candidates[0][1] + 1) < pos(votes[i], candidates[1][1] + 1)) candidates[0][0]++; else candidates[1][0]++; sb.append( candidates[0][0] > candidates[1][0] ? candidates[0][1] + 1 : candidates[1][1] + 1).append(" 2"); } sb.append("\n"); } System.out.print(new String(sb)); }
8
public void secondThread() throws InterruptedException { Random random = new Random(); for (int i = 0; i < 10000; i++) { acquireLocks(lock2, lock1); try { Account.transfer(acc2, acc1, random.nextInt(100)); } finally { lock1.unlock(); lock2.unlock(); } } }
1
private void addItem(int numToAdd, ArrayList<Location> locations, boolean checkTargets) { Random rand = new Random(); //Random number generate to determine locations of spaces randomly for(int i = 0; i < numToAdd; i++) { //Generate random location Location newItem = new Location(rand.nextInt(MAX_X),rand.nextInt(MAX_Y)); // Start by assuming no conflicts with a block or target boolean conflict = false; //Check to see if this location is already blocked for(int j = 0; j < blockedLocs.size(); j++){ if(newItem.equals(blockedLocs.get(j))){ conflict = true; } } // blocks are added first, don't need to check targets if (checkTargets) { //Check to see if this location is already a target for(int j = 0; j < targetLocs.size(); j++){ if(newItem.equals(targetLocs.get(j))){ conflict = true; } } } // Add the location only if it is not already blocked and is not the starting location // for one of the players for (Player player : players) { if (newItem.equals(player.getLocation())) conflict = true; } // If any conflict, we did not add an item, so redo this attempt if(conflict){ i--; } else{ locations.add(newItem); } } }
9
private boolean jj_2_59(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_59(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(58, xla); } }
1
public static void main( String[] args ) { Scanner input = new Scanner( System.in ); int number1; int number2; System.out.println( "Enter The First Integer: " ); number1 = input.nextInt(); System.out.println( "Enter The Second Integer: " ); number2 = input.nextInt(); if ( number1 == number2 ) { System.out.printf( "%d == %d\n", number1, number2 ); } if ( number1 != number2 ) { System.out.printf( "%d != %d\n", number1, number2 ); } if ( number1 < number2 ) { System.out.printf( "%d < %d\n", number1, number2 ); } if ( number1 > number2 ) { System.out.printf( "%d > %d\n", number1, number2 ); } if ( number1 <= number2 ) { System.out.printf( "%d <= %d\n", number1, number2 ); } if ( number1 >= number2 ) { System.out.printf( "%d >= %d\n", number1, number2 ); } }
6
private void readObject(ObjectInputStream stream) throws java.io.IOException, java.lang.ClassNotFoundException { stream.defaultReadObject(); int size = stream.readInt(); this.bytes = new byte[size]; int index = 0, remainder = size; while (index < size) { int numOfBytes = stream.read(bytes, index, remainder); if (numOfBytes == -1) throw new java.io.EOFException( "Unexpected EOF at index " + index + " of " + size); else { index += numOfBytes; remainder -= numOfBytes; } } }
2
public Map getMyCustomEvent() { return myCustomEvent; }
0
void setModuleManager(ModuleManager manager){ this.manager = manager; }
0
public static String[] search(String[][] clientArray, String queryString) { // Durch das Array iterieren und schauen, ob der Suchstring // in den Spalten 1 und 2 eines Datensatzes vorkommt for(String[] client: clientArray) { if(client[1].toLowerCase().indexOf(queryString.toLowerCase())!=-1 || client[2].toLowerCase().indexOf(queryString.toLowerCase())!=-1) { return client; } } return null; }
3
public void setjButtonOK(JButton jButtonOK) { this.jButtonOK = jButtonOK; }
0
public static String act(String text) { text = text.replace("{{עשר המכות}}", ""); text = text.replace("{{אבני החושן}}", ""); text = text.replace("{{פירוש לקוי}}", ""); text = text.replace("{{תחבורה ציבורית}}", ""); // line break - we dont need them text = text.replaceAll("\\{\\{ש\\}\\}", ""); text = text.replaceAll("\\<br\\>", ""); text = text.replaceAll("\\<BR\\>", ""); text = text.replaceAll("<br\\s*/>", ""); /** * Remove all the references to footnotes. */ text = text.replaceAll("\\{\\{הפניה[^\\}]+\\}\\}", ""); // Footnotes to web site text = text.replaceAll("\\[((([A-Za-z]{3,9}:(?:\\/\\/)?)(?:[-;:&=\\+\\$,\\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\\+\\$,\\w]+@)[A-Za-z0-9.-]+)((?:\\/[\\+~%\\/.\\w-_]*)?\\??(?:[-\\+=&;%@.\\w_]*)#?(?:[\\w]*))?)\\]", ""); // Remove images text = text.replaceAll("\\[\\[קובץ:[^\\]]*\\]\\]", ""); if (text.contains("תמונה=")) { text = RegEx.removeAll(text, Pattern.compile("\\{\\{[^\\}]+(תמונה=){1}[^\\}]+\\}\\}", Pattern.MULTILINE)); } text = text.replaceAll("\\{\\{מקור\\}\\}", ""); text = RegEx.removeAll(text, Pattern.compile("\\{\\{מספרים\\|[^}]*\\}\\}")); // make it easier to run on the DOM do { text = text.replaceAll("\n\n", "\n"); } while (text.contains("\n\n")); return text; }
2
public double rateBoard(Board board) { final int width = board.getWidth(); final int maxHeight = board.getMaxHeight(); int sumHeight = 0; int holes = 0; // Count the holes, and sum up the heights for (int x=0; x<width; x++) { final int colHeight = board.getColumnHeight(x); sumHeight += colHeight; int y = colHeight - 2; // addr of first possible hole while (y>=0) { if (!board.getGrid(x,y)) { holes++; } y--; } } double avgHeight = ((double)sumHeight)/width; // Add up the counts to make an overall score // The weights, 8, 40, etc., are just made up numbers that appear to work return (8*maxHeight + 40*avgHeight + 1.25*holes); // 8 // 40 // 1.25 }
3
public static double atom(char s) { switch (s) { case 'C': return C; case 'H': return H; case 'O': return O; } return N; }
3
private Map<ProcessModel, Set<Action>> getNoActivityInputActions() { Map<ProcessModel, Set<Action>> noActivityInputActions = new HashMap<ProcessModel, Set<Action>>(); Set<Action> mainSTSActions = new HashSet<Action>(); for (Action action : mainSTS.getInputActions()) { if (!action.isRelatedToAnActivity() && !action.getName().startsWith("Resume")) { mainSTSActions.add(action); } } noActivityInputActions.put(originalModel, mainSTSActions); for (Adaptation ad : this.adaptationSTSs.keySet()) { STS sts = this.adaptationSTSs.get(ad); Set<Action> adaptActions = new HashSet<Action>(); for (Action action : sts.getInputActions()) { if (!action.isRelatedToAnActivity() && !action.getName().startsWith("Resume")) { adaptActions.add(action); } } noActivityInputActions.put(ad.getAdaptationModel(), adaptActions); } return noActivityInputActions; }
7