method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
fa26e387-0613-4ba8-80d8-469d55470ba7
7
@EventHandler(priority = EventPriority.NORMAL) public void onPlayerChat(PlayerChatEvent event) { Player p = event.getPlayer(); for (String pl : this.getPlugin().list.keySet()) { //remove chat from all players applying event.getRecipients().remove(this.getPlugin().getServer().getPlayer(pl)); } if (this.getPlugin().list.containsKey(p.getName())) { event.setCancelled(true); Applicant c = this.getPlugin().list.get(p.getName()); todo t = c.getNext(); switch (t) { case GOODAT: c.setGoodat(event.getMessage()); c.setNext(todo.BANNED); p.sendMessage(""); p.sendMessage(ChatColor.RED + "Alright. " + ChatColor.WHITE + "Next question: Have you ever been" + ChatColor.RED + " banned" + ChatColor.WHITE + " before?"); p.sendMessage("And if yes, " + ChatColor.RED + "why? " + ChatColor.WHITE + "Please be honest."); return; case BANNED: c.setBanned(event.getMessage()); c.setNext(todo.NAME); p.sendMessage(""); p.sendMessage("Okay. We're almost done, just" + ChatColor.RED + " three " + ChatColor.WHITE + "more questions to go."); p.sendMessage("What is your " + ChatColor.RED + "first name?"); return; case NAME: c.setName(event.getMessage()); c.setNext(todo.AGE); p.sendMessage(""); p.sendMessage("Alright, " + ChatColor.RED + "almost done!"); p.sendMessage("How " + ChatColor.RED + "old" + ChatColor.WHITE + " are you?"); return; case AGE: c.setAge(event.getMessage()); c.setNext(todo.COUNTRY); p.sendMessage(""); p.sendMessage(ChatColor.GREEN + "Last question!"); p.sendMessage("In what " + ChatColor.RED + "country" + ChatColor.WHITE + " do you live?"); return; case COUNTRY: c.setCountry(event.getMessage()); p.sendMessage(""); p.sendMessage("Okay, you've completed the application. Double check it before sending it off."); p.sendMessage("Good at: " + ChatColor.RED + c.getGoodat()); p.sendMessage("Banned: " + ChatColor.RED + c.getBanned()); p.sendMessage("Name: " + ChatColor.RED + c.getName()); p.sendMessage("Age: " + ChatColor.RED + c.getAge()); p.sendMessage("Country: " + ChatColor.RED + c.getCountry()); p.sendMessage("If you've completed it correctly, type " + ChatColor.RED + "/apply " + ChatColor.WHITE + "To confirm! Otherwise, type " + ChatColor.RED + "/apply reset"); } } }
8b240d72-dcee-4b85-bba3-abb1204b4a33
2
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onPlayerDamageEvent (EntityDamageEvent event) { if(event.getEntity() instanceof Player) { Player p = (Player) event.getEntity(); if(playersInSM.contains(p.getName())) //check if player is in ServiceMode { //if(event.getCause() == event.) // optional: look what caused the damage. (to not have a complete god mode) event.setCancelled(true); // if yes, dont apply damage (e.g. from falling into lava or creeper explosion) } } }
56890a4a-18c6-4544-b715-83104204ce68
2
private String getVmRef( String vmName) throws ConnectorException{ String vmSearch = doGet(apiLink + Utils.VMS_QUERY_SUFFIX); Document doc = RestClient.stringToXmlDocument(vmSearch); NodeList list = doc.getElementsByTagName(Constants.VM_RECORD); for(int i=0; i < list.getLength(); i++){ if(list.item(i).getAttributes().getNamedItem(Constants.NAME).getTextContent().trim().equalsIgnoreCase(vmName)) { return list.item(i).getAttributes().getNamedItem(Constants.HREF).getTextContent().trim(); } } throw new ConnectorException("The following Vm is not being found or is corrupted: " + vmName); }
0fadab3e-0112-4166-811e-108452ac0086
9
@Test public void stessTest() { try { Server server = new Server(4445, debug); server.start(); String address = "localhost"; int number = 1000; Socket user[] = new Socket[number]; ObjectInputStream in[] = new ObjectInputStream[number]; ObjectOutputStream out[] = new ObjectOutputStream[number]; for (int i = 0; i < number; i++) { user[i] = new Socket(address, 4445); if (i < 500) { in[i] = new ObjectInputStream(user[i].getInputStream()); assert(checkMessage((Message)in[i].readObject(), "MESSAGE { Type: Response, Code: 100, Status: Welcome }")); out[i] = new ObjectOutputStream(user[i].getOutputStream()); } else try { in[i] = new ObjectInputStream(user[i].getInputStream()); assert(false); } catch (Exception e2) { } } for (int i = 0; i < 500; i++) { Message message = new Message(); message.setType(Type.Login); message.setUser(String.format("user%d", i)); out[i].writeObject(message); assert(checkMessage((Message)in[i].readObject(), String.format("MESSAGE { Type: Login, Code: 101, Status: Welcome user%d }", i))); } for (int i = 0; i < 500; i = i + 5) { Message message = new Message(); message.setType(Type.Friends); String[] friends = new String[4]; for (int j = 0; j < 4; j++) { friends[j] = String.format("user%d", j+1); } message.setFriends(friends); out[i].writeObject(message); message = (Message)in[i].readObject(); checkMessage(message, ""); assert(message.getCode() == 303); for (int j = 1; j < 5; j++) { assert(checkMessage((Message)in[j].readObject(), String.format("MESSAGE { Type: Friends, User: user%d, Code: 305 }", i))); } } for (int i = 0; i < 500; i = i + 5) { } server.kill(); } catch (Exception e) { System.out.println("Marco"); assert(false); } }
fa8e082a-04c8-423e-ad85-c4e7f754cf45
8
public synchronized void handleFailure(NodeId nodeId) { if (nodeId == null) { return; } // This should never happen if(nodeId.equals(localNode.getNodeId())) { //throw new IllegalArgumentException("Can't handle a failure for local node"); return; } Bucket bucket = bucketTrie.select(nodeId); Contact node = bucket.get(nodeId); if (node == null) { // None of the contacts in the route table has the specified nodeId return; } // Ignore failure if we start getting to many disconnections in a row /*if (consecutiveFailures >= RoutingSettings.MAX_CONSECUTIVE_FAILURES) { if (LOG.isTraceEnabled()) { LOG.trace("Ignoring node failure as it appears that we are disconnected"); } return; }*/ node.handleFailure(); if (node.isDead()) { if (bucket.containsBucketContact(nodeId)) // the contact is in the bucket { // The node has failed too many times and have to be replaced // with the MRS node from the cache. If the cache is empty // the dead node will remain in the bucket and will be removed // with the next "replaceContactInBucket" bucket.removeBucketContact(nodeId); if (bucket.getCacheSize() > 0) { Contact mrs = null; while((mrs = bucket.getMostRecentlySeenCachedContact()) != null) { bucket.removeCachedContact(mrs.getNodeId()); //bucket.removeBucketContact(nodeId); //assert (bucket.isBucketFull() == false); bucket.addBucketContact(mrs); break; } } } else // the contact is in the cache { // On first glance this might look like as if it is // not necessary since we're never contacting cached // Contacts but that's not absolutely true. FIND_NODE // lookups may return Contacts that are in our cache // and if they don't respond we want to remove them... bucket.removeCachedContact(nodeId); } } //TODO:gestione fallimenti provvisoria! modifica if (++consecutiveFailures == 20) { System.err.println(controlNode.getUserId() + " DISCONNECTING (too many falures)"); controlNode.exit(true); } }
ed12dc23-73b9-4956-8ab1-4f06f8356b2f
9
public void update(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); Dimension dim = getSize(); int width = dim.width; int height = dim.height; g2.setColor(getBackground()); g2.fillRect(0, 0, width, height); g2.setFont(font); bound.setRect(width / 10, height / 10, width / 3, width / 3); int r = bound.x + bound.width + 20; int s = bound.y + 10; int legendX1 = width / 8; int legendX2 = width / 4; float t = 0.0f; int n = percent.length; for (int i = 0; i < n; i++) { g2.setColor(colors[i]); arcs[i].setArc(bound, t, percent[i] * 360.0f, Arc2D.PIE); if (isEnabled()) { if (i < n - 1) { endPoint = arcs[i].getEndPoint(); hotspots[i].x = (float) (endPoint.getX() - hotspots[i].width * 0.5); hotspots[i].y = (float) (endPoint.getY() - hotspots[i].height * 0.5); } } g2.fill(arcs[i]); g2.fillRect(r, s + i * 20, 20, 10); g2.setColor(Color.black); g2.draw(arcs[i]); g2.drawRect(r, s + i * 20, 20, 10); g2.drawString(legends[i], r + legendX1, s + 10 + i * 20); if (total == 0) { g2.drawString(format.format(percent[i] * 100.0) + "%", r + legendX2, s + 10 + i * 20); } else { g2.drawString(format.format(percent[i] * 100.0) + "% (" + format.format(percent[i] * total) + ")", r + legendX2, s + 10 + i * 20); } t += percent[i] * 360.0f; } if (isEnabled()) { for (int i = 0; i < hotspots.length; i++) { g2.setColor(Color.white); g2.fill(hotspots[i]); g2.setColor(Color.black); g2.draw(hotspots[i]); } } if (text != null) { g2.setColor(Color.black); for (int i = 0; i < legends.length; i++) { if (text[i] != null) g2.drawString(text[i], bound.x, bound.y + bound.height + 30 + 20 * i); } } }
37d96d7a-06ce-44ec-aa7a-97e2f113081e
1
protected void init(int size) { id = new int[size]; for (int i = 0; i < size; i++) { id[i] = i; } }
a2d1b712-ef9c-4036-8d26-115088d99a7f
0
public NFAToDFAAction(FiniteStateAutomaton automaton, Environment environment) { super("Convert to DFA", null); this.automaton = automaton; this.environment = environment; /* * putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke (KeyEvent.VK_R, * MAIN_MENU_MASK+InputEvent.SHIFT_MASK)); */ }
e3d8caa0-d8e5-4546-8f2d-fddf87e52b19
7
private List<Class<?>> getTypeHierarchy(Class<?> type) { if (type.isPrimitive()) { type = primitiveTypeToWrapperMap.get(type); } Set<Class<?>> typeHierarchy = new LinkedHashSet<Class<?>>(); collectTypeHierarchy(typeHierarchy, type); if (type.isArray()) { typeHierarchy.add(Object[].class); } typeHierarchy.add(Object.class); return new ArrayList<Class<?>>(typeHierarchy); }
6e8a2969-e75a-4a29-b541-6795df4fb9d2
7
public static void firstPalindrome(int num) { int forward = num; int backward = num; int countf = 0; int countb = 0; while (!isPalindrome(forward) && !isPalindrome(backward)) { countf++; countb++; forward++; backward--; } if (isPalindrome(forward)) { countb++; } if (isPalindrome(backward)) { countf++; } if (countf == countb) { System.out.println(forward + " " + backward); } if (countf > countb) { System.out.println(backward); } if (countf < countb) { System.out.println(forward); } }
02b39e1a-92a4-4aff-92a0-8ff43b01d55a
0
public void removeed(Watcher watcher) { list.remove(watcher); }
3b39c6bb-35ad-42ef-8662-7ad9e8e40910
2
private static GtfsSchemaCreationImpl ommitShapeColumn(GtfsSchemaCreationImpl beforeSchema){ GtfsSchemaCreationImpl afterSchema = new GtfsSchemaCreationImpl(beforeSchema); ArrayList<Integer> afterTypes = new ArrayList<Integer>(); afterTypes.addAll(afterSchema.getTypes()); for(int i=0; i<afterTypes.size(); i++){ if(afterTypes.get(i) == SeColumnDefinition.TYPE_SHAPE) afterSchema.deleteColumn(i); } return afterSchema; }
5b7a876b-42c0-4325-94b5-0c43b582338f
7
private static byte[] scanPrivateKey(CryptobyConsole console) { byte[] retKey = null; do { scanner = new Scanner(System.in); String keyText = ""; // Input Private Key for decryption System.out.println("\nEnter the private Key (Type '" + quit + "' to Escape):"); try { while (!scanner.hasNext(CryptobyHelper.getEOBString())) { if (scanner.hasNext(quit)) { rsaCrypterText(console); } keyText = keyText + scanner.next(); } retKey = CryptobyHelper.hexStringToBytes(keyText); keySize = retKey.length * 4; } // Catch false format of Input catch (NumberFormatException exp) { System.out.println("Not allowed Characters in Private Key! Just lower alphanumeric Characters!"); retKey = BigInteger.ZERO.toByteArray(); keySize = 0; } catch (NullPointerException exp) { System.out.println("NullPointerException catched! Try again!"); retKey = BigInteger.ZERO.toByteArray(); keySize = 0; } } while (keySize != 1024 && keySize != 2048 && keySize != 4096); return retKey; }
f9d1d426-48b7-4006-8e7e-53f24c6a9427
2
public void updateSize() { int gw = fm.stringWidth(name); for (int i = 0; i < sizeInformation(); i++) gw = fm.stringWidth((String) (data.getValue(getCodeInformation(i), DictionnaireTable.NAME))) < gw ? gw : fm .stringWidth((String) (data.getValue(getCodeInformation(i), DictionnaireTable.NAME))); int gh = (fm.getMaxDescent() + 15) * (sizeInformation() - 1); this.setWidth(gw + 20); this.setHeight(50 + gh); }
65c5f24e-91bf-4598-a996-b40ecad6af44
0
@SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jSplitPane1 = new javax.swing.JSplitPane(); jPanel1 = new javax.swing.JPanel(); jLabelTitre = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jTextFieldComNom = new javax.swing.JTextField(); jTextFieldComp = new javax.swing.JTextField(); jButtonPrevious = new javax.swing.JButton(); jButtonNext = new javax.swing.JButton(); jButtonClose = new javax.swing.JButton(); jLabel8 = new javax.swing.JLabel(); jTextFieldCode = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); jTextFieldPrix = new javax.swing.JTextField(); jComboBoxFamille = new javax.swing.JComboBox(); jScrollPane1 = new javax.swing.JScrollPane(); jTextAreaEffIndesir = new javax.swing.JTextArea(); jScrollPane2 = new javax.swing.JScrollPane(); jTextAreaContreIndic = new javax.swing.JTextArea(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBorder(new javax.swing.border.MatteBorder(null)); jLabelTitre.setText("Medicaments"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(219, 219, 219) .addComponent(jLabelTitre) .addContainerGap(219, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelTitre, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE) ); jLabel2.setText("Famille"); jLabel3.setText("Composition"); jLabel4.setText("Effets indésirables"); jLabel5.setText("Contre indications"); jLabel6.setText("Prix échantillon"); jTextFieldComNom.setText("jTextField1"); jTextFieldComp.setText("jTextField3"); jButtonPrevious.setText("Précédent"); jButtonNext.setText("Suivant"); jButtonClose.setText("Fermer"); jLabel8.setText("Nom commercial"); jTextFieldCode.setText("jTextField6"); jLabel9.setText("Code"); jTextFieldPrix.setText("jTextField7"); jComboBoxFamille.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jTextAreaEffIndesir.setColumns(20); jTextAreaEffIndesir.setRows(5); jScrollPane1.setViewportView(jTextAreaEffIndesir); jTextAreaContreIndic.setColumns(20); jTextAreaContreIndic.setRows(5); jScrollPane2.setViewportView(jTextAreaContreIndic); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel6) .addComponent(jLabel8) .addComponent(jLabel9) .addComponent(jLabel2) .addComponent(jLabel5)) .addGap(52, 52, 52) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextFieldComNom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextFieldComp, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextFieldCode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBoxFamille, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButtonNext) .addComponent(jTextFieldPrix, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane1) .addComponent(jScrollPane2))) .addGroup(layout.createSequentialGroup() .addGap(66, 66, 66) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(175, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(112, 112, 112) .addComponent(jButtonPrevious) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonClose) .addGap(37, 37, 37)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(26, 26, 26) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(jTextFieldCode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(jTextFieldComNom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jComboBoxFamille, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jTextFieldComp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(20, 20, 20) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(31, 31, 31) .addComponent(jLabel4) .addGap(35, 35, 35) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(55, 55, 55)) .addGroup(layout.createSequentialGroup() .addGap(0, 10, Short.MAX_VALUE) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextFieldPrix, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)))) .addGap(22, 22, 22) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButtonPrevious) .addComponent(jButtonNext)) .addGap(12, 12, 12)) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jButtonClose) .addContainerGap()))) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)))) ); pack(); }// </editor-fold>//GEN-END:initComponents
8b8b6630-8d25-41d0-b533-50144c6d5e1f
2
public MenuPrincipal() { //sérialisation lors du lancement de la frame try { FileInputStream f = new FileInputStream("sauvegarde.csv"); ObjectInputStream s = new ObjectInputStream(f); MainProjet.lesEntreprises = (ArrayList<Entreprise>) s.readObject(); MainProjet.lesOffres = (ArrayList<OffreStage>) s.readObject(); } catch(IOException e) {System.out.println("Nouveau fichier");} catch(ClassNotFoundException e) {System.out.println("Probleme");} initComponents(); }
d6d0c43e-6778-4eb8-abef-92501507d5f0
4
public Pesquisador() { File f = new File(Arquivo.ARQ_ARVOREB); if(!f.exists()){ arvoreB = new ArvoreB<String, ArrayList<String>>(); TrataArquivo arqLivro = new TrataArquivo(Arquivo.ARQ_LIVRO, Arquivo.LIVRO); ArrayList livros = arqLivro.leArquivo(); ComparadorLivro comparador = new ComparadorLivro(); comparador.setIdCampo(Livro.INDICE_EDITORA); Collections.sort(livros, comparador); ArrayList<String> livrosAux = new ArrayList<String>(); Object lvAnterior = livros.get(0); //pega o primeiro for(int i = 1; i < livros.size(); i++){ Object lvAtual = livros.get(i); String editoraAnterior = lvAnterior.toString().split(Arquivo.TAB)[Livro.INDICE_EDITORA]; livrosAux.add(lvAnterior.toString()); String editoraAtual = lvAtual.toString().split(Arquivo.TAB)[Livro.INDICE_EDITORA]; lvAnterior = lvAtual; if(!editoraAnterior.equals(editoraAtual) || (i == livros.size() - 1)){ arvoreB.put(editoraAnterior, livrosAux); livrosAux = new ArrayList<String>(); } livros.set(i, null); //Pra ajudar na memoria } TrataArquivo.gravaObjeto(arvoreB, Arquivo.ARQ_ARVOREB); } else { arvoreB = (ArvoreB<String, ArrayList<String>>)TrataArquivo.getObjeto(Arquivo.ARQ_ARVOREB); } }
cd201954-31f6-4250-a87a-fc1619a5241d
9
private void btn_GuardarPreguntasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_GuardarPreguntasActionPerformed btn_guardarOpcion.setEnabled(true); if(txt_DescripcionPregunta.equals("")){ JOptionPane.showMessageDialog(null, "Debe ingresar una descripción"); txt_DescripcionPregunta.requestFocus(); return; } p.setDescripcionPregunta(txt_DescripcionPregunta.getText()); // p.setTipo(cb_TipoPreg.getSelectedIndex() + 1); // // p.setObligatorioa((String) cb_EsObligatoria.getSelectedItem()); Pregunta pregaux = new Pregunta(); if (cb_ListaPreguntas.getSelectedItem().equals("Ninguno")) { pregaux.setCodigo(0); } else { if (cb_OrdenPreguntas.getSelectedIndex()!= 0) { JOptionPane.showMessageDialog(this, "Verifique sus condiciones, no pueden ingresar dos condicionamientos diferentes"); return; } pregaux.setCodigo(cb_ListaPreguntas.getSelectedIndex() + 1); } p.setDespuesDePregunta(pregaux); p.setOrden(cb_OrdenPreguntas.getSelectedIndex() + 1); latex lt = new latex(); try { if (lt.crearPregunta(p) == 1) { //preguntaDAO pDAO = new preguntaDAO(); if (seleccion == 2) { //Duplicar ls backSlashh! if (ctrlPreg.crearPregunta(p) == 1) { lblInformacion.setText( "Pregunta "+p.getCodigo()+ " almacenada correctamente!"); btn_guardarOpcion.setEnabled(true); // JOptionPane.showMessageDialog(this, "Pregunta almacenada correctamente!"); } } else { if (ctrlPreg.modificarPregunta(p) == 1) { lblInformacion.setText( "Pregunta "+p.getCodigo()+ " modificada correctamente!"); //JOptionPane.showMessageDialog(this, "Pregunta modificada correctamente!"); } } } } catch (IOException ex) { Logger.getLogger(administrarEnunciado.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(administrarEnunciado.class.getName()).log(Level.SEVERE, null, ex); } // TODO add your handling code here: }//GEN-LAST:event_btn_GuardarPreguntasActionPerformed
3b7b39b1-d85a-41ce-8f3d-54d45f6dd793
5
static final int method244(int i) { anInt8622++; if ((double) Class75.aFloat1249 == 3.0) return 37; if (i != 37) return 11; if ((double) Class75.aFloat1249 == 4.0) return 50; if ((double) Class75.aFloat1249 == 6.0) return 75; if ((double) Class75.aFloat1249 == 8.0) return 100; return 200; }
cdd55f45-fdcd-42dc-b548-1e294a63732d
2
public void setSeatsInRow(int rowNumber, int numOfSeatsInRow){ if (numOfSeatsInRow <= MAX_SEATS_PER_ROW) { ArrayList<Seat> tmpList = new ArrayList<>(); for (int i = 0; i < numOfSeatsInRow; i++) { Seat tmp = new Seat(rowNumber + ":" + i); tmpList.add(tmp); } seats.add(tmpList); }else { setSeatsInRow(rowNumber, MAX_SEATS_PER_ROW); } }
d0bbd36d-fbe6-4ac7-8ea2-d2392646a4c4
7
private void invokePopupMenu(int x, int y) { selectedAnnotationHostAtom = getAnnotationHost(Attachment.ATOM_HOST, x, y); selectedAnnotationHostBond = getAnnotationHost(Attachment.BOND_HOST, x, y); if (selectedAnnotationHostAtom < 0 && selectedAnnotationHostBond < 0) { selectedAtom = findNearestAtomIndex(x, y); selectedBond = findNearestBondIndex(x, y); // when both selected if (selectedAtom >= 0 && selectedBond >= 0) { int[] bondPair = getBondAtoms(selectedBond); if (bondPair[0] == selectedAtom || bondPair[1] == selectedAtom) { // if the selected atom forms the selected bond, favor the selected atom selectedBond = -1; } else { // otherwise, compare the z-depth of the selected bond and the selected atom Point3i pAtom = getAtomScreen(selectedAtom); Point3i pBond = getBondCenterScreen(selectedBond); if (pAtom.z > pBond.z) { selectedAtom = -1; } else { selectedBond = -1; } } } } else { selectedAtom = -1; selectedBond = -1; } setClickedAtom(selectedAtom); setClickedBond(selectedBond); createPopupMenu(); hidePopupText(); popupMenu.show(popupMenu.getInvoker(), x + 5, y + 5); }
d6738709-974c-4821-994d-2c76b80081ce
4
public static int addConnectionThread(Thread con) { boolean added = false; int num = 0; for(int k = 0;k<=5;k++) { if(MainThread.uploadConnectionThreads[k] == null && added == false) { MainThread.uploadConnectionThreads[k] = con; added = true; } } if(added = false) { return 99; } return num; }
c4e91655-97d9-4bdd-87f4-e846d8afa23f
9
private boolean isLabelIncluded( final String sampleLabel ) { // check if label is included boolean included = true; if( includedRegEx != null && ! includedRegEx.isEmpty() ) { included = false; for( Pattern regEx : includedRegEx ) { if( regEx.matcher( sampleLabel ).matches() ) { included = true; break; } } } if( included && excludedRegEx != null && ! excludedRegEx.isEmpty() ) { for( Pattern regEx : excludedRegEx ) { if( regEx.matcher( sampleLabel ).matches() ) { included = false; break; } } } return included; }
6f566649-3b4d-4c6e-b903-dc6a887b7f95
7
public static Interval negExpr(Interval i1) { /* -[a,b] = [-b, -a] */ if (i1 != null && i1.isBottom()) return Interval.BOTTOM; if (i1 == null) return new Interval(NEGATIVE_INF, POSITIVE_INF); long lower = -i1.getUpperBound(); long upper = -i1.getLowerBound(); if (i1.getUpperBound() == POSITIVE_INF) lower = NEGATIVE_INF; if (i1.getUpperBound() == NEGATIVE_INF) lower = POSITIVE_INF; if (i1.getLowerBound() == POSITIVE_INF) upper = NEGATIVE_INF; if (i1.getLowerBound() == NEGATIVE_INF) upper = POSITIVE_INF; return new Interval(lower, upper); }
0562e860-ede1-4592-95ed-d0700a3afcf6
0
public String toString() { StringBuffer sb = new StringBuffer(super.toString()); sb.append(" : tokens("); sb.append(tokens); sb.append(") at "); sb.append(center); sb.append(" with "); sb.append(Arrays.asList(results)); return sb.toString(); }
fa27dd21-ae2d-4279-a56c-6579c14cec8f
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SearchGenre other = (SearchGenre) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
33f4b6e8-a848-4ca4-9c3c-115fdeb5fb35
6
public ArrayList<String> createUsernameArrayList() { ArrayList<String> usernames = new ArrayList<String>(); ResultSet rs = null; PreparedStatement statement = null; try { statement = conn.prepareStatement("select Username from Accounts"); rs = statement.executeQuery(); while (rs.next()) { usernames.add(rs.getString("Username")); } } catch(SQLException e){ e.printStackTrace(); } finally { try { if (rs != null) rs.close(); } catch (Exception e) {} try { if (statement != null) statement.close(); } catch (Exception e) {} } return usernames; }
88db0f08-a1f5-4957-b0ef-153516a739db
2
public double readDouble() throws IOException { mark(DEFAULT_READ_LIMIT); int cfaslOpcode = read(); switch (cfaslOpcode) { case CFASL_P_FLOAT: return readFloatBody(false); case CFASL_N_FLOAT: return readFloatBody(true); default: reset(); throw new RuntimeException("Expected a double but received OpCode=" + cfaslOpcode); } }
2f0dceba-89a6-4523-8be8-337b1b7250d8
7
void extractPages(Page page) { if (cancelled) return; // Unterseiten hinzufügen (sofern welche vorhanden sein könnten) if (page.containsPages()) { for (PageExtractor pe : Extractors.getInstance().getPageExtractors()) { if (!pe.isSelected() || !pe.isApplicable(page)) continue; page.addSubPages(pe.extractPages(page)); } } // Namen von dieser Seite extrahieren (sofern welche vorhanden sein könnten) if (page.containsNames()) { page.addNames(extractNames(page)); } page.releaseContent(); // Rekursiv alle Unterseiten bearbeiten for (PageInfo p : page.getSubPages()) { extractPages((Page)p); } }
bd0634f7-585c-4218-b61f-15322d272c71
7
@Override public void bind(float dt) { if (mIsPaused || mCurrentFrame == mStopAt) { mFrames[mCurrentFrame].bind(dt); return; } mCurrentTime += dt; while (mCurrentTime >= mFrameSwapTimes[mCurrentFrame]) { mCurrentTime -= mFrameSwapTimes[mCurrentFrame]; if (mShouldReverse) { if (mReversing) { mCurrentFrame--; } else { mCurrentFrame++; } if (mCurrentFrame == mFrames.length) { mCurrentFrame -= 2; mReversing = true; } else if (mCurrentFrame == -1) { mCurrentFrame += 2; mReversing = false; } } else { mCurrentFrame = (mCurrentFrame + 1) % mFrames.length; } } mFrames[mCurrentFrame].bind(dt); }
a2c24b32-7ccf-4d78-a43e-46ae5cfe9ed8
0
@Override public void update(News news) { System.out.println(name + ", was informed about - News(" + news.getHeading() + ")"); }
ac1102ce-4f76-4f6c-95c1-2317f3607809
0
@Test public void singleInsertSizeAndContent() { a.insert(v); assertEquals(v, a.get(0)); assertEquals(1, a.getSize()); }
b140ea6f-784c-4db1-828d-e9de7f95c6f4
1
public float getMaxGain() { float gainMax = -9999.0f; if (audioDevice instanceof JavaSoundAudioDevice) { JavaSoundAudioDevice jsAudio = (JavaSoundAudioDevice) audioDevice; gainMax = jsAudio.getMaxGain(); } return gainMax; }
1f2ebc8a-8555-4a97-89a5-7fa8ef8f7552
8
public Card disproveSuggestion(String person, String room, String weapon) { ArrayList<Card> solutions = new ArrayList<Card>(); // If player has one or more of the cards, return one of the ones they have randomly for( Card card : cards ) { if( card.getName().equalsIgnoreCase(person) && card.getType() == Card.CardType.PERSON ) { solutions.add(card); } else if( card.getName().equalsIgnoreCase(room) && card.getType() == Card.CardType.ROOM ) { solutions.add(card); } else if( card.getName().equalsIgnoreCase(weapon) && card.getType() == Card.CardType.WEAPON ) { solutions.add(card); } } // If player doesn't have any of the given cards... if( solutions.isEmpty() ) { return null; } else { Collections.shuffle(solutions); return solutions.get(0); } }
6806c563-fca8-43b9-9275-465f5b93bd5f
3
private Object getAndTick(Keep keep, BitReader bitreader) throws JSONException { try { int width = keep.bitsize(); int integer = bitreader.read(width); Object value = keep.value(integer); if (JSONzip.probe) { JSONzip.log("\"" + value + "\""); JSONzip.log(integer, width); } if (integer >= keep.length) { throw new JSONException("Deep error."); } keep.tick(integer); return value; } catch (Throwable e) { throw new JSONException(e); } }
c527bbc7-d35f-41d6-8e89-79f15f5a1b68
5
private void execute() { if(sourceFile == null) { printError("-i : No source file specified"); } if(assembler == null || computer == null) { printError("-f : No format specified"); } if(assembler.hasErrors()) { printError("Unable to execute file due to errors"); } print("...preparing to execute program"); if(trace) { print("...opening computer trace files"); addTraceListeners(); } computer.setExecutionSpeed(ExecutionSpeed.FULL); computer.setInstructions(assembler.getInstructions()); computer.addComputerListener(new ComputerAdapter() { public void computerStarted(Computer computer) { print("...Execution started"); } public void computerStopped(Computer computer) { print("...Execution complete"); } }); computer.execute(); }
c28db676-2375-45de-b465-1a809fd8f621
9
private void handleCancelReservation(Sim_event ev) { int src = -1; // sender id boolean success = false; int tag = -1; try { // id[0] = gridletID, [1] = reservID, [2] = transID, [3] = sender ID int[] obj = ( int[] ) ev.get_data(); // get the data inside an array int reservationID = obj[1]; int transactionID = obj[2]; src = obj[3]; // gridletID can be -1 if want to cancel ALL Gridlets in 1 reserv int gridletID = obj[0]; int returnTag = GridSimTags.RETURN_AR_CANCEL; tag = returnTag + transactionID; // check whether this resource can support AR or not success = checkResourceType(src, returnTag, transactionID, GridSimTags.AR_CANCEL_ERROR_RESOURCE_CANT_SUPPORT, "can't cancel a reservation"); if (!success) { return; } // cancels a gridlet of a specific reservation else if (success && gridletID != -1) { ( (ARPolicy) policy_).handleCancelReservation(reservationID, src, gridletID, tag); } // cancels ALL gridlets of a specific reservation else if (success && gridletID == -1) { ( (ARPolicy) policy_).handleCancelReservation(reservationID, src, tag); } } catch (ClassCastException c) { // cancel a list of Gridlets handleCancelList(ev); return; } catch (Exception e) { success = false; } // if there is an exception, then send back an error msg if (!success && tag != -1) { System.out.println(super.get_name() + " : Error - can't cancel a "+ "new reservation."); super.send(src, 0.0, GridSimTags.RETURN_AR_CANCEL, new IO_data(new Integer(GridSimTags.AR_CANCEL_ERROR),SIZE,src)); } }
3737fcb7-ea5e-4d66-90b7-4a17f5aa77e4
6
@Override public boolean setFromString(String value) { this.clear(); String[] values=value.split("\\x00"); for(String v : values) { // handle id3v2.2/2.3 genre lists "(xx)(xx)text" if(v.matches("\\(\\d{1,3}\\).*")) { int endParen=v.indexOf(")"); if(!addNumericId(v.substring(1,endParen))) { // didn't parse this, just add the string this.add(v); } else if(endParen+1 <v.length()) { // did parse an id3 genre, recursively process chain of genre list // (this is probably rare) setFromString(v.substring(endParen+1)); } // handle id3v2.4 reference to genre ID } else if(v.matches("\\d{1,3}")) { if(!addNumericId(v)) { this.add(v); } // handle any other string } else { this.add(v); } } return this.size()>0; }
cfe53868-3ce6-4b61-9c6b-e4a2559045d2
3
public int getNumberLocY(int number) { for (int y = 0; y < map.length; y++) { for (int x = 0; x < map[0].length; x++) { if (map[y][x] == number) return y; } } Logger.log("Can't find number " + number + " in map", Logger.ERROR); Game.exit(1); return -1; }
ffa9dc98-a814-4867-aa34-0d535e406995
2
public void RetrieveSalt(RequestPacket request, DBCollection coll, User user) { try { // Use cursor to find query -> password DBCursor cursor = coll.find(new BasicDBObject("user_name", request.getUser_name())); if(cursor.hasNext()) { String stored_salt = cursor.next().get("salt").toString(); user.sendMessage(msgTransformer.writeMessage(new ResponsePacket().setResponse("salt").setMessage(stored_salt))); } else { salt = BCrypt.gensalt(12); user.sendMessage(msgTransformer.writeMessage(new ResponsePacket().setResponse("salt").setMessage(salt))); } } catch(Exception e) { user.sendMessage(msgTransformer.writeMessage(new ResponsePacket().setResponse("response").setMessage("Invalid username or password"))); } }
9ba7b6a3-1eb5-4c59-b3e5-9771987fd224
9
private void parseAdobeDate(String date) { // total offset count int totalOffset = 0; int currentOffset = 0; // start peeling of values from string if (totalOffset + OFFSET_YYYY <= date.length()) { currentOffset = (totalOffset + OFFSET_YYYY); year = date.substring(totalOffset, currentOffset); totalOffset += currentOffset; } if (totalOffset + OFFSET_MM <= date.length()) { currentOffset = (totalOffset + OFFSET_MM); month = date.substring(totalOffset, currentOffset); totalOffset += OFFSET_MM; } if (totalOffset + OFFSET_DD <= date.length()) { currentOffset = (totalOffset + OFFSET_DD); day = date.substring(totalOffset, currentOffset); totalOffset += OFFSET_DD; } if (totalOffset + OFFSET_HH <= date.length()) { currentOffset = (totalOffset + OFFSET_HH); hour = date.substring(totalOffset, currentOffset); totalOffset += OFFSET_HH; } if (totalOffset + OFFSET_mm <= date.length()) { currentOffset = (totalOffset + OFFSET_mm); minute = date.substring(totalOffset, currentOffset); totalOffset += OFFSET_mm; } if (totalOffset + OFFSET_SS <= date.length()) { currentOffset = (totalOffset + OFFSET_SS); second = date.substring(totalOffset, currentOffset); totalOffset += OFFSET_SS; } if (totalOffset + OFFSET_0 <= date.length()) { currentOffset = (totalOffset + OFFSET_0); timeZoneOffset = date.substring(totalOffset, currentOffset); totalOffset += OFFSET_0; } if (totalOffset + OFFSET_HH <= date.length()) { currentOffset = (totalOffset + OFFSET_HH); timeZoneHour = date.substring(totalOffset, currentOffset); totalOffset += OFFSET_HH; } // lastly pull off 'MM' for timezone minutes if (totalOffset + 4 <= date.length()) { // compensate for the ' in 'MM' timeZoneMinute = date.substring(totalOffset + 1, totalOffset + 3); //System.out.println(timeZoneMinute); } }
40fc7426-3a26-48aa-be6f-d9907ddb6b84
9
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; WhileStatementNode other = (WhileStatementNode) obj; if (exp1 == null) { if (other.exp1 != null) return false; } else if (!exp1.equals(other.exp1)) return false; if (stateSeq1 == null) { if (other.stateSeq1 != null) return false; } else if (!stateSeq1.equals(other.stateSeq1)) return false; return true; }
612d948d-1428-471d-b9a0-2d3c8b559d45
2
public void addEdge(Value v1, Value v2) { HashSet<Value> v1Edges = adjacencyList.get(v1); HashSet<Value> v2Edges = adjacencyList.get(v2); if(v1Edges == null) { v1Edges = new HashSet<Value>(); adjacencyList.put(v1, v1Edges); } if(v2Edges == null) { v2Edges = new HashSet<Value>(); adjacencyList.put(v2, v2Edges); } v1Edges.add(v2); v2Edges.add(v1); }
c529c958-c62d-4e5f-86b5-f9fc211593b0
1
public static void flush() { clearBuffer(); try { out.flush(); } catch (IOException e) { e.printStackTrace(); } }
8e82f032-683f-4de3-b62a-d8ed3ee94b88
0
public Object getValueAt(int row, int column) { return ((Object[]) data.get(row))[column]; }
1d6f225e-1cad-4544-a184-02f305607adc
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Component)) return false; Component other = (Component) obj; return id == other.id && title.equals(other.title) && producer.equals(other.producer) && description.equals(other.description); }
114a97c3-367d-4762-89d2-4437472f3290
2
public String getName(ConnectionWrapper cw, Integer number) throws SQLException { if(number == null) { return null; } String res = numberToName.get(number); if (res == null) { // a new name has popped up in the database, load it loadData(cw); res = numberToName.get(number); } return res; }
c2c48e6e-22d0-4f4e-9d39-fd1d08170087
1
@Override public void render() { textPath = (SVGOMTextPathElement) text.getElementsByTagName("textPath").item(0); if(isMarked()){ textPath.setAttribute("style", "fill:red"); } else { textPath.setAttribute("style", ""); } textPath.setAttribute("startOffset", percentage+"%"); Node pathClone = textPath.cloneNode(true); text.removeChild(textPath); text.appendChild(pathClone); this.textPath = (SVGOMTextPathElement) pathClone; }
bc9c63e8-e62c-44f4-921c-63eefdd635e1
4
public String ElectionSetTurnHolder(int newTurnHolder) { synchronized (peer) { assert peer.isReady(); if (peer.getTurnHolder().getOrd() != newTurnHolder) { System.out.println("Stavo ancora aspettando un word ack, ma è cambiato il turno. Faccio come se l'avessi ricevuto, cancello lastWordTask."); if (peer.lastWordTask != null) { peer.lastWordTask.cancel(); peer.lastWordTask = null; } } System.out.println(String.format("Ricevuto SetTurnHolder. Setto %d come turnHolder.", newTurnHolder)); gameTable.setTurnHolder(peer.peers.get(newTurnHolder).player); // Elimino eventuali timer Elezione in attesa if (peer.firstPhaseElectionTask != null) { peer.firstPhaseElectionTask.cancel(); peer.firstPhaseElectionTask = null; } if (peer.secondPhaseElectionTask != null) { peer.secondPhaseElectionTask.cancel(); peer.secondPhaseElectionTask = null; } // L'elezione è terminata peer.electionActive = false; // Inoltre, questo significa che il turnHolder non è morto peer.rescheduleTurnHolderTimer(); } return "ok"; }
de57df02-bd4c-4e90-8f4b-2c88ce028e35
2
@Override public JSONObject main(Map<String, String> params, Session session) throws Exception { String username = params.get("username"); String passwordClear = params.get("password"); User u = User.findOne("username", username); JSONObject rtn = new JSONObject(); if(u == null) { rtn.put("rtnCode", this.getRtnCode(201)); return rtn; } if(!u.checkPassword(passwordClear)) { rtn.put("rtnCode", this.getRtnCode(202)); return rtn; } session.setActiveUserId(u.getId()); // refresh notification when logging in u.refreshNotificaion(); rtn.put("rtnCode", this.getRtnCode(200)); { rtn.put("user", u.toJson()); } return rtn; }
2c6b44be-2eab-4574-a7e6-e2c9a42df9fa
9
public static void demo_BFS() { System.out.println("------------------ Breadth First Search ------------------"); String[] search_types = { "array-locked", "lock-free" }; int max_threads = 7; int max_reps = 1; int n_graphs_to_evaluate = 1; String[] paths = { "src/data/soc-pokec-relationships.txt" }; boolean isZeroIndexed = false; int graph_sizes = 1632803; int source_node = 2; System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"); long t; double t_graph = 0.0; Graph g = null; for (int i = 0; i < n_graphs_to_evaluate; i++) { if (i < paths.length) { System.out.println("Evaluating graph: " + paths[i] + " ~~~~~~~~~~~~~~~~~~~~~~~~~~~"); t = System.nanoTime(); g = new Graph(paths[i], isZeroIndexed, graph_sizes); t_graph = (System.nanoTime() - t + 0.0) / (Math.pow(10, 9)); } System.out.println("Time to build graph = " + t_graph + " seconds"); int[] shortest_hops_seq = null; int[] shortest_hops_parallel = null; // Executing Sequential Algorithm 10 times double t_seq = 0.0; int n_reps; for (n_reps = 0; n_reps < max_reps; n_reps++) { // Sequential Algorithm Execution BreadthFirstSearch bfs_seq = new SequentialBFS(g); t = System.nanoTime(); shortest_hops_seq = bfs_seq.search(source_node); t_seq += (System.nanoTime() - t + 0.0) / (Math.pow(10, 9)); } System.out.println("Time for sequential search = " + t_seq / n_reps + " seconds"); System.out.println("Approach: Using explicit threads, not thread pool: ~~~~~~~~~~~~~~~~~~~~~~~~~~"); // Parallel Algorithm Execution - old approach (restarting thread // pool at each level) for (String type : search_types) { // Algorithm types System.out.println(" ---------------------------------------------------"); System.out.println("Data structure: " + type); for (int n_threads = 1; n_threads <= max_threads; n_threads++) {// Number // of // threads double t_par = 0.0; for (n_reps = 0; n_reps < max_reps; n_reps++) { BreadthFirstSearch bfs_parallel = null; if (type.equals("array-locked")) { bfs_parallel = new ParallelBFS_lockbased(g, n_threads); } else if (type.equals("lock-free")) { bfs_parallel = new ParallelBFS_lockfree(g, n_threads); } else { System.out.println("not an implementation!"); System.exit(-1); } long t_par_start = System.nanoTime(); shortest_hops_parallel = bfs_parallel.search(source_node); t_par += (System.nanoTime() - t_par_start + 0.0) / (Math.pow(10, 9)); } System.out.println(n_threads + " thread time = " + t_par / n_reps + " seconds"); if (!Arrays.equals(shortest_hops_seq, shortest_hops_parallel)) { System.out.println("Bug!! Not a match"); } } System.out.println(" ---------------------------------------------------"); } System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); } }
a7aae771-e17c-41ee-8277-d31e2edd2d1f
6
public CreateAndSendInvoiceResponse(Map<String, String> map, String prefix) { if( map.containsKey(prefix + "responseEnvelope" + ".timestamp") ) { String newPrefix = prefix + "responseEnvelope" + '.'; this.responseEnvelope = new ResponseEnvelope(map, newPrefix); } if( map.containsKey(prefix + "invoiceID") ) { this.invoiceID = map.get(prefix + "invoiceID"); } if( map.containsKey(prefix + "invoiceNumber") ) { this.invoiceNumber = map.get(prefix + "invoiceNumber"); } if( map.containsKey(prefix + "invoiceURL") ) { this.invoiceURL = map.get(prefix + "invoiceURL"); } for(int i=0; i<10; i++) { if( map.containsKey(prefix + "error" + '(' + i + ')'+ ".errorId") ) { String newPrefix = prefix + "error" + '(' + i + ')' + '.'; this.error.add(new ErrorData(map, newPrefix)); } } }
0ae64b03-8316-4c93-b613-316d9f78dd6d
0
public void visiteurQuitter() { this.getCtrlPrincipal().action(EnumAction.VISITEUR_QUITTER); }
3485dd6e-05a4-4c18-8cfc-c33abc7d06c1
9
public boolean isMatchGreedy(String s, String p) { int n = s.length(); int m = p.length(); int i = 0; int j = 0; int star = -1; int sp = 0; while (i < n) { //one * and multiple *, same effect while (j < m && p.charAt(j) == '*') { star = j++; //* match 0 character sp = i; } if (j == m || (p.charAt(j) != s.charAt(i) && p.charAt(j) != '?')) { if (star < 0) return false; else { j = star + 1; i = ++sp; //* match 1 character } } else { i++; j++; } } while (j < m && p.charAt(j) == '*') j++; return j == m; }
7a90537e-7c6a-4821-93e0-fc15dfe08560
0
public void setIsFaceUp(boolean faceUp) { this.isFaceUp = faceUp; }
e94989ec-1b5c-496a-a0c8-a1f93aaafd08
9
protected boolean simpleEval(Environmental scripted, String arg1, String arg2, String cmp, String cmdName) { final long val1=CMath.s_long(arg1.trim()); final long val2=CMath.s_long(arg2.trim()); final Integer SIGN=signH.get(cmp); if(SIGN==null) { logError(scripted,cmdName,"Syntax",val1+" "+cmp+" "+val2); return false; } switch(SIGN.intValue()) { case SIGN_EQUL: return (val1==val2); case SIGN_EQGT: case SIGN_GTEQ: return val1>=val2; case SIGN_EQLT: case SIGN_LTEQ: return val1<=val2; case SIGN_GRAT: return (val1>val2); case SIGN_LEST: return (val1<val2); case SIGN_NTEQ: return (val1!=val2); default: return (val1==val2); } }
dc2f945d-6b9f-480b-a00b-52b603448568
7
protected void copySelectedComponent() { if (selectedComponent instanceof ImageComponent) { try { pasteBuffer = new ImageComponent(((ImageComponent) selectedComponent).toString()); } catch (Exception e) { // ignore } } else if (selectedComponent instanceof TextBoxComponent) { pasteBuffer = new TextBoxComponent((TextBoxComponent) selectedComponent); } else if (selectedComponent instanceof LineComponent) { pasteBuffer = new LineComponent((LineComponent) selectedComponent); } else if (selectedComponent instanceof RectangleComponent) { pasteBuffer = new RectangleComponent((RectangleComponent) selectedComponent); } else if (selectedComponent instanceof EllipseComponent) { pasteBuffer = new EllipseComponent((EllipseComponent) selectedComponent); } else if (selectedComponent instanceof TriangleComponent) { pasteBuffer = new TriangleComponent((TriangleComponent) selectedComponent); } }
4a9d0b74-f69e-49a9-97bd-e4f9315ae620
7
private void play() { game.updateP1(getPlayerStats(p1) + getPlayerSkills(p1)); game.updateP2(getPlayerStats(p2) + getPlayerSkills(p2)); while (p1.isAlive() && p2.isAlive()) { if (!states.isWaiting()) { game.updateP1(getPlayerStats(p1) + getPlayerSkills(p1)); game.updateP2(getPlayerStats(p2) + getPlayerSkills(p2)); if (states.getTurn() == 1) { if (states.isSuccessful()) { game.removeSkills(); game.addNext(); states.setSuccess(false); states.setWaiting(true); p1.setMana(p1.getMana() + p1.getManaRegen()); } else { game.setLog("It is " + p1.getName() + "'s turn."); game.updateLog(); game.addSkills(p1, p2); states.setWaiting(true); } } else if (states.getTurn() == 2) { if (states.isSuccessful()) { game.removeSkills(); game.addNext(); states.setSuccess(false); states.setWaiting(true); p2.setMana(p2.getMana() + p2.getManaRegen()); } else { game.setLog("It is " + p2.getName() + "'s turn."); game.updateLog(); game.addSkills(p2, p1); states.setWaiting(true); } } } } }
9d401c09-0e90-4da0-8a16-efcc03cc2efb
3
public void run() { for (The5zigModUser user : The5zigMod.getApi().getOnlineModUsers()) { Iterator<The5zigModTimer> it = user.getTimers().iterator(); while (it.hasNext()) { The5zigModTimer timer = it.next(); if (timer.isOver()) it.remove(); } } }
a48b24a9-f1fb-41d8-a05d-0cf27ffc1442
8
public void addCacheListenerImpl(CacheListener listener) { List keys = listener.getInterestedFields(); Iterator i = keys.iterator(); while (i.hasNext()) { String key = (String) i.next(); // Peer.column names are the fields if (validFields != null && validFields.containsKey(key)) { List listeners = (List) listenersMap.get(key); if (listeners == null) { listeners = createSubsetList(key); } boolean isNew = true; Iterator j = listeners.iterator(); while (j.hasNext()) { Object listener2 = ((WeakReference) j.next()).get(); if (listener2 == null) { // do a little cleanup while checking for dupes // not thread-safe, not likely to be many nulls // but should revisit // j.remove(); } else if (listener2 == listener) { isNew = false; break; } } if (isNew) { listeners.add(new WeakReference(listener)); } } } }
39faedd4-4f47-4a04-aee8-95083900ad47
7
private void parseVariables() { int previousSize = 0; Map<String, String> unresolved = new HashMap<>(); for (Entry<String, String> entry : configuration.entrySet()) if (isSubstitution(entry.getValue())) unresolved.put(entry.getKey(), getSubstitution(entry.getValue())); while (previousSize != unresolved.size()) { previousSize = unresolved.size(); List<String> resolved = new ArrayList<>(); for (Entry<String, String> entry : unresolved.entrySet()) if (configuration.containsKey(entry.getValue()) && !unresolved.containsKey(entry.getValue())) { resolved.add(entry.getKey()); configuration.put(entry.getKey(), configuration.get(entry.getValue())); } for (String item : resolved) unresolved.remove(item); } }
9d679550-3ead-4a50-bfba-a2a65ef14531
0
public Transition copy(State from, State to) { return new FSATransition(from, to, myLabel); }
b57c238d-0ca1-4c08-9e09-fea1f5bc6bb6
4
private void processCall(final Call call, final int count) { println();println();println(); String callName = "| Starting call '" + call.getName() + "' |"; println(pad('-', callName.length())); println(callName); println(pad('-', callName.length())); HttpURLConnection connection = null; final CallReport callReport = workflowReport.getCallReports().get(count); try { connection = processRequest(callReport, call.getRequest(), count); println("------------------------------------------------------------------------------------------"); processResponse(callReport, call.getResponse(), connection, count); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); connection = null; } } }
53a9e8be-e849-4c91-abb4-f34048f4bbb6
0
public int distanceBetweenFile(Field otherField) { return otherField.file - this.file; }
fecd17be-3f60-432a-bc0b-3b04e9769695
3
public void actionPerformed(ActionEvent event) { String str; int n; while (true){ // str = JOptionPane.showInputDialog(null, "Please type the number of Undos:", "How many undo?", ""+Universe.curProfile.undo_num, JOptionPane.PLAIN_MESSAGE); str = JOptionPane.showInputDialog("Please type the number of Undos:", ""+Universe.curProfile.undo_num); try { n = Integer.parseInt(str); } catch (NumberFormatException e){ if (str != null) continue; else return; } break; } //we better make sure this option is disabled for places where Undo does not apply. //((AutomatonEnvironment) environment).getUndoKeeper().setNumUndo(n); Universe.curProfile.setNumUndo(n); Universe.curProfile.savePreferences(); }
34c2e7db-8b4e-40e8-9327-7904beb0ce0a
0
public void mouseReleased(MouseEvent e){ mouse = false; }
9c6dad2d-af6b-4e68-aef3-4852cd9eb78a
0
public String getParkAddress() { return parkAddress; }
033a8673-6f21-4d63-b44f-5085c34583ca
8
public void setCustomTablist(Player player, List<String> slots) { if (!this.playerCustomTablists.containsKey(player)) { List<String> tablist = new ArrayList<String>(); for (String string : slots) { tablist.add(string); } for (int i = 0; i < tablist.size(); i++) { String slot = tablist.get(i); slot = userValues(slot, player); slot = textValues(slot); slot = editText(slot); tablist.set(i, slot); } List<Object> packets = new ArrayList<>(); for (Player p : Bukkit.getOnlinePlayers()) { if (player.canSee(p)) { packets.add(this.packet.createTablistPacket(p.getPlayerListName(), false)); } } for (String s : tablist) { packets.add(this.packet.createTablistPacket(s, true)); } for (Player p : Bukkit.getOnlinePlayers()) { if (player.canSee(p)) { packets.add(this.packet.createTablistPacket(p.getPlayerListName(), true, getPing(p))); } } this.playerCustomTablists.put(player, tablist); this.packet.sendPackets(player, packets); } }
db15ae3c-3c99-4729-b6d9-862ac1abc6d5
6
public static int findPossibleDecoding(String s) { if(s.length()==0 || s.length() ==1) { return 1; } int count = 0; //very smart approach .. 0 at any digit will not increase a count.. it will be the part of earlier count if(s.charAt(s.length()-1) >'0') { count = findPossibleDecoding(s.substring(0,s.length()-1)); } // first condition means anything less than 20 and second condition means anything between 20 to 26 .. if(s.charAt(s.length()-2) <'2' || (s.charAt(s.length()-2) == '2' && s.charAt(s.length()-1) <'7')){ count += findPossibleDecoding(s.substring(0,s.length()-2)); } return count; }
f5823756-5130-4eef-b6bc-297a29f81ed2
8
public LivingParticipantBox getParticipantAt(StringBounder stringBounder, NotePosition position) { final int direction = getDirection(stringBounder); if (direction == 1 && position == NotePosition.RIGHT) { return p2; } if (direction == 1 && position == NotePosition.LEFT) { return p1; } if (direction == -1 && position == NotePosition.RIGHT) { return p1; } if (direction == -1 && position == NotePosition.LEFT) { return p2; } throw new IllegalArgumentException(); }
bcdccd9c-4e69-4d04-a2f2-35eac06b52e5
5
private Object[] getTokens(Object context) { if ((this.contextClass != null) && (this.contextClass.isInstance(context))) { try { int numChildren = ((Integer)this.contextClass.getMethod("getChildCount", new Class[0]).invoke(context, new Object[0])).intValue(); Object[] children = new Object[numChildren]; for (int i = 0; i < numChildren; i++) { children[i] = this.contextClass.getMethod("getChild", new Class[] { Integer.TYPE }).invoke(context, new Object[] { Integer.valueOf(i) }); } return children; } catch (InvocationTargetException localInvocationTargetException) {}catch (Exception ex) { ex.printStackTrace(); } } return new Object[0]; }
74ec3a5a-c268-4fc6-b773-0d24a97a85b2
7
@Override public boolean mover(int xIn, int yIn, int xFin, int yFin) { if ((xIn == xFin) && ((yFin == yIn +1)||(yFin == yIn-1))) return true; if (((yIn == 1) || (yIn == 6)) && ((yFin == yIn+2)||yFin == yIn-2)) return true; return false; }
ba128733-c16f-42dc-8afc-3eab98564ae2
5
private static void Fileout(ArrayList<classifiedData> Data, String FileOutLoc){ PrintWriter writer = null; int CEDDSize = 144; int FCTHSize = 192; //write to the data file try { writer = new PrintWriter(FileOutLoc, "UTF-8"); } catch (FileNotFoundException e) { System.err.println("Could not open data file"); } catch (UnsupportedEncodingException e) { System.err.println("Could not encode data to this file"); } //header for .arff file writer.println("@RELATION CEDDFCTHDATA"); writer.println(" "); //Write CEDD out int i = 0; for(i = 0; i < CEDDSize; i++){ writer.println("@ATTRIBUTE CEDDData"+ i + " NUMERIC"); } // System.out.println("CEDD @Atts added: " + i); //write FCTH out int j = 0; for(j = 0; j < FCTHSize; j++){ writer.println("@ATTRIBUTE FCTHData"+ j + " NUMERIC"); } // System.out.println("FCTH @Atts added: " + j); //TODO Expand these classifications? writer.println("@ATTRIBUTE Classification {Healthy, unHealthy}"); writer.println(" "); writer.println("@DATA"); //String to hold all of the data for each new line String tmp = null; //for each object in the data array list for(int k = 0; k < Data.size(); k++){ //fill tmp String with the data tmp = DataToStiring(Data.get(k)); //write it writer.println(tmp); } System.out.println("Finished Writing to File"); writer.close(); }
2200875a-b9c1-448d-a921-75e299771a72
3
public ExternalUser getExternalUserByEmailAndMeetingID(int meetingID, String email){ for(ExternalUser externalUser : externalUsers){ if(meetingID == externalUser.getMeetingID() && email.equals(externalUser.getEmail())) return externalUser; } return null; }
17f0e97e-48bc-4287-8601-9b80c5698413
5
public void asignarRespuestas(String respuesta, int numeroRespuesta){ switch(numeroRespuesta){ case 0: _jtf1.setText(respuesta); break; case 1: _jtf2.setText(respuesta); break; case 2: _jtf3.setText(respuesta); break; case 3: _jtf4.setText(respuesta); break; case 4: _jtf5.setText(respuesta); break; } }
7474b13b-21f4-4a99-8efd-43ceee4f87b9
1
public ResultSet getResult(String sql){ try{ // Execute SQL query result = statement.executeQuery(sql); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); } return result; }
2ac6d5a1-8441-4936-b9a5-2a817eecec5a
7
public void validate(Map<String, ValidationRule> refRules, Map<String, Atdl4jWidget<?>> targets) throws ValidationException { // get the widget from context using field name Atdl4jWidget<?> target = targets.get( field ); if ( target == null ) { // -- Handle "FIX_fieldname" of "NX" -- if ( ( field != null ) && ( field.startsWith( InputAndFilterData.FIX_DEFINED_FIELD_PREFIX ) )&& ( operator == OperatorT.NX ) ) { logger.debug( "Special handling to accept NOT EXISTS (\"NX\") check for FIX_DEFINED_FIELD_PREFIX field: " + field + " avoiding: \"No parameter defined for field\"."); return; } String tempMsg = "No parameter defined for field \"" + field + "\" in this context (ValueOperatorValidationRule) field: " + field + " operator: " + operator + " value: " + value + " parent: " + parent + " refRules: " + refRules; String tempMsg2 = tempMsg + " targets: " + targets; logger.debug( tempMsg2 ); logger.trace( tempMsg2, new Exception( "Stack trace" ) ); throw new ValidationException( null, tempMsg ); } /** * Object fieldValue = parent instanceof StateRuleT ? * target.getControlValueAsComparable() : * target.getParameterValueAsComparable(); // 2/1/2010 Scott Atwell * (handle StateRule specifying "0" vs. displayed "0.00") Object v = value * != null ? target.convertStringToComparable(value) : null; * * AbstractAtdl4jWidget had (thus returning Parameter value even when we are * comparing against Control's value for StateRuleT (divided it into two * methods): public Comparable<?> convertStringToComparable(String string) * throws JAXBException { if (parameterConverter != null) return * parameterConverter.convertValueToComparable(string); else return * controlConverter.convertValueToComparable(string); } **/ Object fieldValue; Object v; if ( parent instanceof StateRuleT ) // Uses Control "display" values { fieldValue = target.getControlValueAsComparable(); v = target.convertStringToControlComparable( value ); } else // StrategyEditT uses Parameter values { fieldValue = target.getParameterValueAsComparable(); v = target.convertParameterStringToParameterComparable( value ); } validateValues( target, fieldValue, operator, v ); }
69b73004-3f79-41e2-9e8a-0c9b829e291a
3
public LinkedList<Light> getCurrentLights(Vector2 pos) { int i = 0; for (GroupedRooms room : rooms) { for (Room r : room.getRooms()) { if (r.contains(pos.X, pos.Y)) return rooms.get(i).getLights(); } i++; } return null; }
a35ab094-f50b-4969-9813-b24d0a91702b
1
private void setState(String name) throws NullPointerException { if (possibleStates.containsKey(name)) { currentState = possibleStates.get(name); } else { throw new NullPointerException(Helpers.concat("Name ", name, " not found within states for the state manager ", getName())); } }
808b2d60-9aa0-4a56-9b10-f0221a53fe4b
6
@EventHandler public void SilverfishResistance(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getSilverfishConfig().getDouble("Silverfish.Resistance.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getSilverfishConfig().getBoolean("Silverfish.Resistance.Enabled", true) && damager instanceof Silverfish && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, plugin.getSilverfishConfig().getInt("Silverfish.Resistance.Time"), plugin.getSilverfishConfig().getInt("Silverfish.Resistance.Power"))); } }
edfc72eb-0dc5-4239-9f25-f325e3c4f77f
8
static ArrayList<Artist>[] kmeans(Artist[] artists,double[][] dist,int k){ int N=dist.length; int[] centerPoints=new int[k]; ArrayList<Integer>[] clusters=new ArrayList[k]; for(int i=0;i<k;i++){ clusters[i]=new ArrayList<Integer>(); clusters[i].add(i); } for(int j=0;j<20;j++){ // We compute the center points and empty the clusters for(int i=0;i<k;i++){ centerPoints[i]=barycenter(clusters[i],dist); clusters[i]=new ArrayList<Integer>(); } for(int i=0;i<N;i++){ double minDist=dist[i][centerPoints[0]]; double minDistCluster=0; for(int l=1;l<k;l++){ double d=dist[i][centerPoints[l]]; if(d<minDist){minDist=d;minDistCluster=l;} } clusters[(int) minDistCluster].add(i); } } ArrayList<Artist>[] clustersArtist=new ArrayList[k]; int i=0; for(ArrayList<Integer> c:clusters){ clustersArtist[i]=new ArrayList<Artist>(); for(int j:c){ clustersArtist[i].add(artists[j]); } i++; } return clustersArtist; }
9e2bad51-56ba-4cd5-95b1-306651f07787
0
public void setPrpCcResponsable(Integer prpCcResponsable) { this.prpCcResponsable = prpCcResponsable; }
58636303-eced-4c97-8946-554d8145f7cb
1
private void readFields(final DataInputStream in) throws IOException { final int numFields = in.readUnsignedShort(); fields = new Field[numFields]; for (int i = 0; i < numFields; i++) { fields[i] = new Field(in, this); } }
5713b301-87c7-425d-b6a8-270867cb0962
5
private static String getWebSite(){ HttpClient httpClient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://itunes.apple.com/en/rss/customerreviews/id=565993818/page=1/xml"); System.out.println("executing request "+httppost.getURI()); ResponseHandler<String> responseHandler = new ResponseHandler<String>(){ @Override public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if(status >= 200 && status <300){ HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity,"UTF-8") : null; }else{ throw new ClientProtocolException("Unexpected response status: " + status); } } }; String responseBody = null; try { responseBody = httpClient.execute(httppost, responseHandler); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Page details : "+responseBody); return responseBody; }
1da76c29-823d-48a6-b95d-59fe539f1ed3
4
private ArrayList<Integer> findWinner() throws Exception { PowerRanking powerRanking = new PowerRanking(); ArrayList<CardPower> cardPowers = new ArrayList<CardPower>(); for (int i = 0; i < playerList.size(); i++) { if (!playerList.get(i).hasFolded()) { ArrayList<Card> playersHoleAndSharedCards = new ArrayList<Card>(); playersHoleAndSharedCards.addAll(playerList.get(i).getHoleCards()); playersHoleAndSharedCards.addAll(state.getSharedCards()); cardPowers.add(powerRanking.calcCardPower(playersHoleAndSharedCards)); // Commit all the actions the current player has made during the hand to the model opponentLogger.showdown(i, playerList.get(i).getHoleCards(), state.getSharedCards()); } else { // if the current player has folded during the hand, he will not get any money cardPowers.add(new CardPower().add(-1)); } } ArrayList<Integer> winners = new ArrayList<Integer>(); // determine strongest hand CardPower maxPower = Collections.max(cardPowers); // compare all hands to the strongest one for (int i = 0; i < cardPowers.size(); i++) { if (cardPowers.get(i).compareTo(maxPower) == 0) { winners.add(i); } } return winners; }
5e23ae1b-0bea-4968-b7da-45b3d8316797
0
@Override public void execute(Runnable command) { //command.run(); new Thread(command).start(); }
00a0f611-434f-4e7a-b3ef-22ebe4238a84
0
public void setPath(Vertex path) { this.path = path; }
4eed5057-2df1-484a-beb9-d134311a7816
7
public synchronized void renderMap(int xScroll, int yScroll, Screen screen) { screen.setOffset(xScroll, yScroll); int x0 = xScroll >> 4; int x1 = (xScroll + screen.width + 16) >> 4; int y0 = yScroll >> 4; int y1 = (yScroll + screen.height + 16) >> 4; for (int y = y0; y < y1; y++) { for (int x = x0; x < x1; x++) { if (x < 0 || x >= width || y < 0 || y >= height) { continue; } getTile(tiles[x + y * width][0]).render(x, y, screen); if (tiles[x + y * width][1] > 0) { screen.renderCracks(x << 4, y << 4, tiles[x + y * width][1]); } } } }
ace59681-1b7f-46f1-a4cf-87fbb27aa3d5
3
public void dumpRegion(String line) { String parens = "{\010{}\010}<\010<>\010>[\010[]\010]`\010`'\010'" .substring(options * 6, options * 6 + 6); pw.print(parens.substring(0, 3)); Enumeration enum_ = childBPs.elements(); int cur = startPos; BreakPoint child = (BreakPoint) enum_.nextElement(); if (child.startPos >= 0) { pw.print(line.substring(cur, child.startPos)); child.dumpRegion(line); cur = child.endPos; } while (enum_.hasMoreElements()) { child = (BreakPoint) enum_.nextElement(); pw.print(line.substring(cur, child.breakPos)); pw.print("!\010!" + breakPenalty); cur = child.breakPos; if (child.startPos >= 0) { pw.print(line.substring(child.breakPos, child.startPos)); child.dumpRegion(line); cur = child.endPos; } } pw.print(line.substring(cur, endPos)); pw.print(parens.substring(3)); }
13252b00-b231-46ad-ab93-522a9fce8ff0
8
static void solve( ){ // print(); for(int i = 0 ; i < clave.length; i++ ){ if(clave[i]==hint[i]){ strong++; usados[i]=true; isMatched[i]=true; } } for(int i = 0 ; i < clave.length; i++ ){ boolean found = false; if( !isMatched[i] ) for (int j = 0; j < hint.length && !found; j++) { if( clave[i]==hint[j] && !usados[j]){ weak++; usados[j]=true; found=true; } } } }
52b942c2-9d41-4807-83e5-49a1aa20adc0
7
private void setRootID(PhraseStructure phraseStructure) throws MaltChainedException { useVROOT = false; PhraseStructureNode root = phraseStructure.getPhraseStructureRoot(); for (ColumnDescription column : dataFormatInstance.getPhraseStructureNodeLabelColumnDescriptionSet()) { if (root.hasLabel(column.getSymbolTable()) && root.getLabelSymbol(column.getSymbolTable()).equals(VROOT_SYMBOL)) { useVROOT = true; break; } } if (useVROOT) { rootID.setLength(0); rootID.append(sentenceID); rootID.append('_'); rootID.append(VROOT_SYMBOL); } else if (phraseStructure.nTokenNode() == 1 && phraseStructure.nNonTerminals() == 0 && !root.isLabeled()) { rootID.setLength(0); rootID.append(sentenceID); rootID.append("_1"); } else { rootID.setLength(0); rootID.append(sentenceID); rootID.append('_'); // if (rootHandling.equals(RootHandling.NORMAL)) { rootID.append(Integer.toString(START_ID_OF_NONTERMINALS+phraseStructure.nNonTerminals())); // } else if (rootHandling.equals(RootHandling.TALBANKEN)) { // rootID.append(Integer.toString(START_ID_OF_NONTERMINALS+1)); // } } }
e2b2d59e-37e0-4961-bb10-d13649cb7885
4
public static ArrayList<Object> selectSortArrayList(double[] aa){ int index = 0; int lastIndex = -1; int n = aa.length; double holdb = 0.0D; int holdi = 0; double[] bb = new double[n]; int[] indices = new int[n]; for(int i=0; i<n; i++){ bb[i]=aa[i]; indices[i]=i; } while(lastIndex != n-1){ index = lastIndex+1; for(int i=lastIndex+2; i<n; i++){ if(bb[i]<bb[index]){ index=i; } } lastIndex++; holdb=bb[index]; bb[index]=bb[lastIndex]; bb[lastIndex]=holdb; holdi=indices[index]; indices[index]=indices[lastIndex]; indices[lastIndex]=holdi; } ArrayList<Object> arrayl = new ArrayList<Object>(); arrayl.add(aa); arrayl.add(bb); arrayl.add(indices); return arrayl; }
f7e14ee1-50bd-4341-b215-1a68f2acf9da
5
private boolean branch_format() { int rs, rt; try { rs = register_file.get_register(inst.get_rs()); rt = register_file.get_register(inst.get_rt()); register_file.validate_index(inst.get_rd()); } catch (RegisterOutOfBoundsException e) { e.printStackTrace(); return false; } switch (inst.get_type()){ case beq : if(rs == rt) simulator.set_alu_zero(); else simulator.reset_alu_zero(); break; case bne: if(rs != rt) simulator.set_alu_zero(); else simulator.reset_alu_zero(); break; } return true; }
bf1522c7-1b39-4abf-a287-bbfb023a8663
1
public void drawMaze(Graphics g) { g.setColor(Color.white); for (Edge edge : this.maze.mst) { Point p = this.drawMazeHelper(edge.to, edge.from); g.fillRect(p.x, p.y, this.cellWidth - 1, this.cellWidth - 1); } }
993dc5ac-0bf3-416a-b22a-cf1333832813
9
private static final void handleDataDoubleEscapeTag(Tokeniser t, CharacterReader r, TokeniserState primary, TokeniserState fallback) { if (r.matchesLetter()) { String name = r.consumeLetterSequence(); t.dataBuffer.append(name.toLowerCase()); t.emit(name); return; } char c = r.consume(); switch (c) { case '\t': case '\n': case '\r': case '\f': case ' ': case '/': case '>': if (t.dataBuffer.toString().equals("script")) t.transition(primary); else t.transition(fallback); t.emit(c); break; default: r.unconsume(); t.transition(fallback); } }
e09ac7a9-8db9-49c9-9c13-811ace575d4f
4
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; School other = (School) obj; if (id != other.id) return false; return true; }
5b1fecdd-6914-41f3-bbeb-875daba01907
1
private BigDecimal getOperand(CalculatorReader expressionReader) { DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(); decimalFormatSymbols.setDecimalSeparator('.'); NumberFormat NUMBER_FORMAT = new DecimalFormat("0,0", decimalFormatSymbols); ParsePosition position = new ParsePosition(0); Number number = NUMBER_FORMAT.parse(expressionReader.getCurrentExpression(), position); if (number != null) { BigDecimal result = new BigDecimal(number.doubleValue()); expressionReader.incPosition(position.getIndex()); //System.out.println("--getOperand = " + result); return result; } return null; }
040bc1d0-e56e-4326-8433-cf3f084887aa
2
private void deleteFile(String path) { File file = new File(path); if(file.exists()) { String folder = file.getParent(); if(folder.equals("temp")) { file.delete(); } } }
c7ccd35c-567e-47f0-a98c-a6750168ba09
6
private int getArrayIndexOfFirstBall(int frameNumber) { int currentFrame = 1; int currentRollCount = rollCount; if (frameNumber > getCurrentFrame()) { return ++currentRollCount; } for (int i = 0; i < rollCount; i++) { if (currentFrame == frameNumber) { return i; } int pinsKnockedDown = pinsKnockedDownArray[i]; if (pinsKnockedDown == 10) { currentFrame++; } else if (pinsKnockedDown > 0) { int j = i + 1; if (j < rollCount) { currentFrame++; i++; } } } return -1; }
e0071d9f-2365-484e-a87d-ab2085bb29ab
9
private void analyseDataFirstPass(String assemblyLine) throws AssemblerException { boolean legitIntDataLine = Pattern.matches( "[A-Za-z0-9]+\\s+[0-9]+MAU\\s+[^\\s]+", assemblyLine); boolean legitAsciiDataLine = Pattern.matches( "[A-Za-z0-9]+\\s+.ascii\\s+\".+\"", assemblyLine); boolean legitUninitializedDataLine = Pattern.matches( "[A-Za-z0-9]+\\s+[0-9]+MAU", assemblyLine); if (!legitIntDataLine && !legitAsciiDataLine && !legitUninitializedDataLine) throw new AssemblerException(".data line incorrect syntax."); String[] splitDataLine = assemblyLine.split("\\s+"); String label = splitDataLine[0]; int noOfMinAdrUnits = 0; if (legitAsciiDataLine) { String[] splitByQuotation = assemblyLine.split("\"", 2); String asciiData = splitByQuotation[1].substring(0, splitByQuotation[1].length() - 1); int noOfBits = 0; for (int i = 0; i < asciiData.length(); i++) noOfBits += 8; int minAdrUnit = data.getMinAdrUnit(); noOfMinAdrUnits = noOfBits / minAdrUnit; } else if (legitIntDataLine || legitUninitializedDataLine) { String[] splitDataTerm = assemblyLine.split("\\s+"); String minUnitTerm = splitDataTerm[1]; String[] splitMinUnitTerm = minUnitTerm.split("MAU"); String noOfMinAdrUnitsStr = splitMinUnitTerm[0]; noOfMinAdrUnits = Integer.parseInt(noOfMinAdrUnitsStr); } if (symbolTable.get(label) == null && dataTable.get(label) == null) dataTable.put(label, locationCounter); else throw new AssemblerException("\"" + label + "\" already exists in symbol table."); insNumber++; insAdrTable.put(insNumber, locationCounter); locationCounter += noOfMinAdrUnits; }