method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
4736466f-fead-40d3-8928-572a59738144
9
@Override public boolean capturar(Posicao posicaoInicial, Posicao posicaoFinal) { for (int aux = 0; aux < 8; aux++) { if ((posicaoInicial.getColuna() + aux == posicaoFinal.getColuna()) && (posicaoInicial.getLinha() + aux == posicaoFinal.getLinha())) { return true; } if ((posicaoInicial.getColuna() - aux == posicaoFinal.getColuna()) && (posicaoInicial.getLinha() - aux == posicaoFinal.getLinha())) { return true; } if ((posicaoInicial.getColuna() + aux == posicaoFinal.getColuna()) && (posicaoInicial.getLinha() - aux == posicaoFinal.getLinha())) { return true; } if ((posicaoInicial.getColuna() - aux == posicaoFinal.getColuna()) && (posicaoInicial.getLinha() + aux == posicaoFinal.getLinha())) { return true; } } return false; }
012b7685-1e5e-4557-a433-5f7b75d97f95
0
public static void main(String[] args) { // Working with Accessors and Mutators Rectangle rectangle = new Rectangle(20, 50); rectangle.grow(5, 10); System.out.println(rectangle.getWidth()); System.out.println(rectangle.getHeight()); }
549c09c6-8287-4e2b-9929-e5cfaf19cec6
6
public int computeArithmeticValue() { if (!isConstExpression()) { throw new IllegalStateException("not const expression"); } switch (op) { case ADD: return lValue + rValue; case SUB: return lValue - rValue; case MUL: return lValue * rValue; case DIV: return lValue / rValue; case NEG: return -lValue; default: throw new IllegalStateException("not arithemetic op:" + op); } }
ae375cf1-5b5c-43dc-8856-e50c813821c4
4
public boolean isOptOut() { synchronized (optOutLock) { try { // Reload the metrics file configuration.load(getConfigFile()); } catch (IOException ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); } return true; } catch (InvalidConfigurationException ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); } return true; } return configuration.getBoolean("opt-out", false); } }
54a50261-7012-4243-956e-c1c79f73bef7
2
private void initialiseManagers() { if ( SQLManager.initialiseConnections() ) { DatabaseTableManager.createDefaultTables(); AnnouncementManager.loadAnnouncements(); // if ( MainConfig.UserSocketPort ) { // SocketManager.startServer(); // } ChatManager.loadChannels(); PrefixSuffixManager.loadPrefixes(); PrefixSuffixManager.loadSuffixes(); TeleportManager.initialise(); try { WarpsManager.loadWarpLocations(); PortalManager.loadPortals(); SpawnManager.loadSpawns(); } catch ( SQLException e ) { e.printStackTrace(); } //test } else { // setupSQL(); LoggingManager.log( ChatColor.DARK_RED + "Your BungeeSuite is unable to connect to your SQL database specified in the config" ); } }
369c6cbb-6e79-4d7d-974a-125b9bd8f4e3
9
public void teach(double ordM, double invM) throws IOException{ double[] in; NeuronKoh lastWin = winner; while(!teached()){ in = ImageGenerator.getInstance().getRandLetterNoise(ordM,invM); neurons.get(0).trigger(in); winnerNET = neurons.get(3).lastResult; winner = neurons.get(3); for(NeuronKoh n : neurons) { n.trigger(in); if ((n.getLastResult() > winnerNET) ) { winner = n; winnerNET = n.getLastResult(); } } winner.adjustWeights(in, 1); for(NeuronKoh n : neurons) { double s = n.lastResult / (10 * winner.getLastResult()); if (Double.isNaN(s) ) System.out.println("NAN"); if ((n != winner) && (Math.abs(s) < 1) && (n.lastResult * winner.lastResult > 0)) n.adjustWeights(in, s); } winnerNum = neurons.indexOf(winner); System.out.println("winner is "+ String.valueOf(winnerNum)); if (lastWin == winner) winner.timesWin++; iterCount++; this.setWeightsImage(); } mw.getjButton1().enable(); mw.getjButton2().enable(); mw.getjButton3().enable(); mw.getjButton4().enable(); }
a633552f-d6ee-40b5-af5b-6a6a45b84347
0
public static short getSample(byte[] buffer, int position) { return (short)( ((buffer[position+1] & 0xff) << 8) | (buffer[position] & 0xff)); }
9abfc70d-2b1b-4910-b336-0aef5c12668c
9
public static void show(JFrame parent) { createComponents(); JPanel conent = createGUI(); int choice = 0; while (true) { choice = JOptionPane.showOptionDialog(parent, conent, Main.TITLE_MED, JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, new String[] {"Create", "Cancel"}, 0); if (choice != 0) { allOK = false; break; } if (!allOK) { check(); } else { check(); if (allOK) { int port = Integer.parseInt(portField.getText()); int players = Integer.parseInt(playersField.getText()); Settings.setLastCreateInfo(port, players, joinGameBox.isSelected()); Settings.save(); try { Server.start(port, players); StringSelection ipStr = new StringSelection( ipValue.getText() + ":" + portField.getText()); Toolkit.getDefaultToolkit().getSystemClipboard() .setContents(ipStr, null); if (joinGameBox.isSelected()) { Deck deck = Settings.getDeck(); if (deck == null) { JOptionPane.showMessageDialog(parent, "Could not load chosen deck", Main.TITLE_SHORT, JOptionPane.ERROR_MESSAGE); } else { try { new game.Client(parent, Settings.getName(), "localhost", Integer.parseInt(portField.getText()), deck); parent.setVisible(false); } catch (InvalidDeckException ex) { Debug.p("Deck rejected by the server: " + ex); JOptionPane.showMessageDialog(parent, "Your deck has been rejected by the server: " + ex.getLocalizedMessage(), Main.TITLE_SHORT, JOptionPane.WARNING_MESSAGE); break; } catch (Exception ex) { Debug.p("Could not join a host: " + ex, Debug.CE); } } } break; } catch (IOException ex1) { // Logger.getLogger(ServerFrame.class.getName()).log(Level.SEVERE, null, ex1); messagesField.setText("Could not create a server:\n" + ex1); allOK = false; } } } } allOK = false; }
fc2d6392-4405-4765-9ed0-72c542fd8ef7
7
public static void selectWordRightText(OutlinerCellRendererImpl textArea, JoeTree tree, OutlineLayoutManager layout) { Node currentNode = textArea.node; int currentPosition = textArea.getCaretPosition(); String text = textArea.getText(); int text_length = text.length(); if (currentPosition == text_length) { return; } // Update Preferred Caret Position char[] chars = text.substring(currentPosition,text_length).toCharArray(); char c = chars[0]; boolean isWordChar = false; if (Character.isLetterOrDigit(c) || c == '_') { isWordChar = true; } int i = 1; for (; i < chars.length; i++) { c = chars[i]; if ((Character.isLetterOrDigit(c) || c == '_') == !isWordChar) { break; } } int newCaretPosition = currentPosition + i; tree.getDocument().setPreferredCaretPosition(newCaretPosition); // Record the CursorPosition only since the EditingNode should not have changed tree.setCursorPosition(newCaretPosition, false); textArea.moveCaretPosition(newCaretPosition); // Redraw and Set Focus if this node is currently offscreen if (!currentNode.isVisible()) { layout.draw(currentNode,OutlineLayoutManager.TEXT); } // Freeze Undo Editing UndoableEdit.freezeUndoEdit(currentNode); }
6e91651d-d9a9-438c-932b-8f97184a6942
7
@Override public void showDialog(DialogAction dialogAction, int row, String code) { if (DialogAction.UPDATE.equals(dialogAction) && (row == BAD_ROW || code == null)) { throw new UnsupportedOperationException("You can not perform this action"); } JDialogTeacher dialogTeacher = new JDialogTeacher(getParentForDialog()); dialogTeacher.installEscapeCloseOperation(); Teacher teacher; if (DialogAction.UPDATE.equals(dialogAction)) { teacher = teacherController.getByCode(code); dialogTeacher.setEntity(teacher); } dialogTeacher.setVisible(true); teacher = dialogTeacher.getEntity(); if (teacher == null) { return; } switch (dialogAction) { case INSERT: addRow(teacher); break; case UPDATE: setRowValues(row, teacher); break; } }
4df14f4e-b3ac-4dc8-b279-0667bb831ca3
2
public void open() { FileNameExtensionFilter filter = new FileNameExtensionFilter( "Windows BMP file", "bmp"); FileNameExtensionFilter filter2 = new FileNameExtensionFilter( "JPEG file", "jpg", "jpeg"); FileNameExtensionFilter filter3 = new FileNameExtensionFilter("PNG", "png"); // TODO all img FileNameExtensionFilter filter4 = new FileNameExtensionFilter( "All images", "png", "jpg", "jpeg", "bmp"); JFileChooser chooserOpen = new JFileChooser(); chooserOpen.addChoosableFileFilter(filter4); chooserOpen.addChoosableFileFilter(filter); chooserOpen.addChoosableFileFilter(filter2); chooserOpen.addChoosableFileFilter(filter3); if (chooserOpen.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { File file = chooserOpen.getSelectedFile(); GUI.setTitle(file.getName() + " - GrapficEditor " + Constants.ver + " \"" + Constants.verName + "\" " + lang); try { image = ImageIO.read(file); GUI.open(image.getWidth(), image.getHeight()); image = ImageIO.read(file); } catch (IOException e) { e.printStackTrace(); } } }
196d3c85-b9db-4990-ac0a-1d5b6d363479
8
@Override public List<Predicat> createPredicats(Request request, List<Predicat> predicats) throws Exception { DataSetApplication dsApplication = (DataSetApplication) getContext().getAttributes().get("DataSetApplication"); DataSet ds = dsApplication.getDataSet(); Form params = request.getResourceRef().getQueryAsForm(); boolean filterExists = true; int i = 0; while (filterExists) { String index = TEMPLATE_PARAM.replace("#", Integer.toString(i++)); String formParam = params.getFirstValue(index); if (formParam != null) { String[] parameters = formParam.split("\\|"); TYPE_COMPONENT[] types = TYPE_COMPONENT.values(); Boolean trouve = false; for (TYPE_COMPONENT typeCmp : types) { if (typeCmp.name().equals(parameters[TYPE])) { trouve = true; } } if (trouve) { if (checkValues(parameters)) { String[] columnsAlias = parameters[COLUMN].split(","); ArrayList<Column> columns = new ArrayList<Column>(); for (String columnAlias : columnsAlias) { Column col = ds.findByColumnAlias(columnAlias); if (col != null) { columns.add(col); } } SitoolsSQLDataSource dsource = SitoolsSQLDataSourceFactory.getDataSource(ds.getDatasource().getId()); RequestSql requestSql = RequestFactory.getRequest(dsource.getDsModel().getDriverClass()); String longRunColStr = requestSql.convertColumnToString(columns.get(0)); String shortRunColStr = requestSql.convertColumnToString(columns.get(1)); String centerColStr = requestSql.convertColumnToString(columns.get(2)); String anticenterColStr = requestSql.convertColumnToString(columns.get(3)); boolean longRunValue = Boolean.valueOf(SQLUtils.escapeString(values[0])); boolean shortRunValue = Boolean.valueOf(SQLUtils.escapeString(values[1])); boolean centerValue = Boolean.valueOf(SQLUtils.escapeString(values[2])); boolean anticenterValue = Boolean.valueOf(SQLUtils.escapeString(values[3])); Predicat predicat = new Predicat(); predicat.setStringDefinition(" AND ("+longRunColStr+" = "+longRunValue+" OR "+shortRunColStr+" = "+shortRunValue+")"+" AND ("+centerColStr+ " = "+ centerValue+" OR "+anticenterColStr+" = "+anticenterValue+")"); predicats.add(predicat); } } }else { filterExists = false; } } return predicats; }
d89a46e2-2d15-49d3-a291-2de6ec0be266
0
public static boolean keyboardKeyState(int key) { return keyboardState[key]; }
24217f99-c2cb-4fe3-97b2-83d0f90eed2e
6
protected void play() throws Exception { BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in)); tick = 0; printConfig(); printStep(); for (tick = 1; tick <= MAX_TICKS; tick++) { // step by step trace if (trace) { try { System.err.print("$"); buffer.readLine(); } catch (Exception e) {} } // Make a copy of current status Parking[] lcopy = copyList(left); Parking[] rcopy = copyList(right); MovingCar[] movingcopy = movingCars.toArray(new MovingCar[0]); // Let the player set the lights player.setLights(movingcopy, lcopy, rcopy, llights, rlights); printLights(llights, rlights); // simulate one step boolean success = playStep(llights, rlights, tick); // does simulation succeed? if (!success) break; printStep(); // does game end? if (deliveredCars == cars.size()) break; } if (cars.size() != deliveredCars) System.err.println("Player fails to deliver all the cars."); else System.err.println("Player finishes with penalty: " + penalty); }
de4b2464-8c70-45b9-bf02-6dbe4c6e17b4
5
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Coordinate other = (Coordinate) obj; if (x != other.x) return false; if (y != other.y) return false; return true; }
9b090e99-9f37-4996-b85c-77f768e43ed1
8
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PhpposSalesItemsTaxesEntity that = (PhpposSalesItemsTaxesEntity) o; if (itemId != that.itemId) return false; if (Double.compare(that.percent, percent) != 0) return false; if (saleId != that.saleId) return false; if (name != null ? !name.equals(that.name) : that.name != null) return false; return true; }
2df19f3f-159f-44f8-92e8-ea3fd1d0c50f
8
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CPU other = (CPU) obj; if (cacheSize != other.cacheSize) return false; if (frequency != other.frequency) return false; if (numberOfCores != other.numberOfCores) return false; if (numberOfThreads != other.numberOfThreads) return false; if (socket != other.socket) return false; return true; }
01ea0d2a-cb3c-4c44-a717-e27081de3e5d
1
public void ih(String[] n) { for (int i = 0; i < n.length; i++) { System.out.println(n[i]); } }
b0ee7199-a3d9-4796-bf47-3752431a698f
0
private JCellule[][] getGrid() { WindowPrincipale window = (WindowPrincipale) this.getParent().getParent().getParent().getParent().getParent(); return window.getPanelGrid().getGrid(); }
fcd52667-b5c6-497c-b9ef-73d1be11702e
9
private boolean isValidDiagonalMove(int r1, int c1, int r2, int c2) { if (Math.abs(r1 - r2) != Math.abs(c1 - c2)) { return false; } int stepR = r1 - r2 < 0 ? 1 : -1; int stepC = c1 - c2 < 0 ? 1 : -1; if (stepC > 0) { for (int r = r1 + stepR, c = c1 + stepC; c < c2; c += stepC, r += stepR) { if (board[r][c] != EMPTY) { return false; } } } else if (stepC < 0) { for (int r = r1 + stepR, c = c1 + stepC; c > c2; c += stepC, r += stepR) { if (board[r][c] != EMPTY) { return false; } } } return true; }
96ed9750-10bd-4ef5-947c-79b276fffb9c
6
private void Flug ( int num, int lineNum, String str ) { //tOɂG[ switch ( num ) { case 1: System.out.print ( "Error: ̃}bvLqĂ܂Aǂꂩ‚ɓꂵĂ" ); break; case 2: System.out.print ( "Error: Õ|Cgłɑ݂Ă܂" ); break; case 3: System.out.print ( "Error: oH̓łɑ݂Ă܂" ); break; case 4: System.out.print ( "Error: ݂Ȃ|CgQƂ悤Ƃ铹łB@̖OC邩AԂmFĂ" ); break; case 5: System.out.print ( "Error: ǂݍ݂Ɋ֌ŴȂs}Ă܂B@̍s͓ǂݔ΂܂B@Xy~XA`FbNĂ" ); break; case 6: System.out.println ( "Error: ̋Lqɖ肪܂ ‚Ȃ|Cg͓{ɂ‚A‚ł" ); break; default: System.out.print ( "Error: ̑̃G[Ă܂B@YsmF邩AǗ҂ɖ₢킹Ă" ); break; } System.out.println ( "( sԍ" + lineNum + ": " + str + " )" ); //G[bZ[WóAK̃G[̂s߂ }
3b38d10c-a9a8-40ed-9e96-c5e0661e9e9e
7
public int resolve(boolean enhancedVerbosity) { if (upper.equals(BigInteger.ZERO)) return 0; if (upper.equals(BigInteger.ONE)) return 1; int rightMostBit = upper.getLowestSetBit(); BigInteger oddDivisor = upper.shiftRight(rightMostBit); int first = resolveTwoOverLower(rightMostBit); int third = resolveSign(oddDivisor); if (oddDivisor.equals(BigInteger.ONE)) { if (this.logger != null && enhancedVerbosity) { this.logger.log(String.format("%s over %s = %d", upper.toString(), lower.toString(), first * third)); } return first * third; } int second = new JacobiSymbol(lower.mod(oddDivisor), oddDivisor, logger).resolve(enhancedVerbosity); if (this.logger != null && enhancedVerbosity) { this.logger.log(String.format("%s over %s = %d", upper.toString(), lower.toString(), first * second * third)); } return first * second * third; }
f083b629-4ed1-4e03-9138-f7952f2a39de
0
public void clearSelectedTransitions() { selectedTransitions.clear(); }
19ee591f-eef9-4cdd-9e1a-3cd0fe7f5388
1
private JFormattedTextField getTextField( JSpinner spinner ) { JComponent editor = spinner.getEditor(); if ( editor instanceof JSpinner.DefaultEditor ) { return ( ( JSpinner.DefaultEditor )editor ).getTextField(); } else { System.err.println( "Unexpected editor type: " + spinner.getEditor().getClass() + " isn't a descendant of DefaultEditor" ); return null; } }
be82a927-0b1a-4f81-aa04-145361602e5d
8
public List<TreeNode> generateTrees(int n) { if(n<0) return null; myele []Trees =new myele[n+1]; if(n==0) {myele t= new myele();t.add(null);return t.value;} Trees[1] = new myele(1); if(n==1){return Trees[1].value;} TreeNode root; for(int i=2;i<=n;i++) { Trees[i] = new myele(); for(TreeNode node:Trees[i-1].value) { //其余的树作为右子树插入 root = new TreeNode(i); root.left = copy(node); Trees[i].add(root); { //i为单节点插入到 i-1中 TreeNode temp = copy(node); AddTree(temp, i); Trees[i].add(temp); } } //i为父节点,j 到 i-1 作为子节点 插入到 j-1 对应的子树中去 for(int j=i-1;j>1;j--) { for(TreeNode temp:Trees[j-1].value) { int Margin = j-1; for(TreeNode temp2:CreateTree(Trees[i-j].value, Margin)) { root = new TreeNode(i); TreeNode temp3 = copy(temp); AddTree(temp3, root); root.left = temp2; Trees[i].add(temp3); } } } } return Trees[n].value; }
31011962-732f-450a-88f1-2ad69c7ec45c
9
protected synchronized String getLine(String prefix) throws IOException { long midpoint; String rightHalf; String leftHalf; String currentLine; int comparison; String match = null; long lower = 0; long upper = getFileSize(); long range = (upper - lower); long seekTarget = getFilePointer(); // Loop while we still have a part of the file to search while (range > 0) { // Jump to the location in the middle of our search range midpoint = lower + (range / 2); seek(midpoint); // If we're not at the beginning of the file, read the "next" line. if (midpoint > 0) { // Get text that may be a fragment / portion of a line rightHalf = readToNextEndOfLine(); // Get what we KNOW will be a full line currentLine = readToNextEndOfLine(); // If we read part of the last line, there isn't one after it if (currentLine.length() == 0) { leftHalf = readToPriorEndOfLine(midpoint); currentLine = leftHalf + rightHalf; seek(getFileSize()); } } // We're at the very beginning of the file; it's a complete line else { currentLine = readToNextEndOfLine(); rightHalf = ""; } // We have a line we can compare with our search target if (currentLine.length() > 0) { // If it matches, we're done if (currentLine.startsWith(prefix)) { match = currentLine; seekTarget = getFilePointer(); break; } // No match; see if it's less than or greater than else { comparison = prefix.compareTo(currentLine); // If less than, shift lower bound if (comparison > 0) { lower = getFilePointer(); } // It's greater than what we're looking for else { // Get remainder of partial line and compare it leftHalf = readToPriorEndOfLine(midpoint); currentLine = leftHalf + rightHalf; // If the line we landed on is a match we're done if (currentLine.startsWith(prefix)) { match = currentLine; seekTarget = getFilePointer() + match.length() + 1; break; } // No match; see if it's less than or greater than comparison = prefix.compareTo(currentLine); // If less than, shift lower bound if (comparison < 0) { upper = getFilePointer(); } // If we got here the line doesn't exist in the file else { break; } } } } // If we got here, the line doesn't exist in the file else { break; } // Adjust the range range = upper - lower; } // If we have a match, make sure to point past the end of the line if (match != null) { seek(seekTarget); } return match; }
b24918f5-6076-4b26-befa-601b75cd63b0
4
final public void run() { connectionEstablished(); // The message from the server Object msg; // Loop waiting for data try { while (!readyToStop) { // Get data from Server and send it to the handler // The thread waits indefinitely at the following // statement until something is received from the server msg = input.readObject(); // Concrete subclasses do what they want with the // msg by implementing the following method handleMessageFromServer(msg); } } catch (Exception exception) { if (!readyToStop) { try { closeAll(); } catch (Exception ex) { } connectionException(exception); } } finally { clientReader = null; } }
4692c8cc-52df-4afa-bbd3-dcf41b0767d4
3
public void setExpLogica(PExpLogica node) { if(this._expLogica_ != null) { this._expLogica_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._expLogica_ = node; }
409e6e5e-0198-417a-a3e7-dd6f46c492f0
9
public GL_Mesh makeMeshObject(GL_OBJ_Reader objData) { ArrayList verts = objData.vertices; ArrayList txtrs = objData.textureCoords; ArrayList norms = objData.normals; ArrayList faces = objData.faces; // make a new mesh mesh = new GL_Mesh(); mesh.name = objData.filename; mesh.materialLibeName = objData.materialLibeName; mesh.materials = (objData.materialLib != null)? objData.materialLib.materials : null; // add verts to GL_Mesh for (int i = 0; i < verts.size(); i++) { float[] coords = (float[]) verts.get(i); mesh.addVertex(coords[0], coords[1], coords[2]); } // allocate space for groups mesh.makeGroups(objData.numGroups()); // init each group (allocate space for triangles) for (int g = 0; g < objData.numGroups(); g++) { mesh.initGroup(g, objData.getGroupName(g), objData.getGroupMaterialName(g), objData.getGroupTriangleCount(g)); } // add triangles to GL_Mesh. OBJ "face" may be a triangle, // quad or polygon. Convert all faces to triangles. for (int g = 0; g < objData.numGroups(); g++) { int triCount=0; faces = objData.getGroupFaces(g); for (int i = 0; i < faces.size(); i++) { Face face = (Face) faces.get(i); // put verts, normals, texture coords into triangle(s) if (face.vertexIDs.length == 3) { addTriangle(mesh, g, triCount, face, txtrs, norms, 0, 1, 2, face.materialID); triCount++; } else if (face.vertexIDs.length == 4) { // convert quad to two triangles addTriangle(mesh, g, triCount, face, txtrs, norms, 0, 1, 2, face.materialID); triCount++; addTriangle(mesh, g, triCount, face, txtrs, norms, 0, 2, 3, face.materialID); triCount++; } else { // convert polygon to triangle fan, with first vertex (0) // at center: 0,1,2 0,2,3 0,3,4 0,4,5 for (int n = 0; n < face.vertexIDs.length - 2; n++) { addTriangle(mesh, g, triCount, face, txtrs, norms, 0, n + 1, n + 2, face.materialID); triCount++; } } } } // optimize the GL_Mesh mesh.rebuild(); // if no normals were loaded, generate some if (norms.size() == 0) { mesh.regenerateNormals(); } return mesh; }
b2fded24-af99-4722-8b45-891cd439906f
5
public void connect() { if (username.length() == 0) { return; } if (portField.length() == 0) { return; } if (serverField.length() == 0) { return; } int port = 0; try { port = Integer.parseInt(portField); } catch (Exception e) { return; } client = new ClientEngine(serverField, port, username, this); if (!client.start()) return; connected = true; sendText.setEditable(true); sendText.setText(""); connectButton.setEnabled(false); discButton.setEnabled(true); fileLogin.setEnabled(false); connect.setEnabled(false); }
36f5e05d-9662-4cac-b711-68413e75ab80
4
public void removeFromCW() { if (c.castleWarsTeam == 1) { if (c.inCwWait) { Server.castleWars.saradominWait.remove(Server.castleWars.saradominWait.indexOf(c.playerId)); } else { Server.castleWars.saradomin.remove(Server.castleWars.saradomin.indexOf(c.playerId)); } } else if (c.castleWarsTeam == 2) { if (c.inCwWait) { Server.castleWars.zamorakWait.remove(Server.castleWars.zamorakWait.indexOf(c.playerId)); } else { Server.castleWars.zamorak.remove(Server.castleWars.zamorak.indexOf(c.playerId)); } } }
8d3a5984-4b80-47ae-8190-b0d320b0a4ce
6
public static boolean isValidDimension(double width, double height) { if (width < 0 || height < 0) return false; if (width > Double.MAX_VALUE || height > Double.MAX_VALUE) return false; if(Double.isNaN(width) || Double.isNaN(height)) return false; return true; }
cf78fd14-a628-499b-a2e7-ef740a9d38cc
0
@FXML private void handleBtnCancelAction(ActionEvent event) { userAction = UserAction.CANCEL; hide(); }
83636578-fcfc-4bc1-86e4-4c85903b7b5e
6
private void getSaisieCryptanalyse() { ISaisieCryptanalyse s=new SaisieCryptanalyse(this, this.menu); while(s.estEnCours() && !this.stop) { try { Thread.sleep(100); } catch (InterruptedException e) { } } s.masquer(); if(!this.stop) { if(s.getType()!=null) { IMessage m=s.getMessage(); Interface.CODES typ=s.getType(); this.res=Interface.cryptanalyse(m, typ); } else { IMessage m=s.getMessage(); this.res=Interface.cryptanalyseTout(m); } if(this.res.foundMessage()) { s.liberer(); s=null; this.enregistrerMessage(); } else { JOptionPane.showMessageDialog(null, "Echec de la cryptanalyse", "Echec", JOptionPane.WARNING_MESSAGE); s.liberer(); s=null; this.setAction(ACTIONS.CRYPTANALYSE); this.action(); } } }
5b21c663-b8fb-44ad-8ac1-063d5e2973a8
6
public void retry(String query) { boolean passed = false; Connection connection = open(); Statement statement = null; count = 0; while (!passed || count < timeout) { try { statement = connection.createStatement(); statement.executeQuery(query); statement.close(); connection.close(); passed = true; } catch (SQLException ex) { if (ex.getMessage().toLowerCase().contains("locking") || ex.getMessage().toLowerCase().contains("locked") ) { passed = false; count++; this.writeError("Locked",false); } else { this.writeError("Error at SQL Query: " + ex.getMessage(), false); } } } if(count >= timeout) { this.writeError("Failed to write to SQLite database. Timed out.",true); } }
94ec82b2-c57d-42c6-a724-774da4417666
2
public void update() { speedX = bg.getSpeedX() * 5; tileX += speedX; r.setBounds(tileX, tileY, 40, 40); if (r.intersects(Robot.yellowRed) && type != 0) { checkVerticalCollision(Robot.rect, Robot.rect2); checkSideCollision(Robot.rect3, Robot.rect4, Robot.footleft, Robot.footright); } }
f0fcc48f-6372-4cdb-8fa8-80793736def3
6
@SuppressWarnings("unchecked") public synchronized Resource getResource(Object key){//How can I get the referent from the key? I'd like to check if the specified referent has been enqueued. if(shutdown) throw new IllegalStateException(); boolean keyAvailable = true; while(true){ PhantomReference<Object> ref; Resource res = null; if((ref = (PhantomReference<Object>) queue.poll()) != null){ res = refs.get(ref);//"ref" is no longer available. refs.remove(ref); if(res != null){ keyAvailable = false; res.release(); } ref.clear();//Then, "key" referred to by "ref" is retrieved. } else//There is no key to be retrieved. break; } if(keyAvailable){ Resource res = new ResourceImpl(key); Reference<?> ref = new PhantomReference<Object>(key, queue);//It is possible to get the object by way of "ref" from the key. refs.put(ref, res); return res; } //key is not available return null; }
58b8d9e3-ef04-4ddc-a5ed-b8e68fe6aefe
5
public static void main(String[] args) throws PriceException { PropertyConfigurator.configure("src/resources/java/Log4J.properties"); Client cl = new Client("Jan", "Kowalski"); Client cl2 = new Client("Bartosz", "Posiakow"); try { cl.addMotorcycle(Brand.Honda, "CBR 600RR", 59000, 2003); cl.addMotorcycle(Brand.Suzuki, "GSXR 750", 64000, 2002); cl.addMotorcycle(Brand.Yamaha, "R1", 56900, 2001); cl.addMotorcycle(Brand.Aprillia, "Factory", 73000, 2003); } catch (PriceException exception) { logger.error(exception); } cl.printMotoCatalog(); // cl.deleteMotorcycle(cl.findAllMotorcycleByModel("CBR 600RR")); System.out.println("\n_______________________"); ClientDBManager dbClient = new ClientDBManager(); dbClient.addClient(cl); dbClient.addClient(cl2); for (Client client : dbClient.getAllClient()) { System.out.println(client.getSurname()); } System.out.println("\n_______________________"); MotoDBManager dbMoto = new MotoDBManager(); dbMoto.addMotorcycle(new Motorcycle(Brand.BMW, "1000RR", 80000, 2011)); dbMoto.addMotorcycle(new Motorcycle(Brand.Yamaha, "R1", 56900, 2001)); dbMoto.addMotorcycle(new Motorcycle(Brand.Aprillia, "Factory", 73000, 2003)); for (Motorcycle motorcycle : dbMoto.getAllMotorcycles()) { System.out.println("Brand: " + motorcycle.getBrand() + "\tModel: " + motorcycle.getModel() + "\tPrice: " + motorcycle.getPrice() + "\tYear of manufacture: " + motorcycle.getYearOfManufacture()); } ClientMotorcycleDBManager dbClientMotorcycle = new ClientMotorcycleDBManager(); dbClientMotorcycle.addMotorcycleToClient(dbClient.findClientBySurname("Kowalski"), dbMoto.findMotorcycleByModel("R1")); dbClientMotorcycle.addMotorcycleToClient(dbClient.findClientBySurname("Posiakow"), dbMoto.findMotorcycleByBrand(Brand.Aprillia)); System.out.println("_______________________"); System.out.println("Lista motocykli Posiakow"); System.out.println("_______________________"); for (Motorcycle motorcycle : dbClientMotorcycle.getClientMotorcycle(dbClient.findClientBySurname("Posiakow"))) { System.out.println("Brand: " + motorcycle.getBrand() + "\tModel: " + motorcycle.getModel() + "\tPrice: " + motorcycle.getPrice() + "\tYear of manufacture: " + motorcycle.getYearOfManufacture()); } System.out.println("_______________________"); System.out.println("Lista motocykli Kowalski"); System.out.println("_______________________"); for (Motorcycle motorcycle : dbClientMotorcycle.getClientMotorcycle(dbClient.findClientBySurname("Kowalski"))) { System.out.println("Brand: " + motorcycle.getBrand() + "\tModel: " + motorcycle.getModel() + "\tPrice: " + motorcycle.getPrice() + "\tYear of manufacture: " + motorcycle.getYearOfManufacture()); } //----- dbClientMotorcycle.deleteAllClientMotorcycle(); dbMoto.deleteAllMotorcycle(); dbClient.deleteAllClient(); }
9051a322-9323-4f7f-a0f2-5f2e6c90d05c
3
public static SpriteID getSpriteID2(EntityType type) { switch (type) { case OBJ_TREE: return EnviroSprite.tree_dead_1; case OBJ_DOOR_WOOD: return EnviroSprite.door_wooden_open; case ENTR_DUNGEON: return EnviroSprite.stone_hatch_open; } return EnviroSprite.gray_tiled_2; }
a9932096-ba96-442a-8450-354ef0b2605e
9
private boolean execGetFeatureGroup(VectorMap queryParam, StringBuffer respBody, DBAccess dbAccess) throws SQLException { int clntIdx = queryParam.qpIndexOfKeyNoCase("clnt"); String clientName = (String) queryParam.getVal(clntIdx); int usrIdx = queryParam.qpIndexOfKeyNoCase("usr"); if (usrIdx == -1) { WebServer.win.log.error("-The parameter usr is missing: "); return false; } String user = (String) queryParam.getVal(usrIdx); String nameParameter = null; int nameIdx = queryParam.qpIndexOfKeyNoCase("name"); if (usrIdx != -1) { nameParameter = (String) queryParam.getVal(nameIdx); } StringBuilder sql = new StringBuilder(); sql.append("SELECT " + DBAccess.FTRGROUPSFTRS_TABLE_FIELD_GROUP + ",SUM(" + DBAccess.UPROFILE_TABLE_FIELD_NUMVALUE + ") AS val FROM " + DBAccess.UPROFILE_TABLE + "," + DBAccess.FTRGROUPSFTRS_TABLE + " WHERE " + DBAccess.UPROFILE_TABLE + "." + DBAccess.FIELD_PSCLIENT + "='").append(clientName).append("' AND " + DBAccess.FTRGROUPSFTRS_TABLE + "." + DBAccess.FIELD_PSCLIENT + "='").append(clientName).append("'"); sql.append(" AND " + DBAccess.UPROFILE_TABLE_FIELD_USER + "=?"); sql.append(" AND " + DBAccess.UPROFILE_TABLE_FIELD_FEATURE + "=" + DBAccess.FTRGROUPSFTRS_TABLE_TABLE_FIELD_FTR); //creates the sql if (nameParameter != null) { String[] names = nameParameter.split("|"); if (names[0].contains("*")) { sql.append(" AND ( " + DBAccess.FTRGROUPSFTRS_TABLE_FIELD_GROUP + " LIKE ?"); } else { sql.append(" AND ( " + DBAccess.FTRGROUPSFTRS_TABLE_FIELD_GROUP + "=?"); } for (int i = 1; i < names.length; i++) { System.out.println(names[i]); if (names[i].contains("*")) { names[i] = names[i].replace("*", "%"); sql.append(" OR " + DBAccess.FTRGROUPSFTRS_TABLE_FIELD_GROUP + " LIKE ?"); } else { sql.append(" OR " + DBAccess.FTRGROUPSFTRS_TABLE_FIELD_GROUP + "=?"); } } sql.append(")"); } sql.append(" GROUP BY " + DBAccess.FTRGROUPSFTRS_TABLE_FIELD_GROUP + " ORDER BY val"); PreparedStatement stmt = dbAccess.getConnection().prepareStatement(sql.toString()); stmt.setString(1, user); //ads the parameters to prepare statement if (nameParameter != null) { String[] names = nameParameter.split("|"); for (int i = 0; i < names.length; i++) { stmt.setString(2 + i, names[i]); } } ResultSet rs = stmt.executeQuery(); respBody.append(DBAccess.xmlHeader("/resp_xsl/user_feature_groups.xsl")); respBody.append("<result>\n"); while (rs.next()) { String group = rs.getString(1); respBody.append("<row>" + "<group>" + group + "</group>" + "</row>\n"); } respBody.append("</result>"); rs.close(); stmt.close(); return true; }
c58a0ef8-6b23-4d72-8095-f10eb5da6924
7
public JSONArray getJsonValue() throws Exception { List<Element> taskElementList = tasksElement.getChildren("Task"); JSONArray returnJsonArray = new JSONArray(); for (Element taskElement : taskElementList) { String taskUseVar = taskElement.getAttributeValue("var"); if (taskUseVar == null) { JSONObject taskValueJson = new UseVarXml(taskElement, databaseInfoJson, inputJson).getJsonValue(); JSONArray tmpArray = new ExecuteXml(taskElement, databaseInfoJson, inputJson, taskValueJson).getJsonValue(); if (tmpArray != null && !tmpArray.isEmpty()) { returnJsonArray.add(tmpArray); } } else { if (StringUtils.isNotBlank(taskUseVar)) { if (!StringUtils.startsWith(taskUseVar, "I#")) { throw new InputValueErrorException("Tasks -> Task -> var属性必须使用InputPools变量。"); } } JSONArray valueArray = JsonUtils.getInstance().getJsonArray(inputJson, StringUtils.substringBetween(taskUseVar, "I#", "#")); for (int i = 0; i < valueArray.size(); i++) { JSONObject tasksVarJson = valueArray.getJSONObject(i); JSONObject taskValueJson = new UseVarXml(taskElement, databaseInfoJson, inputJson, tasksVarJson).getJsonValue(); returnJsonArray.add(new ExecuteXml(taskElement, databaseInfoJson, inputJson, tasksVarJson, taskValueJson).getJsonValue()); } } } return returnJsonArray; }
7bcd157e-f354-4320-918d-a545a322c68e
8
@EventHandler(priority = EventPriority.NORMAL) public void onBlockBreak(BlockBreakEvent event){ Block block = event.getBlock(); if ((block.getType() == Material.SIGN_POST || block.getType() == Material.WALL_SIGN)) { Sign s = (Sign)block.getState(); if(!plugin.loc.containsKey(block.getLocation())){ for(int i = 0; i<s.getLines().length; i++){ if(s.getLine(i).toLowerCase().contains("[sortal]") || s.getLine(i).toLowerCase().contains(plugin.signContains)){ if(!event.getPlayer().hasPermission("sortal.delsign")){ event.getPlayer().sendMessage("[Sortal] You do not have permissions to destroy a [Sortal] sign!"); event.setCancelled(true); } } } return; } if(!event.getPlayer().hasPermission("sortal.delsign")){ event.getPlayer().sendMessage("[Sortal] You do not have permissions to destroy a registered sign!"); event.setCancelled(true); return; } delLoc(block.getLocation()); plugin.log.info("Registered sign destroyed by " + event.getPlayer().getDisplayName() + ", AKA " + event.getPlayer().getName() + "!"); } }
4debc82b-c691-4250-9c80-e2bea13c4971
2
public String[] getVariablesOnRHS() { ProductionChecker pc = new ProductionChecker(); ArrayList list = new ArrayList(); for (int i = 0; i < myRHS.length(); i++) { char c = myRHS.charAt(i); if (ProductionChecker.isVariable(c)) list.add(myRHS.substring(i, i + 1)); } return (String[]) list.toArray(new String[0]); }
bc51e7df-b901-4c76-a23b-963c66fb9a70
7
public void deleteUser(String username) { boolean active; String activeBoolean = null; try { String table = "users"; String[] fields = {"active"}; crs = qb.selectFrom(fields, table).where("username", "=", username).executeQuery(); if(crs.next()) { active = crs.getBoolean("active"); if(active) { activeBoolean = "0"; } else if (!active){ activeBoolean = "1"; } } if(!activeBoolean.equals(null) && !username.equals("admin")) { String[] values = {activeBoolean}; qb.update(table, fields, values).where("username", "=", username).execute(); } } catch (SQLException e) { e.printStackTrace(); } finally { try { crs.close(); } catch (SQLException e) { e.printStackTrace(); } } }
ca62f715-e472-40a3-abd3-a096c4de18e0
1
protected EngineLog(String name, boolean displayOnConsole) { logger = Logger.getLogger(name); getLogger().setLevel(TRACE_LEVEL); if(displayOnConsole) { ConsoleHandler cLogger = new ConsoleHandler(); cLogger.setLevel(TRACE_LEVEL); getLogger().addHandler(cLogger); } //TODO Add a static path for log //Unique fileLog at the moment /** * FileHandler file = null; try { file = new FileHandler("logfileName.log"); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } logger.addHandler(file); */ }
e99e8f34-7bd2-4aa2-87d2-e11461366405
2
public void deletePatient(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{ log.debug("PatientManager deletePatient method called..."); int healthRecord=Integer.parseInt(request.getParameter("healthrec")); PatientService patientService=new PatientServiceImpl(); try{ if(patientService.deletePatient(healthRecord)>=1){ request.setAttribute("result", "Deleted Successfully..."); log.info("Patient deleted successfully..."); } } catch (Exception e) { request.setAttribute("result", "Error :"+e.toString()); log.error(e.toString()); } RequestDispatcher view=request.getRequestDispatcher("AddPatient.jsp"); view.forward(request, response); }
81125087-a680-4870-9f78-5ccd0b7f68a3
1
public DrawableComponent loadAsModel(boolean state) { if (!opaque) { this.loadAsModel = state; } else { this.loadAsModel = false; } return this; }
2604a2db-2d83-4142-871f-87de4346e717
9
protected void readData() throws IOException { int index, r, g, b; switch (img.data.header.colorType) { case PngImage.COLOR_TYPE_PALETTE: if (length != 1) badLength(1); index = in_data.readUnsignedByte(); if (img.data.palette == null) throw new PngException("hIST chunk must follow PLTE chunk"); img.data.properties.put("background index", new Integer(index)); r = img.data.palette.r_raw[index]; g = img.data.palette.g_raw[index]; b = img.data.palette.b_raw[index]; break; case PngImage.COLOR_TYPE_GRAY: case PngImage.COLOR_TYPE_GRAY_ALPHA: if (length != 2) badLength(2); if (img.data.header.depth == 16) { r = g = b = in_data.readUnsignedByte(); int low = in_data.readUnsignedByte(); img.data.properties.put("background low bytes", new Color(low, low, low)); } else { r = g = b = in_data.readUnsignedShort(); } break; default: // truecolor if (length != 6) badLength(6); if (img.data.header.depth == 16) { r = in_data.readUnsignedByte(); int low_r = in_data.readUnsignedByte(); g = in_data.readUnsignedByte(); int low_g = in_data.readUnsignedByte(); b = in_data.readUnsignedByte(); int low_b = in_data.readUnsignedByte(); img.data.properties.put("background low bytes", new Color(low_r, low_g, low_b)); } else { r = in_data.readUnsignedShort(); g = in_data.readUnsignedShort(); b = in_data.readUnsignedShort(); } } img.data.properties.put("background", new Color(r, g, b)); }
b28f28cc-779b-4fc2-bd0e-048df7e1c908
3
public void repaintTripleBuffer(Rectangle dirty) { if (tripleBuffered && tripleBufferGraphics != null) { if (dirty == null) { dirty = new Rectangle(tripleBuffer.getWidth(), tripleBuffer.getHeight()); } // Clears and repaints the dirty rectangle using the // graphics canvas as a renderer mxUtils.clearRect(tripleBufferGraphics, dirty, null); tripleBufferGraphics.setClip(dirty); graphControl.drawGraph(tripleBufferGraphics, true); tripleBufferGraphics.setClip(null); } }
1e12fb05-7ef2-41b6-a01f-7dede3995655
3
public void writeLine(String line,Color col,Font font) { if (line!=null) { if (logging==true) fileWriteLine(line); if (pauseDisplay==false) display_view.addLine(line,col,font); } }
8370e1a4-9c4e-4509-b5f1-d5a1386412cc
8
private void loadSegments() { File file = null; for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].getName().equals( "roadSeg-roadID-length-nodeID-nodeID-coords.tab")) { file = listOfFiles[i]; break; } } try { Scanner sc = new Scanner(file); sc.nextLine(); while (sc.hasNextLine()) { int roadid = sc.nextInt(); double length = sc.nextDouble(); int inter1id = sc.nextInt(); int inter2id = sc.nextInt(); ArrayList<Location> loc = new ArrayList<Location>(); String line = sc.nextLine(); String[] values = line.split("\\t"); for (int i = 1; i < values.length; i += 2) { double lat = Double.parseDouble(values[i]); double lon = Double.parseDouble(values[i + 1]); loc.add(Location.newFromLatLon(lat, lon)); } Intersection int1 = null; Intersection int2 = null; for (Intersection i : intersections) { if (i.getID() == inter1id) { int1 = i; } else if (i.getID() == inter2id) { int2 = i; } } segments.add(new Segment(roadid, length, int1, int2, loc)); } } catch (FileNotFoundException e) { e.printStackTrace(); } }
d5aab3be-4b7d-4ffc-94b4-a987b6e33295
4
public Iterable<Key> levelOrderTraversal() { Queue<Key> q = new LinkedList<Key>(); if (root == null) return q; Queue<Node> tempQ = new LinkedList<Node>(); Node n = root; tempQ.add(n); while (!tempQ.isEmpty()) { n = tempQ.poll(); q.add(n.key); if (n.left != null) tempQ.add(n.left); if (n.right != null) tempQ.add(n.right); } return q; }
235a907f-dfc6-41ca-9120-db4a42e301c3
7
public static boolean arrayEquals(byte[] a, byte[] b) { if (a == null && b == null) { return true; } else if (a == null || b == null) { return false; } else if (a.length != b.length) { return false; } for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) { return false; } } return true; }
26bafdd9-55de-4097-87b1-82bc424ede8e
9
private boolean isHeap(){ for (int i = 0; i<theHeap.size(); i++){ E toCompare = theHeap.get(i); if ( (hasLeftChild(i) && theHeap.get(leftChild(i))!=null && toCompare.compareTo(theHeap.get(leftChild(i)))*(isMax ? 1:-1)<0) || (hasRightChild(i) && theHeap.get(rightChild(i))!=null && toCompare.compareTo(theHeap.get(rightChild(i)))*(isMax ? 1:-1)<0)) return false; } return true; }
cd5ba455-2af0-40dc-821c-405dff9a3574
4
public static String optimizeText(String s) { for (int i = 0; i < s.length(); i++) { if (i == 0) { s = String.format( "%s%s", Character.toUpperCase(s.charAt(0)), s.substring(1) ); } if (!Character.isLetterOrDigit(s.charAt(i))) { if (i + 1 < s.length()) { s = String.format( "%s%s%s", s.subSequence(0, i+1), Character.toUpperCase(s.charAt(i + 1)), s.substring(i+2) ); } } } return s; }
175a8b97-fda6-40cb-96be-4bdb1740ea03
8
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Node node = (Node) o; if (value != node.value) return false; if (left != null ? !left.equals(node.left) : node.left != null) return false; if (right != null ? !right.equals(node.right) : node.right != null) return false; return true; }
30534173-95a8-4be0-9066-036ecf3da17a
6
private static void createReviewsOfPerson(ObjectBundle bundle, Person person, Integer reviewNr, Integer count, ValueGenerator valueGen, DateGenerator dateGen, NormalDistRangeGenerator prodNrGen, DateGenerator publishDateGen, RandomBucket true70) { for(int i=0;i<count;i++) { int product = prodNrGen.getValue(); int producerOfProduct = getProducerOfProduct(product); int personNr = person.getNr(); Long reviewDate = dateGen.randomDateInMillis(today.getTimeInMillis()-DateGenerator.oneDayInMillis*365,today.getTimeInMillis()); int titleCount = valueGen.randomInt(4, 15); String title = dictionary2.getRandomSentence(titleCount); int textCount = valueGen.randomInt(50, 200); String text = dictionary2.getRandomSentence(textCount); int language = ISO3166.countryCodes.get(person.getCountryCode()); Integer[] ratings = new Integer[4]; for(int j=0;j<4;j++) if((Boolean)true70.getRandom()) ratings[j] = valueGen.randomInt(1, 10); else ratings[j] = null; Review review = new Review(reviewNr, product, personNr, reviewDate, title, text, ratings, language, producerOfProduct); if(!namedGraph) { review.setPublishDate(publishDateGen.randomDateInMillis(reviewDate, today.getTimeInMillis())); } //needed for qualified name review.setPublisher(person.getPublisher()); if(generateUpdateDataset && product>=nrOfMinProductNrForUpdate) updateResourceData.get(product-nrOfMinProductNrForUpdate).add(review); else bundle.add(review); reviewNr++; } }
66fc7513-b5eb-4bbb-b25c-d893f2cd1612
9
private static List<NameAndType> getColumns(Class<?> bean) { List<NameAndType> columns = new ArrayList<NameAndType>(); Field[] fields = bean.getDeclaredFields(); if (fields != null) { for (int i = 0; i < fields.length; i++) { Field field = fields[i]; if (field.isAnnotationPresent(Column.class)) { String name = null; String type = null; Annotation annotation = field.getAnnotation(Column.class); try { Method methodName = Column.class.getMethod("name"); //获取注解上的值 name = (String) methodName.invoke(annotation); // FIXME 目的是判断注解上的值是否存在,不知这么判断是否正确 if (methodName.getDefaultValue().equals(name)) { //注解上的值不存在,则用成员变量的名称 name = field.getName(); } Method methodType = Column.class.getMethod("type"); type = (String) methodType.invoke(annotation); if (methodType.getDefaultValue().equals(type)) { if (int.class.isAssignableFrom(field.getType())) { type = "integer"; } else if (String.class.isAssignableFrom(field.getType())) { type = "text"; } else { throw new RuntimeException("unspported type=" + field.getType().getSimpleName()); } } } catch (Exception e) { e.printStackTrace(); } columns.add(new NameAndType(name, type)); } } } return columns; }
b484168a-415f-48f2-aadc-6c5c1bdcbd42
3
@SuppressWarnings({ "unchecked", "rawtypes" }) public Hashtable getValues() { Hashtable table = new Hashtable(); for (int i = 0; i < textField.size(); i++) { if (!field[i].getClass().isAssignableFrom(ArrayList.class)) { table.put(text.get(i).getText(), textField.get(i).getText()); } else { String[] split = textField.get(i).getText().split(", "); for (int j = 0; j < split.length; j++) table.put(text.get(i).getText(), split[j]); } } return table; }
63026ff4-c7fb-428c-a3e8-ca45602d24c8
4
public String toString() { final String[] SUITS = {"CLUBS", "DIAMONDS", "HEARTS", "SPADES"}; if (value == 0) { return "A" + " " + SUITS[suit]; } else if (value == 12) { return "K" + " " + SUITS[suit]; } else if (value == 11) { return "Q" + " " + SUITS[suit]; } else if (value == 10) { return "J" + " " + SUITS[suit]; } return (value + 1) + " " + SUITS[suit]; }
d3239ed0-19cc-461d-bac8-8ad8715d48ef
1
public Connection getConnection() { try { return DriverManager.getConnection(direccion, usuario, password); } catch (SQLException e) { System.out.println("Fallo la conexion con la base de datos"); e.printStackTrace(); } return null; }
6392b4b5-076e-4072-8d96-fd99f191a934
7
private void onStartRun(){ logPanel.add("Started exposing on <strong>" + _postedTarget + "</strong>", LogPanel.OK, true); if(_dataFormat.hasChanged()) _unsavedSettings = true; if(_unsavedSettings && !EXPERT_MODE) _disableAll(); startRun_enabled = false; stopRun_enabled = true; postApp_enabled = false; resetSDSU_enabled = false; resetPCI_enabled = false; setupServer_enabled = false; powerOn_enabled = false; powerOff_enabled = false; _exposureTime.setText("0"); _spaceUsed.setText("0"); incrementRunNumber(); // This is just a safety measure in case the program has been restarted and // a run started without an application being posted if(_nbytesPerImage == 0){ // Compute number of bytes and time per image for later use by exposure // meters _nbytesPerImage = nbytesPerImage(); _timePerImage = speed(CYCLE_TIME_ONLY); _nexposures = numExpose; } _exposureMeter.restart(); if(_nexposures > 0){ // In this case we want to start a timer to check whether a run // is still active. Start by estimating length of time to avoid // polling the server more than necessary // Timer is activated once per second int pollInterval = Math.max(1000, (int)(1000*_timePerImage)); int initialDelay = Math.max(2000, (int)(1000*(_nexposures*_timePerImage-60.))); if(DEBUG){ System.out.println("Run polling Interval = " + pollInterval + " millseconds"); System.out.println("Initial delay = " + initialDelay + " milliseconds"); } if(_runActive != null) _runActive.stop(); _runActive = new Timer(pollInterval, _checkRun); _runActive.setInitialDelay(initialDelay); _runActive.start(); } _setEnabledActions(); _ucamServersOn.setEnabled(false); }
16c23f44-69b7-4f2c-b12a-37f92b473122
7
@EventHandler( priority = EventPriority.MONITOR ) public void onPlayerInteractMonitor( PlayerInteractEvent event ) { if ( event.isCancelled() ) return; if ( event.getAction() == Action.RIGHT_CLICK_BLOCK && MyDoor.isDoor( event.getClickedBlock() ) ) { final MyDoor var1 = MyDoor.getDoor( event.getClickedBlock() ); if ( var1 == null ) return; event.setCancelled( true ); if ( var1.isAdminDoor() ) { if ( isAdmin( event.getPlayer() ) ) var1.setOpen( !var1.isOpen() ); } else var1.setOpen( !var1.isOpen() ); if ( var1.isOpen() ) Bukkit.getScheduler().scheduleSyncDelayedTask( this, new Runnable() { public void run() { var1.setOpen( false ); } }, 50L ); } }
6e25800e-d4a8-4c4c-852e-b52b11ee70f2
9
public int countDirection(Board board, char token, int column) { int[][] direction = { { -1, 0 }, { -1, 1 }, { 0, 1 }, { 1, 1 }, { 1, 0 }, { 1, -1 }, { 0, -1 }, { -1, -1 }, { -1, 0 } }; int j = board.getTopPosition(column); int count = 0; for (int i = 0; i < 4; i++) { if (verifyIn(board, column + direction[i][0], j + direction[i][1]) && verifyIn(board, column + direction[i + 4][0], j + direction[i + 4][1])) { if (board.get(column + direction[i][0], j + direction[i][1]) == token || board.get(column + direction[i + 4][0], j + direction[i + 4][1]) == token) { count++; } } else if (verifyIn(board, column + direction[i][0], j + direction[i][1])) { if (board.get(column + direction[i][0], j + direction[i][1]) == token) { count++; } } else if (verifyIn(board, column + direction[i + 4][0], j + direction[i + 4][1])) { if (board.get(column + direction[i + 4][0], j + direction[i + 4][1]) == token) { count++; } } } return count; }
9fb048a7-1434-4cbc-bf3a-f847ecd1ac82
7
public static Map<Integer, Set<Integer>> getTestQueryAnswers(String queryAnswersPath) { Map<Integer, Set<Integer>> queryAnswers = new HashMap<Integer, Set<Integer>>(); int queryIdColumn = 0; int queryAnswersColumn = 1; BufferedReader reader = null; String line; String queryAnswersDelimiter = ":"; String answersDelimiter = ","; try { reader = new BufferedReader(new FileReader(queryAnswersPath)); while ((line = reader.readLine()) != null) { String[] columns = line.split(queryAnswersDelimiter); Integer queryId = Integer.parseInt(columns[queryIdColumn]); String answersString = columns[queryAnswersColumn]; Set<Integer> answers = new HashSet<Integer>(); for (String s : answersString.split(answersDelimiter)) { if (!s.equalsIgnoreCase("NO")) answers.add(Integer.parseInt(s)); } queryAnswers.put(queryId, answers); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return queryAnswers; }
812c1618-7a05-4987-98af-714750f86bc1
8
public boolean findParticles(int ChNumber) { int i,TotCh; GenericDialog fpDial = new GenericDialog("Detect Particles"); //String [] DetectOptions = new String [] { // "1. Intensity maximum","2. Intensity shape"}; String [] sSensitivityOptions = new String [] { "Very dim particles (SNR=3)", "Dim particles (SNR=4)" ,"Bright particles (SNR=5)","Brighter particles (SNR=10)", "Pretty bright particles (SNR=20)", "Very bright particles (SNR=30)" }; //fpDial.addChoice("Particle detection method:", DetectOptions, Prefs.get("ComDet.DetectMethod", "Round shape")); fpDial.addMessage("Detection parameters:\n"); if(ChNumber == 2) { fpDial.addMessage("Channel 1:\n"); } fpDial.addNumericField("Approximate particle size, pix", Prefs.get("ComDet.dPSFsigma", 4), 2); fpDial.addChoice("Sensitivity of detection:", sSensitivityOptions, Prefs.get("ComDet.Sensitivity", "Very dim particles (SNR=3)")); if(ChNumber == 2) { fpDial.addMessage("Channel 2:\n"); fpDial.addNumericField("Approximate particle size, pix", Prefs.get("ComDet.dPSFsigmaTwo", 4), 2); fpDial.addChoice("Sensitivity of detection:", sSensitivityOptions, Prefs.get("ComDet.SensitivityTwo", "Very dim particles (SNR=3)")); fpDial.addMessage("\n\n Colocalization analysis:\n"); fpDial.addCheckbox("Calculate colocalization? (requires image with two color channels)", Prefs.get("ComDet.bColocalization", false)); fpDial.addNumericField("Max distance between colocalized spot, pix", Prefs.get("ComDet.dColocDistance", 4), 2); fpDial.addCheckbox("Plot detected particles in both channels?", Prefs.get("ComDet.bPlotBothChannels", false)); } fpDial.showDialog(); if (fpDial.wasCanceled()) return false; //nDetectionMethod = fpDial.getNextChoiceIndex(); //Prefs.set("ComDet.DetectMethod", DetectOptions[nDetectionMethod]); dPSFsigma[0] = fpDial.getNextNumber(); Prefs.set("ComDet.dPSFsigma", dPSFsigma[0]); nSensitivity[0] = fpDial.getNextChoiceIndex(); Prefs.set("ComDet.Sensitivity", sSensitivityOptions[nSensitivity[0]]); if(ChNumber == 2) { dPSFsigma[1] = fpDial.getNextNumber(); Prefs.set("ComDet.dPSFsigmaTwo", dPSFsigma[1]); nSensitivity[1] = fpDial.getNextChoiceIndex(); Prefs.set("ComDet.SensitivityTwo", sSensitivityOptions[nSensitivity[1]]); bColocalization = fpDial.getNextBoolean(); Prefs.set("ComDet.bColocalization", bColocalization); dColocDistance = fpDial.getNextNumber(); Prefs.set("ComDet.dColocDistance", dColocDistance); bPlotBothChannels = fpDial.getNextBoolean(); Prefs.set("ComDet.bPlotBothChannels", bPlotBothChannels); } nThreads = 50; TotCh=1; bTwoChannels = false; if(ChNumber == 2) { TotCh=2; bTwoChannels = true; } for(i=0;i<TotCh;i++) { nAreaMax[i] = (int) (3.0*dPSFsigma[i]*dPSFsigma[i]); dPSFsigma[i] *= 0.5; //putting limiting criteria on spot size nAreaCut[i] = (int) (dPSFsigma[i] * dPSFsigma[i]); nKernelSize[i] = (int) Math.ceil(3.0*dPSFsigma[i]); if(nKernelSize[i]%2 == 0) nKernelSize[i]++; if(nSensitivity[i]<3) { nSensitivity[i] += 3; } else { nSensitivity[i] = (nSensitivity[i]-2)*10; } } return true; }
dd7c8685-0941-47f3-9f26-80a40630f7c2
5
@Override public void update(int id_task, int id_user, Boolean active) { try { connection = getConnection(); ptmt = connection.prepareStatement("UPDATE Task_executors SET id_task=? id_user=? active=?" + " WHERE id_task=? id_user=?;"); ptmt.setInt(1, id_task); ptmt.setInt(2, id_user); ptmt.setBoolean(3, active); ptmt.setInt(4, id_task); ptmt.setInt(5, id_user); ptmt.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(TaskExecutorsDAO.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (ptmt != null) { ptmt.close(); } if (connection != null) { connection.close(); } if (resultSet != null) { resultSet.close(); } } catch (SQLException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } } }
d0c23052-cc9a-48f2-b7fa-b05fbea656ee
0
public Optional<Status> poll(URL url) { RestTemplate restTemplate = new RestTemplate(); return Optional. fromNullable( restTemplate.getForObject(url.toString(), Status.class)); }
23d9ad3f-8d1a-46bb-b717-6328fd0931ff
0
@Override public void sayToBomberman(String message) throws IOException { serverSideWriter.append(message).append("\n").flush(); message = clientSideReader.readLine(); System.out.println("**************************************************"); System.out.println("To player " + this.number); System.out.print(message); System.out.println("**************************************************"); }
3a0275bd-be1b-47d4-ae31-c791f3648166
2
public synchronized T take() { while (elements.isEmpty()) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } T el = elements.removeFirst(); notify(); return el; }
d3443c5e-a4e8-471f-90c1-7a67f7e94278
5
public SpriterKeyFrame[] buildKeyFrameArray(Animation animation){ MainLine mainline = animation.getMainline(); List<TimeLine> timeLines = animation.getTimeline(); List<Key> keyFrames = mainline.getKey(); SpriterKeyFrame[] spriterKeyFrames = new SpriterKeyFrame[keyFrames.size()]; for(int k=0;k<keyFrames.size();k++){ Key key = keyFrames.get(k); List<SpriterObject> tempObjects = new ArrayList<SpriterObject>(); List<SpriterBone> tempBones = new ArrayList<SpriterBone>(); for(BoneRef boneRef : key.getBoneRef()){ tempBones.add(boneMerger.merge(boneRef, timeLines.get(boneRef.getTimeline()).getKey().get(boneRef.getKey()))); } for(AnimationObjectRef objectRef : key.getObjectRef()){ tempObjects.add(objectMerger.merge(objectRef, timeLines.get(objectRef.getTimeline()).getKey().get(objectRef.getKey()))); } for(AnimationObject object : key.getObject()){ tempObjects.add(objectConverter.convert(object)); } spriterKeyFrames[k] = new SpriterKeyFrame(); spriterKeyFrames[k].setObjects(tempObjects.toArray(new SpriterObject[tempObjects.size()])); spriterKeyFrames[k].setBones(tempBones.toArray(new SpriterBone[tempBones.size()])); spriterKeyFrames[k].setStartTime(key.getTime()); spriterKeyFrames[k].setEndTime(k<keyFrames.size()-1 ? keyFrames.get(k+1).getTime()-1 : animation.getLength()); } return spriterKeyFrames; }
54668dd3-26fb-4aa3-bf62-fc63976645cb
1
public void enqueue(double waketime, Agent agent) throws IllegalArgumentException { if (waketime < _currentTime) throw new IllegalArgumentException(); _queue.add(new Node(waketime, agent)); }
50ede17d-86cb-4be8-874a-96ecbedd9328
3
protected void func_27260_a(int var1, int var2, Tessellator var3) { super.func_27260_a(var1, var2, var3); if (this.field_27268_b == 0) { GuiStats.drawSprite(this.field_27274_a, var1 + 115 - 18 + 1, var2 + 1 + 1, 18, 18); } else { GuiStats.drawSprite(this.field_27274_a, var1 + 115 - 18, var2 + 1, 18, 18); } if (this.field_27268_b == 1) { GuiStats.drawSprite(this.field_27274_a, var1 + 165 - 18 + 1, var2 + 1 + 1, 36, 18); } else { GuiStats.drawSprite(this.field_27274_a, var1 + 165 - 18, var2 + 1, 36, 18); } if (this.field_27268_b == 2) { GuiStats.drawSprite(this.field_27274_a, var1 + 215 - 18 + 1, var2 + 1 + 1, 54, 18); } else { GuiStats.drawSprite(this.field_27274_a, var1 + 215 - 18, var2 + 1, 54, 18); } }
d1c68c2f-cb43-42ce-b6d3-382dcf5a94dd
3
@Override public boolean equals(Object o) { if (o instanceof Vector3D) { Vector3D p = (Vector3D) o; double xD = p.x - x, yD = p.y - y, zD = p.z - z; return xD == 0 && yD == 0 && zD == 0; } return false; }
1e51808c-6e4a-437d-bc1a-2686e04b0184
9
public static int getWordEnd(RSyntaxTextArea textArea, int offs) throws BadLocationException { Document doc = textArea.getDocument(); int endOffs = textArea.getLineEndOffsetOfCurrentLine(); int lineEnd = Math.min(endOffs, doc.getLength()); if (offs == lineEnd) { // End of the line. return offs; } String s = doc.getText(offs, lineEnd-offs-1); if (s!=null && s.length()>0) { // Should always be true int i = 0; int count = s.length(); char ch = s.charAt(i); if (Character.isWhitespace(ch)) { while (i<count && Character.isWhitespace(s.charAt(i++))); } else if (Character.isLetterOrDigit(ch)) { while (i<count && Character.isLetterOrDigit(s.charAt(i++))); } else { i = 2; } offs += i - 1; } return offs; }
ff92b7dd-b88b-40e8-b6ce-3a1de02057dc
7
public static int discrete(double[] a) { double EPSILON = 1E-14; double sum = 0.0; for (int i = 0; i < a.length; i++) { if (a[i] < 0.0) throw new IllegalArgumentException("array entry " + i + " is negative: " + a[i]); sum = sum + a[i]; } if (sum > 1.0 + EPSILON || sum < 1.0 - EPSILON) throw new IllegalArgumentException("sum of array entries not equal to one: " + sum); // the for loop may not return a value when both r is (nearly) 1.0 and when the // cumulative sum is less than 1.0 (as a result of floating-point roundoff error) while (true) { double r = uniform(); sum = 0.0; for (int i = 0; i < a.length; i++) { sum = sum + a[i]; if (sum > r) return i; } } }
6604be4f-981f-4cda-a404-3e5fd04f4c33
1
public void test_getDifferenceAsLong_long_long() { assertEquals(0L, iField.getDifferenceAsLong(1L, 0L)); assertEquals(567L, iField.getDifferenceAsLong(567L * 90L, 0L)); assertEquals(567L - 1234L, iField.getDifferenceAsLong(567L * 90L, 1234L * 90L)); assertEquals(567L + 1234L, iField.getDifferenceAsLong(567L * 90L, -1234L * 90L)); try { iField.getDifferenceAsLong(LONG_MAX, -1L); fail(); } catch (ArithmeticException ex) {} }
b75b1a60-45f7-46e6-87b5-24bd82dcd7f1
7
public void reorderIntegerKeys() { List<Object> keys = getOrderedKeys(); int numKeys = keys.size(); if (numKeys <= 0) return; if (!(getOrderedKey(0) instanceof Integer)) return; List<Object> newKeys = new ArrayList<Object>(); List<Object> newValues = new ArrayList<Object>(); for (int i = 0; i < numKeys; i++) { Integer key = (Integer) getOrderedKey(i); Object val = getOrderedValue(i); int numNew = newKeys.size(); int pos = 0; for (int j = 0; j < numNew; j++) { Integer newKey = (Integer) newKeys.get(j); if (newKey.intValue() < key.intValue()) ++pos; else break; } if (pos >= numKeys) { newKeys.add(key); newValues.add(val); } else { newKeys.add(pos, key); newValues.add(pos, val); } } this.clear(); for (int l = 0; l < numKeys; l++) { put(newKeys.get(l), newValues.get(l)); } }
7d89b4a6-b9fe-427d-85f1-6f0962a4f521
5
private int jjMoveStringLiteralDfa6_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(4, old0, 0L); try { curChar = input_stream.readChar(); } catch (java.io.IOException e) { jjStopStringLiteralDfa_0(5, active0, 0L); return 6; } switch (curChar) { case 91: if ((active0 & 0x200L) != 0L) return jjStopAtPos(6, 9); break; case 111: return jjMoveStringLiteralDfa7_0(active0, 0x2000000000L); default: break; } return jjStartNfa_0(5, active0, 0L); }
cdafd622-0349-40ad-93dd-7277feaba6e8
1
private char validateUnusedLetter(char guess) { while(word.isLetterUsed(guess)) { System.out.println("This letter has already been guessed. Please enter a new, unused letter: "); String temp = sc.next(); validateGuessIsALetter(temp); guess = temp.charAt(0); } return guess; }
6ae01158-7cf2-4e90-b88e-06a5d972329c
5
private void skipQuotedValue(char quote) throws IOException { // Like nextNonWhitespace, this uses locals 'p' and 'l' to save inner-loop field access. char[] buffer = this.buffer; do { int p = pos; int l = limit; /* the index of the first character not yet appended to the builder. */ while (p < l) { int c = buffer[p++]; if (c == quote) { pos = p; return; } else if (c == '\\') { pos = p; readEscapeCharacter(); p = pos; l = limit; } else if (c == '\n') { lineNumber++; lineStart = p; } } pos = p; } while (fillBuffer(1)); throw syntaxError("Unterminated string"); }
9e1c3f91-9dae-4b8d-a147-277f2a3a6bdc
0
@Override public void Volum (double n) { this.volume=edge*edge*edge*0.707*n; this.edge = edge*Math.pow(n, 1/3); }
53711761-88a9-48c0-9a0b-5cb32ae06da3
7
public String longestCommonPrefix(String[] strs) { if(strs.length == 0) return ""; if(strs.length == 1) return strs[0]; int p = 0; here: while(true){ if(p >= strs[0].length()) break; char c = strs[0].charAt(p); for(String str : strs) { if(str.length() <= p || str.charAt(p) != c) break here; // or p++ } p++; } return strs[0].substring(0, p); }
77276cc8-b8df-4770-89d5-ecffeeb57b51
9
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((addressFirstLine == null) ? 0 : addressFirstLine.hashCode()); result = prime * result + ((addressSecondLine == null) ? 0 : addressSecondLine .hashCode()); result = prime * result + ((city == null) ? 0 : city.hashCode()); result = prime * result + ((email == null) ? 0 : email.hashCode()); result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); result = prime * result + ((password == null) ? 0 : password.hashCode()); result = prime * result + ((state == null) ? 0 : state.hashCode()); result = prime * result + ((zipcode == null) ? 0 : zipcode.hashCode()); return result; }
47d4c590-dde6-4318-9f03-18fe0d30332a
4
private static int isSelfDescribing(String num) { int occurrences; for(int i = 0; i < num.length(); i++) { occurrences = 0; for(int j = 0; j < num.length(); j++) { int value = Character.getNumericValue(num.charAt(j)); if(value == i) { occurrences++; } } if(occurrences != Character.getNumericValue(num.charAt(i))) { return 0; } } return 1; }
357c8f11-e419-42d3-b014-bb7b437045bf
8
public Item targetItem(MOB target) { final Vector<Item> V=new Vector<Item>(); for(int i=0;i<target.numItems();i++) { final Item I2=target.getItem(i); if((!I2.amWearingAt(Wearable.IN_INVENTORY)) &&(((I2 instanceof Weapon)&&(I2.basePhyStats().damage()>1)) ||((I2 instanceof Armor)&&(I2.basePhyStats().armor()>1))) &&(I2.container()==null)) V.addElement(I2); } if(V.size()>0) return V.elementAt(CMLib.dice().roll(1,V.size(),-1)); return null; }
32169f1a-ec05-4deb-bfb9-87b4b70f38ff
2
public void run() { try { Transaction workerTrans = transQueue.take(); while (!workerTrans.equals(nullTrans)) { // get relevant information from each account int fromAcct = workerTrans.getFrom(); int toAcct = workerTrans.getTo(); int transAmt = workerTrans.getAmt(); // System.out.println("Transaction Complete"); // perform the 'transaction' accounts[fromAcct].withdraw(transAmt); accounts[toAcct].deposit(transAmt); workerTrans = transQueue.take(); } latch.countDown(); // System.out.println("Successfully Counted Down"); } catch (InterruptedException e) { e.printStackTrace(); } }
8a16474e-02b1-4427-b2aa-b6b2149a857a
5
public int readBits(int howManyBits) throws IOException { int retval = 0; if (myInput == null){ return -1; } while (howManyBits > myBitCount){ retval |= ( myBuffer << (howManyBits - myBitCount) ); howManyBits -= myBitCount; try{ if ( (myBuffer = myInput.read()) == -1) { return -1; } } catch (IOException ioe) { throw new IOException("bitreading trouble "+ioe); } myBitCount = BITS_PER_BYTE; } if (howManyBits > 0){ retval |= myBuffer >> (myBitCount - howManyBits); myBuffer &= bmask[myBitCount - howManyBits]; myBitCount -= howManyBits; } return retval; }
cef236a9-68f3-457e-810a-216f8dad2f80
6
final boolean method353(byte byte0, int i) { if (i == -1) { return false; } if (byte0 != -53) { anInt599 = 63; } if (i == anInt612) { return true; } if (anIntArray610 != null) { for (int j = 0; ~j > ~anIntArray610.length; j++) { if (anIntArray610[j] == i) { return true; } } } return false; }
e085ae83-57d8-4576-809a-3c7eef5f95ea
0
@Override public void setDef(String value) {this.def = parseColor(value);}
bdc9e537-b807-44cb-9bdb-e4db5e644c00
8
public static String getC_FineCommandName(int _findCommand){ switch(_findCommand){ case C_FIND_TOTAL: return "FIND_TOTAL"; case C_FIND_ELEMENT: return "FIND_ELEMENT"; case C_FIND_ELEMENT_VALUE: return "FIND_ELEMENT_VALUE"; case C_FIND_SORTED: return "FIND_SORTED"; case C_FIND_INFO: return "FIND_INFO"; case C_FIND_SHOPLIST_INFO: return "FIND_SHOPLIST_INFO"; case C_FIND_DONE: return "FIND_DONE"; case C_FIND_NOTHING: return "FIND_NOTHING"; default: return "WRONG_COMMAND"; } }
3d4fc7c9-64af-40fa-951f-56bae7a6eab7
7
@Override public void run() { this.window.setNetworkStatus(NetworkStatus.WAITING_CONNECTION); this.openSocket(); this.networkUI.setVisible(true); this.networkUI.addMessageListener(this); this.addMessageListener(this.networkUI); this.window.setNetworkStatus(NetworkStatus.CONNECTED); GameController controller = GameController.getInstance(); controller.launch(); try { String line; while ( this.socket.isConnected() ) { line = this.input.readUTF(); if ( line.startsWith("MOVE") ) { Move move = null; try { move = (Move) this.input.readObject(); } catch (ClassNotFoundException ex) { Logger.getLogger(NetworkController.class.getName()).log(Level.SEVERE, null, ex); } controller.doMove(move); this.window.unlock(); } else if(line.startsWith("MSG ")) { for ( MessageListener l : this.listeners ) l.newMessage(line.substring(4)); } else if(line.startsWith("BYE")) { this.window.setNetworkStatus(NetworkStatus.QUIT); } } } catch (IOException ex) { Logger.getLogger(NetworkController.class.getName()).log(Level.SEVERE, null, ex); this.window.setNetworkStatus(NetworkStatus.CONNECTION_ERROR); } }
36be031a-1b6c-483c-b82f-7b719a0ea595
4
public void toggle() { if(hidden == false) { setVisible(false); } if(hidden == true) { setVisible(true); requestFocusInWindow(); } if(hidden == true) { hidden = false; } if(hidden == false) { hidden = true; } }
2c97f08f-3f88-4dfd-bd40-0435a4d817f7
2
private void resetScenario() { forceList.clear(); addAllForcesToList(); for (Force force: forceList) { for (City city: force.getCityList()) { city.getCharacterList().clear(); } force.getCityList().clear(); } forceList.clear(); }
ac597f67-e548-4744-a42a-68de8a21a917
8
static public ParseException generateParseException() { jj_expentries.clear(); boolean[] la1tokens = new boolean[28]; if (jj_kind >= 0) { la1tokens[jj_kind] = true; jj_kind = -1; } for (int i = 0; i < 0; i++) { if (jj_la1[i] == jj_gen) { for (int j = 0; j < 32; j++) { if ((jj_la1_0[i] & (1<<j)) != 0) { la1tokens[j] = true; } } } } for (int i = 0; i < 28; i++) { if (la1tokens[i]) { jj_expentry = new int[1]; jj_expentry[0] = i; jj_expentries.add(jj_expentry); } } jj_endpos = 0; jj_rescan_token(); jj_add_error_token(0, 0); int[][] exptokseq = new int[jj_expentries.size()][]; for (int i = 0; i < jj_expentries.size(); i++) { exptokseq[i] = jj_expentries.get(i); } return new ParseException(token, exptokseq, tokenImage); }
6d93fac4-95ec-445c-bb6d-360206296e08
2
private void print(int[][] a) { for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[0].length; j++) { System.out.print(a[i][j] + " "); } System.out.println(); } System.out.println("------------"); }
a708000a-5bdb-4710-9d8b-6720d25eefc4
0
public Collection<Route> getRoutes() { return this._routes; }
defceff5-f008-4cd2-b492-83182e6d10c4
6
@Override public void actionPerformed(ActionEvent e) { if (e.getSource() == closeBtn) { this.setVisible(false); } else if (e.getSource() == addBtn) { ParameterEditor pe = new ParameterEditor(); if (pe.isOk()) { try { model.add(new Parameter(pe.getName(), pe.getFormula())); } catch (Exception e1) { JOptionPane.showMessageDialog(null, e1.getMessage()); } } } else if (e.getSource() == editBtn) { editParamCell(); } else if (e.getSource() == delBtn) { int row = table.getSelectedRow(); model.delete(row); } }
130980e0-bab8-49ab-8605-d9fb262c8886
1
public static int getDelimiterOffset(final String line, final int start, final char delimiter) { int idx = line.indexOf(delimiter, start); if (idx >= 0) { idx -= start - 1; } return idx; }
1d164e4b-158d-4cc3-8d8f-ffdfd2166118
1
@Override public String toString(){ StringBuffer sb = new StringBuffer(); Node temp = first; while (temp!=null){ sb.append(temp.e).append(","); temp=temp.next; } return sb.toString(); }