method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
09bca461-2edb-4baa-bc3f-b32d9d9c27ed
7
public void findBlockID(){ //System.out.println("train ID: "+ trainId); //System.out.println("train distance: "+ trainDist[trainId-1][1]); double newDist; if(getLineColor() == 0) newDist = totalDistance - trainDistRed[trainId-1][1]; else newDist = totalDistance - trainDistGreen[trainId-1][1]; double blockLength = 0; int blockSpeed = 0; Block b; while(true) { if(getLineColor() == 0) b = trackObject.getBlock((int)trainDistRed[trainId-1][2]); else b = trackObject.getBlock((int)trainDistGreen[trainId-1][2]); blockLength = b.getLength(); blockSpeed = b.getSpeedLimit(); if(blockLength > newDist) { if(getLineColor() == 0) trainDistRed[trainId-1][2] = b.getBlockId(); else trainDistGreen[trainId-1][2] = b.getBlockId(); //System.out.println("on block: "+b.getBlockId()); redraw(b.getBlockId()); break; } else { if(getLineColor() == 0) trainDistRed[trainId-1][1] += blockLength; else trainDistGreen[trainId-1][1] += blockLength; newDist -= blockLength; b.setTrainDetected(false); if(getLineColor() == 0) trainDistRed[trainId-1][2] = trackObject.getBlock((int)trainDistRed[trainId-1][2]).getPrevBlockId(); else trainDistGreen[trainId-1][2] = trackObject.getBlock((int)trainDistGreen[trainId-1][2]).getPrevBlockId(); } } }
d869e119-8524-4a48-819f-538191a72087
1
public boolean InsertarDetallePunto(DetallePunto p){ if (p!=null) { cx.Insertar(p); return true; }else { return false; } }
e15a4eab-613f-437d-a818-7cf6019835b6
8
private static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset, int options) { // Lots of error checking and exception throwing if (source == null) { throw new NullPointerException("Source array was null."); } // end if if (destination == null) { throw new NullPointerException("Destination array was null."); } // end if if (srcOffset < 0 || srcOffset + 3 >= source.length) { throw new IllegalArgumentException( String.format( "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset)); } // end if if (destOffset < 0 || destOffset + 2 >= destination.length) { throw new IllegalArgumentException( String.format( "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset)); } // end if byte[] DECODABET = getDecodabet(options); // Example: Dk== if (source[srcOffset + 2] == EQUALS_SIGN) { // Two ways to do the same thing. Don't know which way I like best. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 // ) // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12); destination[destOffset] = (byte) (outBuff >>> 16); return 1; } // Example: DkL= else if (source[srcOffset + 3] == EQUALS_SIGN) { // Two ways to do the same thing. Don't know which way I like best. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 // ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12) | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6); destination[destOffset] = (byte) (outBuff >>> 16); destination[destOffset + 1] = (byte) (outBuff >>> 8); return 2; } // Example: DkLE else { // Two ways to do the same thing. Don't know which way I like best. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 // ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12) | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6) | ((DECODABET[source[srcOffset + 3]] & 0xFF)); destination[destOffset] = (byte) (outBuff >> 16); destination[destOffset + 1] = (byte) (outBuff >> 8); destination[destOffset + 2] = (byte) (outBuff); return 3; } } // end decodeToBytes
4d30ee60-2ab9-4c9b-94eb-a215daf8fe72
2
public boolean isDescendantOf(TreeContainerRow row) { TreeContainerRow parent = mParent; while (parent != null) { if (parent == row) { return true; } parent = parent.mParent; } return false; }
707b98e3-735d-46bb-a5e6-45ad897f9931
7
private void handlePHPRequest(HttpExchange exchange, String path) throws IOException { String hasil = ""; String phpHome = cliCommand; Headers responseHeaders = exchange.getResponseHeaders(); responseHeaders.set("Content-Type", "text/html"); exchange.sendResponseHeaders(200, 0); OutputStream responseBody = exchange.getResponseBody(); System.err.println("Request waktu per " + new java.util.Date().getHours() + ":" + new java.util.Date().getMinutes() + ":" + new java.util.Date().getSeconds()); File f1 = new File(path); if(f1.exists()) { String stringResult = new PHPSourceParser().getResultRunCompiledPHPCode(path); PHPExecEngine engine = new PHPExecEngine() { @Override public void beforeExecute(PHPExecEngine engine) { } @Override public void afterExecute(PHPExecEngine engine) { } }; String phpResult = engine.getResultExec(phpHome + " \" " + stringResult + " \""); try { hasil = new AppClient().getResultRMIClient(phpResult); } catch(RemoteException ex) { String stackTrace = ""; for(int i = 1; i < ex.getStackTrace().length; i++) { stackTrace += ex.getStackTrace()[i] + "<br/>"; } hasil = ResponseConstant.internalServerError("Internal Server Error", stackTrace); } catch(NotBoundException ex) { String stackTrace = ""; for(int i = 1; i < ex.getStackTrace().length; i++) { stackTrace += ex.getStackTrace()[i] + "<br/>"; } hasil = ResponseConstant.internalServerError("Internal Server Error", stackTrace); } } else { String notFound = ResponseConstant.notFound; responseBody.write(notFound.getBytes()); } try { responseBody.write(hasil.getBytes()); } finally { if(responseBody != null) { responseBody.flush(); responseBody.close(); } if(exchange != null) { exchange.close(); } } }
d2199d4a-39ed-4f25-822d-202859fa7288
8
private Element CreateRows() { Element rows = doc.createElement("rows"); for (int rdx=0; rdx < dataGrid.Rows(); rdx++) { Element row = doc.createElement("row"); Element header = doc.createElement("row-header"); header.appendChild(doc.createTextNode(dataGrid.getRowLabel(rdx))); row.appendChild(header); for (int cdx=0; cdx < dataGrid.Cols(); cdx++) { Element item = doc.createElement("col"); String str = dataGrid.getItem(rdx, cdx).asText().equals("null") ? "*" : dataGrid.getItem(rdx, cdx).asText(); item.appendChild(doc.createTextNode(str)); row.appendChild(item); } if (dataGrid.getRowSummarys().size() > 0) { Element item = doc.createElement("col"); String str = dataGrid.getRowSummaryItem(rdx).asText().equals("null") ? "*" : dataGrid.getRowSummaryItem(rdx).asText(); item.appendChild(doc.createTextNode(str)); row.appendChild(item); } rows.appendChild(row); } if (dataGrid.getColSummarys().size() > 0) { Element row = doc.createElement("row-summary"); Element header = doc.createElement("summary-header"); header.appendChild(doc.createTextNode(dataGrid.getColSummaryLabel())); row.appendChild(header); Integer total = 0; for (int cndx=0; cndx < dataGrid.getColSummarys().size(); cndx++) { Element item = doc.createElement("summary-item"); item.appendChild(doc.createTextNode(dataGrid.getColSummarys().get(cndx).asText())); row.appendChild(item); total += dataGrid.getColSummarys().get(cndx).asInteger(); } if (dataGrid.getRowSummarys().size() > 0) { Element item = doc.createElement("summary-item"); item.appendChild(doc.createTextNode(total.toString())); row.appendChild(item); } rows.appendChild(row); } return rows; }
bfa934df-806c-4b16-ad05-a53df683b0e8
4
public static void handleEnableAsyncMetadataMethod(HTSMsg msg, HTSPServerConnection conn, HTSPMonitor monitor) throws IOException { Collection<String> requiredFields = Arrays.asList(new String[]{}); if (msg.keySet().containsAll(requiredFields)){ HTSMsg reply = new HTSMsg(); handleExtraFields(msg,reply); conn.send(reply); for(HTSMsg tag:monitor.getAllTags()){ tag.remove("members"); conn.send(tag); } for (HTSMsg channel:monitor.getAllChannels()){ conn.send(channel); } for(HTSMsg tag:monitor.getAllTags()){ tag.put("method", "tagUpdate"); conn.send(tag); } //TODO (send dvr) conn.send(new HTSMsg("initialSyncCompleted")); } else{ System.out.println("Faulty request"); } }
85c8d8e7-5f14-43f8-a89f-278340fa793f
0
public String getSourceLine() { return sourceLine; }
786b90f7-f623-4fac-8dc2-9520a2724b64
5
@Override public void mouseReleased(MouseEvent me) { if (echiquier.getPieceCase(this.pInit) != null) { if (me.getPoint().x < 800 && me.getPoint().y < 800) { if (this.echiquier.deplacerPiece(echiquier.getPieceCase(this.pInit), ((ChessFrame) this.fenetre).getCoord(me.getPoint()))) { ((ChessFrame) this.fenetre).changeDisplayJoueur(); } } } if (((ChessFrame) this.fenetre).getChessPiece() != null) { ((ChessFrame) this.fenetre).dropIcon(me.getPoint()); } ((ChessFrame) this.fenetre).afficherEchiquier(this.echiquier.getVue()); ((ChessFrame) this.fenetre).restoreBackGround(); }
4e1d0f2a-a208-4e7f-b9d2-30859f0e0ab9
5
@SuppressWarnings({ "unchecked", "rawtypes" }) public StartDialog(final PacketFactoryInterface pf, Status statusParam) { this.status = statusParam; setResizable(false); setModalityType(ModalityType.APPLICATION_MODAL); setTitle("Start Game"); setBounds(BORDER, BORDER, BORDER2, BORDER3); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new EmptyBorder(PANELSIZE, PANELSIZE, PANELSIZE, PANELSIZE)); getContentPane().add(contentPanel, BorderLayout.CENTER); lblStatus = new JLabel(""); comboBox = new JComboBox(); comboBox.setModel(new DefaultComboBoxModel(PointCalculationStrategy.Strategy.values())); JLabel lblNewLabel = new JLabel("Point Calculation:\r\n"); lblNewLabel.setHorizontalAlignment(SwingConstants.RIGHT); JLabel lblStartingRound = new JLabel("Starting Round:"); lblStartingRound.setHorizontalAlignment(SwingConstants.RIGHT); spinner = new JSpinner(); spinner.setModel(new SpinnerNumberModel(1, 1, MAXFORECAST, 1)); GroupLayout glContentPanel = new GroupLayout(contentPanel); glContentPanel.setHorizontalGroup(glContentPanel.createParallelGroup(Alignment.LEADING).addComponent(lblStatus, GroupLayout.PREFERRED_SIZE, SPACE, GroupLayout.PREFERRED_SIZE).addGroup(glContentPanel.createSequentialGroup().addContainerGap().addGroup(glContentPanel.createParallelGroup(Alignment.LEADING, false).addComponent(lblStartingRound, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(lblNewLabel, GroupLayout.DEFAULT_SIZE, SPACE2, Short.MAX_VALUE)).addPreferredGap(ComponentPlacement.RELATED).addGroup(glContentPanel.createParallelGroup(Alignment.LEADING).addComponent(spinner, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, SPACE4, Short.MAX_VALUE).addComponent(comboBox, 0, SPACE3, Short.MAX_VALUE)).addContainerGap())); glContentPanel.setVerticalGroup(glContentPanel.createParallelGroup(Alignment.TRAILING).addGroup(glContentPanel.createSequentialGroup().addContainerGap().addGroup(glContentPanel.createParallelGroup(Alignment.BASELINE).addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addComponent(lblNewLabel)).addGap(SPACE6).addGroup(glContentPanel.createParallelGroup(Alignment.BASELINE).addComponent(spinner, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addComponent(lblStartingRound)).addPreferredGap(ComponentPlacement.RELATED, SPACE5, Short.MAX_VALUE).addComponent(lblStatus))); contentPanel.setLayout(glContentPanel); { JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { okButton = new JButton("Start!"); okButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { reset(); try { pf.sendStartGamePacket((Strategy) comboBox.getSelectedItem(), (Integer) spinner.getValue()); switch (status.waitForStatus()) { case FAIL: lblStatus.setForeground(Color.RED); lblStatus.setText(status.getText()); break; case SUCCESS: result = Result.OK; dispose(); break; case TIMEOUT: lblStatus.setForeground(Color.RED); lblStatus.setText("TIMEOUT"); break; } } catch (IOException e1) { lblStatus.setForeground(Color.RED); lblStatus.setText("Connection failure!"); } catch (InterruptedException e1) { lblStatus.setForeground(Color.RED); lblStatus.setText("Interrrupted while waiting for answer!"); } } }); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } { JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { result = Result.CANCEL; dispose(); } }); cancelButton.setActionCommand("Cancel"); buttonPane.add(cancelButton); } } }
966b3098-7193-442d-80bf-b663b5b9d17f
5
public boolean match(Sim_event ev) { if (ev == null) { return false; } boolean result = false; try { // find an event with a matching tag first if ( tag_ == ev.get_tag() ) { Object obj = ev.get_data(); // if the event's data contains the correct data if (obj instanceof Object[]) { Object[] array = (Object[]) obj; // if the data contains the correct ID or value Integer intObj = (Integer) array[0]; if (intObj.intValue() == eventID_) { result = true; } } } } catch (Exception e) { result = false; } return result; }
aead856d-a3cf-4d4c-ab9b-90ac53d5c35e
4
public Game.PlayerTurn[][] getGridArray() { boolean test = false; if (test || m_test) { System.out.println("FileManager :: getGridArray() BEGIN"); } if (test || m_test) { System.out.println("FileManager :: getGridArray() END"); } return m_gridArray; }
54d561e3-9afe-4f40-bf27-37d3c9a076e2
2
public void actionPerformed(ActionEvent event) { if(event.getActionCommand().equals(zoomIn.getActionCommand())){ parent.zoomIn(); } else if(event.getActionCommand().equals(zoomOut.getActionCommand())){ parent.zoomOut(); } }
f2bb27e8-413a-49f6-aeaa-b302d5894b0e
0
@Test @Ignore // Callback ordering is not supported public void runTestOrdering1() throws IOException { InfoflowResults res = analyzeAPKFile("Callbacks_Ordering1.apk"); Assert.assertNotNull(res); Assert.assertEquals(0, res.size()); }
e6705f9a-6469-4f2c-b452-90b6651f609d
8
public boolean generate(World par1World, Random par2Random, int par3, int par4, int par5) { for (int var6 = 0; var6 < 20; ++var6) { int var7 = par3 + par2Random.nextInt(4) - par2Random.nextInt(4); int var8 = par4; int var9 = par5 + par2Random.nextInt(4) - par2Random.nextInt(4); if (par1World.isAirBlock(var7, par4, var9) && (par1World.getBlockMaterial(var7 - 1, par4 - 1, var9) == Material.water || par1World.getBlockMaterial(var7 + 1, par4 - 1, var9) == Material.water || par1World.getBlockMaterial(var7, par4 - 1, var9 - 1) == Material.water || par1World.getBlockMaterial(var7, par4 - 1, var9 + 1) == Material.water)) { int var10 = 2 + par2Random.nextInt(par2Random.nextInt(3) + 1); for (int var11 = 0; var11 < var10; ++var11) { if (Block.reed.canBlockStay(par1World, var7, var8 + var11, var9)) { par1World.setBlock(var7, var8 + var11, var9, Block.reed.blockID); } } } } return true; }
2ca3350a-f2b0-48d9-8828-b11b1cec5de7
6
public void realEnvido(boolean envido, boolean envidoEnvido, Humano jugadorH, Contador contador, boolean mentir){ System.out.println("\n"+this.getNombre()+": Real Envido"); ArrayList<Boolean> respuesta = new ArrayList<Boolean>(); respuesta = jugadorH.cantoRealEnvido(envido, envidoEnvido, contador, this, mentir); //COndicional para ver si se canto falta envido o no if(!(respuesta.get(1))){ //Verifico respuesta humano if(respuesta.get(0)){ System.out.println(jugadorH.getNombre()+": Quiero"); int puntosMaquina = this.puntosMano(); int puntosHumano = jugadorH.obtenerPutnos(); System.out.println("\n"+this.getNombre()+": "+puntosMaquina+" puntos"); System.out.println(jugadorH.getNombre()+": "+puntosHumano+" puntos"); //Verifico que el humano no cante mal los puntos if(!(puntosHumano==-1)){ if(puntosMaquina<puntosHumano){ contador.sumarPuntos(jugadorH, contador.realEnvioQuerido(envido, envidoEnvido)); }else if(puntosMaquina>puntosHumano){ contador.sumarPuntos(this, contador.realEnvioQuerido(envido, envidoEnvido)); }else{ if(this.isMano()){ contador.sumarPuntos(this, contador.realEnvioQuerido(envido, envidoEnvido)); }else{ contador.sumarPuntos(jugadorH, contador.realEnvioQuerido(envido, envidoEnvido)); } } }else{ System.out.println("Error "+jugadorH.getNombre()+". Puntos mal cantados, rabón perdido."); contador.sumarPuntos(this, 2); contador.sumarPuntos(this, contador.realEnvioQuerido(envido, envidoEnvido)); this.setManoGanada(2); } }else{ System.out.println(jugadorH.getNombre()+": No Quiero"); contador.sumarPuntos(this, contador.realEnvidoNoQuerido(envido, envidoEnvido)); } } }
ae21a94c-134c-401c-a14d-b7d4efde9f94
5
private static int getPresidence(char inf) throws NotInfix{ /* * Presidence table: * + 0 * - 1 * * 2 * / 3 * ^ 4 */ switch( inf ){ case '+' : return 0; case '-' : return 1; case '*' : return 2; case '/' : return 3; case '^' : return 4; default: throw new NotInfix( inf ); } }
8a119d2b-572c-449e-973d-6e3f506f1123
6
private static void exportPricesCSV() { StringBuilder sb = new StringBuilder(); sb.append("id;price;Typ;Set;Itemname;Level;Stars;Useful;Armortype;"); sb.append("\n"); for (Shoes s : shoes) { String x = s.getPrice() + ""; x = x.replace(".", ","); sb.append(s.getId() + ";" + x + ";Shoes;" + s.getItemset().getName() + ";" + s.getName() + ";" + s.getLevel() + ";" + s.getStars() + ";" + s.getItemset().getUsefulChars() + ";" + s.getTyp()); sb.append("\n"); } for (Pants s : pants) { String x = s.getPrice() + ""; x = x.replace(".", ","); sb.append(s.getId() + ";" + x + ";Pants;" + s.getItemset().getName() + ";" + s.getName() + ";" + s.getLevel() + ";" + s.getStars() + ";" + s.getItemset().getUsefulChars() + ";" + s.getTyp()); sb.append("\n"); } for (Gloves s : gloves) { String x = s.getPrice() + ""; x = x.replace(".", ","); sb.append(s.getId() + ";" + x + ";Gloves;" + s.getItemset().getName() + ";" + s.getName() + ";" + s.getLevel() + ";" + s.getStars() + ";" + s.getItemset().getUsefulChars() + ";" + s.getTyp()); sb.append("\n"); } for (Armor s : armors) { String x = s.getPrice() + ""; x = x.replace(".", ","); sb.append(s.getId() + ";" + x + ";Armor;" + s.getItemset().getName() + ";" + s.getName() + ";" + s.getLevel() + ";" + s.getStars() + ";" + s.getItemset().getUsefulChars() + ";" + s.getTyp()); sb.append("\n"); } for (Helm s : helms) { String x = s.getPrice() + ""; x = x.replace(".", ","); sb.append(s.getId() + ";" + x + ";Helm;" + s.getItemset().getName() + ";" + s.getName() + ";" + s.getLevel() + ";" + s.getStars() + ";" + s.getItemset().getUsefulChars() + ";" + s.getTyp()); sb.append("\n"); } try { File outd = new File("data" + File.separator); outd.mkdirs(); BufferedWriter out = new BufferedWriter( new OutputStreamWriter(new FileOutputStream("data" + File.separator + "prices.csv"), "UTF-8")); out.write(sb.toString()); out.close(); } catch (Exception e) { e.printStackTrace(); } }
1cab3a5c-ff0a-49f6-8e3d-a78872a5b864
2
public Iterator getChilds() { final Iterator fieldIter = fieldIdents.iterator(); final Iterator methodIter = methodIdents.iterator(); return new Iterator() { boolean fieldsNext = fieldIter.hasNext(); public boolean hasNext() { return fieldsNext ? true : methodIter.hasNext(); } public Object next() { if (fieldsNext) { Object result = fieldIter.next(); fieldsNext = fieldIter.hasNext(); return result; } return methodIter.next(); } public void remove() { throw new UnsupportedOperationException(); } }; }
b4aed054-e0e8-40e9-b606-4c4d2dd6d062
2
public static void reloadChannels() { if (ChannelsFile == null) { ChannelsFile = new File(PlayerChat.plugin.getDataFolder(), "channels.yml"); } Channels = YamlConfiguration.loadConfiguration(ChannelsFile); InputStream defConfigStream = PlayerChat.plugin.getResource("channels.yml"); if (defConfigStream != null) { YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream); Channels.setDefaults(defConfig); } }
2b3c68a1-9a75-4004-af21-05cf2b21ec9c
6
@Override public boolean onLoop( Game game, GameState state, GameInput input, Graphics2D gr ) { long nanosElapsed = state.tick(); time += nanosElapsed; int updateCount = 0; while (time >= frameRate && updateCount < maxUpdates) { game.input( input ); input.clear(); if (!game.isPlaying()) { return false; } state.update(); game.update( state ); if (!game.isPlaying()) { return false; } updateCount++; time -= frameRate; } state.interpolate = getStateInterpolation(); state.forward = state.interpolate * state.seconds; state.backward = state.forward - state.seconds; state.draw(); game.draw( state, gr ); if (yield) { long actualTime = time + state.getElapsedSinceTick(); long remainingTime = frameRate - actualTime; if (remainingTime > 0) { Thread.yield(); } } return true; }
d49037d7-a685-413a-bec4-64b39cf9f533
4
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder out = new StringBuilder(); String line = ""; while ((line = in.readLine()) != null) { double[] v = readDoubles(line); boolean allZero = true; for (int i = 0; i < v.length; i++) if (Math.abs(v[i]) > 1e-10) allZero = false; if (allZero) break; Point2D.Double a = new Point2D.Double(v[0], v[1]); Point2D.Double b = new Point2D.Double(v[2], v[3]); Point2D.Double c = new Point2D.Double(v[4], v[5]); Point2D.Double d = new Point2D.Double(v[6], v[7]); Point2D.Double e = new Point2D.Double(v[8], v[9]); Point2D.Double f = new Point2D.Double(v[10], v[11]); Point2D.Double ac = unit(new Point2D.Double(c.x - a.x, c.y - a.y)); Point2D.Double ab = new Point2D.Double(b.x - a.x, b.y - a.y); Point2D.Double de = new Point2D.Double(e.x - d.x, e.y - d.y); Point2D.Double df = new Point2D.Double(f.x - d.x, f.y - d.y); double k = (de.x * df.y - df.x * de.y) / (ac.x * ab.y - ab.x * ac.y); k = Math.abs(k) / 2; Point2D.Double z = new Point2D.Double(ac.x * k, ac.y * k); Point2D.Double h = new Point2D.Double(z.x + a.x, z.y + a.y); Point2D.Double g = new Point2D.Double(z.x + b.x, z.y + b.y); out.append(f(g, h) + "\n"); } System.out.print(out); }
c848aeb1-c35c-4f42-86c9-0cf983178664
6
@Override protected void randomizeData(Random rng, Battle battle, int position) { for (int i = 0; i < battle.objectCount(); i++) { BattleObject obj = battle.getObject(i); int objValue = obj.getValue(); // If object is an enemy, randomize it. if (obj.getType() == BattleObject.Type.ENEMY && obj.getSide() == 1) { // Only randomize regular viruses; not bosses. if (objValue >= 1 && objValue <= 0xAE) { int enemyFamily = (objValue - 1) / 6; int enemyRank = (objValue - 1) % 6; // Do not randomize Rare viruses. if (enemyRank <= 3) { // Choose a random family but keep the same rank. enemyFamily = rng.nextInt(29); } objValue = enemyFamily * 6 + enemyRank + 1; } } obj.setValue(objValue); } }
91585127-ce50-45da-9f13-44eef9fc8d1b
8
public void pullDataFile(String fileName, Course[][] courses) { int courseNumber = 0, creditHours = 0; String department = "", courseTitle = ""; int semester = 0, course = 0; char grade = 'G'; file = new File(fileName); try { Scanner scan = new Scanner(file); while (scan.hasNext()) { semester = scan.nextInt(); course = scan.nextInt(); department = scan.next(); courseNumber = scan.nextInt(); creditHours = scan.nextInt(); if(fileName.equals("InformationSystems.dat") || fileName.equals("WebDevelopment.dat") || fileName.equals("ComputerScience.dat") || fileName.equals("Database.dat") || fileName.equals("Networks.dat") || fileName.equals("SoftwareEngineering.dat")) { courseTitle = scan.nextLine(); } else { String temp = scan.next(); grade = temp.charAt(0); courseTitle = scan.nextLine(); } courses[semester][course] = new Course(semester, course, department, courseNumber, creditHours, grade, courseTitle.substring(1, courseTitle.length())); } scan.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } }
3f2b6ba5-76f7-461f-bb17-2c21eb1b0f66
5
public static ArrayList<String> division(int dividend, int divisor) throws NumberFormatException, IOException{ ArrayList<String> pseudographics = new ArrayList<String>(); try{ ArrayList<Integer> digitsInDividend = new ArrayList<Integer>(); ArrayList<Integer> resultByDigits = new ArrayList<Integer>(); boolean negativeSign = isNegativeSign(dividend, divisor); String indent = " "; isDividendLessZero(dividend, divisor, pseudographics); dividend = Math.abs(dividend); divisor = Math.abs(divisor); digitsInDividend = splitIntoDigits(dividend); int firstDivident = digitsInDividend.get(0); int i = 1; int reminder; while(firstDivident < divisor){ if(i >= digitsInDividend.size()){ break; } firstDivident = firstDivident * 10 + digitsInDividend.get(i); i++; } reminder = extractReminder(firstDivident, divisor, resultByDigits, pseudographics); while(i < digitsInDividend.size()){ if(reminder == 0){ reminder = extractReminder(digitsInDividend.get(i), divisor, resultByDigits, pseudographics); i++; } else { reminder = extractReminder((reminder * 10 + digitsInDividend.get(i)), divisor, resultByDigits, pseudographics); i++; } } pseudographics.add(indent + reminder); pseudographics = combineAllResults(pseudographics, resultByDigits, negativeSign, howMuchDigits(divisor)); } catch (ArithmeticException ie) { System.out.println("You mustn't diveded by zero"); System.out.println("Please, re-enter dividend and divisor"); dividend = input("dividend"); divisor = input("divisor"); division(dividend,divisor); } return pseudographics; }
6ba13a9e-3f93-4ab0-ad48-55e1fcfb033a
1
public VCNTreeItem getCurrentTreeItem() { if (editor == null) { return null; } return editor.getTreeItem(); }
f4e567bd-fe90-486f-8cc1-70e3a14cbaeb
3
Features getFeature(int mouseY) { int numFeatures = Features.count(); if (hexSideInPixels <= 0) { return Features.getFeature(0); } int spacing = 2 * hexSideInPixels + internalMarginInPixels; int i = (mouseY - topMargin + internalMarginInPixels / 2) / (spacing); if (i < 0) { return Features.getFeature(0); } if (i >= numFeatures) { return Features.getFeature(numFeatures - 1); } return Features.getFeature(i); }
16cca0c7-b4ae-4101-83ce-fd737214120d
9
public void printAula( String nomAula){ ArrayList<String> atributs = cper.llegirAula(nomUnitat+"-"+nomAula); int t = Integer.parseInt(atributs.get(0)); String n = atributs.get (1); int c = Integer.parseInt (atributs.get(2)); int b = Integer.parseInt (atributs.get(3)); if (t == 1) System.out.println("\nl'aula es de teoria"); else System.out.println("\nl'aula es de laboratori"); System.out.println("els valors actuals de "+n+" son \n capacitat="+c); if (t==1 && b==1) System.out.println(" te projector\n"); if (t==1 && b==0) System.out.println(" no te projector\n"); if (t==0 && b==1) System.out.println(" te material\n"); if (t==0 && b==0) System.out.println(" no te material\n"); }
7cfe2837-7820-45ab-961c-d96b28ef45df
2
public void parse(String row) { String[] strings = StringUtils.splitPreserveAllTokens(row, this.inputDelimiter); if (initSize == -1) { // Not initialized this.initSize = strings.length; } if (initSize != strings.length) { throw new IllegalArgumentException("Wrong column size. Init Size [" + initSize + "] Column Size [" + strings.length + "]"); } clear(); columns = ArrayUtils.stringArrayToCollection(strings); this.row = row; }
7c2f9320-72ae-47cb-bc65-29c8c30be98a
4
public int getVisibleSize() { if ( (visibleVersionsCount < 0) || dataVisibilityChanged) { int len = langVersions.size() ; int vLen = 0 ; // count all visible languages for ( int t = 0 ; t < len ; t++ ) { // System.out.println( "language " +get(t).getFullLanguageName() ) ; if ( get( t ).isVisible() ) vLen++ ; } visibleVersionsCount = vLen ; } return visibleVersionsCount ; }
119f7e26-fe81-4d2c-83d3-fa061cc3c429
7
private boolean checkHealth0(Node node) { try { NioChannel channel = connectionManager.getChannel(node.getHostname(), node.getPort()); if (channel.isOpen()) { if (!node.isOptionsEnabled()) { return true; } // Put the channel in the recycled channel's list buffer.clear(); buffer.put(getRequest(node).getBytes()).flip(); channel.writeBytes(buffer); buffer.clear(); int n = channel.readBytes(buffer); if (n < 0) { throw new ClosedChannelException(); } else { buffer.flip(); byte bytes[] = new byte[n]; buffer.get(bytes); String response = new String(bytes); // Just retrieve the response line String tab[] = response.split("\r\n")[0].split("\\s+"); int status = Integer.valueOf(tab[1]); String phrase = tab[2]; if (status == 200 && "OK".equalsIgnoreCase(phrase)) { connectionManager.recycle(node, channel); return true; } else if (status == 501) { node.setOptionsEnabled(false); connectionManager.recycle(node, channel); return true; } } } else { channel.setOption(StandardSocketOptions.SO_LINGER, 0); channel.close(); return false; } } catch (Throwable th) { // NOPE return false; } return false; }
0cc800da-67d9-4c6a-b469-d9a80096f50e
9
public static void main(String[] args) { ArrayList<Item> shoppingCart = new ArrayList<Item>(); if (args.length != 1) { System.err.println ("Error: Incorrect number of command line arguments"); System.exit(-1); } try { FileReader freader = new FileReader(args[0]); BufferedReader reader = new BufferedReader(freader); for (String s = reader.readLine(); s != null; s = reader.readLine()) { Input currentInput = new Input(s); boolean test = currentInput.getValidInput(); if(test) { String operation = currentInput.getOperation(); if(operation.contentEquals("insert")) { processInsert(shoppingCart, currentInput); } else if(operation.contentEquals("search")) { processSearch(shoppingCart, currentInput); } else if(operation.contentEquals("update")) { processUpdate(shoppingCart, currentInput); } else if(operation.contentEquals("delete")) { processDelete(shoppingCart, currentInput); } else { processPrint(shoppingCart); } } } reader.close(); } catch (FileNotFoundException e) { System.err.println ("Error: File not found. Exiting..."); e.printStackTrace(); System.exit(-1); } catch (IOException e) { System.err.println ("Error: IO exception. Exiting..."); e.printStackTrace(); System.exit(-1); } }
02974d9b-9778-4ffd-8ac6-53c1955673f8
2
@Override public void actionPerformed(ActionEvent event) { if(((JButton) event.getSource()).getText() == "Annuler") { this.grilleCombinaisonJeu.remiseAZeroCombinaisonAffichée(); } if(((JButton) event.getSource()).getText() == "Valider") { this.combinaisonValidee = true ; } }
1f9720ad-8baa-4ded-8b4a-98061abbf42a
4
public void refreshTagSelector() { // Find the tags that were selected before the refresh HashSet<String> previouslySelected = new HashSet<String>(); for (int index : tagSelector.getSelectedIndices()) { if (tagSelector.isSelectedIndex(index)) { previouslySelected.add(tagSelector.getModel().getElementAt( index)); } } tagSelector.clearSelection(); // Refresh the tags in the selection list // Get tags and sort alphabetically Collection<String> tags = Timeflecks.getSharedApplication() .getTaskList().getAllTags(); tagSelectionChoices = new Vector<String>(tags); Collections.sort(tagSelectionChoices); tagSelector.setListData(tagSelectionChoices); tagSelector.clearSelection(); // Select the tags that were selected before for (int i = 0; i < tagSelectionChoices.size(); ++i) { if (previouslySelected.contains(tagSelectionChoices.get(i))) { tagSelector.addSelectionInterval(i, i); } } }
fc29395a-3e09-4f3e-869f-e01750bb99dd
5
private int stripMultipartHeaders(ByteBuffer b, int offset) { int i; for (i = offset; i < b.limit(); i++) { if (b.get(i) == '\r' && b.get(++i) == '\n' && b.get(++i) == '\r' && b.get(++i) == '\n') { break; } } return i + 1; }
dea4e5e7-fca6-49f2-bd4c-bb9aa2cf1a9c
6
private void fillParameters(ServletRequest request, ParameterGraph parameterGraph) { for (Parameter para : parameterGraph.getParmaeters()) { if (para instanceof SimpleParameter) { SimpleParameter simplePara = (SimpleParameter) para; String[] values = request.getParameterValues(para.getName()); simplePara.setValue(values); } else { if (para instanceof ItemParameter) { ItemParameter itemPara = (ItemParameter) para; for (Item item : itemPara.getItems()) { String[] values = request.getParameterValues(item.getName()); item.setValues(values); } } else { TableParameter tablePara = (TableParameter) para; String[] rows = request.getParameterValues(tablePara.getRowName()); String[] columns = request.getParameterValues(tablePara.getColumnName()); String[] dataCells = request.getParameterValues(tablePara.getDataCellName()); int columnSize = columns.length; for (int i = 0; i < rows.length; i++) { for (int j = 0; j < columns.length; j++) { TableParameterElement element = new TableParameterElement(); element.setRow(rows[i]); element.setColumn(columns[j]); element.setDataCell(dataCells[columnSize * i + j]); tablePara.addElement(element); } } } } } }
c5fb496e-cdb7-4342-b963-0a2f6ea55f42
3
public void updateLauncher(){ try { // URL updatePath = new URL(McLauncher.McLauncherPath); // ReadableByteChannel rbc = Channels.newChannel(updatePath.openStream()); // FileOutputStream fos = new FileOutputStream("McLauncher.jar"); // fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); // fos.close(); String fileName = "McLauncher.jar"; //The file that will be saved on your computer URL link = new URL(McLauncher.McLauncherPath); //The file that you want to download InputStream in = new BufferedInputStream(link.openStream()); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int n = 0; while (-1!=(n=in.read(buf))) { out.write(buf, 0, n); } out.close(); in.close(); byte[] response = out.toByteArray(); FileOutputStream fos = new FileOutputStream(fileName); fos.write(response); fos.close(); noteInfo("Update"); JOptionPane.showMessageDialog(null, "Updated launcher, Please re-launch"); //To be changed to auto-launch, once i figure out how. if(McLauncher.tglbtnCloseAfterUpdate.isSelected()){ //close launcher if enabled System.exit(0); } } catch (IOException e) { e.printStackTrace(); } }
7ec2ae4b-3c70-4de3-a261-cca394a2fd1f
3
public void tourDesMonstres(){ if (!fini()){ for (int i=0; i<monstres.recensement(); i++){ Monstre m = (Monstre) monstres.getSoldat(i); if (!m.estMort()){ // Chaque monstre joue... } } /* Reset des paramètres de tour de la map */ nouveauTour(); } }
b0b4d305-44fd-47c1-8fa4-7c952c975812
8
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); String method = Util.nullToString(request.getParameter("method")); if("viewAllUser".equalsIgnoreCase(method)){//for view all admin user page doViewAllUser(request, response); }else if("viewUser".equalsIgnoreCase(method)) {//for view special user page doEditUser(request, response, false); }else if("editUser".equalsIgnoreCase(method)){//for edit special user page doEditUser(request, response, true); }else if("updateUser".equalsIgnoreCase(method)) { //for update special user page doUpdateUser(request,response); }else if("addUser".equalsIgnoreCase(method)) {//for add user page doAddUser(request, response); }else if("saveUser".equalsIgnoreCase(method)) {//for add user page doSaveUser(request, response); }else if("delUser".equalsIgnoreCase(method)) {//for add user page doDelUser(request, response); }else if("checkUser".equalsIgnoreCase(method)) { doCheckUser(request,response); }else{ doViewAllUser(request, response); } }
5759f33c-84c1-46f4-ad4e-a1b79e782b97
0
Point(int x, int y) { this.x = x; this.y = y; }
fcd5e0e1-34ca-4ba5-a362-51ef06740241
7
protected final Statement prepareStatement(Connection conn, String sql) throws SQLException { final int index = sql.indexOf(';'); Statement stmt = (index >= 0) ? conn.prepareStatement(sql.substring(0, index)) : conn.createStatement(); try { if (stmt instanceof PreparedStatement) { PreparedStatement pstmt = (PreparedStatement)stmt; int i = 0; for (String p : sql.substring(index + 1).split(",", -1)) { pstmt.setString(++i, p); } } setTimeout(stmt); final int limit = Bootstrap.getPropertyAsInt("net.argius.stew.rowcount.limit", Integer.MAX_VALUE); if (limit > 0 && limit != Integer.MAX_VALUE) { stmt.setMaxRows(limit + 1); } } catch (Throwable th) { try { if (th instanceof SQLException) { throw (SQLException)th; } throw new IllegalStateException(th); } finally { stmt.close(); } } return stmt; }
e502746b-1139-4bf7-83c6-6ca7575d686f
3
public FlipHash(int cursorX, int cursorY, boolean[][] traversable, boolean[][] board) { this.cursorX = cursorX; this.cursorY = cursorY; this.board = new BitSet(); final int height = board.length; final int width = board[ 0 ].length; int tiles = 0; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if ( traversable[y][x] ) { this.board.set( tiles++, board[y][x] ); } } } }
c56d27ff-cf41-4e92-a525-2cf3cbdb2390
5
public static byte[] convert(boolean[] pieces) { int length = pieces.length / 8; int mod = pieces.length % 8; if(mod != 0){ ++length; } byte[] retVal = new byte[length]; int boolIndex = 0; for (int byteIndex = 0; byteIndex < retVal.length; ++byteIndex) { for (int bitIndex = 7; bitIndex >= 0; --bitIndex) { // Another bad idea if (boolIndex >= pieces.length) { return retVal; } if (pieces[boolIndex++]) { retVal[byteIndex] |= (byte) (1 << bitIndex); } } } return retVal; }
785f5e3b-c566-4445-aea4-9bded6653edd
7
@Override public int compareTo(Hand otherHand) { List<Card> thisHand = getHandValues().get(this); List<Card> thatHand = getHandValues().get(otherHand); if (thisHand == null || thatHand == null) { return 0; } if (thisHand.size() > thatHand.size()) { return 1; } else if (thisHand.size() < thatHand.size()) { return -1; } for (int i = thisHand.size() - 1; i >= 0; --i) { if (thisHand.get(i).getRank().ordinal() < thatHand.get(i).getRank().ordinal()) { return 1; } else if (thisHand.get(i).getRank().ordinal() > thatHand.get(i).getRank().ordinal()) { return -1; } } return 0; }
a2ff1484-6d1b-42f5-96be-9c587326ab46
3
public boolean removeSection(String name) { String normName = normSection(name); if (this.commonName != null && this.commonName.equals(normName)) { throw new IllegalArgumentException("Can't remove common section"); } if (hasSection(normName)) { this.sections.remove(normName); this.sectionOrder.remove(normName); return true; } else { return false; } }
fd465090-daaa-4d94-9f44-cfe995e27f98
1
public void mouseExited(MouseEvent e) { if(getState() == ENABLED) { textColor = "white"; } else { textColor = "gray"; } }
588b6356-c3ea-4c92-accd-9e9edfd8cd7f
6
public static String reverseWords(String s) { StringBuilder result = new StringBuilder(); for (int i = s.length() - 1, end = 0; i >=0 ; i--) { char c = s.charAt(i); if (c != ' ') result.insert(end, c); else if (result.length() > 0 && result.charAt(result.length() - 1) != ' ') { result.append(c); end = result.length(); } } if (result.length() > 0 && result.charAt(result.length() - 1) == ' ') result.deleteCharAt(result.length() - 1); return result.toString(); }
a26b52a0-ea56-41e2-8a82-0d18b91ff0d9
3
public static String unicode(String src) { byte[] bytes = src.getBytes(Charsets.UTF_16);// 转为UTF-16字节数组 int length = bytes.length; if (length > 2) {// 由于转换出来的字节数组前两位属于UNICODE固定标记,因此要过滤掉 int i = 2; StringBuilder sb = new StringBuilder((length - i) * 3); boolean isOdd = false; for (; i < length; i++) { if (isOdd = !isOdd) { sb.append("\\u"); } sb.append(digits[bytes[i] >> 4 & 0xf]); sb.append(digits[bytes[i] & 0xf]); } return sb.toString(); } else { return ""; } }
383ac506-46ad-4617-b3e0-d18a7a4bc9f9
9
public void movePieceOnBoard(String command, Position pieceStart, Position pieceEnd) { String player = whitePlayerTurn() ? "Black" : "White"; int x1 = pieceStart.getPositionX(); int y1 = pieceStart.getPositionY(); int x2 = pieceEnd.getPositionX(); int y2 = pieceEnd.getPositionY(); String startSpot = command.substring(0,2); String endSpot = command.substring(3,5); Piece piece = board.getChessBoardSquare(x1, y1).getPiece(); Square newSquare = new Square(board.getChessBoardSquare(x2, y2).getPiece(), pieceEnd); Pawn dummyPawn = new Pawn("Pawn"); if(piece.getClass() == dummyPawn.getClass()) { if(piece.getPieceColor() == white) { if(dummyPawn.validWhiteMovement(x1, y1, x2, y2, newSquare)) { // getPiecePath(x1, y1, x2, y2); movePieceCheck(piece, x1, y1, x1, y2, pieceStart, pieceEnd, command, startSpot, endSpot); } else if(dummyPawn.pawnCapturing(x1, y1, x2, y2, piece.getPieceColor(), newSquare)) { // getPiecePath(x1, y1, x2, y2); movePieceCheck(piece, x1, y1, x2, y2, pieceStart, pieceEnd, command, startSpot, endSpot); } else { System.out.print(command + " is an invalid move command! Please revise it!"); System.out.println(); } } else if(piece.getPieceColor() == black) { if(dummyPawn.validBlackMovement(x1, y1, x2, y2, newSquare)) { // getPiecePath(x1, y1, x2, y2); movePieceCheck(piece, x1, y1, x1, y2, pieceStart, pieceEnd, command, startSpot, endSpot); } else if(dummyPawn.pawnCapturing(x1, y1, x2, y2, piece.getPieceColor(), newSquare)) { // getPiecePath(x1, y1, x2, y2); movePieceCheck(piece, x1, y1, x2, y2, pieceStart, pieceEnd, command, startSpot, endSpot); } else { System.out.print(command + " is an invalid move command! Please revise it!"); System.out.println(); } } } else { if(piece.validMovement(x1, y1, x2, y2)) { // getPiecePath(x1, y1, x2, y2); movePieceCheck(piece, x1, y1, x2, y2, pieceStart, pieceEnd, command, startSpot, endSpot); } else { System.out.println(); System.out.print(command + " is an invalid move command! Please revise it!"); System.out.println(); } } }
bf8941e4-57fb-4637-9865-7fc0d8022858
8
public String calculateProbs(String url, double parent_score, double div_score, double anchor_score) { String[] data = new String[5]; data[0] = url; String parent, div, anchor; float relevant_yes, relevant_no, temp_parent[], temp_div[], temp_anchor[]; if(parent_score > 0.6) { parent = "yes"; } else { parent = "no"; } if(div_score > 0.2) { div = "yes"; } else { div = "no"; } if(anchor_score > 0.4) { anchor = "yes"; } else { anchor = "no"; } temp_parent = getCount("parent", parent); temp_div = getCount("div", div); temp_anchor = getCount("anchor", anchor); relevant_yes = temp_parent[0]*temp_div[0]*temp_anchor[0]; relevant_no = temp_parent[1]*temp_div[1]*temp_anchor[1]; values temp; if((relevant_yes*p_of_yes) > (relevant_no*p_of_no)) { temp = new values(url, parent, div, anchor, "yes"); valueVector.add(temp); total += 1; no_of_yes += 1; p_of_yes = (float) no_of_yes/total; p_of_no = (float) no_of_no/total; System.out.println(url + "-" + parent + "-" + div + "-" + anchor + "-" + "yes " + "n(yes): " + no_of_yes); try { st = conn.createStatement(); st.executeUpdate("insert into training_set (Id, url, parent, divi, anchor, total_relevancy) values(" + total + ", '" + url + "', '" + parent + "', '" + div + "', ' " + anchor + "', 'yes')" ); } catch(Exception e) { e.printStackTrace(); } return "yes"; } else if((relevant_yes*p_of_yes) < (relevant_no*p_of_no)) { temp = new values(url, parent, div, anchor, "no"); valueVector.add(temp); total += 1; no_of_no += 1; p_of_no = (float) no_of_no/total; p_of_yes = (float) no_of_yes/total; System.out.println(url + "-" + parent + "-" + div + "-" + anchor + "-" + "no " + "n(no): " + no_of_no); try { st = conn.createStatement(); st.executeUpdate("insert into training_set (Id, url, parent, divi, anchor, total_relevancy) values(" + total + ", '" + url + "', '" + parent + "', '" + div + "', ' " + anchor + "', 'no')" ); } catch(Exception e) { e.printStackTrace(); } return "no"; } else { temp = new values(url, parent, div, anchor, "yes"); valueVector.add(temp); total += 1; no_of_yes += 1; p_of_yes = (float) no_of_yes/total; p_of_no = (float) no_of_no/total; System.out.println("In Else.."); System.out.println(url + "-" + parent + "-" + div + "-" + anchor + "-" + "yes " + "n(yes): " + no_of_yes); try { st = conn.createStatement(); st.executeUpdate("insert into training_set (Id, url, parent, divi, anchor, total_relevancy) values(" + total + ", '" + url + "', '" + parent + "', '" + div + "', '" + anchor + "', 'yes')" ); } catch(Exception e) { e.printStackTrace(); } return "yes"; } }
46668245-ad3d-4da1-9bdd-cfa576ab89f7
2
private void loadpos() { if (cap == null) { return; } String name = cap.text; if (storePosSet.contains(name)) { c = new Coord(Config.window_props.getProperty(name + "_pos", c.toString())); return; } }
a4aac2c1-d059-4e63-a4cf-e863e5fabc2f
9
public static void main(String args[]) throws Throwable { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); for(int i=0;i<lAdy.length;i++)lAdy[i]=new ArrayList<Integer>(); for (String ln;(ln=in.readLine())!=null;) { StringTokenizer st=new StringTokenizer(ln); N=parseInt(st.nextToken()); int K=parseInt(st.nextToken()); for(int i=0;i<N;i++)lAdy[i].clear(); int root=0; for(int i=0;i<N;i++) { st=new StringTokenizer(in.readLine()); int desde=parseInt(st.nextToken())-1; if(desde==-1)root=i; else lAdy[desde].add(i); costo[i]=parseInt(st.nextToken()); padre[i]=desde; } int c=0,p=0; pila[c++]=root; for(int u;c>0;) { u=pila[c-1]; nodo[p]=u; posicion[u]=p++; proxPosicion[u]=posicion[u]; c--; for(int v:lAdy[u]) pila[c++]=v; } for(int i=p-1;i>=1;i--) proxPosicion[padre[nodo[i]]]=max(proxPosicion[padre[nodo[i]]],proxPosicion[nodo[i]]); int s=f(K); System.out.println(s<0?"impossible":s); } System.out.print(new String(sb)); }
7641001b-a0dd-4bf5-bad5-22968d42c5f8
7
public static void addThisYear(double meanUtil, double utilStdDev){ supplies.add(City.economy.getSupplyString()); demands.add(City.economy.getDemandString()); prices.add(City.economy.getPriceString()); String popString = new String(City.year + ","); int male = 0; //must divide by pop int[] homeClass = new int[4]; for(Person curr: City.alive){ if (curr.male) male++; homeClass[Home.getRank(curr.home)]++; } popString += City.alive.size() + "," + ((double)male / (double)City.alive.size())+","+meanUtil+","+utilStdDev+","; for(int i = 0; i<4;i++){ popString += homeClass[i] == 0?",":homeClass[i] + ","; //leave cells with 0 buildings empty. } population.add(popString.trim()); corpClass = new int[Factory.samples.size()]; //running count of corps by type. String corpString = new String(City.year + ","); for(Corporation aCorp:City.allCorps){ if (aCorp.holding.ordinal >= 0){ corpClass[aCorp.holding.ordinal]++; } } for(int i = 0; i<Factory.samples.size();i++){ corpString += corpClass[i] + ","; } corps.add(corpString.trim()); }
f94beec1-abba-400f-b9f4-7ed7d88e37f6
0
public static void f(MyIncrement mi) { mi.increment(); }
daba515b-3ce5-4120-86b8-e3dae299836f
9
public void drawGameOver() { Graphics2D g = image.createGraphics(); int mX = 0; int mY = 0; if ( getMousePosition() != null ) { mX = (int)getMousePosition().getX(); mY = (int)getMousePosition().getY(); } g.setColor( Color.black ); g.fillRect( 0, 0, 800, 600 ); g.setFont( new Font( "Bradley Hand ITC", Font.BOLD, 72) ); g.setColor( Color.red.darker().darker() ); g.drawString( "GAME OVER", 180, 125 ); g.setColor( Color.white ); g.setFont( new Font( "Bradley Hand ITC", Font.BOLD, 60) ); g.drawString( "Play Again?", 225, 275 ); g.setFont( new Font( "Bradley Hand ITC", Font.BOLD, 45) ); g.setColor( (mX>300 && mX<370 && mY<360 && mY > 320)? Color.darkGray:Color.white ); g.drawString( "Yes", 300, 350 ); g.setColor( Color.white ); g.drawString( "/", 375, 350 ); g.setColor( (mX>395 && mX<450 && mY<360 && mY > 320)? Color.darkGray:Color.white ); g.drawString( "No", 395, 350 ); g.setColor( Color.white ); g.drawString( continues + " Continues", 10, 595 ); g.dispose(); }
ec5ab585-6f9b-4f43-bebc-1f2f54860f98
4
public ListNode reverseBetween(ListNode head, int m, int n) { ListNode dummy = new ListNode(0); ListNode p = dummy; dummy.next = head; int i = 1; while(p.next != null && i < m){ p = p.next; ++i; } ListNode back = p.next; ListNode pp = p; while(pp.next != null && i <= n){ pp = pp.next; ++i; } ListNode left = pp.next; pp.next = null; ListNode r = reverse(back); p.next = r; back.next = left; return dummy.next; }
a23a2c7d-09fd-4be4-b084-faafe9f66738
0
public senseDir getSenseDirVal() { return senseDirVal; }
27406d2c-9d47-4eca-bf81-2bfc11bb4b1c
4
public void init() throws RemoteException { for (ICamera camera : serverProxy.getCameras()) { if (cCameraUser == null || (!camera.getOwnerName().equals( cCameraUser.getOwnerName()))) { CCamera cCamera = new CCamera((ACamera) camera, serverProxy, "http://espacezives.free.fr/pyramid.wrl"); cCameras.put(cCamera.getOwnerName(), cCamera); presentation.add(cCamera.getPresentation()); cCamera.refresh(); } } for (IObject object : serverProxy.getObjects()) { CObject cObject = new CObject((AObject) object, serverProxy); cObjects.put(cObject.getName(), cObject); presentation.add(cObject.getPresentation()); cObject.refresh(); } }
edde0593-0af5-45ee-b420-6b29d6e281e5
1
public PlanBoeseKrieg(JSONObject object) throws FatalError { super(object, "BoeseKrieg"); if (PlanBoeseKrieg.list == null) { PlanBoeseKrieg.list = new OpponentList(); } }
92250c53-ba9f-4760-aee3-2f9d01b0aa3a
9
static byte WallSignFix(byte data, String kierunek) { if (kierunek.equals("right")) { if (data == 2) { return 5; } if (data == 4) { return 2; } if (data == 5) { return 3; } if (data == 3) { return 4; } } else { if (data == 5) { return 2; } if (data == 2) { return 4; } if (data == 3) { return 5; } if (data == 4) { return 3; } } return data; }
cfed1797-4563-4e7b-9df8-41a58b06e1cb
3
private int getNumberOfAlive(int time){ if (vectors[0][0] == null){ return vectors[0].length; } int res = 0; for (Vector vector: vectors[time]){ if (vector.getBeing().isHuman()){ res++; } } return res; }
e641199d-da85-4400-a70d-374c88041959
3
public void updateArchive(Archive archive) { dull = true; CacheIndice indice = cache.getIndice(0); try { if (archive == interfaces) { byte[] interfaceData = RSInterface.getData(); archive.updateFile(archive.indexOf("data"), interfaceData); byte[] data = archive.recompile(); indice.updateFile(3, data); } if (archive == media) { byte[] data = mediaArchive.imageArchive.repackArchive(); indice.updateFile(4, data); } cache.rebuildCache(); JOptionPane.showMessageDialog(this, "Archive repacked successfully."); } catch (Exception e) { JOptionPane.showMessageDialog(this, "An error occurred while repacking the archive."); e.printStackTrace(); } dull = false; }
846fa540-c82c-4beb-a50b-ca72ee275c01
1
public void shiftRight() { if(currentIndex < galleryImageIcons.size() - 1) { PopImage.view.setImageIcon(galleryImageIcons.get(++currentIndex)); } }
4341265c-60f0-4ca0-a1c3-3d2152c48d67
0
public Ambient(){}
1db373c5-ba9f-45d7-8734-c36975a8a9e4
7
protected LoginResult charcrANSIDone(final LoginSessionImpl loginObj, final Session session) { final MOB mob=loginObj.mob; session.setMob(loginObj.mob); if((session.getClientTelnetMode(Session.TELNET_MSP)) &&(!CMSecurity.isDisabled(CMSecurity.DisFlag.MSP))) mob.setAttribute(MOB.Attrib.SOUND,true); if((session.getClientTelnetMode(Session.TELNET_MXP)) &&(!CMSecurity.isDisabled(CMSecurity.DisFlag.MXP))) mob.setAttribute(MOB.Attrib.MXP,true); executeScript(mob,getLoginScripts().get("ANSI")); final int themeCode=CMProps.getIntVar(CMProps.Int.MUDTHEME); switch(themeCode) { case Area.THEME_FANTASY: case Area.THEME_HEROIC: case Area.THEME_TECHNOLOGY: loginObj.theme=themeCode; loginObj.state=LoginState.CHARCR_THEMEDONE; break; default: loginObj.state=LoginState.CHARCR_THEMESTART; break; } return null; }
3af87b6b-fcf2-4511-9272-426a8e6d878f
9
public static void check(List<TableEntity> tables) { for (TableEntity table : tables) { List<ColumnEntity> c = table.columns; for (RecordEntity record : table.records) { List<String> e = record.expecteds; List<String> a = record.actuals; if (c.size() != e.size()) { logger.error("expected record size and column size of table [{}][{}] are not matching", table.sheetName, table.name); logger.error("expected record size [{}], column size [{}]", e.size(), c.size()); } if (record.isExisingRecord && (e.size() != a.size())) { logger.error("expected record size and actual record size of table [{}][{}] are not matching", table.sheetName, table.name); logger.error("expected record size [{}], actual record size [{}]", e.size(), a.size()); } for (int i=0; i<e.size(); i++) { if (StringUtils.equals(e.get(i), a.get(i)) || (StringUtils.isEmpty(e.get(i)) && StringUtils.isEmpty(a.get(i)))) { logger.debug("expected [{}] and actual [{}]", e.get(i), a.get(i)) ; } else { logger.error("expected [{}] but actual [{}]", e.get(i), a.get(i)); } } } } }
8e6f6b80-37fb-444f-b49e-e04cb72568a1
4
public static void main(String[] args){ int i = 999; int j = 999; int kaibun; for(i = 999; i > 0; i--) { kaibun = (1000 * i) +(100 * (i % 10)) + (10 * ((i / 10) % 10)) + (1 * ((i / 100) % 10)); for(j = 999; j > 0; j--) { if((kaibun % j == 0) && (kaibun / j) < 1000) { System.out.println("Answer:" + kaibun); return; } } } }
dd793763-acbc-4290-9884-7baf75785bd6
6
public void disconnect() { if (socket != null) { try { socket.close(); } catch (IOException e) { // ignore } socket = null; } if (input != null) { try { input.close(); } catch (IOException e) { // ignore } } if (output != null) { try { output.close(); } catch (IOException e) { // ignore } } }
9e03bb52-0fad-407b-bbb2-d8eec31fa888
9
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NotifiedMethodInvocationReport that = (NotifiedMethodInvocationReport) o; if (invocation != null ? !invocation.equals(that.invocation) : that.invocation != null) return false; if (returnedValue != null ? !returnedValue.equals(that.returnedValue) : that.returnedValue != null) return false; if (throwable != null ? !throwable.equals(that.throwable) : that.throwable != null) return false; return true; }
128e6e8a-fdb7-483e-8992-52485356ae54
5
public ArrayList<Object> ifGift(SalesReceiptPO receipt){ ArrayList<Object> returnPromotions=new ArrayList<Object>(); for(PromotionPO p:promotions){ if(p.getPromotionType()==PromotionSort.Gifts){ if(receipt.getFinalprice()>=p.getLeastPrice() &&checkDateValid(receipt.getSerialNumber(), p) &&checkCustomerValid(receipt.getCustomerPO(), p.getCustomer())){ returnPromotions.add(p); } } } return returnPromotions; }
cceb8e40-520e-402f-8e38-c4155a494080
1
@Override public List<Integer> save(List<TransMode> beans, GenericSaveQuery saveGeneric, Connection conn) throws DaoQueryException { try { return saveGeneric.sendQuery(SAVE_QUERY, conn, Params.fill(beans, (TransMode bean) -> { Object[] objects = new Object[1]; objects[0] = bean.getNameMode(); return objects; })); } catch (DaoException ex) { throw new DaoQueryException(ERR_TRANSMODE_SAVE, ex); } }
c6d9f9b7-143a-4ea4-87de-e8041c3cb227
2
private xAuthPlayer loadPlayer(String playerName) { Connection conn = plugin.getDbCtrl().getConnection(); PreparedStatement ps = null; ResultSet rs = null; try { String sql = String.format("SELECT `id` FROM `%s` WHERE `playername` = ?", plugin.getDbCtrl().getTable(Table.ACCOUNT)); ps = conn.prepareStatement(sql); ps.setString(1, playerName); rs = ps.executeQuery(); if (!rs.next()) return null; return new xAuthPlayer(playerName, rs.getInt("id")); } catch (SQLException e) { xAuthLog.severe(String.format("Failed to load player: %s", playerName), e); return null; } finally { plugin.getDbCtrl().close(conn, ps, rs); } }
3013eb85-11c0-4ae0-a928-cd3da26ccaba
0
public Clock(BufMgr javamgr) { super(javamgr); }
482bbe09-9265-447f-95c7-8451f4be5ef1
5
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof ItemPropertyValue)) { return false; } ItemPropertyValue other = (ItemPropertyValue) object; if ((this.itemPropertyValuePK == null && other.itemPropertyValuePK != null) || (this.itemPropertyValuePK != null && !this.itemPropertyValuePK.equals(other.itemPropertyValuePK))) { return false; } return true; }
a159c8c0-c5d1-4431-a1e7-4503ff356733
6
public boolean insertSkillSet(UserSkillSet userSkillSet) { Connection connection = new DbConnection().getConnection(); PreparedStatement preparedStatement = null; boolean flag = false; List<SkillRating> skillRatings = userSkillSet.getSkills(); Iterator<SkillRating> iterator = skillRatings.iterator(); try { while (iterator.hasNext()) { SkillRating skillRating = iterator.next(); preparedStatement = connection .prepareStatement(INSERT_EMPLOYEE_SKILLS); preparedStatement.setString(1, userSkillSet.getUserId()); preparedStatement.setInt(2, CommonUtil.getSkillId(skillRating.getSkillName())); preparedStatement.setInt(3, skillRating.getRatingId()); preparedStatement.setString(4, skillRating.getGivenBy()); preparedStatement.executeUpdate(); String employeeId = userSkillSet.getUserId(); String givenBy = skillRating.getGivenBy(); if (employeeId.equals(givenBy)) insertSkillScore(employeeId, skillRating.getSkillName(), skillRating.getRatingId()); else updateSkillScore(employeeId, skillRating.getSkillName(), skillRating.getRatingId()); } flag = true; } catch (SQLException e) { m_logger.error(e.getMessage(), e); } finally { try { if (connection != null) connection.close(); if (preparedStatement != null) preparedStatement.close(); } catch (SQLException e) { m_logger.error(e.getMessage(), e); } } return flag; }
adf96569-ab64-4a5e-9d31-5a5429746173
9
WordDescription(XMLStreamReader reader){ WordType type = null; Pattern endsWithPattern = null; String value = null; String functionalGroupType = null; String endsWithGroupValueAtr = null; String endsWithGroupType = null; String endsWithGroupSubType = null; for (int i = 0, l = reader.getAttributeCount(); i < l; i++) { String atrName = reader.getAttributeLocalName(i); String atrValue = reader.getAttributeValue(i); if (atrName.equals("type")){ type = WordType.valueOf(atrValue); } else if (atrName.equals("value")){ value = atrValue; } else if (atrName.equals("functionalGroupType")){ functionalGroupType = atrValue; } else if (atrName.equals("endsWithRegex")){ endsWithPattern = Pattern.compile(atrValue +"$", Pattern.CASE_INSENSITIVE); } else if (atrName.equals("endsWithGroupValueAtr")){ endsWithGroupValueAtr = atrValue; } else if (atrName.equals("endsWithGroupType")){ endsWithGroupType = atrValue; } else if (atrName.equals("endsWithGroupSubType")){ endsWithGroupSubType = atrValue; } } if (type == null) { throw new RuntimeException("Malformed wordRules"); } this.type = type; this.endsWithPattern = endsWithPattern; this.value = value; this.functionalGroupType = functionalGroupType; this.endsWithGroupValueAtr = endsWithGroupValueAtr; this.endsWithGroupType = endsWithGroupType; this.endsWithGroupSubType = endsWithGroupSubType; }
f97ff6ab-b235-42a3-93d9-7cd84a20ff7b
0
public void setX(int x) { this.x = x; }
40be695e-e3ce-4558-8c6a-fcb05e9b5f41
0
public void set(float value) { increase = value > dValue; this.value = value; }
0fb5d42a-979a-48d5-971d-74474c84201e
8
private static boolean isID(String word) { boolean flag = false; int i = 0; if (Word.isKey(word)) return flag; char temp = word.charAt(i); if (isLetter(temp) || temp == '_') { for (i = 1; i < word.length(); i++) { temp = word.charAt(i); if (isLetter(temp) || temp == '_' || isDigit(temp)) continue; else break; } if (i >= word.length()) flag = true; } else return flag; return flag; }
18c32df3-e9e6-47a2-9a5f-db2b7efee934
0
public void setLibelle(String libelle) { this.libelle = libelle; }
4ff2602d-2713-4fcc-99de-b7d9c1ee8a05
2
public Automaton convertToAutomaton(Grammar grammar) { ArrayList list = new ArrayList(); Automaton automaton = new Automaton(); createStatesForConversion(grammar, automaton); Production[] productions = grammar.getProductions(); for (int k = 0; k < productions.length; k++) { list.add(getTransitionForProduction(productions[k])); } Iterator it = list.iterator(); while (it.hasNext()) { Transition transition = (Transition) it.next(); automaton.addTransition(transition); } return automaton; }
d675b179-146e-4543-a426-5d13bc00322f
1
public static boolean zip(String zip){ if(zip.matches("(\\d){5}(-(\\d){4})?")) return true; return false; }
a33342f0-3fa1-41c0-aa4e-2bb2d320f4f8
6
public static byte[] convertPNGToBlob(Image image) throws IOException { //Create the byte array int width = image.width; int height = image.height; byte[] data = new byte[width*height*4]; //Convert pixels to data. int ci = 0; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int argb = image.getPixel(x, y); byte red = (byte) (0xFF & (argb >> 24)); byte green = (byte) (0xFF & (argb >> 16)); byte blue = (byte) (0xFF & (argb >> 8)); byte alpha = (byte) (0xFF & (argb >> 0)); data[ci+3] = alpha; data[ci+0] = red; data[ci+1] = green; data[ci+2] = blue; ci += 4; } } //Compare the header. //Get version and header size. byte version = data[0]; byte headersize = data[1]; if (version != VERSION) { System.err.println("CORE VERSION missmatch! Continuing..."); } if (headersize != HEADERSIZE) { System.err.println("CORE HEADERSIZE missmatch! Continuing..."); } byte gzip = data[2]; //Get version-dependent values. //... nothing for now. //Get blob size. Convert it back from Big Endian to integer. byte[] size = new byte[4]; size[0] = data[(headersize & 0xFF)-4]; size[1] = data[(headersize & 0xFF)-3]; size[2] = data[(headersize & 0xFF)-2]; size[3] = data[(headersize & 0xFF)-1]; int blobsize = (((size[0] & 0xFF) << 24) | ((size[1] & 0xFF) << 16) | ((size[2] & 0xFF) << 8) | (size[3] & 0xFF)); System.out.println("Blob size: "+blobsize); //Get the blob data and return it. byte[] indata = new byte[blobsize]; System.arraycopy(data, headersize, indata, 0, blobsize); byte[] bindata = indata; if (gzip == (byte)((int)1)) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayInputStream bais = new ByteArrayInputStream(indata); GZIPInputStream gis = new GZIPInputStream(bais); byte[] buf = new byte[2048]; int n; while ((n = gis.read(buf)) >= 0) { baos.write(buf, 0, n); } gis.close(); baos.close(); bindata = baos.toByteArray(); } return bindata; }
fb2191d3-9d3f-40bb-9c98-a3429c4c871b
9
public char readCharacter() //exclusively for token { if(console) { if (buffer == null || !buffer.hasMoreTokens()) try { buffer = new StringTokenizer(myInFile.readLine()); return buffer.nextToken().charAt(0); } catch (IOException e) { e.printStackTrace(); } catch (IndexOutOfBoundsException f) { f.printStackTrace(); } try { return buffer.nextToken().charAt(0); } catch (IndexOutOfBoundsException f) { f.printStackTrace(); } return (char)0; } if(nonToken || isEOF) return (char)0; String answer = readString(); try { return answer.charAt(0); } catch (IndexOutOfBoundsException e) //paranoid { e.printStackTrace(); } return (char)0; }
75120da7-2e93-495b-aa61-b457731ca69d
0
public int GetOnBusTicks() { //get the tick time person got on the bus return onBusTicks; }
96d22f24-c28c-45be-bfc8-cb2105937782
2
public void addFirst(E e) { if (e == null) throw new NullPointerException(); elements[head = (head - 1) & (elements.length - 1)] = e; if (head == tail) doubleCapacity(); }
f2e0e946-0a98-44c5-907d-6fee063c6090
0
public void setApodo(String apodo) { this.apodo = apodo; }
79088ea1-ebc9-4706-9315-c658ac9ad4df
4
public static String toString(JSONObject jo) throws JSONException { StringBuilder sb = new StringBuilder(); sb.append(escape(jo.getString("name"))); sb.append("="); sb.append(escape(jo.getString("value"))); if (jo.has("expires")) { sb.append(";expires="); sb.append(jo.getString("expires")); } if (jo.has("domain")) { sb.append(";domain="); sb.append(escape(jo.getString("domain"))); } if (jo.has("path")) { sb.append(";path="); sb.append(escape(jo.getString("path"))); } if (jo.optBoolean("secure")) { sb.append(";secure"); } return sb.toString(); }
aac5ca9f-2bbf-4241-a569-3f5b9ff78185
4
private int start(int i) { int first = this.firstNonEmptyBucket(); if(i < first) { return -1; } else if(i == first) { return 0; } int result = 0; for(int j = first; j < i; j++) { if(buckets[j] != null) { result += buckets[j].size(); } } return result; }
899e12ed-8522-474f-9622-5f0801518a94
8
public void attackPlayersWithin(int gfx, int maxDamage, int range) { for (Player p : server.playerHandler.players) { if(p != null) { client person = (client)p; if((person.playerName != null || person.playerName != "null")) { if(person.distanceToPoint(absX, absY) <= range && person.playerId != playerId && !person.nonWild()) { int damage = misc.random(maxDamage); person.stillgfx(gfx, person.absY, person.absX); if (person.playerLevel[3] - hitDiff < 0) damage = person.playerLevel[3]; person.hitDiff = damage; person.KillerId = playerId; person.updateRequired = true; person.hitUpdateRequired = true; } } } } }
8efd18eb-5c19-4a3c-8251-52488349f897
1
private void jLabel5MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel5MouseClicked if(this.jPanel4.isVisible()) this.jPanel4.setVisible(false); else this.jPanel4.setVisible(true); }//GEN-LAST:event_jLabel5MouseClicked
1133ce42-dd7f-4866-9713-302efb5e4fe7
2
private int compareByte(byte b1, byte b2) { if ((b1 & 0xFF) > (b2 & 0xFF)) // 比较是否大于 return 1; else if ((b1 ^ b2) == 0)// 判断是否相等 return 0; else return -1; }
aeba7904-4612-4405-ad17-21eb354eb918
4
private void GetTasksForAsset(Asset SelectedAsset) { AssetTasks.clear(); taskList.repaint(); ResultSet tasksOnAssetListResultSet = null; Statement statement; try { statement = connection.createStatement(); Asset asset = (Asset) assetList.getSelectedValue(); tasksOnAssetListResultSet = statement.executeQuery("SELECT * FROM Task WHERE assetID = " + asset.getAssetID() + ";"); randSQL.loadAllUsers(); SetOfUsers allusers = randSQL.getAllUsers(); while (tasksOnAssetListResultSet.next()){ int taskID; int projectID; User responsible = null; int taskPriority; String status; String taskName; String taskType; taskID = tasksOnAssetListResultSet.getInt("taskID"); projectID = tasksOnAssetListResultSet.getInt("projectID"); for(int i=0; i<allusers.size();i++){ if(tasksOnAssetListResultSet.getInt("responsiblePerson")==allusers.get(i).getUserID()); { responsible = allusers.get(i); break; } } taskPriority = tasksOnAssetListResultSet.getInt("taskPriority"); status = tasksOnAssetListResultSet.getString("status"); taskName = tasksOnAssetListResultSet.getString("taskName"); taskType = tasksOnAssetListResultSet.getString("type"); Task newTask = new Task(taskID, responsible,taskName, taskPriority , status,projectID, asset, taskType); AssetTasks.add(newTask); taskList.setListData(AssetTasks); TasksListCellRenderer renderer = new TasksListCellRenderer(); //custom cell renderer to display property rather than useless object.toString() taskList.setCellRenderer(renderer); } asset.setSetOfTasks(AssetTasks); } catch (SQLException ex) { Logger.getLogger(ManagerUI.class.getName()).log(Level.SEVERE, null, ex); } }
b58f2001-2de0-4740-aaf2-6074c71dc096
6
public static Strategie getRandom() { Strategie s = new Strategie(); String a1 = parts[(new Random()).nextInt(parts.length)]; String a2 = null; do { a2 = parts[(new Random()).nextInt(parts.length)]; } while(a2.equals(a1)); String a3 = null; do { a3 = parts[(new Random()).nextInt(parts.length)]; } while(a3.equals(a1) || a3.equals(a2)); String d1 = parts[(new Random()).nextInt(parts.length)]; String d2 = null; do { d2 = parts[(new Random()).nextInt(parts.length)]; } while(d2.equals(d1)); String d3 = null; do { d3 = parts[(new Random()).nextInt(parts.length)]; } while(d3.equals(d1) || d3.equals(d2)); s.setAttack(a1, a2, a3); s.setDefens(d1, d2, d3); return s; }
a2ad4101-9b03-43c6-ace9-a7995ee2a860
5
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof TObject)) { return false; } TObject other = (TObject) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
0b65e1a9-3b54-4d5b-a89a-505375fdce0a
1
private void prevQbtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_prevQbtnActionPerformed setResponse(); if(qIndex > 0) { ShowQuestion(qIndex - 1); qIndex--; } }//GEN-LAST:event_prevQbtnActionPerformed
dacc1d2b-98f0-4938-b906-d25798879438
7
public static String printPerfs(List<Counter> list) { if (list == null || list.size() == 0) return ""; StringBuilder builder = new StringBuilder(1024); int maxLength = 0; for (Counter base : list) { maxLength = Math.max(base.getName().length(), maxLength); } String lastCat = null; String lastGroup = null; for (Counter base : list) { if (!base.getCategory().equals(lastCat)) { builder.append(base.getCategory()).append('\n'); lastCat = base.getCategory(); lastGroup = null; } if (!base.getGroup().equals(lastGroup)) { builder.append(" ").append(base.getGroup()).append('\n'); lastGroup = base.getGroup(); } builder.append(" ").append(base.getName()); for (int i = 0; i < (maxLength - base.getName().length()); i++) { builder.append(' '); } builder.append(" ").append(base.getDisplayValue()).append('\n'); } return builder.toString(); }
f1bb7a37-9076-4e96-9fe3-556eca8a80e9
8
public static LocInCell getLocInCell(Dir d1, Dir d2) { if (oneIs(Dir.Up, d1, d2) && oneIs(Dir.Left, d1, d2)) return LocInCell.UpperLeft; if (oneIs(Dir.Up, d1, d2) && oneIs(Dir.Right, d1, d2)) return LocInCell.UpperRight; if (oneIs(Dir.Down, d1, d2) && oneIs(Dir.Left, d1, d2)) return LocInCell.LowerLeft; if (oneIs(Dir.Down, d1, d2) && oneIs(Dir.Right, d1, d2)) return LocInCell.LowerRight; else throw new RuntimeException("Invalid directions"); }
ca2e7a3f-8fce-4db6-8b13-b4fadcd73827
3
public void setLines() { lines = new ArrayList<>(); panels = new ArrayList<>(); for (DrawableItem pi : this.l.getDrawable()) { if (pi instanceof PathItem && !((PathItem) pi).hidden) { lines.add((GeneralPath) ((GeneralPath) (pi.getShape())).clone()); } } }
f2af793e-7d05-4358-a69a-59a7d97323c4
7
public Enumeration enumerateRequests() { Vector newVector = new Vector(); if (m_subFlowPreview != null) { String text = "Show preview"; if (m_previewWindow != null) { text = "$"+text; } newVector.addElement(text); } for (int i = 0; i < m_subFlow.size(); i++) { BeanInstance temp = (BeanInstance)m_subFlow.elementAt(i); if (temp.getBean() instanceof UserRequestAcceptor) { String prefix = (temp.getBean() instanceof WekaWrapper) ? ((WekaWrapper)temp.getBean()).getWrappedAlgorithm().getClass().getName() : temp.getBean().getClass().getName(); prefix = prefix.substring(prefix.lastIndexOf('.')+1, prefix.length()); prefix = ""+(i+1)+": ("+prefix+")"; Enumeration en = ((UserRequestAcceptor)temp.getBean()).enumerateRequests(); while (en.hasMoreElements()) { String req = (String)en.nextElement(); if (req.charAt(0) == '$') { prefix = '$'+prefix; req = req.substring(1, req.length()); } newVector.add(prefix+" "+req); } } } return newVector.elements(); }