method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
c38701c0-232b-4d90-9b1d-b40f5919fc4d
6
@Override public void connect() throws NotConnectedException, IOException, AuthenticationNotSupportedException, FtpIOException, FtpWorkflowException { setConnectionStatusLock(FTPConnection.CSL_INDIRECT_CALL); socketProvider = new SocketProvider(); // Only for logging String hostAndPort = getAddress().getHostName() + ":" + getAddress().getPort(); try { socketProvider.socket().setSoTimeout(getTimeout()); socketProvider.connect(getAddress(), getProxy(), getDownloadBandwidth(), getUploadBandwidth()); log.debug("connected to:" + hostAndPort); socketProvider.socket().setKeepAlive(true); } catch (IOException ioe) { String error = "Error connection to:" + hostAndPort; log.error(error, ioe); throw new NotConnectedException(error); } Reply connectReply = ReplyWorker.readReply(this.socketProvider); if (connectReply != null) this.fireReplyMessageArrived(new FTPEvent(this, this.getConnectionStatus(), connectReply)); connectReply.dumpReply(); Reply reply = sendCommand(new Command(Command.USER, getUser())); reply.dumpReply(); reply.validate(); if (getPassword() != null && getPassword().length() > 0) { reply = sendCommand(new Command(Command.PASS, getPassword())); reply.dumpReply(); reply.validate(); } if (getAccount() != null && getAccount().length() > 0) { reply = sendCommand(new Command(Command.ACCT, getAccount())); reply.dumpReply(); reply.validate(); } checkFeatures(); this.setConnectionStatus(FTPConnection.CONNECTED); this.setConnectionStatus(FTPConnection.IDLE); checkSystem(); setConnectionStatusLock(FTPConnection.CSL_DIRECT_CALL); }
457e08bd-3a95-4e57-9b2e-4dc47b51e5bc
3
public void execute() { String commandWithArgs; System.out.println("Enter some command: "); while (true) { try { commandWithArgs = br.readLine(); String result = executeCommand(commandWithArgs); System.out.println(result); if ("exit".equals(result)) { break; } } catch (IOException e) { e.printStackTrace(); } } }
420f8ae2-9cc9-49d4-8174-a5dfdce7d3e7
4
private Point generateDoor(Room room, Direction direction) { switch (direction) { case NORTH: return new Point(generator.nextInt(room.getWidth() - 3) + 1, 0); case SOUTH: return new Point(generator.nextInt(room.getWidth() - 3) + 1, room.getHeight() - 1); case EAST: return new Point(0, generator.nextInt(room.getHeight() - 3) + 1); case WEST: return new Point(room.getWidth() - 1, generator.nextInt(room.getHeight() - 3) + 1); default: return null; } }
0c343856-74ca-44be-b0c8-b56800e5f732
5
public void setHit(){ if(hit)return; hit = true; animation.setDelay(70); if(dx > 0 || dx < 0){ dx = 0; } if(dy > 0 || dy < 0){ dy = 0; } }
e41f05e6-887f-409d-9dc8-5c7a6e8f8dbf
1
@SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); txt_num_estado = new javax.swing.JTextField(); txt_num_simbolo = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); table_trans = new javax.swing.JTable(); jLabel1 = new javax.swing.JLabel(); cbxeorigen = new javax.swing.JComboBox(); jLabel4 = new javax.swing.JLabel(); cbxsimbolo = new javax.swing.JComboBox(); jLabel5 = new javax.swing.JLabel(); cbxedestino = new javax.swing.JComboBox(); jButton3 = new javax.swing.JButton(); rbbefinal = new javax.swing.JRadioButton(); cbxFile = new javax.swing.JComboBox(); jButton4 = new javax.swing.JButton(); setClosable(true); setIconifiable(true); jLabel2.setText("Numero de estados: "); jLabel3.setText("Numero de simbolos: "); jButton1.setText("Generar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("Guardar xml"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jScrollPane2.setAutoscrolls(true); table_trans.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {"q0", "1000", "1001", "1002"}, {"q1", "1000", "1001", "1002"}, {"q2", "1000", "1001", "1002"}, {"q3", "1000", "1001", "1002"} }, new String [] { "Estados\\Simbolo", "S0", "S1", "Otros" } ) { boolean[] canEdit = new boolean [] { false, true, true, true }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); table_trans.setToolTipText(""); table_trans.setUpdateSelectionOnSort(false); jScrollPane2.setViewportView(table_trans); if (table_trans.getColumnModel().getColumnCount() > 0) { table_trans.getColumnModel().getColumn(1).setResizable(false); table_trans.getColumnModel().getColumn(2).setResizable(false); table_trans.getColumnModel().getColumn(3).setResizable(false); } jLabel1.setText("Estado Origen: "); cbxeorigen.setEditable(true); cbxeorigen.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); cbxeorigen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cbxeorigenActionPerformed(evt); } }); jLabel4.setText("Simbolo:"); cbxsimbolo.setEditable(true); cbxsimbolo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jLabel5.setText("Estado destino:"); cbxedestino.setEditable(true); cbxedestino.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jButton3.setText("OK"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); rbbefinal.setText("Estado Final"); cbxFile.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jButton4.setText("Cargar"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); 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() .addContainerGap() .addComponent(jScrollPane2)) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cbxeorigen, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cbxsimbolo, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cbxedestino, 0, 1, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(rbbefinal) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton4)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txt_num_estado, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txt_num_simbolo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButton1) .addGap(18, 18, 18) .addComponent(jButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 183, Short.MAX_VALUE) .addComponent(cbxFile, javax.swing.GroupLayout.PREFERRED_SIZE, 242, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addContainerGap()) ); layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {txt_num_estado, txt_num_simbolo}); layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel2, jLabel3}); layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cbxedestino, cbxeorigen, cbxsimbolo}); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(txt_num_estado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3) .addComponent(txt_num_simbolo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1) .addComponent(jButton2) .addComponent(cbxFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(6, 6, 6) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(cbxedestino, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton3) .addComponent(rbbefinal) .addComponent(jButton4)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(cbxsimbolo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(cbxeorigen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 542, Short.MAX_VALUE) .addContainerGap()) ); layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {cbxedestino, cbxeorigen, cbxsimbolo}); pack(); }// </editor-fold>//GEN-END:initComponents
b8b26aa5-261f-46e9-8289-42bd9964f20c
2
public void visit( DataVisitor visitor ){ visitor.visit( this ); for( Data<?> data : this ){ data.visit( visitor ); } }
d670dfe3-0e5b-4d47-adf1-be36ad45b26e
2
public void paddleBounce(float center) { velX *= -1; velY += (getCenterY() - center) * DAMPING; if (velY > MAX_SPEEDY) velY = MAX_SPEEDY; else if (velY < -MAX_SPEEDY) velY = -MAX_SPEEDY; }
b85d2cbd-acf0-4220-8b33-25d362d3d3f4
8
public long GetLargestPrimeFactor(long maxValue) { if (knownPrimes.size() > 0) { if (maxValue < (knownPrimes.get(knownPrimes.size() - 1))) { for (int knowPrimeIndex = knownPrimes.size() - 1; knowPrimeIndex > 0; knowPrimeIndex--) { if ((knownPrimes.get(knowPrimeIndex) <= maxValue) && ((maxValue % (knownPrimes.get(knowPrimeIndex))) == 0)) return knownPrimes.get(knowPrimeIndex); } } } for (int i = 2; i < maxValue; i++) { if (IsPrime(i)) { if (maxValue % i == 0) { return GetLargestPrimeFactor(maxValue / i); } } } return maxValue; }
d511f6d5-1cb0-4d7c-8b71-2070020405ab
5
private static void addImgToXmlData(String data) { try { File fXmlFile = new File(path); DocumentBuilderFactory dbFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); Document dataDoc = dBuilder.parse(new InputSource( new ByteArrayInputStream(data.getBytes("utf-8")))); doc.getDocumentElement().normalize(); dataDoc.getDocumentElement().normalize(); NodeList nListFromFile = doc.getElementsByTagName("gallery"); Element eListFromData = (Element) dataDoc.getElementsByTagName( "gallery").item(0); String galleryNameData = eListFromData.getAttribute("name"); NodeList nListDataDoc = dataDoc.getElementsByTagName("image"); int len = nListFromFile.getLength(); for (int i = 0; i < len; i++) { Node eNode = nListFromFile.item(i); Element eElement = (Element) eNode; String name = eElement.getAttribute("name"); if (name.equals(galleryNameData)) { NodeList subNode = eElement.getElementsByTagName("image"); int leng = subNode.getLength(); for (int j = 0; j < leng; j++) { Node image = subNode.item(0); Element imageElement = (Element) image; eElement.removeChild(imageElement); } leng = nListDataDoc.getLength(); for (int p = 0; p < leng; p++) { Node imageDataDoc = nListDataDoc.item(p); Element imageDataDocElement = (Element) imageDataDoc; Node eDocImportedNode = doc.importNode( imageDataDocElement, true); eElement.appendChild(eDocImportedNode); } } } doc.getDocumentElement().normalize(); TransformerFactory transformerFactory = TransformerFactory .newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(path)); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(source, result); // System.out.println("XML file updated successfully"); } catch (Exception ex) { ex.printStackTrace(); } }
d3dbb109-e85b-4e65-9fb2-e4cd486d36e1
7
private Receiver(ClientDavParameters parameters, List subscriptionInfos) throws Exception { connection = new ClientDavConnection(parameters); connection.connect(); connection.login(); DataModel dataModel = connection.getDataModel(); Iterator infoIterator = subscriptionInfos.iterator(); while(infoIterator.hasNext()) { List<SystemObject> objects = new LinkedList<SystemObject>(); SubscriptionInfo subscriptionInfo = (SubscriptionInfo)infoIterator.next(); String objectSpec = subscriptionInfo.getObjectSpec(); objects = ConfigurationHelper.getObjects(objectSpec, dataModel); String[] dataSpecs = subscriptionInfo.getSplittedData(":", 3); AttributeGroup attributeGroup = dataModel.getAttributeGroup(dataSpecs[0]); if(attributeGroup == null) { debug.error("Attributgruppe \"" + dataSpecs[0] + "\" existiert nicht."); System.exit(1); } Aspect aspect = dataModel.getAspect(dataSpecs[1]); if(aspect == null) { debug.error("Aspekt \"" + dataSpecs[1] + "\" existiert nicht."); System.exit(1); } DataDescription dataDescription; String simulationVariantText = ""; if(dataSpecs.length == 3) { short simulationVariant = Short.parseShort(dataSpecs[2]); simulationVariantText = ":" + simulationVariant; dataDescription = new DataDescription( attributeGroup, aspect, simulationVariant ); } else { dataDescription = new DataDescription(attributeGroup, aspect); } debug.config( subscriptionInfo.getOptions() + "-Anmeldung als " + subscriptionInfo.getReceiverRole() + " für " + attributeGroup.getNameOrPidOrId() + ":" + aspect.getNameOrPidOrId() + simulationVariantText ); debug.config(" Objekte: " + objects); /* XXX * Work around: Ist die Simulationsvariante -1 (also nicht explizit * über die Aufrufparameter gesetzt), so wird sie durch die * DaV-Applikationsfunktionen automatisch auf 0 gesetzt. Dieses * Verhalten ist unerwünscht und wird hier bis auf weiteres * umgangen. */ short rescueSimulationVariant = dataDescription.getSimulationVariant(); connection.subscribeReceiver( pmc.getProtocoller(), objects, dataDescription, subscriptionInfo.getOptions(), subscriptionInfo.getReceiverRole() ); /* XXX * Work around (s. o.) */ dataDescription.setSimulationVariant(rescueSimulationVariant); } BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String inputLine = ""; while(true) { inputLine = in.readLine(); if(inputLine == null) { // nicht mehr weiter lesen, aber nicht das Programm terminieren break; } else if(inputLine.startsWith("q")) { //Programm kontrolliert terminieren System.exit(0); } } }
6b74e60f-7f1c-4d2d-9810-048967f800a1
3
public LifeFrame nextFrame() { LifeFrame next = new LifeFrame(new String[frame.height()][frame.width()]); for (int i = 0; i < frame.height(); i++) { for (int j = 0; j < frame.width(); j++) { LifePosition lifePosition = new LifePosition(i, j); if (shouldALive(lifePosition).equals(LifeStatus.alive)) next.changeStatusToAlive(lifePosition); else next.changeStatusToDead(lifePosition); } } refreshFrame(next); return frame; }
72e52c32-3b71-4780-ba57-b3ad89e9a0a0
6
private boolean isItemStackEqual(ItemStack par1ItemStack) { return this.stackSize != par1ItemStack.stackSize ? false : (this.itemID != par1ItemStack.itemID ? false : (this.itemDamage != par1ItemStack.itemDamage ? false : (this.stackTagCompound == null && par1ItemStack.stackTagCompound != null ? false : this.stackTagCompound == null || this.stackTagCompound.equals(par1ItemStack.stackTagCompound)))); }
a837b61a-6c78-4654-8eef-9d1e7f9851d1
6
public static boolean presaPossibile(ICard card, List<ICard> tableCards, List<ICard> presa) { List<List<ICard>> possibiliPrese = getPrese(card, tableCards); for(List<ICard> subp : possibiliPrese){ boolean equalsPresa = true; if(subp.size() != presa.size()) equalsPresa = false; if(equalsPresa) for(ICard c : subp){ if(!presa.contains(c)) equalsPresa = false; } if(equalsPresa) return true; //la presa � tra quelle possibili } return false; }
992092fe-e8e5-4ff4-a579-e731767c99b5
1
private Path writeToPatchContent() throws Exception { if (getPatchMap().containsKey(etag)) { return Files.write(getPath(), getPatchMap().get(etag)); } return Files.write(getPath(), "default content".getBytes()); }
d63a267c-80ce-4ba0-adf8-28a2977fd3b6
9
public double[] prob(int[] ps, int pos) { double[] p = new double[4]; double[] scores = new double[4]; for (int i = 0; i < windowsize; i++) { if (i != whalf || true) { scores[0] += matrix[0][ps[pos]][ps[pos + i - whalf]][i]; scores[1] += matrix[1][ps[pos]][ps[pos + i - whalf]][i]; scores[2] += matrix[2][ps[pos]][ps[pos + i - whalf]][i]; } } p[0] = (Math.exp(scores[0]) / (1.0 + Math.exp(scores[0]))); p[1] = (Math.exp(scores[1]) / (1.0 + Math.exp(scores[1]))); p[2] = (Math.exp(scores[2]) / (1.0 + Math.exp(scores[2]))); if (p[0] > p[1] && p[0] > p[2]) p[3] = 0; else if (p[1] > p[0] && p[1] > p[2]) p[3] = 1; else if (p[2] > p[0] && p[2] > p[1]) p[3] = 2; else p[3] = 3; return p; }
3cf0cca7-0e00-4463-8e3d-743e034465bc
3
public static ExpressionParser createExpressionParser(ExpressionType type) { switch (type) { case SQL: return SQL_PARSER; case CACHE_KEY: return KEY_PARSER; case MONGO_SHELL: return SHELL_PARSER; default: return null; } }
c43103f9-4a49-458f-b9a3-c28226a66cf5
5
public void hit() { hp--; switch(hp) { case 0: this.color = Color.black; break; case 1: this.color = Color.yellow; break; case 2: this.color = Color.orange; break; case 3: this.color = Color.blue; break; case 4: this.color = Color.red; break; } }
3824bb2e-8010-410d-89e6-b40c451bcc38
1
protected void passBaton(ServletRequest req, ServletResponse resp) { if (nextFilter != null) { nextFilter.doFilter(req, resp); } }
fd25dda7-9f50-4e84-87c0-6c3445a9375b
9
int parse(String s) { if (parseOne(s)) return 1; if (parseTwo(s)) return 2; if (parseThree(s)) return 3; if (parseFour(s)) return 4; if (parseFive(s)) return 5; if (parseSix(s)) return 6; if (parseSeven(s)) return 7; if (parseEight(s)) return 8; if (parseNine(s)) return 9; return 0; }
50f8e2e6-0089-40d4-a70f-9026d497fcce
3
private int updateBeteckning() { int res = 0; if (!Validate.tfEmpty(tfBeteckning) && Validate.notOverSize(tfBeteckning)) { try { String query = "update spelprojekt set beteckning='" + tfBeteckning.getText() + "' where sid=" + selectedSpelprojekt; DB.update(query); res = 1; } catch (InfException e) { e.getMessage(); } } else { lblError.setVisible(true); lblError.setText("Beteckningen får inte vara tom eller vara över 255 tecken."); } return res; }
8b9eb943-ccec-487d-9f7c-0221fa4b25e6
5
public Norm containsNormBelief(Belief blf, NormType nt) { for ( Norm norm: getAllRestrictNorms().values() ) { Belief b = norm.getNormResource().getBelief(); if ( b!=null && b.getName().equalsIgnoreCase(blf.getName()) && norm.getNormType() == nt && norm.isActive() ) { return norm; } } return null; }
27562828-6f75-45ae-a5b1-adca90551319
1
public void enderman(Boolean mode){ if (mode != null){ enderman = mode; }else{ enderman = true; } }
531d6c2d-6e55-4996-8b52-6dcd4db4c0cd
8
public static void FESVoDistanceFrequency (int src) { // sorted sets for x and y values: TreeSet<Integer> setX = new TreeSet<Integer>(); TreeSet<Integer> setY = new TreeSet<Integer>(); for (GeoTag tag : DATA.keySet()){ if (tag.sourceID == src){ setX.add(tag.x); setY.add(tag.y); }//if }//for // Mapping distance to its frequency: Map<Integer, Integer> freqX = new HashMap<Integer, Integer>(); Map<Integer, Integer> freqY = new HashMap<Integer, Integer>(); // calculate distance frequency for X: Object [] x = setX.toArray(); for (int i=0; i < x.length-1; i+=2){ // calculate distance: int dis = ((Integer)x[i+1]).intValue() - ((Integer)x[i]).intValue(); // update frequency: Integer freq = freqX.get(dis); freqX.put(dis, (freq == null? 1 : freq+1)); } // calculate distance frequency for Y: Object [] y = setY.toArray(); for (int i=0; i < y.length-1; i+=2){ // calculate distance: int dis = ((Integer)y[i+1]).intValue() - ((Integer)y[i]).intValue(); // update frequency: Integer freq = freqY.get(dis); freqY.put(dis, (freq == null? 1 : freq+1)); } // print results to file: FESVoSystem.out.println("X Distance Frequency:"); FESVoSystem.out.println("---------------------"); for (Integer disX : freqX.keySet()){ FESVoSystem.out.println(disX + ": " + freqX.get(disX)); }//for FESVoSystem.out.println("\n"); FESVoSystem.out.println("Y Distance Frequency:"); FESVoSystem.out.println("---------------------"); for (Integer disY : freqY.keySet()){ FESVoSystem.out.println(disY + ": " + freqY.get(disY)); }//for }
b12c5ca5-9dda-4a31-b969-240b401200a6
2
public void paint(Graphics graphics) { Graphics2D g = (Graphics2D) graphics; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); for (DrawableItem item : items) { if (item.getType() == 0) { dic.paint(item, g); } else { dic.paintPath(item, g); } } }
52078cf7-147b-4a78-9cbc-4bb140e4e69e
7
public ShipComponent(ArrayList<Double> stat, String shipType, int team) { try{ music = AudioSystem.getAudioInputStream(new File("CylonProjectile.wav")); clip = AudioSystem.getClip(); clip.open(music); }catch (UnsupportedAudioFileException|IOException|LineUnavailableException e) { System.out.println("Error reading sound file"); } rec = new Rectangle2D.Double(-50,-50,100,100); //centered around origin of graphics xPos = stat.get(0); //sets all the starting stuff based on input. yPos = stat.get(1); theta = stat.get(7); xVel = stat.get(2); yVel = stat.get(3); xAcc = stat.get(4); yAcc = stat.get(5); speed = stat.get(6); turnSpeed = stat.get(8); teamNumber = team; maxSpeed = 0; maxTheta = 0; lastPressProcessed = 0; toTurn = 0; close = true; scrollX = 0; scrollY = 0; targetX = xPos; targetY = yPos; firingTargetX = 0; firingTargetY = 0; numWeapons = 0; weaponOffsetX = new int[0]; weaponOffsetY = new int[0]; weaponDirectionality = new int[0]; weaponDamage = new double[0]; weaponFireRate = new int[0]; weaponFile = new int[0]; lastFired = new long[0]; //fireRate = 200; lastFire = System.currentTimeMillis(); isFiring = false; shippic = new ImageIcon("failure.png"); shipimg = shippic.getImage(); polyFileName = shipType; numPoints = 0; xPa = new int[0]; yPa = new int[0]; hp=0; destroyed = false; //now with individual weapon directionality! try { BufferedReader inputStream = new BufferedReader(new FileReader(polyFileName + ".poly")); inputStream.readLine(); String imgFile = inputStream.readLine(); if(team == 1){ imgFile = imgFile.substring(0, imgFile.indexOf(".")) + "Red" + imgFile.substring(imgFile.indexOf("."), imgFile.length()); //System.out.println(imgFile); } else if (team == 2) { imgFile = imgFile.substring(0, imgFile.indexOf(".")) + "Blue" + imgFile.substring(imgFile.indexOf("."), imgFile.length()); } shippic = new ImageIcon("ships/" + imgFile); shipimg = shippic.getImage(); String defaultvars = inputStream.readLine(); maxSpeed = Double.parseDouble(defaultvars.substring(0, defaultvars.indexOf(","))); maxTheta = Double.parseDouble(defaultvars.substring(defaultvars.indexOf(",")+1, nthIndexOf(defaultvars,',',2))); hp = Integer.parseInt(defaultvars.substring(nthIndexOf(defaultvars,',',2)+1, nthIndexOf(defaultvars,',',3))); maxHP = hp; //fireRate = Integer.parseInt(defaultvars.substring(nthIndexOf(defaultvars,',',3)+1,defaultvars.length())); numWeapons = Integer.parseInt(inputStream.readLine()); weaponOffsetX = new int[numWeapons]; weaponOffsetY = new int[numWeapons]; weaponDirectionality = new int[numWeapons]; weaponDamage = new double[numWeapons]; weaponFireRate = new int[numWeapons]; lastFired = new long[numWeapons]; weaponFile = new int[numWeapons]; for(long l: lastFired) { l = System.currentTimeMillis(); } String test = ""; for(int i = 0; i<numWeapons; i++) { test = inputStream.readLine(); weaponOffsetX[i] = (int) Double.parseDouble(test.substring(0, test.indexOf(","))); weaponOffsetY[i] = (int) Double.parseDouble(test.substring(test.indexOf(",")+1,nthIndexOf(test,',',2))); weaponDirectionality[i] = (int) Double.parseDouble(test.substring(nthIndexOf(test,',',2)+1, nthIndexOf(test,',',3))); weaponDamage[i] = Double.parseDouble(test.substring(nthIndexOf(test,',',3)+1, nthIndexOf(test,',',4))); weaponFireRate[i] = (int) Double.parseDouble(test.substring(nthIndexOf(test,',',4)+1, nthIndexOf(test,',',5))); weaponFile[i] = (int) Integer.parseInt(test.substring(nthIndexOf(test,',',5)+1, test.length())); } numPoints = Integer.parseInt(inputStream.readLine()); xPa = new int[numPoints]; yPa = new int[numPoints]; test = ""; for(int i = 0; i<numPoints; i++) { test = inputStream.readLine(); xPa[i] = (int) Double.parseDouble(test.substring(0, test.indexOf(","))); yPa[i] = (int) Double.parseDouble(test.substring(test.indexOf(",")+1, test.length())); } inputStream.close(); } catch(IOException|NumberFormatException i) { System.out.println("Error parsing polygon file " + polyFileName); } }
62c9575c-0171-4d51-9994-73ec0d6a1df9
0
@Override public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { log.debug("method ends:" + method); }
601bd576-10e6-48ce-96db-442c72a10b73
2
private void calculateChanges() { // Collection pcs = prices.values(); TreeSet<Float> dates = new TreeSet<Float>(PRICES.keySet()); // float[][] asArray = new float[dates.size()][dbSet.length]; // allocate variables float[] startPrices = null; float[] endPrices; Iterator<Float> datadays = dates.iterator(); float startDate = 0; // get initial prices array and timekey if (datadays.hasNext()) { startDate = datadays.next(); startPrices = PRICES.get(startDate); } // cycle through the rest calculating changes while (datadays.hasNext()) { float endDate = datadays.next(); endPrices = PRICES.get(endDate); // calculates price change array and adds it to UNFORESEEN // System.out.println("start: " + Arrays.toString(startPrices)); // System.out.println("end : " + Arrays.toString(endPrices)); calculateAllChangesForInterval(startDate, startPrices, endPrices); startDate = endDate; startPrices = endPrices; } }
ba16130b-8d2e-4a03-a4ef-93b7e611cadc
0
private Animation createLimpioAnim(Image img1, Image img2, Image img3, Image img4, Image img5, Image img6,Image img7, Image img8, Image img9, Image img10, Image img11, Image img12, Image img13, Image img14,Image img15, Image img16, Image img17) { Animation anim = new Animation(); anim.addFrame(img1, 100); anim.addFrame(img2, 100); anim.addFrame(img3, 100); anim.addFrame(img4, 100); anim.addFrame(img5, 100); anim.addFrame(img6, 100); anim.addFrame(img7, 100); anim.addFrame(img8, 100); anim.addFrame(img9, 100); anim.addFrame(img10, 100); anim.addFrame(img11, 100); anim.addFrame(img12, 100); anim.addFrame(img13, 100); anim.addFrame(img14, 100); anim.addFrame(img15, 100); anim.addFrame(img16, 100); anim.addFrame(img17, 600); return anim; }
61c84e19-c569-46fd-89af-5a3e98be0fd3
0
public Grammar getLambdaProductionlessGrammar(Grammar grammar, Set lambdaSet) { Grammar g = new ContextFreeGrammar(); g.addProductions(getProductionsToAddToGrammar(grammar, lambdaSet)); return g; }
f7b06f12-7b4a-41b6-a02e-16e9527c069a
8
public static void printMaxInWindow(int[] A, int windowSize) { Deque<Integer> queue = new LinkedList<Integer>(); int i = 0; while (i < windowSize) { if (queue.isEmpty() || A[queue.getLast()] > A[i]) queue.add(i++); else queue.removeLast(); } while (i < A.length) { System.out.print(A[queue.peek()] + " "); while (!queue.isEmpty() && A[queue.getLast()] < A[i]) queue.removeLast(); if (!queue.isEmpty() && i - queue.peek() >= windowSize) queue.removeFirst(); queue.add(i++); } System.out.println(A[queue.peek()]); }
190b6c8b-7c1d-42aa-8136-496ebae2561c
1
public Value naryOperation(final AbstractInsnNode insn, final List values) throws AnalyzerException { if (insn.getOpcode() == MULTIANEWARRAY) { return newValue(Type.getType(((MultiANewArrayInsnNode) insn).desc)); } else { return newValue(Type.getReturnType(((MethodInsnNode) insn).desc)); } }
8e4cd09e-0fe1-4939-83da-db9ac0884fc9
9
private void CommandNewLibrary(Class<?> classArgs) { initialized(SET, false); String headerMessage = "Initializing "; if (soundLibrary != null) { currentLibrary(SET, null); // we are switching libraries headerMessage = "Switching to "; soundLibrary.cleanup(); soundLibrary = null; } message(headerMessage + SoundSystemConfig.getLibraryTitle(classArgs), 0); message("(" + SoundSystemConfig.getLibraryDescription(classArgs) + ")", 1); try { soundLibrary = (Library) classArgs.newInstance(); } catch (InstantiationException ie) { errorMessage("The specified library did not load properly", 1); } catch (IllegalAccessException iae) { errorMessage("The specified library did not load properly", 1); } catch (ExceptionInInitializerError eiie) { errorMessage("The specified library did not load properly", 1); } catch (SecurityException se) { errorMessage("The specified library did not load properly", 1); } if (errorCheck(soundLibrary == null, "Library null after " + "initialization in method 'newLibrary'", 1)) { lastException(SET, new SoundSystemException(className + " did not load properly. " + "Library was null after initialization.", SoundSystemException.LIBRARY_NULL)); importantMessage("Switching to silent mode", 1); try { soundLibrary = new Library(); } catch (SoundSystemException sse) { lastException(SET, new SoundSystemException( "Silent mode did not load properly. " + "Library was null after initialization.", SoundSystemException.LIBRARY_NULL)); initialized(SET, true); return; } } try { soundLibrary.init(); } catch (SoundSystemException sse) { lastException(SET, sse); initialized(SET, true); return; } lastException(SET, null); initialized(SET, true); return; }
c460bae5-da45-46f6-9906-7f04f5013530
7
public ClientReceivingSubscription( final boolean isLocal, final long applicationId, final long userId, final boolean drain, final boolean delayed, final boolean delta, final int state, final int conState) { _local = isLocal; _applicationId = applicationId; _userId = userId; _drain = drain; _delayed = delayed; _delta = delta; if(applicationId == 0){ _application = _connection.getDataModel().getConfigurationAuthority(); _user = _connection.getDataModel().getConfigurationAuthority(); } else{ _application = _connection.getDataModel().getObject(applicationId); _user = _connection.getDataModel().getObject(userId); } switch(state) { case 1: _state = SubscriptionState.NoSendersAvailable; break; case 2: _state = SubscriptionState.SendersAvailable; break; case 3: _state = SubscriptionState.Waiting; break; case 4: _state = SubscriptionState.NotAllowed; break; case 6: _state = SubscriptionState.NotResponsible; break; case 7: _state = SubscriptionState.MultiRemoteLock; break; default: _state = SubscriptionState.InvalidSubscription; } _connectionState = ClientConnectionState.values()[conState]; }
b9d50b5a-6acf-4731-9532-f11c82580820
0
public void mousePressed(MouseEvent e) { dragStartScreen = e.getPoint(); dragEndScreen = null; }
b0126e35-415a-401e-9f4f-f298962788c8
5
public Object remove(int index) { Object value; // This method also checks that the index is valid (the queue is not // empty) index = getIndex(index); value = queueData[index]; if (index == first) { // This is the most common case for a queue queueData[first] = null; first = (first + 1) % queueData.length; } else if (index < last) { // Case 1 (non wrapped) or // Case 2 when index is less than last (in the first part of the array) last--; if (index < last) { // An element in the middle is removed System.arraycopy(queueData, index + 1, queueData, index, last - index); } queueData[last] = null; } else if ((last == 0) && (index == queueData.length - 1)) { // Special case when no elements exists at the beginning of the data // array and the removed index is last in the data array // (wrap the last pointer to the end of the array) queueData[index] = null; last = queueData.length - 1; } else { // Case 2 (wrapped) and index must be larger than first // (in the middle of end of the array) // (we have already checked index==first) System.arraycopy(queueData, first, queueData, first + 1, index - first); queueData[first++] = null; } size--; return value; }
5caf41a9-c874-4fd2-ba12-57887e433477
4
private void closeTextInFile() { try{ if (in != null) {in.close();} if (inputStreamReader != null) {inputStreamReader.close();} if (fileInputStream != null) {fileInputStream.close();} } catch(IOException e){ //ignore error while trying to close the file //could log the error message in the future } }//end of ADataClass::closeTextInFile
666eb3b4-24ab-4017-9a70-f6e1d487e0a5
6
public boolean getBoolean(int index) throws JSONException { Object object = this.get(index); if (object.equals(Boolean.FALSE) || (object instanceof String && ((String)object).equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String)object).equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONArray[" + index + "] is not a boolean."); }
6c6cab8a-176f-4294-b682-8588d3e9e63f
1
private Rectangle copyRectangle(Rectangle from, Rectangle to) { if (to == null) { to = new Rectangle(); } to.x = from.x; to.y = from.y; to.width = from.width; to.height = from.height; return to; }
976804fb-3148-4463-9328-a9715b262597
3
private boolean isDifficulty(String cmd) { for (GameDifficulty gD : GameDifficulty.values()) { if (cmd.equalsIgnoreCase(gD.getName())) { if (gD != GameDifficulty.CUSTOM) { Minesweeper.getInstance().getOptionPanel().setDifficulty(gD); Minesweeper.getInstance().restart(); return true; } } } return false; }
e16ec0a6-0bf0-4cce-bc23-2f76f342bd27
3
public String toString() { // Fourni les codes couleur et l'indication des familles String s = ""; String s1; String s2; for (int i = 0; i < 8; i++) { s1 = ""; s2 = ""; for (int j = 0; j < 8; j++) { s1 += matrix[i][j] + " "; s2 += (matrixb[i][j] ? 1 : 0) + " "; } s += s1 + " " + s2 + '\n'; } return s; }
fd2f9d3b-1212-4857-a62c-10683bc3d5ba
9
void run(){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(), T = sc.nextInt(), S = sc.nextInt(); int[] a = new int[n], b = new int[n]; for(int i=0;i<n;i++){ a[i] = sc.nextInt(); b[i] = sc.nextInt(); } int[][] dp = new int[n][T+1]; for(int j=b[0];j<=T;j++){ dp[0][j] = dp[0][j-1]; if(!(j-b[0]<S&&S<j))dp[0][j] = a[0]; } for(int i=1;i<n;i++)for(int t=1;t<=T;t++){ dp[i][t] = Math.max(dp[i-1][t], dp[i][t-1]); if(b[i]<=t&&!(t-b[i]<S&&S<t))dp[i][t] = Math.max(dp[i][t], dp[i-1][t-b[i]]+a[i]); } System.out.println(dp[n-1][T]); }
d17a5208-ab04-46db-91c1-0c5832a9c7e2
1
public void testConstructor_ObjectStringEx5() throws Throwable { try { new LocalTime("T10:20:30.040+04:00"); fail(); } catch (IllegalArgumentException ex) {} }
b45e8124-1e47-4907-8c47-19c0be153631
8
private void destroy(int x, int y) { int mouseX = x; int mouseY = y; int rowCount = genX / blockSize; int startY = (Math.round(mapY / blockSize))* rowCount + 1; int endY = (Math.round((mapY + screenHeight) / blockSize) - 1)* rowCount; if(startY < 0) startY = 0; if(endY > map.length) endY = map.length; playerHitBox.setLocation(mouseX, mouseY + mapY); for(int i = startY; i < endY; i++){ if(playerHitBox.intersects(map[i]) && map[i].type != 0){ if(map[i].type != -1)type = map[i].type; blockBreakTimer += delta; blockAnimTimer += delta; if(blockAnimTimer > 100){ map[i].switchBlockColor(type); blockAnimTimer = 0; } blockBreakTimer += delta; if(blockBreakTimer > map[i].breakTime){ playerInv.addItem(type); map[i].type = 0; blockBreakTimer = 0; } } } }
cc73a53e-634e-414a-b245-ef055d210340
3
@Override public void addProgram(Program program) { Double currentFitness = 0.0; if(program.getFitness() == null) fitnessFunction.computeFitness(program); currentFitness = program.getFitness(); int index = 0; while (index < programs.size() && currentFitness > fitness.get(index)) { index++; } this.programs.add(index, program); this.fitness.add(index, currentFitness); }
1d14d61c-e3f8-4aca-9e32-674b1e649170
1
@Override public void changedMostRecentDocumentTouched(DocumentRepositoryEvent e) { if (e.getDocument() == null) { setEnabled(false); } else { setEnabled(true); } }
7af00227-2558-47d1-9d12-2294e574a265
0
public List<Speaker> findSpeakersByHallEventId(final Long hallEventId) { return new ArrayList<Speaker>(); }
2739522b-213c-4ab1-88e9-84e20f5f9929
3
public static String[] getYMLConfig(String fileName) throws IOException{ String[] str = new String[2] ; JarFile jarFile = new JarFile (fileName) ; JarEntry jarEntry = jarFile.getJarEntry( StaticValue.JAR_YMLFILE ) ; //Read .yml File InputStream input = jarFile.getInputStream(jarEntry) ; InputStreamReader inputReader = new InputStreamReader(input) ; BufferedReader reader = new BufferedReader(inputReader) ; //Read String line = null ; while((line = reader.readLine() ) != null){ if(line.contains("name")){ str[0] = line.split(":")[1].trim() ; } if(line.contains("package")){ str[1] = line.split(":")[1].trim() ; } } //Close Readstream reader.close() ; jarFile.close() ; return str ; }
f697b45e-7759-4c98-b568-6cde9bf08b4b
5
Class358(int[] is, int[] is_1_, int[] is_2_, float[][] fs) { try { ((Class358) this).anIntArray4414 = is_2_; ((Class358) this).aFloatArrayArray4412 = fs; ((Class358) this).anIntArray4415 = is_1_; ((Class358) this).anIntArray4416 = is; } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929 (runtimeexception, ("ew.<init>(" + (is != null ? "{...}" : "null") + ',' + (is_1_ != null ? "{...}" : "null") + ',' + (is_2_ != null ? "{...}" : "null") + ',' + (fs != null ? "{...}" : "null") + ')')); } }
b8fe9407-5b5b-462a-80a3-d6463bae328a
5
public void mousePressed(MouseEvent e) { boolean drag = dragNormal || dragPrecise; if (!drag && (e.getModifiers() & InputEvent.BUTTON1_MASK) != 0) { dragNormal = true; mouseSelect(e); } if (!drag && (e.getModifiers() & InputEvent.BUTTON3_MASK) != 0) { dragPrecise = true; dragPreciseX = e.getPoint().x; } }
2857d680-93d5-4d61-8c2a-32434d766391
6
void trim() { while(white()) { skip(); } while (!eof() && curr() == '#') { while(!eof() && curr() != '\n') { skip(); } while(white()) { skip(); } } }
b010bdd1-f65a-4adf-a715-5eabced17c75
3
public static void square(double x, double y, double r) { if (r < 0) throw new RuntimeException("square side length can't be negative"); double xs = scaleX(x); double ys = scaleY(y); double ws = factorX(2*r); double hs = factorY(2*r); if (ws <= 1 && hs <= 1) pixel(x, y); else offscreen.draw(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs)); show(); }
3dbb4216-fe03-4061-9973-cccdde8a81b1
5
@Override public int altaDepartamento(Departamento departamento) { departamento.setIdDepartamento(-1); EntityManager em = null; EntityManagerFactory ef = null; try { ef = Persistence.createEntityManagerFactory("MerkaSoftPU"); em = ef.createEntityManager(); em.getTransaction().begin(); Departamento departamentoAux = null; List results = em.createNamedQuery("Departamento.findByNombre") .setParameter("nombre", departamento.getNombre()) .getResultList(); if (results.size() > 0) departamentoAux = (Departamento)results.get(0); if (departamentoAux != null) { if (!departamentoAux.getDisponible()) { departamentoAux.setDisponible(true); em.merge(departamentoAux); departamento.setIdDepartamento(departamentoAux.getIdDepartamento()); em.getTransaction().commit(); } else { System.out.println("Ya existe el departamento"); em.getTransaction().rollback(); } } else { em.persist(departamento); em.getTransaction().commit(); } } finally { if (em != null) em.close(); if (ef != null) ef.close(); } return departamento.getIdDepartamento(); }
1dfbaa7b-4c57-4e14-b800-1bbd5273a369
5
private Float searchRgb(int[] rgb) throws InterpException { for (Section paletteSection : sections) { if (paletteSection.inSection(rgb)) { return paletteSection.process(rgb, true); } } int diff = 0; while (diff < 5) { diff++; for (Section paletteSection : sections) { if (paletteSection.inSection(rgb, diff)) { return paletteSection.process(rgb, false); } } } return null; // throw new InterpException("Not in any sections :S. " + rgb[0] + "," + // rgb[1] + "," + rgb[2]); }
09820cf2-2e35-49a0-8db9-cb1866987c2a
5
@Override public void keyPressed(int k) { if(k == KeyEvent.VK_LEFT) player.setLeft(true); if(k == KeyEvent.VK_RIGHT) player.setRight(true); if(k == KeyEvent.VK_UP) player.setUp(true); if(k == KeyEvent.VK_DOWN) player.setDown(true); if(k == KeyEvent.VK_Z) player.setPummeling(); }
99e37ba8-2865-4db2-8af9-99d3cea26b50
1
private boolean isPlaying() { return client.getSession() != null && client.getSession().getState() == ClientSession.State.PLAYING; }
6b9eaae9-9002-4153-b643-3f525ec070c5
9
private void heapifyAlaspain(int aloitusSolmu) { int vasen = vasen(aloitusSolmu); int oikea = oikea(aloitusSolmu); if (taulukko[aloitusSolmu] == null) return; if( oikea >= taulukko.length && vasen >= taulukko.length ) return; if (taulukko[oikea] == null && taulukko[vasen] == null) return; int oikeaFrekvenssi = Integer.MAX_VALUE; int vasenFrekvenssi = Integer.MAX_VALUE; if (taulukko[oikea] != null) oikeaFrekvenssi = taulukko[oikea].annaFrekvenssi(); if (taulukko[vasen] != null) vasenFrekvenssi = taulukko[vasen].annaFrekvenssi(); int pienempiLapsi = oikeaFrekvenssi > vasenFrekvenssi ? vasen : oikea; if (taulukko[aloitusSolmu].compareTo(taulukko[pienempiLapsi]) > 0) { vaihdaElementit(pienempiLapsi, aloitusSolmu); heapifyAlaspain(pienempiLapsi); } }
123ed913-21f9-43a7-9dc2-0561a363964b
3
public static double getScoreTopology(Graph[] g, Vector<String>[] seed) { int i=0, j=0, k=0; double scoreTopology=0.0; for(i=0;i<seed.length;i++) { for(j=i+1;j<seed.length;j++) { double scorePair=0.0; for(k=0;k<seed[i].size();k++) { double[] mapSource=getAdiacMap(g[i],seed[i],seed[i].get(k)); double[] mapDest=getAdiacMap(g[j],seed[j],seed[j].get(k)); scorePair+=getPairwiseScore(mapSource,mapDest); } scoreTopology+=scorePair; } } scoreTopology=scoreTopology/(seed[0].size()*g.length*(g.length-1)/2); return scoreTopology; }
78050c3a-6544-4187-8803-0ed65cbfa052
4
public List<Trip> getTripsByUser(User user) throws UserNotLoggedInException { List<Trip> tripList = new ArrayList<Trip>(); User loggedUser = UserSession.getInstance().getLoggedUser(); boolean isFriend = false; if (loggedUser != null) { for (User friend : user.getFriends()) { if (friend.equals(loggedUser)) { isFriend = true; break; } } if (isFriend) { tripList = TripDAO.findTripsByUser(user); } return tripList; } else { throw new UserNotLoggedInException(); } }
8b2ac6a5-42d6-4db3-9862-9c25fbf165a0
1
public ArrayList getAnswers() { ArrayList collectedAnswers = new ArrayList<String>(); for (int i = 0; i < table.getModel().getRowCount(); i++) { collectedAnswers.add(tableModel.getValueAt(i, 0)); } return collectedAnswers; }
9a83da5c-2e7c-4c10-80ba-c8955dd98456
4
public void run() { ArrayList<String> arrayAll = new ArrayList<>(); int fileServerSocketPort= 7000+ClientMain.myID_Num; arrayAll=SQLiteView.viewAllContentInCDB(); System.out.println(">>>>>>>>>> CheckTheThroughput Start!!! <<<<<<<<<<"); for(String provider : arrayAll) { if(provider.split("@Status=")[1].matches("proposition")&&provider.split("@ContentName=")[1].split("@")[0].matches(ClientMain.contentName)) { FunctionClass.sendServiceMessage(Integer.toString(ClientMain.myID_Num), "R", provider.split("@PMACaddr=")[1].split("-")[0], "P", "checkTheThroughput_47",fileServerSocketPort+ "@" +ClientMain.contentName, socket); try { Thread.sleep(5000); //each agent is assigned sleep time } catch (InterruptedException e) { // TODO Auto-generated catch block System.out.println("Interrupt !!! call!!"); } } } System.out.println(">>>>>>>>>> CheckTheThroughput End!!! <<<<<<<<<<"); }
a0bcc3f8-c5ca-401e-a012-ddd8cd6fe005
1
private static boolean isDoublePalindrome(int n){ return isPanlindrome(Integer.toBinaryString(n)) && isPanlindrome(Integer.toString(n)); }
0f8645b8-b1f1-4c90-bdba-8f5b8c51b6b3
9
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed int row = jTable1.getSelectedRow(); int opc = select.getSelectedIndex(); jLabel2.setText(""); if (vendas_nao_avaliadas.size() > 0 && opc == 1 && row != -1) { Venda v = (Venda) vendas_nao_avaliadas.get(row); new UIAvVenda(c, v).setVisible(true); this.dispose(); } else if (servs_oficina_nao_avaliados.size() > 0 && opc == 2 && row != -1) { ServicoOficina s = (ServicoOficina) servs_oficina_nao_avaliados.get(row); new UIAvOficina(c, s).setVisible(true); this.dispose(); } else if (atendimentos_nao_avaliados.size() > 0 && opc == 3 && row != -1) { Atendimento a = (Atendimento) atendimentos_nao_avaliados.get(row); new UIAvAtendimento(c, a).setVisible(true); this.dispose(); } else { jLabel2.setText("Nenhum item selecionado!"); } }//GEN-LAST:event_jButton1ActionPerformed
4fa0fa29-0600-4906-a456-b5e0531bea1f
9
public void start() { Parameters params = view.setParameters(); while (!params.checkIfParamsCorrect()) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } EvaluatedLens lens = new EvaluatedLens(new Lens(params.getNumberOfPoints()), params); this.algorithm = new OnePlusOneAlgorithm<EvaluatedLens>(lens, 1.0, 0.3, 10, 0.82, 1.2); view.createFrame(lens); boolean sth = true; while (true) { Waiter.getInstance().stop(); try { if( sth ){ Thread.sleep(1000); sth = false; } } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } //process algorithm.nextIteration(); IterationResult generationResult = algorithm.getStatus(); lens = algorithm.getObject(); view.setLens(lens); view.drawView(); if (generationResult == IterationResult.FINISHED_WITHOUT_RESULT ) { logger.info("Simulation finished without result!"); System.exit(0); } // TODO: w jakis sposób zaimplementować wybór, czy fitness ma byc minimalizowany czy maksymalizowany int score = lens.getScore(); logger.info("Best fitness is now " + generationResult); if (score > params.getFocusingAccuracy() ) { logger.info("Simulation finished with result in generation no. " + algorithm.getIterationNo() + " with score " + generationResult); try { Thread.sleep(20000); } catch (Exception e) { System.err.println(e); } System.exit(0); } } }
d5a099aa-478c-4fcb-a2f3-1ccc741414a3
0
public void endGame(){ exit=true; }
ba200670-f6a4-4155-b0ab-660d814f466f
7
public Object nextValue() throws JSONException { char c = this.nextClean(); String string; switch (c) { case '"': case '\'': return this.nextString(c); case '{': this.back(); return new JSONObject(this); case '[': this.back(); return new JSONArray(this); } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuffer sb = new StringBuffer(); while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = this.next(); } this.back(); string = sb.toString().trim(); if ("".equals(string)) { throw this.syntaxError("Missing value"); } return JSONObject.stringToValue(string); }
09abe65b-f7bc-4564-88e4-40fe2dfd1f36
3
public void setSymtab(Symtab st) { if (f != null) f.setSymtab(st); else if (sd != null) { Symtab structTable = new Symtab(); sd.setSymtab(st, structTable); boolean isNew = st.enter(sd.getStructName(), new SymtabEntry(sd.getStructName(), "struct", structTable)); if (!isNew) Main.error("Struct " + sd.getStructName() + " defined twice!"); } }
7be7b776-2d82-4a68-947a-5fa5e571715f
0
public Path(City a, City b){ first_city = a; second_city = b; }
b7505f9a-6964-41d8-b966-0d2107c507d2
8
static private int jjMoveStringLiteralDfa0_0() { switch(curChar) { case 40: return jjStopAtPos(0, 15); case 41: return jjStopAtPos(0, 16); case 42: return jjStopAtPos(0, 13); case 43: return jjStopAtPos(0, 11); case 45: return jjStopAtPos(0, 12); case 47: return jjStopAtPos(0, 14); case 59: return jjStopAtPos(0, 10); case 61: return jjStopAtPos(0, 9); default : return jjMoveNfa_0(2, 0); } }
ecef0a53-fe00-4c07-8b82-3a65bb96be1a
6
public static int dehexchar(char c) { if(c >= '0' && c <= '9') { return c - '0'; } if(c >= 'A' && c <= 'F') { return c - ('A' - 10); } if(c >= 'a' && c <= 'f') { return c - ('a' - 10); } return -1; }
744bc903-f95a-418b-b234-9ff40702751f
3
private void diffDesc(int what, ArrayList<Change> list, DescRec rec, HashMap<String, Object> map) { if (map == null) { System.out.println("Category '" + rec.getId() + "' is used but no longer listed"); return; } // Name or description changed? String b = (String) map.get("name"); if (Change.fieldChanged(rec.getName(), b)) { list.add(DescChange.setName(rec, b)); } b = (String) map.get("description"); if (Change.fieldChanged(rec.getDescription(), b)) { list.add(DescChange.setDescription(rec, b)); } }
179e11b2-a5b7-4cb6-b010-e85092b171eb
4
private synchronized int flipBuffers() { if(!closed) { synchronized (buffer) { // wait until while(buffer.size() <= 0) { try { buffer.wait(); } catch (InterruptedException exc) { // ignore it } if(!closed) return -1; } // reset read buffer with buffer from output stream this.count = buffer.size(); this.buf = buffer.replaceBuffer(); this.pos = 0; this.mark = 0; } return this.count; } else { return -1; } }
8f0667e6-4dbe-48b5-ac51-6d1cb400e68d
4
public void describeBehaviour(Description d) { if (applied != null) { ///if (stage == STAGE_TRANSPORT) super.describedByStep(d) ; if (! super.describedByStep(d)) d.append("Treating") ; d.append(" ") ; d.append(patient) ; d.append(" for ") ; d.append(applied) ; } else if (type == TYPE_RECONSTRUCT) { d.append("Reconstructing ") ; d.append(patient) ; } else if (type == TYPE_PSYCH_EVAL) { d.append("Performing Psych Eval for ") ; d.append(patient) ; } else { d.append("Treating ") ; d.append(patient) ; } }
5f49b170-3aaa-4e33-9810-66911d0c6510
7
protected int myEndif(StringBuffer s, int i, String[] lastFoundMacro) { int endifsToFind = 1; for (; i < s.length(); i++) { if (s.charAt(i) == '@') { final String foundMacro = parseFoundMacro(s, i, lastFoundMacro, true); if ((foundMacro != null) && (foundMacro.length() > 0)) { if (foundMacro.startsWith("if?")) endifsToFind++; else if (foundMacro.equalsIgnoreCase("endif")) { endifsToFind--; if (endifsToFind <= 0) return i; } } } } return -1; }
e11c5929-12aa-4e77-93e0-2c46387aec03
7
private boolean isDragOk( final java.io.PrintStream out, final java.awt.dnd.DropTargetDragEvent evt ) { boolean ok = false; // Get data flavors being dragged java.awt.datatransfer.DataFlavor[] flavors = evt.getCurrentDataFlavors(); // See if any of the flavors are a file list int i = 0; while( !ok && i < flavors.length ) { // BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added. // Is the flavor a file list? final DataFlavor curFlavor = flavors[i]; if( curFlavor.equals( java.awt.datatransfer.DataFlavor.javaFileListFlavor ) || curFlavor.isRepresentationClassReader()){ ok = true; } // END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added. i++; } // end while: through flavors // If logging is enabled, show data flavors if( out != null ) { if( flavors.length == 0 ) log( out, "FileDrop: no data flavors." ); for( i = 0; i < flavors.length; i++ ) log( out, flavors[i].toString() ); } // end if: logging enabled return ok; }
1080c40e-a8a4-4e83-9b43-c32b05eca11f
8
public void writeExampleFiles() { File dataFolder = getDataFolder(); File configFile = new File(dataFolder, "config.yml"); if (!configFile.exists()){ String content = ConfigUtil.fetchResource(SimpleTreasure.class, "resources/default.yml"); if (content != null){ if (ConfigUtil.writeFile(configFile, content)) System.out.println("[SimpleTreasure] Added example configuration: config.yml"); } } File examplesFolder = new File(dataFolder, "examples"); if (!examplesFolder.exists()) examplesFolder.mkdirs(); for (String name : exampleFileNames){ File file = new File(examplesFolder, name); if (!file.exists()){ String content = ConfigUtil.fetchResource(SimpleTreasure.class, "resources/"+name); if (content != null){ if (ConfigUtil.writeFile(file, content)) System.out.println("[SimpleTreasure] Added example configuration: " + name); } } } }
cfc6cf27-746a-47ec-a727-a07972431a09
3
@Override public void actionPerformed(ActionEvent e) { switch(e.getActionCommand().charAt(0)) { case 'u': { if(!TextUpload.upload(frame.text.getText())) break; } case 'c': { frame.dispose(); break; } } }
1208fba9-4751-4294-801c-4d2b7d243b95
4
public static void addPrestigeTree(String prestige) { BlankTree bt = new BlankTree(); //we do not allow multiple of the same tree for(ClassTree ct : takenPrestigeTrees){ if(ct.getPrestige().equals(prestige)) return; } //find the first tree that is blank and replace the blank tree with our new class tree for(EnhancementTree e : takenPrestigeTrees){ if(e.getClass().equals(bt.getClass())){ takenPrestigeTrees.set(takenPrestigeTrees.indexOf(e) , new ClassTree(prestige)); break; } } // if(takenPrestigeTrees.size() < 6) //only 6 trees allowed // takenPrestigeTrees.add(new ClassTree(prestige)); return; }
2f99e7ea-8488-466f-88ad-3ac4e2c42437
5
@Override public boolean isValide(String antwoord) { String delimiter = ";"; String[] tempAntwoord = antwoord.split(delimiter); String[] tempJuistAntwoord = super.getAntwoord().split(delimiter); if (tempJuistAntwoord.length > 1) { if (!antwoord.contains(delimiter)) { this.valideerTekst = "Het antwoord is niet gesplitst met de het nodige ';' teken"; return false; }else if (tempAntwoord.length < tempJuistAntwoord.length) { this.valideerTekst = "Het antwoord bevat niet genoeg waarden"; return false; }else if (tempAntwoord.length > tempJuistAntwoord.length) { this.valideerTekst = "Het antwoord bevat te veel waarden"; return false; }else { this.valideerTekst = "Het antwoord bevat het juiste aantal waarden"; return true; } }else { if (tempAntwoord.length > 1) { this.valideerTekst = "Het antwoord bevat te veel waarden"; return false; }else { this.valideerTekst = "Het antwoord bevat het juiste aantal waarden"; return true; } } }
34940af8-fb2a-4be5-ba8e-ad956ab0f02d
9
public static void main(String[] args) { int[] onesLen = new int[ONES.length]; int[] teensLen = new int[TEENS.length]; int[] tensLen = new int[TENS.length]; for (int i = 0; i < 10; i++) { onesLen[i] = ONES[i].length(); teensLen[i] = TEENS[i].length(); tensLen[i] = TENS[i].length(); } int thousandLen = THOUSAND.length(); int hundredLen = HUNDRED.length(); long n = 0; int c; for (int i = 1; i <= 1000; i++) { int v = i; c = 0; //System.out.print(i + ": "); if (v / 1000 > 0) { c += thousandLen; c += onesLen[1]; v -= 1000; //System.out.println("onethousand"); } if (v / 100 > 0) { c += hundredLen; c += onesLen[v / 100]; //System.out.print(ONES[v / 100] + "hundred"); v -= (v / 100) * 100; //integer math } if (v / 10 > 1) { c += tensLen[v / 10]; //System.out.print(TENS[v / 10]); v -= (v / 10) * 10; //integer math } else if (v / 10 > 0) { c += teensLen[v - 10]; //System.out.print(TEENS[v - 10]); v -= v; } if (v > 0) { c += onesLen[v]; ///System.out.print(ONES[v]); v -= v; } //AND. //Just to make life more difficult. if (i > 99 && i % 100 != 0) { c += 3; } n += c; //System.out.println(" - " + c); } System.out.println(n); }
46c9e732-9db6-4919-9942-38f1d73b0c5f
9
private void readAttribute( int index, Annotation[][] annotations, ConstantPool cp, ClassInputStream in ) throws IOException { String name = cp.utf( in.uint16bit() ); int length = in.int32bit(); if ( "Code".equals( name ) ) { CodeAttribute code = CodeAttribute.read( cp, in ); codes[index] = code.code(); methodReferences[index] = code.references(); readAttributes( index, annotations, in, cp ); } else { if ( "Deprecated".equals( name ) ) { //TODO reflect somehow } else if ( "Signature".equals( name ) ) { String signature = cp.utf( in.uint16bit() ); //TODO reflect somehow } else if ( "RuntimeVisibleAnnotations".equals( name ) || "RuntimeInvisibleAnnotations".equals( name ) ) { Annotation[] annotations2 = AnnotationAttribute.readAnnotations( cp, in ); if ( index < 0 ) { classAnnotations = annotations2; } else { annotations[index] = annotations2; } } else if ( "RuntimeVisibleParameterAnnotations".equals( name ) || "RuntimeVisibleParameterAnnotations".equals( name ) ) { int num = in.uint8bit(); for ( int i = 0; i < num; i++ ) { AnnotationAttribute.readAnnotations( cp, in ); } } else { in.skipBytes( length ); } } }
301536ba-3051-444c-9e72-3df320ecd991
3
public static void init() { if (!loaded) { try { metronomeTick = AudioLoader.getAudio("WAV", ResourceLoader.getResourceAsStream(FilePaths.METRONOME_TICK)); metronomeBell = AudioLoader.getAudio("WAV", ResourceLoader.getResourceAsStream(FilePaths.METRONOME_BELL)); noteF5 = AudioLoader.getAudio("WAV", ResourceLoader.getResourceAsStream(FilePaths.NOTE_F5)); noteD5 = AudioLoader.getAudio("WAV", ResourceLoader.getResourceAsStream(FilePaths.NOTE_D5)); noteC5 = AudioLoader.getAudio("WAV", ResourceLoader.getResourceAsStream(FilePaths.NOTE_C5)); noteBb4 = AudioLoader.getAudio("WAV", ResourceLoader.getResourceAsStream(FilePaths.NOTE_Bb4)); noteG4 = AudioLoader.getAudio("WAV", ResourceLoader.getResourceAsStream(FilePaths.NOTE_G4)); noteF4 = AudioLoader.getAudio("WAV", ResourceLoader.getResourceAsStream(FilePaths.NOTE_F4)); noteD4 = AudioLoader.getAudio("WAV", ResourceLoader.getResourceAsStream(FilePaths.NOTE_D4)); noteC4 = AudioLoader.getAudio("WAV", ResourceLoader.getResourceAsStream(FilePaths.NOTE_C4)); funk = new Music(FilePaths.MUS_FUNK); loaded = true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SlickException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
d4ec2582-ebb3-4674-a93a-c15d79abf375
3
public void paintComponent(Graphics g) { super.paintComponent(g); for (MyLine line : lines) { line.draw(g); } for (MyRectangle rectangle : rectangles) { rectangle.draw(g, rectangle.getFilled()); } for (MyOval oval : ovals) { oval.draw(g, oval.getFilled()); } }
7090b396-da10-40a1-901b-ca685da43676
6
@Override public void train(Matrix features, Matrix labels, int k) throws Exception { double[][] adjacencyMatrix = initializeAdjacencyMatrix(features); String[] clusterNames = new String[features.rows()]; for (int i = 0; i < features.rows(); i++) { clusterNames[i] = i + ""; } // Change this to change the given linking rule. // LinkingRule howToCluster = new SingleLinkingRule(); LinkingRule howToCluster = new CompleteLinkingRule(); // LinkingRule howToCluster = new AverageLinkingRule(); // Main clustering algorithm ClusteringAlgorithm algorithm = new ClusteringAlgorithm(); System.out.println("k = " + k); List<Cluster> finalClusters = algorithm.performClustering(adjacencyMatrix , clusterNames , howToCluster , k , features); int counter = 0; double totalSSE = 0; System.out.println("=`=`=`=`=`=`=`=`=`=`=`=`=`=`=`\n"); System.out.println("FINAL\n"); for (Cluster finalCluster : finalClusters) { Set<Integer> instances = new HashSet<Integer>(); finalCluster.findChildren(instances); finalCluster.setAllInstances(instances); finalCluster.updateCentroid(features); totalSSE += finalCluster.getSSE(features); System.out.println("Cluster " + counter); printCentroids(features, finalCluster); counter++; } System.out.println("Total SSE : " + totalSSE); double min = 100000; for (Cluster finalCluster : finalClusters) { for (Cluster otherCluster : finalClusters) { if (otherCluster != finalCluster) { double distance = getEuclidDistance(otherCluster.getCentroid() , finalCluster.getCentroid() , features); if (min > distance) min = distance; } } } // System.out.println(min); // System.out.println(totalSSE); // DendrogramPanel dp = new DendrogramPanel(); // dp.setModel(finalCluster); // displayDendrogram(finalCluster); }
31c7a56e-d2b9-401e-bfcd-bb0887413174
3
private void renderDeck(Graphics2D g) { Queue<Card> deck = game.getDeck(); Card topCard = deck.size() == 0 ? null : deck.peek(); double x = X_BOARD_OFFSET; double y = DECK_Y; g.setColor(Color.white); g.drawString(deck.size() + " cards in deck", (float) x, (float) y - 1); if (topCard != null && topCard.isHidden()) { topCard = null; } renderCard(topCard, g, x, y); }
b2bdba4c-9a1d-4d63-9585-624e9a1d21f4
9
public static void quickSortNativeVector(edu.isi.stella.Stella_Object[] vector, int start, int end, java.lang.reflect.Method predicate) { for (;;) { { int length = end - start; Stella_Object splitelement = null; Stella_Object element = null; int lowcursor = start; int highcursor = end; if (length <= 1) { return; } else if (length >= 10) { splitelement = Stella.quickSortPickSplitElement(vector, start, end, predicate); } else { splitelement = vector[start]; } while (lowcursor < highcursor) { loop002 : while (lowcursor < highcursor) { highcursor = highcursor - 1; element = vector[highcursor]; if (((Boolean)(edu.isi.stella.javalib.Native.funcall(predicate, null, new java.lang.Object [] {element, splitelement}))).booleanValue()) { vector[lowcursor] = element; break loop002; } } loop003 : while (lowcursor < highcursor) { lowcursor = lowcursor + 1; element = vector[lowcursor]; if (((Boolean)(edu.isi.stella.javalib.Native.funcall(predicate, null, new java.lang.Object [] {splitelement, element}))).booleanValue()) { vector[highcursor] = element; break loop003; } } } vector[highcursor] = splitelement; if (((start + end) >> 1) < highcursor) { Stella.quickSortNativeVector(vector, highcursor + 1, end, predicate); end = highcursor; } else { Stella.quickSortNativeVector(vector, start, highcursor, predicate); start = highcursor + 1; } } } }
a9c5826a-c0ce-4746-b413-2b8504cacf37
3
private boolean jj_3R_25() { if (jj_scan_token(ARRAY)) return true; if (jj_scan_token(OF)) return true; if (jj_scan_token(INTEGER_LITERAL)) return true; return false; }
67643fb8-6cce-48c8-8f02-656f0de43186
0
public void setVariableA(String s) { A = s; }
e7e551a0-4a47-4df1-9e39-e617bc02f466
7
@Override public void follows(Hero hero) { Random random = new Random(); if (random.nextInt(3)>0) { if (hero.getX() == super.getX()) { if (hero.getY()>super.getY()) { super.setDirection(Direction.DOWN); } else if (hero.getY()<super.getY()) { super.setDirection(Direction.UP); } } else if (hero.getY()==super.getY()) { if (hero.getX()>super.getX()) { super.setDirection(Direction.RIGHT); } else if (hero.getX()<super.getX()) { super.setDirection(Direction.LEFT); } } } }
5926a01b-06cc-4760-94eb-ddfe8dd173ef
3
public set Intersection(set FirstSet, set SecondSet) { //Make a new set set ThirdSet = new set(); //Cycle through the first array and compare to the second //to see what's in the first and the second //add those elements to the third array for (int i = 0; i < FirstSet.stuff.size(); i++) { int item = FirstSet.stuff.get(i); if (SecondSet.stuff.contains(item) == true) { ThirdSet.stuff.add(item); } } //Print out the combined set you just made System.out.println("\rThe intersecting elements are:"); for (int i = 0; i < ThirdSet.stuff.size(); i++) { int item = ThirdSet.stuff.get(i); System.out.print(item + " "); } System.out.print("\r"); return ThirdSet; }
dadc4cfa-5122-4f61-9c1c-327f03db47b2
2
public void removeIncomingLink(Link l) { Iterator<Link> iter = getIncomingLinks().iterator(); while (iter.hasNext()) { if (iter.next().getLinkID() == l.getLinkID()) { iter.remove(); } } }
50af8681-216d-4611-9b2a-06230aa255bc
0
public void close() { this.vue.setVisible(false); }
9cbe4fdb-8b1d-4aef-8b66-2ff141ba17e4
6
public boolean checkCollision(int uid, float x,float y){ Actor a; // Comprobamos que este dentro del escenario if (Math.sqrt((x*x)+(y*y))>radius) { return true; } // Comprobamos que no este chocando con otro actor for (Map.Entry entry : actores.entrySet()) { a = (Actor)entry.getValue(); if (a.health >0 && a.uid!= uid &&(Math.abs(a.posX-x) < 2 && Math.abs(a.posY-y) < 2)){ return true; } } return false; }
83593217-90fa-4e7c-9b14-954bf54efee0
4
public void setCorrect(int attempts) { if (attempts != 1) { handler.getDataHandler().negateCorrect(); System.out.println("Negating attempts"); } handler.getDataHandler().getAnswered().add(handler.getDataHandler().getFrame().getNumber()); handler.getDataHandler().getAttempts().putIfAbsent(handler.getDataHandler().getFrame().getNumber(), attempts); final long time = System.currentTimeMillis() - handler.getDataHandler().getStartQuestionTime().longValue(); handler.getDataHandler().setStartQuestionTime(System.currentTimeMillis()); handler.getDataHandler().getTimeTakenMap().putIfAbsent(handler.getDataHandler().getFrame().getNumber(), time); if (handler.getDataHandler().getAnswered().size() == handler.getDataHandler().getTotalNumberQuestions().intValue()) { handler.validateFinished(); DrawChart chart = new DrawChart(handler.getDataHandler().getTimeTakenMap(), handler.getComputer(), handler.getDataHandler().getAttempts()); handler.getUiHandler().checkRetry(chart); return; } final Integer number = generateNumber(); if (!handler.getDataHandler().getAnswered().contains(number) && handler.getDataHandler().getGenerated().contains(number)) { handler.getDataHandler().getFrame().setQuestion(number); } handler.validateFinished(); }
47adadf3-fbf9-4c2c-a256-a7c0a7f036d8
1
@Test public void findEstudentInActiviteTest() throws InstanceNotFoundException { Activity a = activityService.find(0); for (Student s : a.getStudents()) { activityService.unEnrollsStudentToActivity(s, a); } Student s = familyService.findStudent(0); activityService.enrollmentStudentInActivity(s, a); assertTrue("Too many students in this activity", activityService .findStudents(a).size() == 1); }
f9ffbe31-cb07-4691-8e74-deea81965aba
6
public boolean reduceMemory(int reductionPolicy) { int numToDo = 0; synchronized (leastRectlyUsedLock) { int lruSize = leastRecentlyUsed.size(); if (reductionPolicy == MemoryManagerDelegate.REDUCE_AGGRESSIVELY) { numToDo = lruSize * 75 / 100; } else if (reductionPolicy == MemoryManagerDelegate.REDUCE_SOMEWHAT) { if (lruSize > 5) numToDo = lruSize * 50 / 100; else if (lruSize > 0) numToDo = 1; } //System.out.println("LazyObjectLoader.reduceMemory() reductionPolicy: " + reductionPolicy + ", numToDo: " + numToDo + ", lruSize: " + lruSize); for (int i = 0; i < numToDo; i++) { ObjectStream objStm = leastRecentlyUsed.remove(0); if (objStm != null) objStm.dispose(true); } } return numToDo > 0; }
39ac1b31-145a-49aa-81c7-5223c24d4bc7
9
ExecuteInfo multipleRuns(){ //the process which is called by the main function of SingleSourceKDiverseShortPath long timeStart = System.currentTimeMillis(); int numItr = 0; long maxHeap = 0; long timeToReadMem = 0; Random aRandom = new Random(); while(numNodesFoundKDivPath < numNodes){ int numDeletedEdges = 0; ExecuteInfo stats = this.flowStart(); //start K shortest paths algorithm maxHeap = Math.max(stats.maxHeap, maxHeap); timeToReadMem += stats.timeToReadMem; for(int i=0; i < numNodes ; i++){ importances[i].initialize(); } //delete edges according to the counts of edges for(int i=0; i<numNodes; i++) for(int j=0; j < directEdges[i].size(); j++){ int count = directEdges[i].elementAt(j).count; if(count > SingleSourceKDiverseShortPaths.KShortestPaths / 2){ //only count / SingleSourceKDiverseShortPaths.KShortestPaths > 1/2 would be deleted float prob = (float)count / SingleSourceKDiverseShortPaths.KShortestPaths; if(aRandom.nextFloat() < prob){ this.deleteDirectEdge(i,j); j--; numDeletedEdges++; } } } //System.out.println("number of delete edges:"+numDeletedEdges); //the count of each node is initialized to 0; for(int i=0; i<numNodes; i++) for(int j=0; j < directEdges[i].size(); j++) directEdges[i].elementAt(j).count = 0; numItr++; if( numDeletedEdges < (double)numEdges/numNodes) //if there are no deleted edges in this iteration, convergence and so stop the iteration break; } // System.out.println("total iterations:"+numItr); ExecuteInfo result = new ExecuteInfo((System.currentTimeMillis()-timeStart-timeToReadMem)/1000F, numItr); result.maxHeap = maxHeap; return result; }
4f1dad65-87a7-4635-ab10-8e0641f45849
2
@Override public int hashCode() { int result = username != null ? username.hashCode() : 0; result = 31 * result + (password != null ? password.hashCode() : 0); result = 31 * result + personId; return result; }
d5d5ad55-404a-4ef5-ba2b-c1f602810383
1
public JSONObject optJSONObject(int index) { Object o = opt(index); return o instanceof JSONObject ? (JSONObject)o : null; }
09b55eca-d3db-4553-abc9-8c3a2a58e09a
7
private void initStatusListFontMenu(Color bg) { this.statustextListPanel = new JPanel(); this.statustextListPanel.setBackground(bg); this.statustextListPanel.setLayout(new VerticalLayout(5, VerticalLayout.LEFT)); String initFontTmp = this.skin.getStatustextFont(); int initFontSizeTmp = this.skin.getStatustextFontsize(); Color initFontColorTmp = new Color(this.skin.getStatustextFontcolor()[1], this.skin.getStatustextFontcolor()[2], this.skin.getStatustextFontcolor()[3]); boolean boldTmp = this.skin.getStatustextFonttype() == Fonttype.BOLD; boolean underlineTmp = (this.skin.getStatustextFontstyle() == Fontstyle.UNDERLINE) || (this.skin.getStatustextFontstyle() == Fontstyle.SHADOWUNDERLINE); boolean shadowTmp = (this.skin.getStatustextFontstyle() == Fontstyle.SHADOW) || (this.skin.getStatustextFontstyle() == Fontstyle.SHADOWUNDERLINE); this.statustextFontfield = new FontField(bg, strFontFieldTitle, initFontTmp, initFontSizeTmp, initFontColorTmp, boldTmp, underlineTmp, shadowTmp) { private final long serialVersionUID = 1L; @Override public void fontChosen(String input) { if (!input.equals("")) { FontChangesMenu.this.skin.setStatustextFont(input); updateFont(FontChangesMenu.this.skin.getStatustextFont()); } else { FontChangesMenu.this.skin.setStatustextFont(null); } } @Override public void sizeTyped(String input) { if (input != null) { FontChangesMenu.this.skin.setStatustextFontsize(parseInt(input)); updateSize(FontChangesMenu.this.skin.getStatustextFontsize()); } else { FontChangesMenu.this.skin.setStatustextFontsize(-1); } } @Override public void colorBtnPressed(int[] argb) { FontChangesMenu.this.skin.setStatustextFontcolor(argb); updateColor(new Color(FontChangesMenu.this.skin.getStatustextFontcolor()[1], FontChangesMenu.this.skin.getStatustextFontcolor()[2], FontChangesMenu.this.skin.getStatustextFontcolor()[3])); } @Override public void boldPressed(boolean selected) { FontChangesMenu.this.skin.setStatustextFonttype(selected ? Fonttype.BOLD : Fonttype.NORMAL); updateBold(FontChangesMenu.this.skin.getStatustextFonttype() == Fonttype.BOLD); } @Override public void underlinePressed(boolean selected) { FontChangesMenu.this.skin.setStatustextFontstyle(getUnderlineFontstyle(selected, FontChangesMenu.this.skin.getStatustextFontstyle())); updateUnderline((FontChangesMenu.this.skin.getStatustextFontstyle() == Fontstyle.UNDERLINE) || (FontChangesMenu.this.skin.getStatustextFontstyle() == Fontstyle.SHADOWUNDERLINE)); } @Override public void shadowPressed(boolean selected) { FontChangesMenu.this.skin.setStatustextFontstyle(getShadowFontstyle(selected, FontChangesMenu.this.skin.getStatustextFontstyle())); updateShadow((FontChangesMenu.this.skin.getStatustextFontstyle() == Fontstyle.SHADOW) || (FontChangesMenu.this.skin.getStatustextFontstyle() == Fontstyle.SHADOWUNDERLINE)); } }; this.statustextListPanel.add(this.statustextFontfield); }
d30ce441-4f31-43ec-90c8-6508634923dd
4
public UserModel getUserByUserId(String userId) { if (userId == null || userId.trim().isEmpty()) return null; String hql = "from UserModel where userId = :userId"; List<UserModel> list = entityManager.createQuery(hql).setParameter("userId", userId).getResultList(); if (list == null || list.size() == 0) return null; return list.get(0); }