method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
4978c9cd-3863-48c5-854b-868dfe765010
8
public boolean checkNick(String nick) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = getConnection(); pstmt = conn .prepareStatement("select nickname from member where nickname=?"); pstmt.setString(1, nick); rs = pstmt.executeQuery(); if (rs.next()) { return true; } } catch (Exception e) { e.printStackTrace(); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } return false; }
f5a6a0d9-fd08-4228-a453-3cbf318453fb
8
@Override public Vector solve(Basis b) { BigInteger[][] big = convertToBigInteger(b); LLL.integral_LLL(big, big.length, big[0].length); // TODO: Not actually necessary to do this conversion, // because we have to convert to double for solving linear equations int[][] reduced = convertToInteger(big); double shortest = Double.MAX_VALUE; int vectorIndex = -1; for(int i = 0; i < b.vecCount; i++) { double vLen = Vector.vectorLength(reduced[i]); //System.out.println(String.format("%s", vLen)); // Find the shortest vector and solve a system of linear equations // to reconstruct it if(vLen < shortest){ shortest = vLen; vectorIndex = i; } } // Need to swap dimensions here: // The LinearSolve library expects vectors in columns (not rows) // and the matrix must be square // (the rest are sufficiently large, but linearly independent so they // won't prevent solving the system of linear equations) int sysSize = Math.max(b.dim, b.vecCount); double[][] A = new double[sysSize][sysSize]; for(int i = 0; i < sysSize; i++){ for(int j = 0; j < sysSize; j++){ A[i][j] = 10000000 + i + j; } } for(int v = 0; v < b.vecCount; v++) { for(int d = 0; d < b.dim; d++) { A[d][v] = b.vectors[v][d]; // NOTE: dimension swap } } // coefficients to solve for (1 per basis vector) double[] coefs = new double[sysSize]; // Copy coordinate values from the shortest vector (target) double[] sVecVals = new double[b.dim]; for(int i = 0; i < b.dim; i++){ sVecVals[i] = reduced[vectorIndex][i]; } LinearSolve linearSolver = new LinearSolve(A); linearSolver.solve(coefs, sVecVals); // Construct the vector with these coefficients Vector v = b.zeroVector(); for(int i = 0; i < b.vecCount; i++){ v.coef[i] = (int)Math.round(coefs[i]); } updateIfBest(v); return v; }
cb8520bc-f412-47d2-a3ff-b64f5dfb67c5
6
private void openSerialPort(CommPortIdentifier commPortIdentifier) { if (openedPort != null) { serialPort.close(); } if (commPortIdentifier != null) { try { serialPort = (SerialPort) commPortIdentifier.open("MonitorConsole", 2000); } catch (PortInUseException e) { serialPort = null; System.out.println(e); } if (serialPort != null) { try { outputStream = serialPort.getOutputStream(); inputStream = serialPort.getInputStream(); } catch (IOException e) { System.out.println(e); } setSerialPortParams(); } serialPort.notifyOnDataAvailable(true); try { serialPort.addEventListener(new CommPortListener()); } catch (TooManyListenersException e) { System.out.println(e); } } openedPort = commPortIdentifier; }
7fc505b2-4856-41b0-9533-20494117f744
6
public boolean render(Level var1, int var2, int var3, int var4, ShapeRenderer var5) { boolean var6 = false; float var7 = 0.5F; float var8 = 0.8F; float var9 = 0.6F; float var10; if(this.canRenderSide(var1, var2, var3 - 1, var4, 0)) { var10 = this.getBrightness(var1, var2, var3 - 1, var4); var5.color(var7 * var10, var7 * var10, var7 * var10); this.renderInside(var5, var2, var3, var4, 0); var6 = true; } if(this.canRenderSide(var1, var2, var3 + 1, var4, 1)) { var10 = this.getBrightness(var1, var2, var3 + 1, var4); var5.color(var10 * 1.0F, var10 * 1.0F, var10 * 1.0F); this.renderInside(var5, var2, var3, var4, 1); var6 = true; } if(this.canRenderSide(var1, var2, var3, var4 - 1, 2)) { var10 = this.getBrightness(var1, var2, var3, var4 - 1); var5.color(var8 * var10, var8 * var10, var8 * var10); this.renderInside(var5, var2, var3, var4, 2); var6 = true; } if(this.canRenderSide(var1, var2, var3, var4 + 1, 3)) { var10 = this.getBrightness(var1, var2, var3, var4 + 1); var5.color(var8 * var10, var8 * var10, var8 * var10); this.renderInside(var5, var2, var3, var4, 3); var6 = true; } if(this.canRenderSide(var1, var2 - 1, var3, var4, 4)) { var10 = this.getBrightness(var1, var2 - 1, var3, var4); var5.color(var9 * var10, var9 * var10, var9 * var10); this.renderInside(var5, var2, var3, var4, 4); var6 = true; } if(this.canRenderSide(var1, var2 + 1, var3, var4, 5)) { var10 = this.getBrightness(var1, var2 + 1, var3, var4); var5.color(var9 * var10, var9 * var10, var9 * var10); this.renderInside(var5, var2, var3, var4, 5); var6 = true; } return var6; }
44905e62-6607-427b-a370-1bd628e71747
1
public Tester(String name) { this.name = name; }
8d415657-a01c-4f37-92b4-4b337ad65cd6
7
public void updateDrawableRect(int compWidth, int compHeight) { int x = currentRect.x; int y = currentRect.y; int width = currentRect.width; int height = currentRect.height; //Make the width and height positive, if necessary. if (width < 0) { width = 0 - width; x = x - width + 1; if (x < 0) { width += x; x = 0; } } if (height < 0) { height = 0 - height; y = y - height + 1; if (y < 0) { height += y; y = 0; } } //The rectangle shouldn't extend past the drawing area. if ((x + width) > compWidth) { width = compWidth - x; } if ((y + height) > compHeight) { height = compHeight - y; } //Update rectToDraw after saving old value. if (rectToDraw != null) { previousRectDrawn.setBounds( rectToDraw.x, rectToDraw.y, rectToDraw.width, rectToDraw.height); rectToDraw.setBounds(x, y, width, height); } else { rectToDraw = new Rectangle(x, y, width, height); } }
12a1b474-66d4-482e-9ef6-b0097c34b4b6
5
public synchronized void update() { //Check the collision of the between the robot and the walls. checkTileMapCollision(); updatePosition(); //Animation if (currentAnimation == SCRATCH) { if (animation.hasPlayedOnce()) { isScratching = false; notifyAll(); } } if (isScratching == true) { if (currentAnimation != SCRATCH) { currentAnimation = SCRATCH; animation.setFrames(sprites.get(SCRATCH)); animation.setDelay(50); width = 60; } } else if (currentAnimation != IDLE) { currentAnimation = IDLE; animation.setFrames(sprites.get(IDLE)); animation.setDelay(400); width = 30; } animation.update(); }
114f18dd-a55e-4e86-8408-dfd17d1aef52
8
public static int floodFill(State s) { // Initialization Queue<Position> fringe = new LinkedList<>(); Set<Position> visitedStates = new HashSet<>(); fringe.add(s.player); visitedStates.add(s.player); while (fringe.size() > 0) { //Pop new state Position state = fringe.poll(); //Expand the state List<Position> nextStates = new ArrayList<>(); for (int i = 0; i < 4; i++) { Position newP = new Position(state.getRow() + MOVE_Y[i], state.getCol() + MOVE_X[i]); if (isValidPosition(newP) && isEmptyPosition(newP) && !s.boxes.contains(newP)) { nextStates.add(newP); } } for (Position p : nextStates) { if (!visitedStates.contains(p)) //Add next States to the fringe if they are not visited { fringe.add(p); visitedStates.add(p); } } }//end while /*Now we have all the reachable positions on the visitedStates list*/ int result = 0; for (Position p : visitedStates) { result += 3 * p.getRow() + 7 * p.getCol(); } return result; }
3e3663cb-3e00-4334-b34a-8580160af826
7
@Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { log.debug("{} public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException:", getClass()); log.debug("params: uri={}, localName={}, qName={}, attrs={}", new Object[]{uri, localName, qName, attrs}); this.qName = qName; if (qName != null) { qName = qName.trim(); if (qName.equalsIgnoreCase(ProductsConstants.CATEGORY.getContent())) { category = new Category(); categories.add(category); category.setName(attrs.getValue(0)); } else { if (!qName.equalsIgnoreCase(ProductsConstants.CATEGORY_LIST.getContent())) { if (qName.equalsIgnoreCase(ProductsConstants.SUBCATEGORY.getContent())) { subcategory = new Subcategory(); category.add(subcategory); subcategory.setName(attrs.getValue(0)); } else { if (qName.equalsIgnoreCase(ProductsConstants.PRODUCT.getContent())) { product = new Product(); subcategory.add(product); product.setProductName(attrs.getValue(0)); } else { if ((qName.equalsIgnoreCase(ProductsConstants.NOT_IN_STOCK.getContent())) && (product != null)) { product.setNotInStock(true); } } } } } } }
50e5b9b4-d846-431e-a4fb-d234df8cd2f5
9
private void GenerateAttackPayloadsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GenerateAttackPayloadsButtonActionPerformed PreparedStatement ps = null, ps_attack = null; ResultSet rs = null; Connection conn = null; String HTTPRequest = "", ParameterName = "", ParameterValue = "", ParameterEncodedValue = "", HTTPRequestHeader = "", HTTPRequestGET = "", NewHTTPRequestGET = "", HTTPRequestPOST = "", Type = ""; int ATTACK_PAYLOADS_ID = 0; int posStart = -1, posEnd = -1, ContentLength = 0, count = 0; ToolEncodeDecode encodeDecode = new ToolEncodeDecode(); try { if ((conn = JavaDBAccess.setConn()) != null) { System.out.println("Connected to database " + JavaDBAccess.getDatabaseName()); } else { throw new Exception("Not connected to database " + JavaDBAccess.getDatabaseName()); } conn.setAutoCommit(false); ps = conn.prepareStatement("DELETE FROM ATTACK_PAYLOADS"); ps.executeUpdate(); //Inserting the Foreign Keys in the ATTACK_PAYLOADS table //Although there is a DISTINCT clause in the following query, there it does not work because of a annoying "bug"/"feature" of the JavaDB. //This error can be seen if executing the query directely in a JAvaDB console //I corrected the error by using a GROUP BY instead of the DISTINCT!!!!!!!! ps = conn.prepareStatement("INSERT INTO ATTACK_PAYLOADS (VULNERABILITY_INJECTION_RESULT,TARGET_PHP_FILES_RUNS_FUNCTION,TARGET_PHP_FILES_VARIABLE,PAYLOAD,TYPE) (SELECT VULNERABILITY_INJECTION_RESULTS.ID,TARGET_PHP_FILES_RUNS_FUNCTIONS.ID,VULNERABILITY_INJECTION_RESULTS.TARGET_PHP_FILES_VARIABLE,PAYLOADS.ID,TARGET_PHP_FILES_RUNS_FUNCTIONS_VARIABLES.TYPE FROM VULNERABILITY_INJECTION_RESULTS,TARGET_PHP_FILES_VARIABLES,TARGET_PHP_FILES_RUNS_FUNCTIONS_VARIABLES,TARGET_PHP_FILES_RUNS_FUNCTIONS,PAYLOADS WHERE TARGET_PHP_FILES_VARIABLES.ID=VULNERABILITY_INJECTION_RESULTS.TARGET_PHP_FILES_VARIABLE AND TARGET_PHP_FILES_VARIABLES.ID=TARGET_PHP_FILES_RUNS_FUNCTIONS_VARIABLES.TARGET_PHP_FILES_VARIABLE AND TARGET_PHP_FILES_RUNS_FUNCTIONS_VARIABLES.TARGET_PHP_FILES_RUNS_FUNCTION=TARGET_PHP_FILES_RUNS_FUNCTIONS.ID AND TARGET_PHP_FILES_RUNS_FUNCTIONS.MODE='INSPECTION')"); ps.executeUpdate(); ps.close(); ps = conn.prepareStatement("SELECT ATTACK_PAYLOADS.ID,ATTACK_PAYLOADS.TARGET_PHP_FILES_RUNS_FUNCTION,TARGET_PHP_FILES_RUNS_FUNCTIONS_VARIABLES.TYPE,TARGET_PHP_FILES_RUNS_FUNCTIONS_VARIABLES.NAME,TARGET_PHP_FILES_RUNS_FUNCTIONS_VARIABLES.VALUE,PAYLOADS.PAYLOAD,TARGET_PHP_FILES_RUNS_FUNCTIONS.HTTP_REQUEST_HEADER,TARGET_PHP_FILES_RUNS_FUNCTIONS.HTTP_REQUEST_GET,TARGET_PHP_FILES_RUNS_FUNCTIONS.HTTP_REQUEST_POST FROM ATTACK_PAYLOADS,TARGET_PHP_FILES_RUNS_FUNCTIONS_VARIABLES,PAYLOADS,TARGET_PHP_FILES_RUNS_FUNCTIONS WHERE TARGET_PHP_FILES_RUNS_FUNCTIONS_VARIABLES.TARGET_PHP_FILES_VARIABLE=ATTACK_PAYLOADS.TARGET_PHP_FILES_VARIABLE AND PAYLOADS.ID=ATTACK_PAYLOADS.PAYLOAD AND TARGET_PHP_FILES_RUNS_FUNCTIONS.ID=ATTACK_PAYLOADS.TARGET_PHP_FILES_RUNS_FUNCTION AND TARGET_PHP_FILES_RUNS_FUNCTIONS.ID=TARGET_PHP_FILES_RUNS_FUNCTIONS_VARIABLES.TARGET_PHP_FILES_RUNS_FUNCTION AND ATTACK_PAYLOADS.TYPE=TARGET_PHP_FILES_RUNS_FUNCTIONS_VARIABLES.TYPE"); rs = ps.executeQuery(); while (rs.next()) { count++; ATTACK_PAYLOADS_ID = rs.getInt("ID"); HTTPRequestHeader = rs.getString("HTTP_REQUEST_HEADER"); HTTPRequestGET = rs.getString("HTTP_REQUEST_GET"); HTTPRequestPOST = rs.getString("HTTP_REQUEST_POST"); Type = rs.getString("TYPE"); ParameterName = rs.getString("NAME"); //Apply the Payload ParameterValue = rs.getString("VALUE") + " " + rs.getString("PAYLOAD"); ParameterEncodedValue = encodeDecode.Encode(ParameterValue, false, "", "HTTP"); if (Type.contentEquals("GET")) { posStart = HTTPRequestGET.lastIndexOf(ParameterName); posEnd = HTTPRequestGET.indexOf("&", posStart); if (posEnd == -1) { NewHTTPRequestGET = HTTPRequestGET.substring(0, posStart) + ParameterName + "=" + ParameterEncodedValue; } else { NewHTTPRequestGET = HTTPRequestGET.substring(0, posStart) + ParameterName + "=" + ParameterEncodedValue + HTTPRequestGET.substring(posEnd); } posStart = HTTPRequestHeader.indexOf(HTTPRequestGET); posEnd = posStart + HTTPRequestGET.length(); HTTPRequestGET = NewHTTPRequestGET; HTTPRequestHeader = HTTPRequestHeader.substring(0, posStart) + HTTPRequestGET + HTTPRequestHeader.substring(posEnd); } else if (Type.contentEquals("POST")) { posStart = HTTPRequestPOST.lastIndexOf(ParameterName); posEnd = HTTPRequestPOST.indexOf("&", posStart); if (posEnd == -1) { HTTPRequestPOST = HTTPRequestPOST.substring(0, posStart) + ParameterName + "=" + ParameterEncodedValue; } else { HTTPRequestPOST = HTTPRequestPOST.substring(0, posStart) + ParameterName + "=" + ParameterEncodedValue + HTTPRequestPOST.substring(posEnd); } } posStart = HTTPRequestHeader.indexOf("Content-Length: "); if (posStart > 0) { posEnd = HTTPRequestHeader.indexOf("\r\n", posStart); ContentLength = HTTPRequestPOST.length(); HTTPRequestHeader = HTTPRequestHeader.substring(0, posStart + 16) + ContentLength + HTTPRequestHeader.substring(posEnd); } HTTPRequest = HTTPRequestHeader + HTTPRequestPOST; ps_attack = conn.prepareStatement("UPDATE ATTACK_PAYLOADS SET ATTACK_INPUT=?, ATTACK_EXPECTED_OUTPUT=?, HTTP_REQUEST=? WHERE ID=?"); ps_attack.setString(1, ParameterName + "=" + ParameterEncodedValue); ps_attack.setString(2, ParameterValue); ps_attack.setString(3, HTTPRequest); ps_attack.setInt(4, ATTACK_PAYLOADS_ID); ps_attack.executeUpdate(); } ps.close(); conn.commit(); conn.close(); AttackTextArea.setText(count + " Attack Payloads generated!\n"); } catch (Throwable e) { System.out.println("Errors in GenerateAttackPayloadsButtonActionPerformed!"); System.out.println("exception thrown:"); if (e instanceof SQLException) { JavaDBAccess.printSQLError((SQLException) e); } else { e.printStackTrace(); } } }
e9f393a9-a792-4c16-be26-82374a2a3b30
9
public Emage buildEmage(Timestamp lastEmageCreationTime, long windowSizeMS) { filterPointQueueByWindow(windowSizeMS); this.pointQueue.addAll(this.pointStream.getAndClearNewPointsQueue()); Iterator<STTPoint> pointIterator = this.pointQueue.iterator(); GeoParams geoParams = this.pointStream.getGeoParams(); //Initialize grid to correct values double[][] valueGrid = createEmptyValueGrid(geoParams, this.operator); //For holding the counts so we can compute the avg of each cell double[][] avgAssistGrid = createEmptyValueGrid(geoParams, Operator.AVG); while (pointIterator.hasNext()) { STTPoint currPoint = pointIterator.next(); int x = getXIndex(geoParams, currPoint); int y = getYIndex(geoParams, currPoint); if (x>=0 && y >=0) { try { switch (this.operator) { case MAX: valueGrid[x][y] = Math.max(valueGrid[x][y], currPoint.getValue()); break; case MIN: valueGrid[x][y] = Math.min(valueGrid[x][y], currPoint.getValue()); break; case SUM: valueGrid[x][y] += currPoint.getValue(); break; case COUNT: valueGrid[x][y]++; break; case AVG: double total = valueGrid[x][y]*avgAssistGrid[x][y]; //Add one to the count from that cell, valueGrid[x][y] = (total+currPoint.getValue())/++avgAssistGrid[x][y]; break; } } catch (Exception e) { System.out.println("Caught an array index error due to a bug"); System.out.println(currPoint); System.out.println("x: "+x+", y: "+y); } } } return new Emage(valueGrid, lastEmageCreationTime, new Timestamp(System.currentTimeMillis()), this.pointStream.getAuthFields(), this.pointStream.getWrapperParams(), geoParams); }
d5417ed1-49bb-40b8-b8f8-64b8ac1a9847
6
@EventHandler public void MagmaCubeWither(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getMagmaCubeConfig().getDouble("MagmaCube.Wither.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if ( plugin.getMagmaCubeConfig().getBoolean("MagmaCube.Wither.Enabled", true) && damager instanceof MagmaCube && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.WITHER, plugin.getMagmaCubeConfig().getInt("MagmaCube.Wither.Time"), plugin.getMagmaCubeConfig().getInt("MagmaCube.Wither.Power"))); } }
250151ed-ecb7-4175-ae3a-39525bf2c32c
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(cadastroforn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(cadastroforn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(cadastroforn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(cadastroforn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new cadastroforn().setVisible(true); } }); }
22a9504d-20a1-4acc-91b4-15dec7fe0962
9
public static String clasificar(String path){ DiccionarioXml dic = new DiccionarioXml("/home/borja/proyectos/ecloud/logica/palabras.xml"); String palabras[]=dic.getPalabras(); /*for(String palabra:palabras) System.out.println(palabra); */ ArrayList<Integer> contadoresTema= new ArrayList<Integer>(); ArrayList<Integer> contadoresSubTema= new ArrayList<Integer>(); for(int i=0;i<dic.getNTemas();i++){ contadoresTema.add(0); } for(int i=0;i<dic.getNSubTemas();i++){ contadoresSubTema.add(0); } //Obtenemos el texto del docuemtno int marcadorTema=-1,marcadorSubTema=-1; int cantidad; String texto=AbrirXml.open(path)[0]; for(String palabra:palabras){ if(palabra.equals("%")) marcadorTema++; else if (palabra.equals("*")) marcadorSubTema++; else{ cantidad=ObtenerTema.BuscarPalabra(texto, palabra); contadoresTema.set(marcadorTema, contadoresTema.get(marcadorTema)+cantidad); contadoresSubTema.set(marcadorSubTema, contadoresSubTema.get(marcadorSubTema)+cantidad); } } int posicion=0; int mayor=0; for(int i=0;i<contadoresTema.size();i++){ if (contadoresTema.get(i)>mayor){ mayor=contadoresTema.get(i); posicion=i; } } String tema=dic.getTema(posicion); posicion=0; mayor=0; for(int i=0;i<contadoresSubTema.size();i++){ if (contadoresSubTema.get(i)>mayor){ mayor=contadoresSubTema.get(i); posicion=i; } } String subTema=dic.getSubTema(posicion); //System.out.println("El tema es: "+tema+" y el subtema: "+subTema); AbrirXml.saveKind(path, tema); AbrirXml.saveSubKind(path, subTema); return path; }
7b277ebc-0275-46c3-8d0f-17caed02b1b2
0
public String getQuantity() { return quantity; }
124b8b62-39a7-4688-8dd8-0ec65b4a4820
9
public static final void safeShutdown(final boolean restart, int delay) { if (exiting_start != 0) return; exiting_start = Utils.currentTimeMillis(); exiting_delay = (int) delay; for (Player player : World.getPlayers()) { if (player == null || !player.hasStarted() || player.hasFinished()) continue; player.getPackets().sendSystemUpdate(delay); } CoresManager.slowExecutor.schedule(new Runnable() { @Override public void run() { try { for (Player player : World.getPlayers()) { if (player == null || !player.hasStarted()) continue; player.realFinish(); } IPBanL.save(); PkRank.save(); Launcher.restart(); } catch (Throwable e) { Logger.handle(e); } } }, delay, TimeUnit.SECONDS); }
f603fc68-514f-4768-b5fa-5c17aeb61e23
1
public boolean add(Administrador admin){ PreparedStatement ps; try { ps = mycon.prepareStatement("INSERT INTO Administradores VALUES(?,?,?)"); ps.setString(1, admin.getNombre()); ps.setString(2, admin.getPassword()); ps.setString(3, admin.getDNI()); return (ps.executeUpdate()>0); } catch (SQLException ex) { Logger.getLogger(AdministradorCRUD.class.getName()).log(Level.SEVERE, null, ex); } return false; }
8d1b830f-014c-4496-9b53-1ff355bda23a
6
protected void updateEntityActionState() { ++this.entityAge; if (this.entityAge > 100) { this.randomMotionVecX = this.randomMotionVecY = this.randomMotionVecZ = 0.0F; } else if (this.rand.nextInt(50) == 0 || !this.inWater || this.randomMotionVecX == 0.0F && this.randomMotionVecY == 0.0F && this.randomMotionVecZ == 0.0F) { float var1 = this.rand.nextFloat() * (float)Math.PI * 2.0F; this.randomMotionVecX = MathHelper.cos(var1) * 0.2F; this.randomMotionVecY = -0.1F + this.rand.nextFloat() * 0.2F; this.randomMotionVecZ = MathHelper.sin(var1) * 0.2F; } this.despawnEntity(); }
fac1f08e-ca3b-4898-ab14-7bdccf6d99fb
3
public boolean canCreateUnit(int id) { if (id >= 11 && id <= 16 && candy >= candyTable.get(id)) return true; else return false; }
de70ba8b-d752-47ac-926b-c431527ece6c
4
public boolean carOnLane(Car fCar, Lane lane) { double x = fCar.getPosition().getX(); double y = fCar.getPosition().getY(); if (x >= lane.getMinX() && x <= lane.getMaxX() && y >= lane.getMinY() && y <= lane.getMaxY()) { return true; } return false; }
fe951eb0-4ec4-4df3-bfc9-96f23a897e16
7
@Override public void actionPerformed(ActionEvent e) { //System.out.println("EndAction"); OutlinerCellRendererImpl textArea = null; boolean isIconFocused = true; Component c = (Component) e.getSource(); if (c instanceof OutlineButton) { textArea = ((OutlineButton) c).renderer; } else if (c instanceof OutlineLineNumber) { textArea = ((OutlineLineNumber) c).renderer; } else if (c instanceof OutlineCommentIndicator) { textArea = ((OutlineCommentIndicator) c).renderer; } else if (c instanceof OutlinerCellRendererImpl) { textArea = (OutlinerCellRendererImpl) c; isIconFocused = false; } // Shorthand Node node = textArea.node; JoeTree tree = node.getTree(); OutlineLayoutManager layout = tree.getDocument().panel.layout; //System.out.println(e.getModifiers()); switch (e.getModifiers()) { case 0: if (isIconFocused) { if (tree.getSelectedNodes().size() > 1) { changeSelectionToNode(tree, layout); } else { changeFocusToTextArea(textArea, tree, layout); } } else { end(node, tree, layout); } break; } }
5206aaa9-4835-490b-a109-3adb8303cd33
5
public void menuTextAsym() { int choice; do { System.out.println("\n"); System.out.println("Text Cryption Menu"); System.out.println("Select Asymmetric Cryption Methode"); System.out.println("----------------------------------\n"); System.out.println("1 - RSA"); System.out.println("2 - Back"); System.out.print("Enter Number: "); while (!scanner.hasNextInt()) { System.out.print("That's not a number! Enter 1 or 2:"); scanner.next(); } choice = scanner.nextInt(); } while (choice < 1 || choice > 2); switch (choice) { case 1: RsaUI.rsaCrypterText(this); break; case 2: this.menuTextCrypt(); break; default: this.menuTextSym(); } }
f89e2cf8-a7dd-4b2c-9dc0-23dddfb821c9
8
public static void readRelevanceJudgments( String p,HashMap < String , HashMap < Integer , Double > > relevance_judgments){ try { BufferedReader reader = new BufferedReader(new FileReader(p)); try { String line = null; while ((line = reader.readLine()) != null){ // parse the query,did,relevance line Scanner s = new Scanner(line).useDelimiter("\t"); String query = s.next(); int did = Integer.parseInt(s.next()); String grade = s.next(); double rel = 0.0; // convert to binary relevance if (grade.equals("Perfect")){ rel = 10.0; } else if(grade.equals("Excellent")){ rel = 7.0; } else if(grade.equals("Good")){ rel = 5.0; } else if(grade.equals("Fair")){ rel = 1.0; } else if(grade.equals("Bad")){ rel = 0.0; } if (relevance_judgments.containsKey(query) == false){ HashMap < Integer , Double > qr = new HashMap < Integer , Double >(); relevance_judgments.put(query,qr); } HashMap < Integer , Double > qr = relevance_judgments.get(query); qr.put(did,rel); } } finally { reader.close(); } } catch (IOException ioe){ System.err.println("Oops " + ioe.getMessage()); } }
a9fa9a51-c29b-4bcc-97d1-6ce8045ca229
9
public static void UpdateStateTestImageTransform() { int selection = m_MenuTestImageTransform.UpdateMenuKeys(); switch (selection) { case MENU.TEST_IMAGE_TRANSFORM.OPT_IMAGE_TRANS_NONE: case MENU.TEST_IMAGE_TRANSFORM.OPT_IMAGE_TRANS_ROT90: case MENU.TEST_IMAGE_TRANSFORM.OPT_IMAGE_TRANS_ROT180: case MENU.TEST_IMAGE_TRANSFORM.OPT_IMAGE_TRANS_ROT270: case MENU.TEST_IMAGE_TRANSFORM.OPT_IMAGE_TRANS_MIRROR: case MENU.TEST_IMAGE_TRANSFORM.OPT_IMAGE_TRANS_MIRROR_ROT90: case MENU.TEST_IMAGE_TRANSFORM.OPT_IMAGE_TRANS_MIRROR_ROT180: case MENU.TEST_IMAGE_TRANSFORM.OPT_IMAGE_TRANS_MIRROR_ROT270: { int[] params = {GetStateID(), GetTransform(selection - MENU.TEST_IMAGE_TRANSFORM.OPT_IMAGE_TRANS_NONE)}; ChangeState(STATE.TEST_IMAGE_SIZES.ID, params); break; } case MENU.TEST_IMAGE_TRANSFORM.OPT_BACK: ChangeState(STATE.IMAGE_TESTS_MENU.ID); break; } }
8c15c97f-deef-4df2-9cde-613c10cb7ebd
6
public static GameMode getGameMode(String gamemode) { if (gamemode.equalsIgnoreCase("survival") || gamemode.equalsIgnoreCase("0")) { return GameMode.SURVIVAL; } else if (gamemode.equalsIgnoreCase("creative") || gamemode.equalsIgnoreCase("1")) { return GameMode.CREATIVE; } else if (gamemode.equalsIgnoreCase("adventure") || gamemode.equalsIgnoreCase("2")) { return GameMode.ADVENTURE; } else { return GameMode.SURVIVAL; } }
f8f9df99-32a5-46eb-9825-5a67f262bf29
7
@Override public String runMacro(HTTPRequest httpReq, String parm, HTTPResponse httpResp) { final java.util.Map<String,String> parms=parseParms(parm); if(parms.containsKey("CURRENT")) return Integer.toString(httpReq.getClientPort()); if(Thread.currentThread() instanceof CWThread) { final CWConfig config=((CWThread)Thread.currentThread()).getConfig(); return CMParms.toListString(config.getHttpListenPorts()); } if(httpReq.getClientPort()==0) { String serverType = parms.containsKey("ADMIN") ? "ADMIN" : "PUB"; for(MudHost host : CMLib.hosts()) { try { String var = host.executeCommand("WEBSERVER "+serverType+" PORT"); if(var.length()>0) return var; } catch (Exception e) { } } } return Integer.toString(httpReq.getClientPort()); }
b24be0b4-480e-486e-aecc-d34ccd466689
0
public boolean isSeed() { return this.torrent.isComplete(); }
ff80922b-5c0d-4fd6-8201-7d57333952e2
4
public int get(int key) { if(map.containsKey(key)){ Node n=map.get(key); if(n.prev!=null){ if(dll.last==n) dll.last=n.prev; n.prev.next=n.next; if(n.next!=null) n.next.prev=n.prev; n.prev=null; n.next=dll.first; dll.first.prev=n; dll.first=n; } return n.value; }else{ return -1; } }
57d8d059-1b9c-43a2-8d83-e5b58b3e4309
6
public ArrayList<Object> selectPath() { if(paths.size() == 0) { System.out.println("Path not found."); } else { if(paths.size() == 1) { System.out.println("One path founded."); printPaths(); return paths.get(0); } else { Scanner scanner = new Scanner(System.in); boolean val = true; String opt = ""; int selected = 0; System.out.println("Several paths founded, select one: "); printPaths(); do { val = true; System.out.println("Write the number of path: "); opt = scanner.nextLine(); if(Util.isInteger(opt)) { selected = Integer.parseInt(opt); if(selected < 1 || selected > paths.size()) { System.err.println("Out range number. Try again."); val = false; } } else { System.err.println("The number isn't a integer. Try again."); val = false; } }while(!val); scanner.close(); return paths.get(selected - 1); } } return null; }
e64c27f7-ee1e-44b7-a3eb-c25a20cf2fba
7
public void connect() throws ConnectionException, IOException { if(clientConnection == null || clientConnection.isClosed()) { try { clientConnection = new ServerSocket(port); Fluid.log("Target: Accepting connections on port " + port); } catch(BindException e) { throw new ConnectionException(e); } } if(username != null && password != null) new Client(this, clientConnection.accept(), idleTimeout, max, ruleFile, username, password); else new Client(this, clientConnection.accept(), idleTimeout, max, ruleFile); try { synchronized(this) { // give it at most one second wait(1000); } } catch(InterruptedException e) { // nada } if(!hasRequested) { throw new IOException("No request was made"); } }
f3c5b0a9-6c56-4f7a-b859-97b2584d4f06
9
@Override public void render(PApplet g) { g.pushMatrix(); g.translate(x, y); g.rotate(theta); g.scale(PIXEL_WIDTH, -PIXEL_WIDTH); g.noSmooth(); g.imageMode(PConstants.CENTER); switch (animationState) { case UP: if (!hitOnce) g.image(sprite1, 0, 0); else g.image(hitSprite1, 0, 0); break; case DOWN: if (!hitOnce) g.image(sprite2, 0, 0); else g.image(hitSprite2, 0, 0); break; case EXP_1: g.image(eSprites[0], 0, 0); break; case EXP_2: g.image(eSprites[1], 0, 0); break; case EXP_3: g.image(eSprites[2], 0, 0); break; case EXP_4: g.image(eSprites[3], 0, 0); break; case EXP_5: g.image(eSprites[4], 0, 0); break; default: break; } g.popMatrix(); }
bd9ea4ea-f2bd-4501-ab34-75c10db78acc
4
public int jump(int[] A) { int steps = 0, max = 0, next = 0; for (int i = 0; i < A.length - 1 && next < A.length - 1; i++) { max = Math.max(max, i + A[i]); if (i == next) { // ready to jump if (max == next) return -1; // unreachable next = max; steps++; } } return steps; }
935446cb-1b87-4ca6-9945-e6c761887eaf
6
public int run (String[] args) throws Exception { long startTime = System.currentTimeMillis() / 1000L; for(int i = 0; i < args.length; i++){ System.out.println(i + " : " + args[i]); } if (args.length < 2) { System.err.printf("Usage: %s [Hadoop Options] <d> <maxDimensions> <dataSets> <key> <input> <input2?> <output> <prevrun?> \n" + "Required Hadoop Options:\n" + "ff.N=# Number of columns (or rows, whatever the first dimension is) for the primary matrix or tensor. (This dimension will be shared with coupled data.)\n" + "ff.M0=# Range of second dimension in 1st data set\n" + "ff.rank=# Rank of the decomposition\n" + "ff.stepSize=# Step size for SGD. This is typically 1/N where N is the number of non-zero elements\n" + "mapred.reduce.tasks=# This should be set to the value of d so that the number of reducers matches the parallelism of the problem precisely\n\n" + "Optional Hadoop Options:\n" + "ff.P0=# Range of third dimension in 1st data set\n" + "ff.M1=# Range of second dimension in 2nd data set\n" + "ff.P1=# Range of third dimension in 2nd data set\n" + "ff.weight0=# - Weight data set 1 loss by this weight\n" + "ff.weight1=# - Weight data set 2 loss by this weight\n" + "ff.initMean=# - We will initialize the factors to be a Gaussian around this number (with variance 1)\n" + "ff.regularizerLambda=# - Weight L1 penalty with this lambda value\n" + "ff.sparse=1 - If set to 1 will add an L1 penalty to the loss\n" + "ff.nnmf=1 - If set to 1 will do a projection to make sure all factors are non-negative\n" + "ff.kl=1 - If set to 1 will use the KL divergence for the loss function\n" + "ff.debug=1 - If set to 1 will use plain text files and will be more verbose\n\n", getClass().getSimpleName()); ToolRunner.printGenericCommandUsage(System.err); return -1; } int d = Integer.parseInt(args[0]); boolean is2D = (Integer.parseInt(args[1]) < 3); int iter = d; if(!is2D) { iter = d*d; } boolean isPaired = (Integer.parseInt(args[2]) == 2); iter = 1; for(int i = 0; i < iter; i++) { System.out.println("Sub-iteration " + i); JobConf conf = getJobInstance(i,isPaired); FileSystem fs = FileSystem.get(conf); conf.setInt("ff.d", d); conf.setInt("ff.subepoch", i); int outputIndex = 4; if(isPaired) { MultipleInputs.addInputPath(conf, new Path(args[4]), KeyValueTextInputFormat.class, FFMapper.class); MultipleInputs.addInputPath(conf, new Path(args[5]), KeyValueTextInputFormat.class, FFMapperPaired.class); outputIndex = 6; } else { FileInputFormat.addInputPath(conf, new Path(args[4])); outputIndex = 5; } //FileOutputFormat.setOutputPath(conf, new Path(args[outputIndex] + "/iter"+i+"/")); //FileOutputFormat.setOutputPath(conf, new Path(args[outputIndex] + "/final/")); conf.setStrings("ff.outputPath", args[outputIndex]); if(args.length > outputIndex + 1) { conf.setStrings("ff.prevPath", args[outputIndex+1]); } else { conf.setStrings("ff.prevPath", ""); } RunningJob job = JobClient.runJob(conf); } long endTime = System.currentTimeMillis() / 1000L; BufferedWriter timeResults = new BufferedWriter(new FileWriter("time" +"-" + args[3]+ ".txt",true)); ; timeResults.write(startTime + "\t" + endTime + "\t" + (endTime-startTime) + "\n"); timeResults.close(); return 0; }
f2dfd907-c8c5-4e97-8f1c-6a7d499919c0
6
public static void main(String args[]) { /* * Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* * If Nimbus (introduced in Java SE 6) is not available, stay with the * default look and feel. For details see * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new MainPage().setVisible(true); } }); }
bece2b4e-29a6-4223-ae53-3fadfc5066fc
1
private boolean isElementPresent(By by) { try { driver.findElement(by); return true; } catch (NoSuchElementException e) { return false; } }
1658ee14-a18c-4d52-b730-e499dfce6cb0
0
@Test public void testMetadataRetrieval() throws SQLException { Populator p = new Populator(); System.err.println(p.metaDataDao.tableNames("linse")); System.err.println(p.metaDataDao.foreignKeys()); }
e37f916c-d268-4db8-b3db-37cb8e846abc
4
public Boolean leftFantasma(int n){ Query q2; switch(n){ case 0: q2 = new Query("leftBlinky"); return q2.hasSolution(); case 1: q2 = new Query("leftClyde"); return q2.hasSolution(); case 2: q2 = new Query("leftInky"); return q2.hasSolution(); case 3: q2 = new Query("leftPinky"); return q2.hasSolution(); default: return false; } }
4fad0ed5-3760-4a47-a136-ba0fed2bf2bc
6
@EventHandler public void CreeperInvisibility(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getCreeperConfig().getDouble("Creeper.Invisibility.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if ( plugin.getCreeperConfig().getBoolean("Creeper.Invisibility.Enabled", true) && damager instanceof Creeper && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, plugin.getCreeperConfig().getInt("Creeper.Invisibility.Time"), plugin.getCreeperConfig().getInt("Creeper.Invisibility.Power"))); } }
c2f13637-b5f8-48b8-a882-a4063187f3ee
8
private Point[] getItemCoordinates() { switch (GameLevel.currentLevel) { case 3: Point[] level_3 = {new Point(195, 75), new Point(195, 135), new Point(255, 135)}; return level_3; case 4: Point[] level_4 = {new Point(225, 45), new Point(225, 105), new Point(285, 45)}; return level_4; case 5: Point[] level_5 = {new Point(225, 75), new Point(225, 135), new Point(285, 105)}; return level_5; case 6: Point[] level_6 = {new Point(285, 105), new Point(165, 105), new Point(225, 135)}; return level_6; case 7: Point[] level_7 = {new Point(135, 165), new Point(135, 105), new Point(135, 45), new Point(195, 45), new Point(255, 45), new Point(315, 45)}; return level_7; case 8: Point[] level_8 = {new Point(135, 135), new Point(225, 135), new Point(315, 135), new Point(315, 75), new Point(225, 75), new Point(135, 75)}; return level_8; case 9: Point[] level_9 = {new Point(165, 165), new Point(165, 105), new Point(165, 45), new Point(225, 45), new Point(285, 45), new Point(345, 45)}; return level_9; case 10: Point[] level_10 = {new Point(165, 195), new Point(195, 195), new Point(225, 195), new Point(225, 165), new Point(225, 135), new Point(225, 105)}; return level_10; } return null; }
fd400faf-bd34-4f4b-9ae9-d27c61f948bd
8
@Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (args.length == 0) { TimeBanHelpCommand command = new TimeBanHelpCommand(plugin); command.setManPage("help"); if(sender != null && sender instanceof Player) { command.setReceiver((Player) sender); } if(command.executionAllowed()) { command.execute(); } return true; } // fetch args for command String subCommand = args[0]; String[] commandArgs = new String[0]; if (args.length > 1) { commandArgs = Arrays.copyOfRange(args, 1, args.length); commandArgs = CommandLineParser.normalizeArgs(commandArgs); } // create command AbstractCommand command = CommandBuilder.createCommand(plugin, subCommand); if (sender != null && sender instanceof Player) { command.setReceiver((Player) sender); } // execute command if (command.executionAllowed()) { AbstractConfigurator configurator = ConfiguratorFactory.getConfigurator(plugin.getConfig(), command); configurator.configure(command, commandArgs); command.execute(); } else { HashMap<String, String> values = new HashMap<String, String>(1); values.put("{command}", command.getCommandType().getName()); String message = MessagesUtil.formatMessage("no_permission", values); sender.sendMessage(message); } return true; }
c661e0be-3802-48fa-928b-72b719d5ef82
0
public String getShopAddress() { return shopAddress; }
62cb445d-b976-4016-8bfa-d2984a32551c
6
public void setDate(int year, int month, int day) { //verify the year is in bounds if (year < 1867 || year > Calendar.getInstance().get(Calendar.YEAR)){ return; } //verify month if (month < 0 || month > 12) { return; } //verify day if (day < 0 || day > 31) { return; } //if valid paramaters, set the new date date = LocalDate.of(year, month, day); }
e667af16-0d52-4ba2-b4e1-3bc4145bfcbd
9
public String execute(HttpServletRequest request, HttpServletResponse arg1) throws Exception { ResourceBundle bundle = Resource.getInstance().getRequestToObjectMap(); this.txtId = generalTools.NullToEmpty((String)request.getParameter("txtId")); this.txtDescription = generalTools.NullToEmpty((String)request.getParameter("txtDescription")); this.txtStatus = generalTools.NullToEmpty((String)request.getParameter("txtStatus")); this.hMode = generalTools.NullToEmpty((String)request.getParameter("hMode")); this.id = generalTools.NullToEmpty((String)request.getParameter("id")); PaymentMethodTO paymentMethodTO = paymentMethodService.setAll(txtId, txtDescription, txtStatus); String btn = (String)request.getParameter("btn"); if (btn!=null) { if (btn.equalsIgnoreCase(Multilingual.getLabel(null, "common.save"))) { if (hMode.equalsIgnoreCase(ConstantValue.NEW)) { if (paymentMethodService.checkMandatoryValues(paymentMethodTO)) { paymentMethodService.insertRecord(paymentMethodTO); paymentMethodTO = paymentMethodService.loadRecordByDesc(paymentMethodTO.getDescription()); msg = "common.insert_success"; } else { request.setAttribute("hMode", ConstantValue.NEW); msg = "alert.insert_mandatory"; } } else { boolean updateBranchPaymentMethod = false; PaymentMethodTO checkTO = paymentMethodService.loadRecordById(txtId); if (!checkTO.getStatus().equalsIgnoreCase(paymentMethodTO.getStatus())) { updateBranchPaymentMethod = true; } if (paymentMethodService.checkMandatoryValues(paymentMethodTO)) { boolean isSuccess = paymentMethodService.updateRecord(paymentMethodTO); if (isSuccess && updateBranchPaymentMethod) { BranchPaymentMethodTO branchPymtMthd = new BranchPaymentMethodTO(); PaymentMethodTO pymtMthdTO = new PaymentMethodTO(); branchPymtMthd.setPaymentMethod(pymtMthdTO); branchPymtMthd.getPaymentMethod().setId(paymentMethodTO.getId()); branchPymtMthd.setStatus(paymentMethodTO.getStatus()); paymentMethodService.updateBranchPaymentMethodRecord(branchPymtMthd); } paymentMethodTO = paymentMethodService.loadRecordById(paymentMethodTO.getId()); msg = "common.update_success"; } else { paymentMethodTO = checkTO; msg = "alert.insert_mandatory"; } } } } else if (this.id!=null) { paymentMethodTO = paymentMethodService.loadRecordById(id); } else { hMode = ConstantValue.NEW; } request.setAttribute("paymentMethodTO", paymentMethodTO); request.setAttribute("msg", msg); request.setAttribute("includePage", bundle.getString("admin/paymentMethodIUD.URL")); return CommandHelper.getTempate(request, bundle); }
4c42d05b-c4c7-41d0-b027-18f95ca3fd9e
3
public static Date getDateParam(SessionRequestContent request, String name){ String param = (String) request.getParameter(name); if (param != null && !param.isEmpty()) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); try { Date currDate = formatter.parse(param); return currDate; } catch (ParseException ex) { return null; } } return null; }
3aa098ec-6907-4dcf-88ab-c64facf3466d
8
public boolean isInChannel(String channel, String bot) { for (User user : getUsers(channel)) { if (bot.equalsIgnoreCase("%note") && user.getNick().equalsIgnoreCase("Kitteh")) { return true; } if (bot.equalsIgnoreCase("!note") && user.getNick().equalsIgnoreCase("benderj2")) { return true; } if (bot.equalsIgnoreCase(".note")) { if (user.getNick().equalsIgnoreCase("Kitteh") || user.getNick().equalsIgnoreCase("benderj2")) { return true; } } } return false; }
6135ae9d-2e53-4294-91df-09a1d0251d43
5
public static final boolean isNumeric(String str) { int length; if (str == null || (length = str.length()) == 0) { return false; } char[] chars = str.toCharArray(); do { // 48-57 if (chars[--length] < '0' || chars[length] > '9') { return false; } } while (length > 0); return true; }
8d3d691c-50d4-4798-8095-0887eae49d71
3
public File unzipFile(ZipFile in, File fileLocationOnDiskToDownloadTo) throws IOException { FileOutputStream dest; Enumeration<? extends ZipEntry> zipFileEnum = in.entries(); while (zipFileEnum.hasMoreElements()) { ZipEntry entry = zipFileEnum.nextElement(); File destFile = new File(fileLocationOnDiskToDownloadTo + "/" + entry.getName()); destFile.getParentFile().mkdirs(); if (!entry.isDirectory()) { dest = new FileOutputStream(destFile); InputStream inStream = in.getInputStream(entry); IOUtils.copyLarge(inStream, dest); dest.close(); inStream.close(); } else { destFile.mkdirs(); } } in.close(); return fileLocationOnDiskToDownloadTo; }
6b0e8e0e-5e95-4926-ac59-22ccaeedb4bc
2
public void initWindow(boolean full) { // Create game window... setIgnoreRepaint( true ); setResizable(false); this.addWindowListener(this); // Add the WindowListening events to the GameWindow if(full) { // Disable fullScreen this.setSize(WIDTH, HEIGHT); this.setUndecorated(true); gd.setFullScreenWindow(this); if( gd.isDisplayChangeSupported() ) { // Checks if Window can be put in fullscreen gd.setDisplayMode( new DisplayMode( WIDTH, HEIGHT, DisplayMode.BIT_DEPTH_MULTI, DisplayMode.REFRESH_RATE_UNKNOWN ) // Sets window to full screen ); } } else { this.pack(); // Need to pack once to get the insets this.setSize(WIDTH + this.getInsets().left + this.getInsets().right, HEIGHT + this.getInsets().top + this.getInsets().bottom); } // Create canvas for painting... this.setLocationRelativeTo(null); setVisible(true); c.setContainer(this); c.setWidthInsets(this.getInsets().left); c.setHeightInsets(this.getInsets().top); add(c); c.requestFocusInWindow(); pack(); // Refreshes the canvas on the Window }
b12848ba-b938-43d5-b99a-5a4c9078f480
1
public static int arrayDimension(String desc) { int dim = 0; while (desc.charAt(dim) == '[') ++dim; return dim; }
711ffde6-6932-463b-adc4-2aa25feadc1a
8
private static Date parseDateWithLeniency(String str, String[] parsePatterns, boolean lenient) throws ParseException { if (str == null || parsePatterns == null) { throw new IllegalArgumentException("Date and Patterns must not be null"); } SimpleDateFormat parser = new SimpleDateFormat(); parser.setLenient(lenient); ParsePosition pos = new ParsePosition(0); for (int i = 0; i < parsePatterns.length; i++) { String pattern = parsePatterns[i]; // LANG-530 - need to make sure 'ZZ' output doesn't get passed to SimpleDateFormat if (parsePatterns[i].endsWith("ZZ")) { pattern = pattern.substring(0, pattern.length() - 1); } parser.applyPattern(pattern); pos.setIndex(0); String str2 = str; // LANG-530 - need to make sure 'ZZ' output doesn't hit SimpleDateFormat as it will ParseException if (parsePatterns[i].endsWith("ZZ")) { int signIdx = indexOfSignChars(str2, 0); while (signIdx >=0) { str2 = reformatTimezone(str2, signIdx); signIdx = indexOfSignChars(str2, ++signIdx); } } Date date = parser.parse(str2, pos); if (date != null && pos.getIndex() == str2.length()) { return date; } } throw new ParseException("Unable to parse the date: " + str, -1); }
8ca8f8ef-2d3e-4939-bea1-d854caf26082
8
protected Result parseInsruction(String nextInstruction) { String[] parsed = nextInstruction.split("\\s+"); if (parsed.length > 4){ return Result.createError(Errors.TOO_MANY_PARAMS, nextInstruction); } if(allowableCommands.contains(parsed[CMDINDX])){ //further processing if ( "GET".equals(parsed[CMDINDX]) || "LATEST".equals(parsed[CMDINDX])){ return processGetLatest(parsed); } if("CREATE".equals(parsed[CMDINDX]) || "UPDATE".equals(parsed[CMDINDX])){ return processCreateUpdate(parsed); } if("DELETE".equals(parsed[CMDINDX])){ return processDelete(parsed); } if("QUIT".equals(parsed[CMDINDX])){ return Result.createError(Errors.TERMINATION, ""); } System.out.println(parsed); } return Result.createError(Errors.INVALID_COMMAND, parsed[CMDINDX]); }
5ac4a568-6ec7-439e-ab02-c1638b9c339a
2
public Bipartite(Graph G) { marked = new boolean[G.V()]; color = new boolean[G.V()]; isBipartite = true; for (int v = 0; v < G.V(); v++) if (!marked[v]) { dfs(G, v); } }
5e36f37f-0d64-4040-8d82-c5b0e836360b
8
private boolean evaluateBuildRBondClause(String str) { String[] s = str.split(REGEX_SEPARATOR); if (s.length != 3) return false; int n = model.getAtomCount(); double x = parseMathExpression(s[0]); // index of atom 1 if (Double.isNaN(x)) return false; int i = (int) x; if (i >= n) { out(ScriptEvent.FAILED, "Atom index out of limit: i=" + i + ">=" + n); return false; } x = parseMathExpression(s[1]); // index of atom 2 if (Double.isNaN(x)) return false; int j = (int) x; if (j >= n) { out(ScriptEvent.FAILED, "Atom index out of limit: j=" + j + ">=" + n); return false; } if (j == i) { out(ScriptEvent.FAILED, "Cannot build a radial bond between a pair of identical atoms: i=j=" + i); return false; } x = parseMathExpression(s[2]); // strength if (Double.isNaN(x)) return false; Atom a1 = model.getAtom(i); Atom a2 = model.getAtom(j); if (x > ZERO) { RBond rb = view.addRBond(a1, a2); rb.setStrength((float) x); view.repaint(); model.notifyChange(); } return true; }
5a8c96f1-4f1c-4d3b-8799-bf628adcec7f
5
@Test public void test2(){ String outputString = ""; String buffer = ""; File data = new File("german"); try { BufferedReader reader = new BufferedReader(new FileReader(data)); while((buffer = reader.readLine()) != null) { outputString += buffer; buffer = null; } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } ArrayList<String> list = new ArrayList<String>(); ArrayList<String> words = new ArrayList<String>(); Collections.addAll(list, outputString.split(" ")); int a = list.size(); for(String key : list){ key = key.substring(0, 1).toUpperCase() + key.substring(1).toLowerCase(); words.add(key); words.add(key.toLowerCase()); } Dictionary test = new Dictionary(); long start = System.currentTimeMillis(); for(String key : words){ test.getWordStatus(key); } System.out.println("Impoted: " + words.size() + " words!"); System.out.println("Import consumes: " + (System.currentTimeMillis() - start) + " ms"); }
79c47868-9ed0-46fc-a648-45b890094aa0
1
public void clear() { final Iterator iter = iterator(); while (iter.hasNext()) { ((Stmt) iter.next()).cleanup(); } super.clear(); }
e06ff12b-aea6-408b-93d9-ee88d11aa41a
0
@Override public void startSetup(Attributes atts) { outliner = this; setTitle(atts.getValue(A_TITLE)); // Load Preferences loadPrefsFile(PARSER, ENCODINGS_FILE); // Setup the FileFormatManager and FileProtocolManager fileFormatManager = new FileFormatManager(); fileProtocolManager = new FileProtocolManager(); loadPrefsFile(PARSER, FILE_FORMATS_FILE); }
6db3731f-e625-4c5c-b66d-b238be12a2ce
4
Grid (){ //gen 4x4 grid = new ArrayList<>(4); //gen y then x for (int i = 0; i < 4; i++) { grid.add(new ArrayList<Tile>()); for (int j =0 ; j < 4; j++){ grid.get(i).add(null); } } for (int i = 0; i < 2; i++) { if(!genTile()){ System.err.println("Grid: ctor> Grid full or could not gen any Tiles"); } } }
a55fe5fa-f9bf-4d5a-b3ec-2267ac7ae246
3
public void eliminaUltimo(){ if(this.inicio == null){ System.out.println("La lista esta vacia"); }else{ if(this.inicio.getLiga() == null){ this.inicio = null; }else{ Nodo<T> nodoQ = this.inicio; Nodo<T> nodoT = null; while(nodoQ.getLiga() != null){ nodoT = nodoQ; nodoQ = nodoQ.getLiga(); } nodoT.setLiga(null); } } }
1b80d54f-0966-4ee6-815a-6ae093b772b8
9
@Override public boolean sendDeath() { WorldTasksManager.schedule(new WorldTask() { int loop; @Override public void run() { if (loop == 0) { player.setNextAnimation(new Animation(836)); } else if (loop == 1) { player.getPackets().sendGameMessage( "Oh dear, you have died."); } else if (loop == 3) { int weaponId = player.getEquipment().getWeaponId(); if (weaponId == 4037 || weaponId == 4039) { CastleWars.setWeapon(player, null); CastleWars.dropFlag(player, weaponId == 4037 ? CastleWars.SARADOMIN : CastleWars.ZAMORAK); } else { Player killer = player .getMostDamageReceivedSourcePlayer(); // temporary // so // ppl // have // reason // to // play // cw if (killer != null) killer.increaseKillCount(player); } player.reset(); player.setNextWorldTile(new WorldTile( team == CastleWars.ZAMORAK ? CastleWars.ZAMO_BASE : CastleWars.SARA_BASE, 1)); player.setNextAnimation(new Animation(-1)); } else if (loop == 4) { player.getPackets().sendMusicEffect(90); stop(); } loop++; } }, 0, 1); return false; }
332297ed-b425-4592-8678-7837ead4dcec
4
public void setForecastDayAndNight(int aftertoday,Iterator<Element>tempit,WeatherInfo tempweather,int isNight){ Element tempElement; int i=0; while(tempit.hasNext()){ tempElement=tempit.next(); switch (i) { case 0:tempweather.setForecasttype(aftertoday, tempElement.getText(), isNight);break; case 1:tempweather.setForecastWindDirection(aftertoday,tempElement.getText(), isNight);break; case 2:tempweather.setForecastWindForce(aftertoday, tempElement.getText(), isNight);break; default: break; } i++; } }
c4d48873-3cd1-4328-89af-9ba580bc51bd
4
public static void main(String... args) { int biggestNum = 0; for (int i = 1000 - 1; i >= 100; i--) { for (int j = 1000 - 1; j >= 100; j--) { int target = (i * j); if (isPalindrome(target) && target > biggestNum) { biggestNum = target; } } } System.out.println(biggestNum); }
535b6752-aad8-4386-a977-8a35a343d03f
3
public void set(int symbol, int freq) { if (symbol < 0 || symbol >= frequencies.length) throw new IllegalArgumentException("Symbol out of range"); if (freq < 0) throw new IllegalArgumentException("Negative frequency"); total = checkedAdd(total - frequencies[symbol], freq); frequencies[symbol] = freq; cumulative = null; }
d3a4e5e5-decb-4465-bb94-5a04a1296488
3
public void activate(Robot paramRobot, int paramInt) { super.activate(paramRobot, paramInt); if (this.state != null) { Vector localVector = this.state.getSpecialProgramParts(); Enumeration localEnumeration = localVector.elements(); while (localEnumeration.hasMoreElements()) if ((localEnumeration.nextElement() instanceof Launch)) return; localVector.addElement(new Launch()); } }
f4ac2155-f9dd-4cf9-b2e1-42e9c8510aa0
5
private static void readSettings(){ //Checkbox was changed: Save changes to wini Wini ini; //Ini handler boolean firstSetup = false; try{ File settings = new File(NineManMill.settingsfile); if (!settings.exists()) { //If settings file does not exist, leave the default values settings.createNewFile(); firstSetup = true; return; } //load settings file ini = new Wini(settings); if (firstSetup){ //set values instead of reading them ini.put("Settings", "playmusic", 1); ini.put("Settings", "playsfx", 1); } else { //read values PLAY_SFX = (ini.get("Settings", "playsfx", int.class) == 1) ? true : false; //if the settings has 1 for playsfx, play, otherwise don't PLAY_MUSIC = (ini.get("Settings", "playmusic", int.class) == 1) ? true : false; //if the settings has 1 for playsfx, play, otherwise don't } ini.store(); } catch (IOException e1) { System.err.println("ERROR: Error with I/O when operating on settings file. Settings may not save."); e1.printStackTrace(); } }
78c1bd43-61a0-4682-abae-13549ab209d5
1
protected String removeCDATA(String title) { return ( title.indexOf("<![CDATA[") != NOT_FOUND ) ? title.substring(9, title.length() - 3) : title; }
3bdbb683-075c-4655-99a3-267e85216e29
0
private void btnCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCerrarActionPerformed //Cierra la interfaz de registro setVisible(false); }//GEN-LAST:event_btnCerrarActionPerformed
3b539f45-ad13-4137-a60e-e5e2d717e28c
2
@Override public void startUp(GameTime gameTime) { // Call the startUp methods of all the register GameLayers super.startUp(gameTime); // Change the mouse GameEngine.setCustomCursor(GameAssetManager.getInstance().getObject(BufferedImage.class, Configuration.GUI.Misc.GAME_MOUSE)); // Realign all of the menus off to the side int x = -menuWidth; // I remember reading that a foreach loop is faster than get(i), i have // no source to back this up though. We iterate through each logical // child added to the menuOptions gamelayer, in this case it will be // only the GameButtonGraphical children, and restart them to their // desired positions /** * Alternate between the menu item being to the left of the screen and * to the right of the screen so that they can be zoomed in */ int i = 0; for (ILogical logicalObject : menuOptions.getAllLogicalChildren()) { GameButton option = (GameButton) logicalObject; option.setX(i++ % 2 == 0 ? -menuWidth : GameSettings.getGameWidth()); } // Default the starting state of the stateManager to start animating the // menu buttons stateManager.setStartingState("animatingButtons"); }
1bae0f2e-ded5-450f-9edd-9f02e187b4c5
2
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: String file_name = "storage.txt"; try { ReadFile file = new ReadFile(file_name); String[] aryLines = file.OpenFile(); Integer b = i; if (i!=0){ i--; String[] info = (aryLines[i].split(";")); nameLabel.setText(info[0]); addressLabel.setText(info[1]); phoneLabel.setText(info[2]); mailLabel.setText(info[3]); num1Label.setText(b.toString()); } } catch (IOException e) { System.out.println( e.getMessage()); } }//GEN-LAST:event_jButton2ActionPerformed
e2ee0227-3266-4a39-acaf-32fa8b004f59
0
public void setInitialHeight(int initialHeight) { this.initialHeight = initialHeight; }
072d9ff8-c68e-4d90-b8b7-c65689daf6f2
0
public void setFirstName(String firstName) { this.firstName.set(firstName); }
9a173aa1-42d4-4f22-ae8c-3127446b2e85
9
@Override public void dragOver(DropTargetDragEvent event) { TreePanel panel = getPanel(); int x = panel.toHeaderView(new Point(event.getLocation())).x; TreeColumn overColumn = panel.overColumn(x); if (overColumn != null && overColumn != mColumn) { ArrayList<TreeColumn> columns = new ArrayList<>(panel.getColumns()); int over = columns.indexOf(overColumn); int cur = columns.indexOf(mColumn); int midway = panel.getColumnStart(over) + overColumn.getWidth() / 2; if (over < cur && x < midway || over > cur && x > midway) { if (cur < over) { for (int i = cur; i < over; i++) { columns.set(i, columns.get(i + 1)); } } else { for (int j = cur; j > over; j--) { columns.set(j, columns.get(j - 1)); } } columns.set(over, mColumn); panel.restoreColumns(columns); } } event.acceptDrag(DnDConstants.ACTION_MOVE); }
21c582f0-fcff-4ba6-8506-157a55061acb
2
private void closeOpenInterfaces() { // clearTopInterfaces outputStream.writeOpcode(130); if (invOverlayInterfaceID != -1) { invOverlayInterfaceID = -1; needDrawTabArea = true; aBoolean1149 = false; tabAreaAltered = true; } if (backDialogID != -1) { backDialogID = -1; inputTaken = true; aBoolean1149 = false; } openInterfaceId = -1; }
dd0ab2b7-9e60-4a52-97f7-cc93f1b1dfa5
7
@Override public void update(double time) { if (Input.getKeyDown(Keyboard.KEY_W) || Input.getKeyDown(Keyboard.KEY_UP)) { if (selectedOption > 0) { selectedOption--; } } if (Input.getKeyDown(Keyboard.KEY_S) || Input.getKeyDown(Keyboard.KEY_DOWN)) { if (selectedOption < 1) { selectedOption++; } } if (Input.getKeyDown(Keyboard.KEY_RETURN)) { buttonPressed(); } }
b1afe46f-8121-47b7-9b49-721f78f854db
8
public void run(){ RConsole.openUSB(10000); long updateStart, update; boolean objectDetected = false; boolean obstacle = false; boolean foam = false; int buffer = 0; while (true) { updateStart = System.currentTimeMillis(); ColorSensor.Color vals = censor.getColor(); ColorSensor.Color rawVals = censor.getRawColor(); int lightValue = vals.getBlue(); int rawBlue = rawVals.getBlue(); RConsole.println("Light Value"+ vals.getBlue()); RConsole.println("Raw value " + rawVals.getBlue()); if(lightValue > 50){ buffer++; if(buffer == 3){ objectDetected = true; } if(objectDetected == true){ if(rawBlue >= 450 && rawBlue <= 550){ RConsole.println("foam"); LCD.drawString(" foam " + rawBlue, 0, 1); foam = true; }else{ obstacle = true; LCD.drawString(" Obstacle " + rawBlue, 0, 1); RConsole.println(" obstacle"); } } }else{ buffer = 0; objectDetected = false; obstacle = false; foam = false; } update = System.currentTimeMillis(); if (update - updateStart < UPDATE_PERIOD) { try { Thread.sleep(UPDATE_PERIOD - (update - updateStart)); } catch (InterruptedException e) { } } } }
e2703d9f-3c01-4bc1-bc0b-22355e580ab1
4
private void optimizeMathe(){ //Mathe: 4 hjs mandatory if(myData.subjects[MATHE].writtenExamSubject==false){ int hjsToAdd; if(myData.subjects[MATHE].oralExamSubject==true){ hjsToAdd = 3; //since 13.2 is already in C } else {hjsToAdd = 4;} for(int hj=0; hj<hjsToAdd; hj++){ bScore += myData.subjects[MATHE].semesters[hj].mark; myData.subjects[MATHE].semesters[hj].usedState = Semester.UsedState.mandLegible; if (myData.subjects[MATHE].semesters[hj].mark>=5) failer.add1ToCounter(); } } }
2e07c9c8-6c31-44a4-b024-49dc79053b45
0
public static void main(String[] args) { System.out.println(ncr(40, 20)); }
34e01f2f-d2cb-47ad-9e4c-9aea55d85133
3
public static void closeDatabaseEngine() throws SQLException { try { dbProperties.put("shutdown", "true"); DriverManager.getConnection(dbProperties.getProperty("derby.url"), dbProperties); } catch (SQLException ex) { dbProperties.remove("shutdown"); // At database engine shutdown, Derby throws error 50.000 and SQLState XJ015 to show // that the operation was successful. int errorCode = ex.getErrorCode(); if (!(errorCode == 50000 && "XJ015".equals(ex.getSQLState()))) { throw ex; } log.info("Successfully disconnected from the database engine: {}", errorCode); } }
6d570f04-fdbf-4bf2-b695-5f9d1fbde126
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Stage other = (Stage) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
3cf311d7-f6fd-4b4b-b3fa-085174701f33
0
public void put(Object o) { addFirst(o); }
9db29fd4-1b33-434b-a5dc-3b909faf5adb
2
public static void main(String[] args) { // Listは宣言時に値を設定できる。 List<String> list1 = Lists.newArrayList("hoge", "huga", "piyo", "tao", "tarou"); SimpleLogger.debug(list1.toString()); // newHashMapは宣言時に値を設定できない、ImmutableMapはできるけど。 Map<String, Person> map1 = Maps.newHashMap(ImmutableMap.of( // "hoge", new Person(), "fuga", new Person("bbb", 11))); SimpleLogger.debug(map1.toString()); // Collectionにフィルターをかけられる。けどなんかくどい。 List<Integer> list2 = Lists.newArrayList(1, 2, 3, 4, 5, 6); Collection<Integer> list3 = Collections2.filter(list2, new Predicate<Integer>() { @Override public boolean apply(Integer input) { return (input % 2 == 0); } }); SimpleLogger.debug("filterd..." + list3.toString()); // Collectionに変換をかけられる。Mapはむりぽ。 Collection<String> list4 = Collections2.transform(list2, new Function<Integer, String>() { @Override public String apply(Integer input) { return "[" + input + "]"; } }); SimpleLogger.debug("transformed..." + list4.toString()); // Immutableなコレクション List<String> il = ImmutableList.of("hoge", "hufa", "piyo"); try { il.add("hoge"); } catch (UnsupportedOperationException e) { SimpleLogger.debug("immutable List is not Operation"); // 操作できない } Map<String, Person> im = ImmutableMap.of("hoge", new Person("taro", 1), "huga", new Person("jiro", 3)); try { im.remove("hoge"); } catch (UnsupportedOperationException e) { SimpleLogger.debug("immutable Map is not Operation"); // 操作できない。 } }
b188a625-a5b3-481d-85af-b4bef9d1cbec
2
private int popupSauvegarde () { if ( this.fileName == null ) return JOptionPane.CLOSED_OPTION ; int choix = GUIUtilities.question_YES_NO_CANCEL (Utilities.getLangueMessage( Constantes.MESSAGE_SAUVEGARDER_FICHIER_ENCOURS )) ; if (choix == JOptionPane.YES_OPTION) save(); return choix ; }
2c44f548-f952-4f5e-b850-25789669db6f
3
public static Subject[] findFLangSubjects(Data myData) { List<Subject> results = new ArrayList<>(); results.add(myData.subjects[ITA]); for(Subject thisWahlfach:myData.getWahlfaecher()) { if(thisWahlfach.getSubjectType()==FOREIGN_LANG) results.add(thisWahlfach); } if(results.isEmpty()) throw new NoSuchElementException(); Subject[] resultsArr = new Subject[results.size()]; resultsArr = results.toArray(resultsArr); return resultsArr; }
79494392-b3a5-4b58-ade2-624a2efb40e7
8
public void actionPerformed(ActionEvent e) { if (btnReadRow == e.getSource()) { try { readRow(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else if (btnWriteRow == e.getSource()) { writeRow(); } else if (btnReadCol == e.getSource()) { try { readCol(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else if (btnWriteCol == e.getSource()) { writeCol(); } else if (btnModRow == e.getSource()) { modifyRow(); } else if (btnModCol == e.getSource()) { modifyCol(); } }
621780e0-c179-4393-8c8d-28304839edce
5
private final void method1595(byte i, int i_17_, ByteBuffer class348_sub49) { anInt2852++; if (i >= 5) { if ((i_17_ ^ 0xffffffff) == -2) ((Class218) this).anInt2853 = class348_sub49.getShort(); else if ((i_17_ ^ 0xffffffff) != -3) { if (i_17_ == 3) ((Class218) this).aBoolean2854 = true; else if (i_17_ == 4) ((Class218) this).anInt2853 = -1; } else ((Class218) this).anInt2856 = class348_sub49.getTri(); } }
50daa7d2-a793-4bdc-8010-55262cb1a409
8
public TriangleContainer clone(){ TriangleContainer ret = new TriangleContainer(); if (leftAnglePoint!=null) ret.leftAnglePoint = new Point3D(leftAnglePoint); if (topAnglePoint!=null) ret.topAnglePoint = new Point3D(topAnglePoint); if (rightAnglePoint!=null) ret.rightAnglePoint = new Point3D(rightAnglePoint); if (middleTrianglePoint!=null) ret.middleTrianglePoint = new Point3D(middleTrianglePoint); if (normal!=null) ret.normal = normal.clone(); if (currentTriangleColor!=null) ret.currentTriangleColor = new Color(currentTriangleColor.getRGB()); if (Kd!=null) ret.Kd = Kd.clone(); if (Kf!=null) ret.Kf = Kf.clone(); return ret; }
a108480e-40a0-4cfc-8fbe-7bb811dd3ec1
3
public static boolean containsElement(Object[] array, Object element) { if (array == null) { return false; } for (Object arrayEle : array) { if (nullSafeEquals(arrayEle, element)) { return true; } } return false; }
5289a8f9-f437-46c4-99a3-edb5e0696d4d
0
public DynamicArray() { this.array = new Object[10]; this.size = 0; }
7b783166-f715-41dd-83de-1bf8193aef40
9
public SkillsPanel(EVECharacter character){ this.character = character; setLayout(new BorderLayout()); DBHandler db = new DBHandler(); for(int i=0;i<character.getSkills().size();i++){ Skill currentSkill = character.getSkills().get(i); if( isGroupExists(currentSkill.getType().getGroupID()) ){ getGroup(currentSkill.getType().getGroupID()).addSkill(currentSkill); }else{ this.groups.add(new SkillGroup(currentSkill.getType().getGroupID(),db.getGroupNameByID(currentSkill.getType().getGroupID()))); getGroup(currentSkill.getType().getGroupID()).addSkill(currentSkill); } } DefaultMutableTreeNode top = new DefaultMutableTreeNode("Skills"); int countlvl5=0; for(int i=0;i<groups.size();i++){ DefaultMutableTreeNode currentGroup = new DefaultMutableTreeNode(groups.get(i).getName()+" - "+Utils.formatLong(groups.get(i).getGroupSP())+" SP - "+groups.get(i).getLvl5()+" skills on lvl5"); for(int n=0;n<groups.get(i).getSkills().size();n++){ Skill currentSkill = groups.get(i).getSkills().get(n); if( currentSkill.getSkillLevel() == 4 ){ DefaultMutableTreeNode currSkillNode = new DefaultMutableTreeNode("<html><font color=#117777>"+currentSkill+" - lvl "+currentSkill.getSkillLevel()+"</font></html>"); currentGroup.add(currSkillNode); }else if( currentSkill.getSkillLevel() == 5 ){ DefaultMutableTreeNode currSkillNode = new DefaultMutableTreeNode("<html><font color=#117711>"+currentSkill+" - lvl "+currentSkill.getSkillLevel()+"</font></html>"); currentGroup.add(currSkillNode); }else{ DefaultMutableTreeNode currSkillNode = new DefaultMutableTreeNode("<html><font color=#771111>"+currentSkill+" - lvl "+currentSkill.getSkillLevel()+"</font></html>"); currentGroup.add(currSkillNode); } } countlvl5+=groups.get(i).getLvl5(); top.add(currentGroup); } top.setUserObject("Skills - "+Utils.formatLong(character.getSkillpoints())+" - "+countlvl5+" skills on lvl5"); tree = new JTree(top); DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer(); ImageIcon leaf = ImageHandler.getTypeIMG(character.getSkills().get(0).getType().getId()); ImageIcon root = null; try{ root = new ImageIcon(ImageIO.read(new File("img/0_32.png"))); }catch(Exception ex){ System.out.println("EX: "+ex.getMessage()); } if( leaf != null ){ renderer.setLeafIcon(leaf); if( root != null ){ renderer.setClosedIcon(root); renderer.setOpenIcon(root); }else{ renderer.setClosedIcon(leaf); renderer.setOpenIcon(leaf); } } tree.setCellRenderer(renderer); JScrollPane treeView = new JScrollPane(tree); treeView.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15)); add(treeView,BorderLayout.CENTER); }
a93c0ffb-e307-421c-b3db-27b5cb3b34de
6
public static <GInput, GOutput> Converter<GInput, GOutput> conditionalConverter(final Filter<? super GInput> condition, final Converter<? super GInput, ? extends GOutput> acceptConverter, final Converter<? super GInput, ? extends GOutput> rejectConverter) throws NullPointerException { return new Converter<GInput, GOutput>() { @Override public GOutput convert(final GInput input) { if (condition.accept(input)) return acceptConverter.convert(input); return rejectConverter.convert(input); } @Override public String toString() { return Objects.toInvokeString("conditionalConverter", condition, acceptConverter, rejectConverter); } }; }
7f1eec1d-bacd-477c-9d41-ec571707ada6
1
private void setCursor(Point point) { Point worldCoords = getWorldCoordinates(point); if (worldCoords != null) { ClientPlayer me = client.getSession().getSelf(); double angle = Math.atan2(worldCoords.y - me.getShooterMount().y, worldCoords.x - me.getShooterMount().x); me.setShooterAngle(angle); AdjustShooterAnglePacket packet = new AdjustShooterAnglePacket(); packet.angle = angle; client.send(packet); } }
442eff97-7250-41aa-9289-654f267f6df1
6
@Override public void run() { if (Updater.this.url != null) { // Obtain the results of the project's file feed if (Updater.this.read()) { if (Updater.this.versionCheck(Updater.this.versionName)) { if ((Updater.this.versionLink != null) && (Updater.this.type != UpdateType.NO_DOWNLOAD)) { String name = Updater.this.file.getName(); // If it's a zip file, it shouldn't be downloaded as the plugin's name if (Updater.this.versionLink.endsWith(".zip")) { final String[] split = Updater.this.versionLink.split("/"); name = split[split.length - 1]; } Updater.this.saveFile(new File(Updater.this.plugin.getDataFolder().getParent(), Updater.this.updateFolder), name, Updater.this.versionLink); } else { Updater.this.result = UpdateResult.UPDATE_AVAILABLE; } } } } }
fc645a08-6597-499f-a9dd-16aa837851a8
1
public void test_toFormatter() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); try { bld.toFormatter(); fail(); } catch (UnsupportedOperationException ex) {} bld.appendLiteral('X'); assertNotNull(bld.toFormatter()); }
86ad8e50-eebf-4fc7-8f76-b1b163b25f66
3
public void setToolBar(JToolBar newToolBar) { JToolBar oldToolBar = getToolBar(); if (oldToolBar == newToolBar) { return; } if (oldToolBar != null) { headerPanel.remove(oldToolBar); } if (newToolBar != null) { newToolBar.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); headerPanel.add(newToolBar, BorderLayout.EAST); } updateHeader(); firePropertyChange("toolBar", oldToolBar, newToolBar); }
67ef088e-32d4-4deb-a597-4484bb906c19
4
public static void main(String[] args){ PrintTimes printer = new PrintTimes(); PrintClusters cprinter = new PrintClusters(); TunableParameters params = TunableParameters.getInstance(); int runs = 1; int[][] allClusters = new int[runs][params.getDataSetSize()]; int[][] allKMClusters = new int[runs][params.getDataSetSize()]; for(int j = 0; j < runs; j ++){ System.out.println("Run: " + j); ArrayList<Double> times = new ArrayList<Double>(); ArrayList<String> titles = new ArrayList<String>(); double startTime = System.currentTimeMillis(); //read in dataset //BaseGraph rawGraph = new BaseGraph(); CSVReader rawGraph = new CSVReader(); //i think this creates a connected graph? //creating a planar graph might speed things up later on? times.add(System.currentTimeMillis()-startTime); titles.add("build graph"); //create MST // find MST using Prim's System.out.println("Finding MST"); PrimsMST primsMST = new PrimsMST(rawGraph.getGraph()); times.add(System.currentTimeMillis()-startTime); titles.add("create the MST"); //find relative distances //construct affinity matrix System.out.println("Finding affinity matrix"); AffinityMatrix am = new AffinityMatrix(primsMST); times.add(System.currentTimeMillis()-startTime); titles.add("find the affinity matrix"); //construct laplacian System.out.println("find eigen vectors"); Matrix laplacian = am.getUnnormLaplacian(); Matrix U = laplacian.eig().getV(); //times.add(System.currentTimeMillis()-startTime); //titles.add("laplacian"); //Laplacian lm = new Laplacian(am); //DataClusterer dc = new DataClusterer() // find eigenvectors associated with k smallest positve eigenvalues; int k = params.getNumberOfClusters(); double[][] Uarray = U.getArray(); double[][] Uarrayk = new double[Uarray.length][k]; for(int i = 0; i < Uarray.length; i++) { System.arraycopy(Uarray[i], 0, Uarrayk[i], 0, k); } times.add(System.currentTimeMillis()-startTime); titles.add("Finding Eigen Vectors"); //perform cluster evaluation KMeans km = new KMeans(Uarrayk,k); int[] clusters = km.calcClusters(); times.add(System.currentTimeMillis()-startTime); titles.add("cluster analysis"); //print clusters for(int i = 0; i < clusters.length; i++){ allClusters[j][i] = clusters[i]; } printer.print(times , "times" , titles); // plain ol kmeans on normalized data KMeans kmog = new KMeans(rawGraph.getDataAs2DArray(),k); int[] kMeansClusters = kmog.calcClusters(); for(int i = 0; i < clusters.length; i++){ allKMClusters[j][i] = kMeansClusters[i]; } } // print clusters cprinter.print(allClusters, "clusters"); cprinter.print(allKMClusters, "kmeans"); System.out.println("done"); }
4b40c445-0656-4b4d-afb0-0ba739c4a919
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(AddCompany.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AddCompany.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AddCompany.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AddCompany.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new AddCompany().setVisible(true); } }); }
3e8f6ef0-bd9b-4b1c-a386-a8bd7be8c643
6
public ListNode getIntersectionNode(ListNode headA, ListNode headB) { int firstCount = 0; int secondCount = 0; //First number of nodes in first list ListNode A = headA; while (A != null) { firstCount = firstCount + 1; A = A.next; } //Find number of nodes in second list ListNode B = headB; while (B != null) { secondCount = secondCount + 1; B = B.next; } if (firstCount > secondCount) { int diff = firstCount - secondCount; while (diff > 0) { headA = headA.next; diff = diff - 1; } } else if (secondCount > firstCount) { int diff = secondCount - firstCount; while (diff > 0) { headB = headB.next; diff = diff - 1; } } return getNode(headA, headB); }
a59b6af1-3af7-469e-a912-625a578f7e71
0
public MergeSort(int[] array){ this.array = array; }
5668efca-d821-4a3c-b40d-585b1b6d3e8d
9
@Override public void insert(K k) { // induction basis: BinarySearchTreeItem<K> p; if (root == null) { p = new BinarySearchTreeItem<K>(k); p.left = null; p.right = null; } else { p = root; } // induction step: while (true) { if (p.key == k) { if (p.left == null) { p.left = new BinarySearchTreeItem<K>(k); p.left.left = null; p.left.right = null; break; } else if (p.right == null) { p.right = new BinarySearchTreeItem<K>(k); p.right.left = null; p.right.right = null; break; } else { p = p.left; } } else if ((Integer) p.key > (Integer) k) { if (p.left == null) { p.left = new BinarySearchTreeItem<K>(k); p.left.left = null; p.left.right = null; break; } else { p = p.left; } } else if ((Integer) p.key < (Integer) k) { if (p.right == null) { p.right = new BinarySearchTreeItem<K>(k); p.right.left = null; p.right.right = null; break; } else { p = p.right; } } } }
f182a7a2-7fde-43e1-a6b4-22c8bccf0528
9
private static String calculate(String input) throws Exception { if (input.equals("")) { return(input); } double val1, val2, result; String output = null; String symbol; Stack<Double> stack; String[] symbols; stack = new Stack<Double>(); symbols = input.split(" "); for (int i = 0; i < symbols.length; i++) { symbol = symbols[i]; if (symbol.equals("")) { continue; } if (symbol.equals("+")) { val1 = stack.pop(); val2 = stack.pop(); result = val1 + val2; stack.push(result); } else if (symbol.equals("*")) { val1 = stack.pop(); val2 = stack.pop(); result = val1 * val2; stack.push(result); } else if (symbol.equals("-")) { val1 = stack.pop(); val2 = stack.pop(); result = val2 - val1; stack.push(result); } else if (symbol.equals("/")) { val1 = stack.pop(); val2 = stack.pop(); result = val2 / val1; stack.push(result); } else if (symbol.equals("=")) { output = fmt(stack.pop()); if (!stack.empty()) { throw new TooManyValuesException(); } } else { val1 = Double.parseDouble(symbol); stack.push(val1); } } return output; }
244400ca-1264-448b-a5fa-64ce84ffa4f0
9
public static int sizeOf(Class<?> cls) { if(cls == boolean.class) return 1; if(cls == byte.class) return 1; if(cls == char.class) return 2; if(cls == short.class) return 2; if(cls == int.class) return 4; if(cls == long.class) return 8; if(cls == float.class) return 4; if(cls == double.class) return 8; throw new IllegalArgumentException( "Cannot request size of non-primitive type"); }