method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
87d5d594-ed1f-430d-9932-f84767bf4320
1
public Player() { for (int i = 0; i < 11; i++) { frame[i] = new Frame(); accumScore[i] = -1; } }
0de01410-6950-4763-baed-98e7b0187e4b
8
private int[] paataSuunta(int i, int j){ Random r = new Random(); int suunta = r.nextInt(4); int[] palkoord = new int[2]; if(suunta == 0){ if(tarkistin(i, j+1)){ palkoord[0] = i; palkoord[1] = j+1; } } else if(suunta == 1){ if(tarkistin(i+1, j)){ palkoord[0] = i+1; palkoord[1] = j; } } else if(suunta == 2){ if(tarkistin(i, j-1)){ palkoord[0] = i; palkoord[1] = j-1; } } else if(suunta == 3){ if(tarkistin(i-1, j)){ palkoord[0] = i-1; palkoord[1] = j; } } return palkoord; }
e2023c58-25d7-4e81-bbec-3b7227732c6a
7
@Override public void actionPerformed(ActionEvent e) { if (e.getSource() == btnGenerate) { int w = 0, h = 0; try { w = Integer.parseInt(tfMazeWidth.getText()); h = Integer.parseInt(tfMazeHeight.getText()); if (w < 5 || h < 5) { throw new NumberFormatException(); } } catch (NumberFormatException nfe) { tfMazeWidth.setText("" + main.getMazeWidth()); tfMazeHeight.setText("" + main.getMazeHeight()); return; } if(w % 2 == 0) w++; if(h % 2 == 0) h++; main.setMazeWidth(w); main.setMazeHeight(h); tfMazeWidth.setText("" + w); tfMazeHeight.setText("" + h); main.generate(); } else if (e.getSource() == btnSolve) { main.solve(); } }
a5baf557-da0d-415a-91ee-c74acbe445bb
2
@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Theme)) return false; Theme theme = (Theme) o; return id == theme.id; }
ed1abb75-3850-408f-ba27-c3350056eabe
8
public Element handle(FreeColServer server, Player player, Connection connection) { ServerPlayer serverPlayer = server.getPlayer(connection); Unit carrier; try { carrier = player.getFreeColGameObject(carrierId, Unit.class); } catch (Exception e) { return DOMMessage.clientError(e.getMessage()); } if (!carrier.canCarryGoods()) { return DOMMessage.clientError("Not a goods carrier: " + carrierId); } else if (!carrier.isInEurope()) { return DOMMessage.clientError("Not in Europe: " + carrierId); } GoodsType type = server.getSpecification().getGoodsType(goodsTypeId); if (type == null) { return DOMMessage.clientError("Not a goods type: " + goodsTypeId); } else if (!player.canTrade(type)) { return DOMMessage.clientError("Goods are boycotted: " + goodsTypeId); } int amount; try { amount = Integer.parseInt(amountString); } catch (NumberFormatException e) { return DOMMessage.clientError("Bad amount: " + amountString); } if (amount <= 0) { return DOMMessage.clientError("Amount must be positive: " + amountString); } int present = carrier.getGoodsCount(type); if (present < amount) { return DOMMessage.clientError("Attempt to sell " + Integer.toString(amount) + " " + type.getId() + " but only " + Integer.toString(present) + " present."); } // Try to sell. return server.getInGameController() .sellGoods(serverPlayer, carrier, type, amount); }
2294dbc9-88e8-4171-b526-2c7a2426b992
8
private boolean camposCompletos (){ if((!field_codigo.getText().equals(""))&& (!field_descripcion.getText().equals(""))&& (!field_cantidad.getText().equals(""))&& (!field_costo_u.getText().equals(""))&& (!field_precio_venta.getText().equals(""))&& (!field_tasa_iva.getText().equals(""))){ if (combo_tipo_imp.getSelectedIndex()==0){ return true; } else{ if (!field_impuesto.getText().equals("")){ return true; } else{ return false; } } } else{ return false; } }
55d9decd-a647-41f0-b767-76e0a2b92969
2
public boolean hitWall(Wall w){ if(this.isLive && this.getRect().intersects(w.getRect())){ this.stay(); return true; } else return false; }
d96ab1ec-6ff9-4616-99d2-027b72f978c7
7
void exec_if() throws StopException, SyntaxError{ var_type cond; return_state r; cond = evalOrCheckExpression(false); //evaluate the conditional statement if(cond.value.doubleValue()!=0){ // if any bit is not 0 statementColor = trueHightlightColor; symbolTable.pushLocalScope(); r = interp_block(block_type.CONDITIONAL, false); // execute block symbolTable.popScope(); if(r == return_state.FUNC_RETURN) return; token = lexer.get_token(); if(token.key==keyword.ELSE){ //find the end of the else token = lexer.get_token(); if(!token.value.equals("{")){ lexer.putback(); findEndOfStatement(); } else{ find_eob(); } } else{ lexer.putback(); } } else{ //skip around block, check for else statementColor = falseHightlightColor; //find the end of the if token = lexer.get_token(); if(!token.value.equals("{")){ lexer.putback(); findEndOfStatement(); } else{ find_eob(); } token = lexer.get_token(); if(token.key != keyword.ELSE){ lexer.putback(); } else{ symbolTable.pushLocalScope(); r = interp_block(block_type.CONDITIONAL, false); symbolTable.popScope(); if(r == return_state.FUNC_RETURN) return; }
27717f36-489b-4e84-96b0-e7a70092671c
1
public void mettreAJourLignes() { //synchronized(MenuDroite.modelListeLigne) { MenuDroite.modelListeLigne.clear(); Iterator it = Main.lignes.entrySet().iterator(); while(it.hasNext()) { Map.Entry pairs = (Map.Entry)it.next(); System.out.println(pairs.getKey()); MenuDroite.modelListeLigne.addElement(pairs.getKey()); } //} }
968a644b-e35a-4e15-a881-012fd428dd1b
2
public static void setSpeed(int x) { if(x < 1 || x > 10) return; diff = x * 0.1; }
85818fc7-8692-4414-8a64-d359c1aacbbb
5
public void hit(Card card) { cards.add(card); try { score += Integer.parseInt(card.getValue()); } catch (NumberFormatException e) { if (card.getValue().equals("KING") || card.getValue().equals("JACK") || card.getValue().equals("QUEEN")) { score += 10; } if (card.getValue().equals("ACE")) { score += 11; } } }
40c75523-bf5f-4506-a9f2-ff4410ecef81
8
public void paivitaTilanne(int creaturetPoydassa) { if (this.tuplamanat&&this.cradle) { this.mana = (creaturetPoydassa + this.landit) * 2; } else if (this.tuplamanat&&!this.cradle) { this.mana = this.landit * 2; }else if (!this.tuplamanat&&this.cradle) { this.mana = this.landit + creaturetPoydassa; } else if (!this.tuplamanat&&!this.cradle) { this.mana = this.landit; } }
7a241ed0-d6de-46fe-ae66-dbeefd672346
8
public static boolean isPrimitiveWrapper(Object o) { return o instanceof Boolean || o instanceof Character || o instanceof Byte || o instanceof Short || o instanceof Integer || o instanceof Long || o instanceof Float || o instanceof Double || o instanceof Void; }
5cb6069a-bf10-4a5e-b8ef-676607536ac5
6
public boolean getBoolean(int index) throws JSONException { Object object = this.get(index); if (object.equals(Boolean.FALSE) || (object instanceof String && ((String) object) .equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String) object) .equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONArray[" + index + "] is not a boolean."); }
cabe0114-206d-4fd1-b599-6e9c850e9702
8
private boolean saveSettings() { int maxDownloads, downloadPartCount, serverCheckInterval; float deleteLimit; try { maxDownloads = Integer.parseInt(maxParallelDownloadsText.getText()); if (maxDownloads < 0) throw new NumberFormatException(); } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(null, "Please enter a valid number as maximum parallel downloads!", "Error", JOptionPane.ERROR_MESSAGE); return false; } try { downloadPartCount = Integer.parseInt(downloadPartsText.getText()); if (downloadPartCount < 1) throw new NumberFormatException(); } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(null, "Please enter a valid number as download part count!", "Error", JOptionPane.ERROR_MESSAGE); return false; } try { serverCheckInterval = Integer.parseInt(serverCheckIntervalText.getText()); if (serverCheckInterval < 0) throw new NumberFormatException(); } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(null, "Please enter a valid number as server check interval!", "Error", JOptionPane.ERROR_MESSAGE); return false; } try { deleteLimit = Float.parseFloat(fileSizeCheckText.getText()); if (deleteLimit < 0.0f) throw new NumberFormatException(); } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(null, "Please enter a valid number as the limit for deleting small files!", "Error", JOptionPane.ERROR_MESSAGE); return false; } UserPreferences.PREF_USERNAME = usernameText.getText(); UserPreferences.PREF_API_SECRET = String.valueOf(apiSecretText.getPassword()); UserPreferences.PREF_PASSWORD = String.valueOf(passwordText.getPassword()); UserPreferences.PREF_USERTOKEN = userTokenText.getText(); UserPreferences.PREF_USE_PROXY = proxyUseCheck.isSelected(); UserPreferences.PREF_PROXY_ADDRESS = proxyAddressText.getText(); UserPreferences.PREF_PROXY_PORT = proxyPortText.getText(); UserPreferences.PREF_AUTO_CONNECT = autoConnectCheck.isSelected(); UserPreferences.PREF_START_IN_TRAY = startInTrayCheck.isSelected(); UserPreferences.PREF_AUTO_DOWNLOAD = autoDownloadCheck.isSelected(); UserPreferences.PREF_DOWNLOAD_TARGET = downloadTargetText.getText(); UserPreferences.PREF_MAX_DOWNLOADS = maxDownloads; UserPreferences.PREF_DOWNLOAD_PART_COUNT = downloadPartCount; UserPreferences.PREF_FILE_SIZE_CHECK = fileSizeCheckCheck.isSelected(); UserPreferences.PREF_FILE_SIZE_FOR_CHECK = deleteLimit; UserPreferences.PREF_FILE_SIZE_DELETE = fileSizeDeleteCheck.isSelected(); UserPreferences.PREF_AUTO_CLEAN = autoCleanCheck.isSelected(); UserPreferences.PREF_LOAD_SHARED = loadSharedCheck.isSelected(); UserPreferences.PREF_SERVER_CHECK_INTERVAL = serverCheckInterval; UserPreferences.PREF_DONT_ASK_DOWNLOAD_AGAIN = redownloadCheck.isSelected(); UserPreferences.PREF_BEHAVIOR_DOWNLOAD_AGAIN = redownloadCombo.getSelectedIndex(); UserPreferences.PREF_DONT_ASK_OVERWRITE = overwriteCheck.isSelected(); UserPreferences.PREF_BEHAVIOR_OVERWRITE = overwriteCombo.getSelectedIndex(); UserPreferences.PREF_BEHAVIOR_SORT_BY = serverSortByCombo.getSelectedIndex(); UserPreferences.PREF_BEHAVIOR_DOWNLOAD_EVERYTHING = everythingRadio.isSelected(); UserPreferences.saveUserPreferences(); return true; }
50fd64f9-ac6c-41fd-921f-2fb9e7f5e189
6
public void init() { // se inicializa la pausa en falso booPausa = false; //se inicializa guardar en false booGuardar = false; // se inicializa space en false booSpace = false; // se incializa la ayuda en true para que se muestre la informacion booAyuda = true; // se da el nombre del archivo strNombreArchivo = "Inicio.txt"; // incializo las iCae iCae = ((int) (Math.random() * 2)) + 4; // inicializa la direccion en 0 iDireccion = 0; // incializa velocidad en 1 iVelocidad = 2; // incializa el score en 0 iScore = 0; // incializa las colisiones en 0 iColRoja = 0; //inicializa las colisiones en 0 iColAzul = 0; // inicializa las colision 1 iColision = 1; // inicializa el contador de colisiones de mentafetamina en 0 iColMenta = 0; // posiciones del sombrero int posX = (getWidth()/2); int posY = (getHeight()); //se crea la animacion de sombrero Image sombrero1 = Toolkit.getDefaultToolkit().getImage( this.getClass().getResource("imagen/sombrero.png")); Image sombrero2 = Toolkit.getDefaultToolkit().getImage( this.getClass().getResource("imagen/sombrero2.png")); Image sombrero3 = Toolkit.getDefaultToolkit().getImage( this.getClass().getResource("imagen/sombrero3.png")); animSombrero = new Animacion(); animSombrero.sumaCuadro(sombrero1, 100); animSombrero.sumaCuadro(sombrero2, 100); animSombrero.sumaCuadro(sombrero3, 100); // se crea el sombrero perSombrero = new Personaje(posX,posY, animSombrero.getImagen()); perSombrero.setX(posX-perSombrero.getAncho()/2); perSombrero.setY(posY-perSombrero.getAlto()); //se establece la velocidad del sombrero en 4 perSombrero.setVelocidad(4); // posiciones de bolita int posXBol = (getWidth() / 2); int posYBol = (getHeight()-perSombrero.getAlto()); // se crea imagen de bolita URL urlImagenAtomo = this.getClass().getResource("atomo.gif"); // se crea a bolita perBolita = new Personaje(posXBol,posYBol, Toolkit.getDefaultToolkit().getImage(urlImagenAtomo)); perBolita.setX(posXBol-perBolita.getAncho()/2); perBolita.setY(posYBol-perBolita.getAlto()/2); perBolita.setVelocidad(4); int posXMen = (getWidth()/2); int posYMen = 150; // se crea la Mentafetamina URL urlImagenMentafetamina = this.getClass(). getResource("mentafetamina.png"); perMentafetamina = new Personaje( posXMen, posYMen, Toolkit.getDefaultToolkit().getImage(urlImagenMentafetamina)); perMentafetamina.setX(posXMen - perMentafetamina.getAncho()/2); perMentafetamina.setY(posYMen - perMentafetamina.getAlto()/2); int posXPil = 40; int posYPil = 190; // se crea la lista de pildora roja objPildoraRoja = new LinkedList(); // inicializa la lista de pildora1 for ( int iI = 0; iI < 9; iI++) { // se posiciona la pildora 1 en la tabla periodica for (int iJ = 0; iJ < 5; iJ++) { URL urlImagenPildora = this.getClass(). getResource("pildora1.png"); Personaje perPildora1 = new Personaje(posXPil, posYPil, Toolkit.getDefaultToolkit().getImage(urlImagenPildora)); objPildoraRoja.add(perPildora1); posYPil= posYPil+40; } posXPil= posXPil +40; posYPil= 190; } int posXPil2 = 410; int posYPil2 = 190; // se crea la lista de pildora azul objPildoraAzul = new LinkedList(); // inicializa la lista de pildora2 for ( int iI = 0; iI < 9; iI++) { // se posiciona la pildora 2 en la tabla periodica for (int iJ = 0; iJ < 5; iJ++) { URL urlImagenPildora2 = this.getClass(). getResource("pildora2.png"); Personaje perPildora2 = new Personaje(posXPil2, posYPil2, Toolkit.getDefaultToolkit().getImage(urlImagenPildora2)); objPildoraAzul.add(perPildora2); posYPil2= posYPil2+40; } posXPil2= posXPil2 +40; posYPil2= 190; } // se crea la lista de los billetes objBilletes = new LinkedList(); //se crea la lista de los billetes for( int iI = 1; iI <=20; iI++) { // se posicion la galleta en alguna parte al azar del cuadrante // inferior derecho posX = (int) (Math.random() * (getWidth()- 60)); posY = (int) (Math.random() * (getHeight()/2))*(-1); URL urlImagenBillete = this.getClass().getResource("billete1.png"); // se crea el objeto galleta Personaje perBillete = new Personaje(posX,posY, Toolkit.getDefaultToolkit().getImage(urlImagenBillete)); objBilletes.add(perBillete); } //se crea la lista de objetos de billetes2 objBilletes2 = new LinkedList(); //se crea la lista de los billetes for( int iI = 1; iI <=20; iI++) { // se posiciona el billete fuera del applet posX = (int) (Math.random() * (getWidth()- 60)); posY = (int) (Math.random() * (getHeight()/3))*(-1); URL urlImagenBillete2 = this.getClass().getResource("billete2.png"); // se crea el objeto billete Personaje perBillete2 = new Personaje(posX,posY, Toolkit.getDefaultToolkit().getImage(urlImagenBillete2)); objBilletes2.add(perBillete2); } iPosXAnim= (int) (Math.random() * (getWidth()- 60)); iPosYAnim = (int) (Math.random() * (getHeight()/2))*(-1); Image ambulancia1 = Toolkit.getDefaultToolkit().getImage( this.getClass().getResource("imagenes/sirena1.png")); Image ambulancia2 = Toolkit.getDefaultToolkit().getImage( this.getClass().getResource("imagenes/sirena2.png")); animAmbulancia = new Animacion(); animAmbulancia.sumaCuadro(ambulancia1, 100); animAmbulancia.sumaCuadro(ambulancia2, 100); perAmbulancia =new Personaje(iPosXAnim, iPosYAnim, animAmbulancia.getImagen()); // se crea la imagend e las vidas iPosXBotella = (int) (Math.random() * (getWidth()- 60)); iPosYBotella = (int) (Math.random() * (getHeight()))*(-1); URL urlImagenVidas = this.getClass().getResource("vidas.png"); perVidas = new Personaje(iPosXBotella, iPosYBotella, Toolkit.getDefaultToolkit().getImage(urlImagenVidas)); // establece la velocidad en la que caera la botella perVidas.setVelocidad(4); souFondo = new SoundClip("Tema.wav"); souFinal = new SoundClip("Final.wav"); souColision = new SoundClip("rompe.wav"); souFondo.setLooping(true); souFondo.play(); grabaArchivo(); addKeyListener(this); }
bdddea07-9551-4eba-8f42-931685533723
0
@Override public void startSetup(Attributes atts) { super.startSetup(atts); addActionListener(this); }
e1777b2f-367f-45ac-b0f8-91a51a156bd3
1
public String getSelectedFastbootDevice() { if (jList2.getSelectedValue() != null) return (String) jList2.getSelectedValue(); else return null; }
ee890d51-8f00-43f1-aef1-3b013d509b8c
3
void createSetGetGroup() { /* * Create the button to access set/get API functionality. */ final String [] methodNames = getMethodNames (); if (methodNames != null) { final Button setGetButton = new Button (otherGroup, SWT.PUSH); setGetButton.setText (ControlExample.getResourceString ("Set_Get")); setGetButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); setGetButton.addSelectionListener (new SelectionAdapter() { public void widgetSelected (SelectionEvent e) { if (getExampleWidgets().length > 0) { if (setGetDialog == null) { setGetDialog = createSetGetDialog(methodNames); } Point pt = setGetButton.getLocation(); pt = display.map(setGetButton.getParent(), null, pt); setGetDialog.setLocation(pt.x, pt.y); setGetDialog.open(); } } }); } }
8429f59c-5101-4bad-9ce7-63b8e208d023
0
public void skladanie(){ dysk = fabrykaPodzespolowKomputerowych.produkujemyDysk().dawajDysk(); grafika = fabrykaPodzespolowKomputerowych.produkujemyGrafike().dawajGrafike(); procesor = fabrykaPodzespolowKomputerowych.produkujemyProcesor().dawajProcesor(); ram = fabrykaPodzespolowKomputerowych.produkujemyRam().dawajRam(); }
725d7862-7095-41ca-8821-2656da094c17
0
public String getAgencia() { return this.agencia ; }
82d874fa-55e0-4b0d-8217-f16eac0fab19
1
public static void writeXML() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document highScoreListe = builder.newDocument(); Element root = highScoreListe.createElement("root"); for (SlidingPuzzleHighscore thisScore : puzzleHighscores) { Element userElement = highScoreListe.createElement("user"); userElement.setAttribute("name", thisScore.getUserName()); userElement.setAttribute("score", thisScore.getUserScore()); root.appendChild(userElement); } highScoreListe.appendChild(root); DOMSource source = new DOMSource(highScoreListe); PrintStream ps = new PrintStream("highscore.xml"); StreamResult result = new StreamResult(ps); TransformerFactory transformerFactory = TransformerFactory .newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(source, result); }
81a6b870-3f74-49c1-ada2-3b84f77dae60
5
@Override public boolean activate() { return (!Inventory.isFull() && Settings.root.getRoot() == 1 && !Inventory.contains(Constants.INVENTORY_BURNED_ROOT_ID) && !validate(Constants.WAITFOR_WIDGET) && !validate(Constants.FLETCH_WIDGET) && !Settings.burning ); }
c9e603aa-d38e-45e0-82bc-4ca76a7fd305
2
private boolean isWinningMove(Move move) { return winsOnColumn(move) || winsOnRow(move) || winsOnDiagnal(move); }
8a057aeb-7a69-485e-9704-7dce4ecc1075
3
public void addRow(Object... params) { if (params.length != definition.length) { Session.logger .warn("Element counts doesn't match column definition"); } TableRow row = new TableRow(definition.length); int len = (params.length < definition.length ? params.length : definition.length); for (int i = 0; i < len; i++) { TableCell cell = new TableCell(); cell.setColumn(i); cell.setRow(rows.size()); cell.setValue(params[i]); row.getCells()[i] = cell; } rows.add(row); }
e7da717d-1ded-4489-8d01-67e4672c1e57
2
public void serializationLoadNo() { if (JOptionPane.showConfirmDialog(this, "This will erase the existing data. Continue?", "Confirm Operation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) { StartupSequence.deleteSerializedData(); CardLayout cl = (CardLayout) (getLayout()); if (StartupSequence.checkIfCSVDataExists()) { cl.show(this, "csvLoadCard"); } else { cl.show(this, "scrapeInfoCard"); } } }
b393281e-6e3e-4ee3-a3a2-8d2cdef61c87
5
private boolean isThreeOfAKind(ArrayList<Card> player) { if(isFullHouse(player)){ return false; } ArrayList<Integer> sortedHand= sortHand(player); int tripleCounter=0; for(int i=0;i<player.size()-1;i++) { if(sortedHand.get(i)==sortedHand.get(i+1)) tripleCounter++; else { if(tripleCounter==1) tripleCounter=0; } } if(tripleCounter==2) return true; else return false; }
90910519-2b00-413f-bae2-00ccd5a05c43
0
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) public List<Film> getFilm() { return film; }
8e2eada0-7086-4a3f-bed7-b074ca2fcb90
8
private void gaussianHeightScaling() { int kernel_size = (int)(Math.sqrt(gaussian_kernel.length)); int kernel_size2 = kernel_size / 2; int startx = FROMx == 0 ? kernel_size2 : FROMx; int starty = FROMy == 0 ? kernel_size2 : FROMy; int endx = TOx == detail ? detail - kernel_size2 : TOx; int endy = TOy == detail ? detail - kernel_size2 : TOy; for(int x = startx; x < endx; x++) { for(int y = starty; y < endy; y++) { double sum = 0; for(int k = x - kernel_size2, p = 0; p < kernel_size; k++, p++) { for(int l = y - kernel_size2, t = 0; t < kernel_size; l++, t++) { sum += temp_array[k][l] * gaussian_kernel[p * kernel_size + t]; } } vert[x][y][1] = (float)sum; } } }
183a29b8-5049-423a-85df-02e796f0dee1
7
private void extractFile(ZipFile zipFile, ZipEntry src, String destDir) { String filename = src.getName(); /*check existence of subdirectory*/ String[] paths = filename.split("/"); String curP = ""; for (int i = 0; i < paths.length; i++) { if (paths[i] != null && !paths[i].equals("") && i < paths.length - 1) { /*check existience of directory, if not, create it*/ curP += paths[i] + dir_escape; if (!(new File(destDir + File.separator + curP)).exists()) { (new File(destDir + File.separator + curP)).mkdir(); } } } /*real single file name*/ //filename = paths[paths.length - 1]; try { /*now extract the real single files*/ copyInputStream(zipFile.getInputStream(src), new BufferedOutputStream(new FileOutputStream(destDir + File.separator + filename))); /*make the file executable*/ if (!System.getProperty("os.name").startsWith("Windows")) { runCommand("chmod +x " + destDir + File.separator + filename); } } catch (IOException ex) { Logger.getLogger(JarUpdate.class.getName()).log(Level.SEVERE, null, ex); } }
1c048173-e7c1-454e-ab95-0533a1654868
6
public void draw(Graphics g, JPanel p, int x, int y, int height, int width) { Image img = null; if(getModel() == null) { try { img = ImageIO.read(new File("empty.jpg")); g.drawImage(img, x, y, p); } catch (IOException e) { e.printStackTrace(); } } else { if (((Pion)getModel()).getPion() == 'X') { try { img = ImageIO.read(new File("cross.jpg")); g.drawImage(img, x, y, p); } catch (IOException e) { e.printStackTrace(); } } else if (((Pion)getModel()).getPion() == 'O') { try { img = ImageIO.read(new File("round.jpg")); g.drawImage(img, x, y, p); } catch (IOException e) { e.printStackTrace(); } } } }
e184edae-5abb-4ade-9611-2cc2c8d749d8
6
private void debugPrint(GameBoard game) { String title = "Tetris"; for (int i = 0; i < ((game.COLUMS - (title.length()/2) )/ 2); i++) { System.out.print(SPACE); } System.out.println(title); System.out.print('+'); for (int i = 0; i < game.COLUMS; i++) { System.out.print(i); } System.out.println('+'); for (int i = 0; i < game.ROWS; i++) { System.out.print("|"); for (int j = game.COLUMS; j > 0; j--) { if (game.getFallingBlock().exist(game.COLUMS / 2 + 1 - j - game.getFallingBlock().getMovedX(), -1 * game.getFallingBlock().getMovedY() - i)) { System.out.print('#'); } else System.out.print(SPACE); } System.out.println('|'); } System.out.print('+'); for (int i = 0; i < game.COLUMS; i++) { System.out.print('-'); } System.out.println('+'); }
c1b96e71-c242-4e21-9687-dd4f5165db8b
9
public static boolean isPalindrome(String string) { if (string == null || string.length() == 0) return false; String s = string.toLowerCase(); String regex = "[a-z]"; Pattern pattern = Pattern.compile(regex); int leftIndex = 0; int rightIndex = string.length() - 1; while (leftIndex < rightIndex) { // while leftIndex points to non-letter character, increment while (leftIndex < rightIndex && !pattern.matcher(s.subSequence(leftIndex, leftIndex + 1)).matches()) leftIndex++; // while rightIndex points to non-letter character, decrement while (leftIndex < rightIndex && !pattern.matcher(s.subSequence(rightIndex, rightIndex + 1)).matches()) rightIndex--; if (leftIndex < rightIndex && s.charAt(leftIndex++) != s.charAt(rightIndex--)) return false; } return true; }
473cc1cd-ffc4-4da0-be42-10c7f9224113
2
@Override public ArrayList<Visiteur> getAll() throws DaoException { ArrayList<Visiteur> result = new ArrayList<Visiteur>(); ResultSet rs; // préparer la requête String requete = "SELECT * FROM VISITEUR"; try { PreparedStatement ps = Jdbc.getInstance().getConnexion().prepareStatement(requete); rs = ps.executeQuery(); // Charger les enregistrements dans la collection while (rs.next()) { Visiteur unVisiteur = chargerUnEnregistrement(rs); result.add(unVisiteur); } } catch (SQLException ex) { throw new modele.dao.DaoException("DaoVisiteur::getAll : erreur requete SELECT : " + ex.getMessage()); } return result; }
38595faa-5f9d-4d82-a1c0-17d9f250f01d
8
public void handleInput() { if ((p.health <= 1) || (op.health <= 1) || (endResult.length() > 1)) { if (KeyHandler.isPressed(KeyHandler.ENTER)) { gsm.setState(GameStateManager.STARTMENU); } return; } p.setLeft(KeyHandler.keyState[KeyHandler.LEFT]); p.setRight(KeyHandler.keyState[KeyHandler.RIGHT]); p.setJumping(KeyHandler.keyState[KeyHandler.UP]); if(KeyHandler.isPressed(KeyHandler.UP)){ aerialCombo =1; } if (KeyHandler.isPressed(KeyHandler.SPACE)) { p.setAttacking(); } if (KeyHandler.isPressed(KeyHandler.D)) { setDiff(getDiff() < 2 ? getDiff() + 1 : 0); op.maxSpeed = 0.3; op.maxSpeed = 0.3 + (0.1*getDiff()); } }
c8dcf3c8-72bf-4c84-bae1-2e13bccece13
0
@Override public Set<String> getWorlds() { return getList(worldYamlConfiguration); }
dcf6a86c-f67a-4952-9786-7bb608beb8c7
8
private double[][] generatePerlinNoise(double[][] baseNoise, int octaveCount) { int width = baseNoise.length; int height = baseNoise[0].length; double[][][] smoothNoise = new double[octaveCount][][]; // an array of 2D arrays containing //double persistance = 0.5f; // generate smooth noise for (int i = 0; i < octaveCount; i++) { smoothNoise[i] = generateSmoothNoise(baseNoise, i); } double[][] perlinNoise = new double[width][height]; for (int i = 0; i < perlinNoise.length; i++) { for (int j = 0; j < perlinNoise[i].length; j++) { perlinNoise[i][j] = 0; } } double amplitude = 1.0f; double totalAmplitude = 0.0f; for (int octave = octaveCount - 1; octave >= 0; octave--) { amplitude *= getPersistance(); totalAmplitude += amplitude; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { perlinNoise[i][j] += smoothNoise[octave][i][j] * amplitude; } } } for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { perlinNoise[i][j] /= totalAmplitude; } } return perlinNoise; }
290cd22b-961f-46d7-bfcf-91cc87c0d616
9
public void runProgram() throws FileNotFoundException, IOException { //Deserializes the file objectsVector = deSerFile.DeserializeFile(); //Count the number of each object if(debug.getDebugVal() == 0) { int numType1 = 0; int numType2 = 0; Boolean bln = true; //Check & display unique # of class instances for(int i = 0; i < objectsVector.size(); i++) { for(int j = i+1; j < objectsVector.size(); j++) { if(objectsVector.elementAt(i).equals(objectsVector.elementAt(i))) { bln = false; } } if(bln == true) { //There is a unique instance if(objectsVector.elementAt(i) instanceof MyAllTypesFirst) { numType1++; } if(objectsVector.elementAt(i) instanceof MyAllTypesSecond) { numType2++; } } bln = true; } System.out.println("MyAllTypesFirst Unique Instances: " + numType1); System.out.println("MyAllTypesSecond Unique Instances: " + numType2); } //If the debug value is 2, this will print all the objects // that were parsed if(debug.getDebugVal() == 2) for(int i = 0; i < objectsVector.size(); i ++) { System.out.println(i + " " + objectsVector.elementAt(i).toString()); } //Open output file and error check serFile = new Serialize(debug, outputFilename, objectsVector); //Serializes all the files serFile.SerializeAll(); }
c63b9fdf-c808-454c-8958-87223a48109c
1
final Object pop() { int size = stack.size(); return size == 0 ? null : stack.remove(size - 1); }
f10e3eca-40c1-4f68-9822-b704055bd8e0
9
@Override public void projectChanged(Project source, ProjectInfo i) { if ((i.isSimulationControlStateModified() || i.isSimulationChanged()) && source.hasSimulation() && source == session.getCurrentProject()) { simulationTimer.setDelay(source.getTimerDelay()); if (source.isSimulationPaused()) { simulationTimer.stop(); } else { simulationTimer.start(); } } else if (i.isSimulationChanged() && !source.hasSimulation()) { simulationTimer.stop(); } if (i.isCircuitChanged() && source.getCircuit() == null) { simulationTimer.stop(); } }
a8cf78da-d67f-44e6-8397-a1fbdd8c83c5
4
public String processInstructions(String instructions) { /*regex to check if the input is valid. to break it down further: ^\d+ \d+\n checks for a number followed by a space and a number, then a line break. This is the platform size. Then, (\d+ \d+ [NESW] check is the same but followed by one of N E W or S, the initial position. The rest \n[LRM]+\n?)+$ checks that the last line is formed from L R and M, for the instructions. The command section that is not the platform size can also repeat as many times as necessary. */ String inputPattern = "^\\d+ \\d+\\n(\\d+ \\d+ [NESW]\\n[LRM]+\\n?)+$"; //if we don't match the pattern, there could be anything as input, so we stop here. if (!instructions.matches(inputPattern)) { throw new IllegalArgumentException("Input not recognised as valid!"); } //instructions look good, so get commands and size from the text-based instructions ArrayList<RoverCommand> commands = getRoverCommands(instructions); String platformSize = getPlatformSize(instructions); for (int i = 0; i < commands.size(); i++) { //and add a rover for each command rovers.add(new Rover(platformSize, commands.get(i), this)); } String ret = ""; //then build up the output of each rover's final position for (int j = 0; j < rovers.size(); j++) { ret += rovers.get(j).getOutput() + "\n"; } //and strip the last line break to conform with the brief if (ret.contains("\n")) { ret = ret.substring(0, ret.length() - 1); } return ret; }
00f1e34b-0fe8-4ae5-9942-f037fbf3acd6
1
public int[] next() { if (repeat-- > 0) { shuffle(p, random); return p; } else return null; }
d1cc0b1b-aeda-4124-9816-6384be6bd316
5
public void paint( Graphics g ){ super.paint(g); if (isSelect()) g.setColor(getColorSelect()); else g.setColor(getColorNormal()); switch (relacion.getTipo()){ case CONST.R_ASOCIACION : pintarAsociacion(g); break; case CONST.R_AGREGACION : pintarAgregacion(g);break; case CONST.R_HERENCIA : pintarGeneralizacion(g);break; case CONST.R_COMPOSICION : pintarComposicion(g);break; default : pintarAsociacion(g); } }
af429efb-e5d1-422b-bba4-71691a1fd27d
5
public String addEdge(String src_region, String src_agent, String src_plugin, String dst_region, String dst_agent, String dst_plugin, String className) { String edge_id = null; int count = 0; try { while((edge_id == null) && (count != retryCount)) { edge_id = IaddEdge(src_region, src_agent, src_plugin, dst_region, dst_agent, dst_plugin, className); count++; } if((edge_id == null) && (count == retryCount)) { System.out.println("GraphDBEngine : addEdge : Failed to add node in " + count + " retrys"); } } catch(Exception ex) { System.out.println("GraphDBEngine : addEdge : Error " + ex.toString()); } return edge_id; }
f7c045d7-738c-4f96-8e43-f629dc60bc3c
9
public boolean isBlocked(Location l, boolean playersBlock){ if (playersBlock) { //Return true if occupied by any player for (Player player : players) { if (l.equals(player.getLocation())) return true; } } //Return true if the location is beyond the edge of the map if(l.getX() >= MAX_X || l.getX() < 0 || l.getY() >= MAX_Y || l.getY() < 0){ return true; } //Return true if the location is blocked for(int i = 0; i < blockedLocs.size(); i++){ if(l.equals(blockedLocs.get(i))){ return true; } } //Otherwise return false return false; }
c04c2f71-782d-49ba-a5a9-22cb63ff1bb2
5
public Ausrichtung string2Ausrichtung(String input) { int richtung = 0; // -1,1,-2,2 == -x,x,y,-y Ausrichtung ausrichtung = null; try { richtung = Integer.parseInt(input); } catch (Exception e) { // Nothing } switch (richtung) { case 1: ausrichtung = Ausrichtung.XPLUS; break; case -1: ausrichtung = Ausrichtung.XMINUS; break; case 2: ausrichtung = Ausrichtung.YPLUS; break; case -2: ausrichtung = Ausrichtung.YMINUS; break; default: ausrichtung = Ausrichtung.KEINE; break; } return ausrichtung; }
87df4269-d219-435b-8da5-fd713a35c4f7
0
public void setTopping(String topping) { this.topping = topping; }
fcc853cf-db66-42a3-ba58-1bf1f561f78a
2
void inputAppend(String s){ int maxLength = 4; if (currentState == MasterMindGraphic.FEEDBACK) { maxLength = 2; } if (input.length() < maxLength) { this.input += s; } }
8853460c-07f3-455a-ab5a-1d7e24d7ce69
2
public void testGetValue() throws Throwable { MockPartial mock = new MockPartial(); assertEquals(1970, mock.getValue(0)); assertEquals(1, mock.getValue(1)); try { mock.getValue(-1); fail(); } catch (IndexOutOfBoundsException ex) {} try { mock.getValue(2); fail(); } catch (IndexOutOfBoundsException ex) {} }
dd6b7f0d-1e1b-4e9c-972a-c9283c15f0af
8
@Override public void keyPressed(KeyEvent e) { int KeyCode = e.getKeyCode(); if (KeyCode == KeyEvent.VK_A || KeyCode == KeyEvent.VK_LEFT) { left = true; } if (KeyCode == KeyEvent.VK_D || KeyCode == KeyEvent.VK_RIGHT) { right = true; } if (KeyCode == KeyEvent.VK_CONTROL || KeyCode == KeyEvent.VK_SPACE || KeyCode == KeyEvent.VK_W || KeyCode == KeyEvent.VK_UP) { shoot = true; } }
afd76891-60c4-43ec-a5f5-0b7f14962583
6
public UserDTO getUserByNickname( String nickname ) throws DAOException{ UserDTO user = null; query = ""; query += "SELECT \n"; query += "id, passwd, register_date, email, status \n"; query += "FROM chat_user \n"; query += "WHERE nickname = ? \n"; try{ connection = DBManager.getConnection( ); statement = connection.prepareStatement( query ); statement.clearParameters( ); statement.setString( 1 , nickname ); resultSet = statement.executeQuery( ); if( resultSet.next( ) ){ user = new UserDTO( ); user.setId( resultSet.getInt( 1 ) ); user.setNickname( nickname ); user.setPasswd( resultSet.getString( 2 ) ); user.setRegisterDate( resultSet.getDate( 3 ) ); user.setEmail( resultSet.getString( 4 ) ); user.setStatus( resultSet.getInt( 5 ) ); } else{ logger.error( "Can't find user:DBERROR" ); throw new DataBaseException( ); } } catch( SQLException e ) { logger.error( "Can't get prepared statement from connection:DBERROR" ); throw new DAOException( ); } catch ( DataBaseException e ) { logger.error( "Unable to get user register:DBERROR" ); throw new DAOException( ); } finally{ try { statement.close( ); } catch ( SQLException e ) { logger.error( "Can't close statement:DBERROR" ); } try { resultSet.close( ); } catch ( SQLException e ) { logger.error( "Can't close result set:DBERROR" ); } try { connection.close( ); } catch ( SQLException e ) { logger.error( "Can't close connection:DBERROR" ); } } return user; }
54d550e6-8d27-4e45-9bdc-b75c35c46e1f
6
@Override public void run() { boolean done = false; try { Shell sh = ShellManager.getReference().getShell(m_ConnectionData.getLoginShell()); do { sh.run(this); if (m_Dead) { done = true; break; } sh = getNextShell(); if (sh == null) { done = true; } } while (!done || m_Dead); } catch (Exception ex) { log.error("run()", ex); // Handle properly } finally { // call close if not dead already if (!m_Dead) { close(); } } log.debug("run():: Returning from " + toString()); }// run
efa3fff0-c7d3-4128-9a06-ef2999d7123c
6
private List<MorrisLineAdjacent> getColumnLineAdjacent() { List<MorrisLineAdjacent> lines = new ArrayList<MorrisLineAdjacent>(); boolean bu = this.hasUp(); boolean bd = this.hasDown(); MorrisLineAdjacent oneLine = null; if (bu && bd) { //this is in the middle oneLine = new MorrisLineAdjacent(this, this.up(), this.down()); lines.add(oneLine); } else { if (bu) { //this is in the most down MorrisIntersection u = this.up(); if (u.hasUp()) { oneLine = new MorrisLineAdjacent(this, u, u.up()); lines.add(oneLine); } } if (bd) { //this is in the most up MorrisIntersection d = this.down(); if (d.hasDown()) { oneLine = new MorrisLineAdjacent(this, d, d.down()); lines.add(oneLine); } } } return lines; }
1a1a9d94-5f51-493d-909c-80e12a8b00d0
6
public ArrayList<String> apiGetLinks (String Client_ID, String url) throws IOException { ArrayList<String> foundLinks = new ArrayList<String>(); if(isRunning){//We only want to do this if the app is running. String YOUR_REQUEST_URL = url; URL imgURL = new URL(YOUR_REQUEST_URL); HttpURLConnection conn = (HttpURLConnection) imgURL.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Authorization", "Client-ID " + Client_ID); BufferedReader bin = null; bin = new BufferedReader(new InputStreamReader(conn.getInputStream())); //below will print out bin String jsonString = ""; String line; while ((line = bin.readLine()) != null){ //System.out.println(line); jsonString = jsonString + line; } bin.close(); //System.out.println("jsonString: "+jsonString); //String [] foundLinks = new String[200]; JSONParser parser = new JSONParser(); try{ JSONObject obj = (JSONObject) parser.parse(jsonString); JSONArray data = (JSONArray) obj.get("data"); if(data.isEmpty()){ parent.gui.mainCanvas.header.inputArea.button.doClick(20); parent.gui.mainCanvas.header.inputArea.textField.setText("No Results Found!"); parent.gui.mainCanvas.header.inputArea.textField.selectAll(); } System.out.println(jsonString); for(int i = 0; i < data.size(); i++){ JSONObject img = (JSONObject)data.get(i); String link = (String) img.get("link"); if(linkIsAlbum(link)){ String albumID = getAlbumID(link); foundLinks.addAll(apiGetLinks(Client_ID, "https://api.imgur.com/3/album/"+albumID+"/images")); }else{ foundLinks.add(link); queue.enQueue(link); //this will do the downloading. } //System.out.println(link); } }catch(ParseException pe){ parent.gui.mainCanvas.header.inputArea.textField.setText("No Images Found"); //parent.gui.mainCanvas.header.inputArea.getTextField().updateUI(); System.out.println("setTextHERE"); System.out.println("position: " + pe.getPosition()); System.out.println(pe); } } return foundLinks; }
9953bd8e-e2f4-4f44-b4d8-071f1f0eaeb1
9
@Override public long periodUntil(DateTime endDateTime, PeriodUnit unit) { if (endDateTime instanceof LocalTime == false) { throw new DateTimeException("Unable to calculate period between objects of two different types"); } LocalTime end = (LocalTime) endDateTime; if (unit instanceof ChronoUnit) { long nanosUntil = end.toNanoOfDay() - toNanoOfDay(); // no overflow switch ((ChronoUnit) unit) { case NANOS: return nanosUntil; case MICROS: return nanosUntil / 1000; case MILLIS: return nanosUntil / 1000000; case SECONDS: return nanosUntil / NANOS_PER_SECOND; case MINUTES: return nanosUntil / NANOS_PER_MINUTE; case HOURS: return nanosUntil / NANOS_PER_HOUR; case HALF_DAYS: return nanosUntil / (12 * NANOS_PER_HOUR); } throw new DateTimeException("Unsupported unit: " + unit.getName()); } return unit.between(this, endDateTime).getAmount(); }
f330612e-de97-4495-80db-2d8f9296363e
6
public static void main(String[] args) throws ClassNotFoundException,SQLException { Connection conn = null; PreparedStatement ps = null; try{ conn = DBConnection.getConnection(); //just a test to get some user input and insert into the db Scanner scanner = new Scanner(System.in); System.out.println("Enter your username"); String userName = scanner.nextLine(); System.out.println("Enter your first name"); String firstName = scanner.nextLine(); System.out.println("Enter your last name"); String lastName = scanner.nextLine(); System.out.println("Enter your password"); String passWord = scanner.nextLine(); //inserting user input into the db System.out.println("Inserting records into the table..."); String query = "INSERT INTO users " + "VALUES(?, ?, ?, ?, ?, ?)"; ps = conn.prepareStatement(query); ps.setNull(1, java.sql.Types.INTEGER); ps.setString(2, userName); ps.setString(3, firstName); ps.setString(4, lastName); ps.setString(5, passWord); ps.setString(6, "true"); ps.executeUpdate(); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(ps!=null) conn.close(); }catch(SQLException se){ }// do nothing try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!"); }//end main
f7278ddf-534b-461b-94a9-e2ac2d43cd73
1
@Override public void display(UserInterface ui) { UserInterface.print("Breakpoints cleared on lines: "); for (String breakpointLine : breakpointLinesToClear) { UserInterface.print(breakpointLine + " "); } UserInterface.println("\n"); ui.signalNeedToDisplayFunction(); }
1117180b-866e-4717-b243-8d48133b82ca
3
@Override public void render(Graphics2D g) { double angle = Math.toDegrees(connectedObject.getRotationAngle()); angle = angle < 0 ? 360 + angle : angle; double radius = connectedObject.getRadius(); double diameter = 2 * radius; double x = connectedObject.getX() - radius; double y = connectedObject.getY() - radius; Arc2D.Double arc = new Arc2D.Double(x, y, diameter, diameter, 0, -angle, Arc2D.PIE); String text = Math.round(angle) + "°"; float textX = (float) (connectedObject.getX() + radius + 5); float textY = (float) connectedObject.getY(); if (color != null) { g.setColor(color); g.fill(arc); } if (border != null) { g.setColor(border); g.draw(arc); } drawString(g, text, textX, textY); }
3fbade63-b649-4473-80f2-9dd2715d36ee
1
public void setNumber(int number) { if (number <= 0) { throw new IllegalArgumentException("Number should be bigger than zero."); } this.number = number; }
313a2c4d-3c6e-42cf-b584-cdd283e23bc2
3
private boolean isCorrect(JTextField field) { boolean correct = false; if (field.getText().length() == 5) { String[] pieces = field.getText().split(":"); if (Utils.isNumeric(pieces[0]) && Utils.isNumeric(pieces[1])) { correct = true; } } return correct; }
caa2134e-f78c-4a89-ab17-87b6939cd84b
7
public boolean isBoundingBoxBurning(AxisAlignedBB var1) { int var2 = MathHelper.floor_double(var1.minX); int var3 = MathHelper.floor_double(var1.maxX + 1.0D); int var4 = MathHelper.floor_double(var1.minY); int var5 = MathHelper.floor_double(var1.maxY + 1.0D); int var6 = MathHelper.floor_double(var1.minZ); int var7 = MathHelper.floor_double(var1.maxZ + 1.0D); if (this.checkChunksExist(var2, var4, var6, var3, var5, var7)) { for (int var8 = var2; var8 < var3; ++var8) { for (int var9 = var4; var9 < var5; ++var9) { for (int var10 = var6; var10 < var7; ++var10) { int var11 = this.getBlockId(var8, var9, var10); if (var11 == Block.fire.blockID || var11 == Block.lavaMoving.blockID || var11 == Block.lavaStill.blockID) { return true; } } } } } return false; }
00eab101-8831-4537-9d26-1847ed20c57c
8
public static void setText(ArrayList<JavaProcess> newLabel){ newLabels = newLabel; labelListValue = labelList.size()/6; newLabelsValue = newLabels.size(); //System.out.println(newLabels.size() + " "+ labelList.size()); if(newLabelsValue < labelListValue){ SwingUtilities.invokeLater(new Runnable(){ public void run(){ for(int i=((labelListValue-newLabels.size())*6); i>0;i--){ gui.frame.remove(labelList.get(i)); labelList.remove(i); } } }); } if(newLabelsValue > labelListValue){ SwingUtilities.invokeLater(new Runnable(){ public void run(){ for(int i=0; i<(newLabelsValue-labelListValue);i++){ labelList.add(new JLabel("",SwingConstants.CENTER)); labelList.add(new JLabel("",SwingConstants.CENTER)); labelList.add(new JLabel("",SwingConstants.CENTER)); labelList.add(new JLabel("",SwingConstants.CENTER)); labelList.add(new JLabel("",SwingConstants.CENTER)); labelList.add(new JLabel("",SwingConstants.CENTER)); } for(int i=labelListValue; i <labelList.size();i++){ //labelList.get(i).setBorder(BorderFactory.createEtchedBorder()); labelList.get(i).setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY)); gui.frame.add(labelList.get(i)); } } }); } SwingUtilities.invokeLater(new Runnable(){ public void run(){ int i=0;int j=1; for(JavaProcess jps: newLabels){ if(j==1){ labelList.get(i).setOpaque(false); labelList.get(i++).setText(jps.getName()); labelList.get(i).setOpaque(false); labelList.get(i++).setText(jps.getCPU()); labelList.get(i).setOpaque(false); labelList.get(i++).setText(jps.getMem()); labelList.get(i).setOpaque(false); labelList.get(i++).setText(jps.getTime()); labelList.get(i).setOpaque(false); labelList.get(i++).setText(jps.getMaxCpu()); labelList.get(i).setOpaque(false); labelList.get(i++).setText(jps.getMaxMem()); j++; } else { labelList.get(i).setBackground(Color.LIGHT_GRAY); labelList.get(i).setOpaque(true); labelList.get(i++).setText(jps.getName()); labelList.get(i).setBackground(Color.LIGHT_GRAY); labelList.get(i).setOpaque(true); labelList.get(i++).setText(jps.getCPU()); labelList.get(i).setBackground(Color.LIGHT_GRAY); labelList.get(i).setOpaque(true); labelList.get(i++).setText(jps.getMem()); labelList.get(i).setBackground(Color.LIGHT_GRAY); labelList.get(i).setOpaque(true); labelList.get(i++).setText(jps.getTime()); labelList.get(i).setBackground(Color.LIGHT_GRAY); labelList.get(i).setOpaque(true); labelList.get(i++).setText(jps.getMaxCpu()); labelList.get(i).setBackground(Color.LIGHT_GRAY); labelList.get(i).setOpaque(true); labelList.get(i++).setText(jps.getMaxMem()); j=1; } } newLabels=null; gui.frame.pack(); } }); if(firstRun){ firstRun=false; gui.frame.setVisible(true); } }
20d8e3e5-d9d8-4bf0-b0f2-3fd782e019ed
8
public void roundComplete() throws Exception { this.roundCount++; if (roundCount % 100 == 0) { List<Statistics> stats = listStats(); Collections.sort(stats); if (stats.size() < 3) //not enough stats yet { return; } Statistics winnerStats = stats.get(stats.size() - 1); WinnerConfidence winnerConfidence = getWinnerConfidence(stats); if ((System.currentTimeMillis() - lastStatsPrintTime) > 5000) { //print every 5 secs max printStatsAndWinner(stats, winnerStats, winnerConfidence); lastStatsPrintTime = System.currentTimeMillis(); } if (winnerConfidence.finalConfidence >= 1.0) { printStatsAndWinner(stats, winnerStats, winnerConfidence); handleWinner(winnerStats); } //drop loser every 10k rounds if (doLoserDrop && roundCount % 10000 == 0 && pwdList.size() > 7) { String loserPwd = stats.get(0).getPwd(); System.out.println("Dropping fastest canididate: " + loserPwd); pwdList.remove(loserPwd); synchronized (measurements) { measurements.remove(loserPwd); } } //hopefully eliminate any order bias Collections.shuffle(pwdList); } //BAIL if (requestCount.get() / initalPwdCount >= 1000000) { System.err.println("Max request hit (1000000 per pwd). This server is probably NOT vulnerable."); isDone = true; } }
8627bfeb-268b-43cc-b84e-c47a0e82006c
6
public static boolean innersolveSudoku(char[][] board) { for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[i].length; j++) { if ('.' == board[i][j]) { for (int k = 0; k < 9; k++) { board[i][j] = (char) ('1' + k); if (isValidSudoku(board)) { if (innersolveSudoku(board)) return true; } board[i][j] = '.'; } return false; } } } return true; }
2fadb069-e038-4608-b866-b1be4a4ea41c
7
public static final Formula empiricalFromMolecular(String formula) { int gcd = Integer.MAX_VALUE; Formula empiricalFormula = FtHelper.parseFormula(formula); List<Integer> subscripts = empiricalFormula.getSubscripts(); // We'll find GCDs in pairs and store them in tryGCD int[] tryGcd = new int[10]; for (int x = 0; x < subscripts.size() - 1; x++) { // First find the initial min and max of the pair. int min = Math.min(subscripts.get(x), subscripts.get(x + 1)); int max = Math.max(subscripts.get(x), subscripts.get(x + 1)); // Now loop and use the algorithm. for (int y = 0; y < 1000; y++) { max -= min; min = Math.min(max, min); max = Math.max(max, min); if (max == min) { tryGcd[x] = min; break; } } } // Loop through tryGCD, find the smallest GCD that isn't 0, and set GCD to it. for (int candidateGcd : tryGcd) { if (candidateGcd != 0) { if (candidateGcd < gcd) { gcd = candidateGcd; } } } // Now that we finally have the GCD, divide the subscripts by it // and return the empirical formula. List<Integer> newSubscripts = new ArrayList<Integer>(); for (int subscript : subscripts) { newSubscripts.add(subscript / gcd); } empiricalFormula.setSubscripts(newSubscripts); return empiricalFormula; }
0ca2ab7e-7d44-428b-a0f8-86e88a8b9dd2
6
public static void removeWordsStartWithConsonant(Text text, int length) { log.trace("Subtask N12"); for (int i = 0; i < text.getAllElements().size(); i++) { Sentence sentence = text.getChildElement(i); if (sentence.getClass() != Listing.class) { for (int j = 0; j < sentence.getAllElements().size(); j++) { SentencePart sentencePart = sentence.getChildElement(j); if (sentencePart instanceof Word) { Word word = (Word) sentencePart; if (word.getLength() == length && isStartsWithConsonant(word)) { sentence.remove(word); } } } } } }
08e7fb38-6c77-4e83-b90e-4d0268e4277c
4
public static void navigate(String url) { if (java.awt.Desktop.isDesktopSupported()) { try { Desktop.getDesktop().browse(new URI(url)); } catch (IOException e) { BmLog.error(e); } catch (URISyntaxException e) { BmLog.error(e); } catch (NullPointerException npe) { BmLog.error("URL is empty, nothing to open in browser", npe); } } }
6e04f571-e714-4ca8-abd3-26ac9697d66a
2
public static void closeDB(DB db) { if (db != null) { LOGGER.trace("正在关闭MongoDB[" + db.getName() + "]"); try { db.requestDone(); } catch (Throwable ex) { LOGGER.debug("关闭MongoDB时发生未知异常", ex); } } }
f574776c-9c3f-4b84-99c0-8993499c25e9
0
@Override public void dosomething() { super.dosomething(); this.anothing(); }
c2565ce9-7dfa-4152-b8ef-309b2ee7e4b9
4
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = (caseSensitive) ? value.toString() : value.toString().toLowerCase(); for (String pattern : patternsToSkip) { line = line.replaceAll(pattern, ""); } String[] split = line.split("href=\""); if(split.length > 1) { split = split[1].split("\""); split[0].replace("\t", ""); context.write(new Text(split[0]), one); } context.getCounter(Counters.INPUT_WORDS).increment(1); if ((++numRecords % 100) == 0) { context.setStatus("Finished processing " + numRecords + " records " + "from the input file: " + inputFile); } }
fdde79bf-003e-4364-948d-d21a4416b0eb
8
public void handleEntityMovement() { MovementPoint walkingPoint = null, runningPoint = null; if (getEntity().getUpdateFlags().contains("teleporting")) { resetMovement(); } else { walkingPoint = getNextPoint(); if (isRunning()) { runningPoint = getNextPoint(); } getEntity().setWalkingDirection(walkingPoint == null ? -1 : walkingPoint.getDirection()); getEntity().setRunningDirection(runningPoint == null ? -1 : runningPoint.getDirection()); int deltaX = getEntity().getPosition().getX() - getEntity().getLastPosition().getRegionalX() * 8; int deltaY = getEntity().getPosition().getY() - getEntity().getLastPosition().getRegionalY() * 8; if (deltaX < 16 || deltaX >= 88 || deltaY < 16 || deltaY > 88) { ((Player) getEntity()).send(new RegionalUpdatePacket()); } } }
d1a1f7c9-c310-4624-a71d-bc88797c35e4
9
protected void printTopWordsDistribution(int topK, String topWordFile) { Arrays.fill(m_sstat, 0); System.out.println("print top words"); for (_Doc d : m_trainSet) { for (int i = 0; i < number_of_topics; i++) m_sstat[i] += m_logSpace ? Math.exp(d.m_topics[i]) : d.m_topics[i]; } Utils.L1Normalization(m_sstat); try { System.out.println("top word file"); PrintWriter betaOut = new PrintWriter(new File(topWordFile)); for (int i = 0; i < topic_term_probabilty.length; i++) { MyPriorityQueue<_RankItem> fVector = new MyPriorityQueue<_RankItem>( topK); for (int j = 0; j < vocabulary_size; j++) fVector.add(new _RankItem(m_corpus.getFeature(j), topic_term_probabilty[i][j])); betaOut.format("Topic %d(%.3f):\t", i, m_sstat[i]); for (_RankItem it : fVector) { betaOut.format("%s(%.3f)\t", it.m_name, m_logSpace ? Math.exp(it.m_value) : it.m_value); System.out.format("%s(%.3f)\t", it.m_name, m_logSpace ? Math.exp(it.m_value) : it.m_value); } betaOut.println(); System.out.println(); } betaOut.flush(); betaOut.close(); } catch (Exception ex) { System.err.print("File Not Found"); } }
c7728fd7-b56f-40b3-bfe8-cc143b0e67e3
2
private static void printBuildingTable(ArrayList<ParkerPaulTaxable> taxables) { double totalTaxes = 0.00; // total taxes for items double minTaxes = -1.00; // min taxes for items double maxTaxes = 0.00; // max taxes for items int count = 0; // count of items printBuildingHeader(); for (ParkerPaulTaxable taxable : taxables) { if ((taxable instanceof ParkerPaulBuilding)) { // accumulate footer values double tax = taxable.getTax(); // tax for item totalTaxes += tax; minTaxes = getMinTax(minTaxes, tax); maxTaxes = Math.max(maxTaxes, tax); count++; // print info for item printBuildingInfo((ParkerPaulBuilding) taxable, count); } } printFooter(totalTaxes, minTaxes, maxTaxes, count); }
94a2421a-3eb1-496e-8af2-5dcdb0e54178
8
public void save(File file) { FileOutputStream outputStream = null; try { if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } if (file.canWrite()) { outputStream = new FileOutputStream(file); for (Device device : devicesHistory.values()) { device.write(outputStream); } for (Host host : hosts.values()) { if (!LOCALHOST.equals(host.getHostname())) { host.write(outputStream); } } } } catch (IOException e) { } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { // do nothing } } } }
0a337bcb-b9dd-492b-94a2-fc64fa849470
4
public void monitorFileModify(Path file){ if(file.startsWith(targetPath) && !Files.isDirectory(file)){ Path subPath = targetPath.relativize(file); Path newPathSource = sourcePath.resolve(subPath); Path newPathTarget = targetPath.resolve(subPath); try { if(!FileUtils.contentEquals(newPathSource.toFile(),newPathTarget.toFile())){ logger.debug("Target modified"); logger.debug("Pfad 1 : "+newPathSource.toString()); logger.debug("Pfad 2 : "+newPathTarget.toString()); logger.debug("Target content:"); logger.debug(FileUtils.readFileToString(newPathTarget.toFile())); logger.debug("End Target content--"); File backup = new File(newPathSource.toFile().getAbsolutePath()+".bak"); FileUtils.copyFile(newPathSource.toFile(), backup); FileUtils.copyFile(newPathTarget.toFile(), newPathSource.toFile()); JOptionPane.showMessageDialog(App.window, subPath+" got Modified in target "+targetPath+". Copied the target to your source and made a backup of the source to "+backup); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { App.window.toFront(); App.window.repaint(); } }); } } catch (IOException e) { JOptionPane.showMessageDialog(App.window, e.getMessage()); e.printStackTrace(); } } }
dadf0d8d-dcab-4488-a6ce-f3f554b3e606
7
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Customer customer = (Customer) o; if (!firstName.equals(customer.firstName)) return false; if (!id.equals(customer.id)) return false; if (!lastName.equals(customer.lastName)) return false; if (!orders.equals(customer.orders)) return false; return true; }
6897c15b-2ccb-491e-a575-a2589088d486
9
static final void loadScriptSettings(int i) { if (i != 1) aString1761 = null; anInt1760++; FileOnDisk class234 = null; try { SignlinkRequest class144 = Class348_Sub23_Sub1.signlink.method2233((byte) -46, "2", true); while ((class144.state ^ 0xffffffff) == -1) Class286_Sub5.method2161((byte) 63, 1L); if ((class144.state ^ 0xffffffff) == -2) { class234 = (FileOnDisk) class144.returnObj; byte[] is = new byte[(int) class234.method1662((byte) -46)]; int i_0_; for (int i_1_ = 0; (i_1_ ^ 0xffffffff) > (is.length ^ 0xffffffff); i_1_ += i_0_) { i_0_ = class234.read(is, i_1_, (byte) -12, is.length + -i_1_); if ((i_0_ ^ 0xffffffff) == 0) throw new IOException("EOF"); } AbstractImageFetcher.readScriptSettings(new ByteBuffer(is), (byte) -40); } } catch (Exception exception) { /* empty */ } do { try { if (class234 == null) break; class234.method1657(false); } catch (Exception exception) { break; } break; } while (false); }
1d32ec75-7b83-4872-94d8-dce9eddb21ec
2
public void showPersonalPosts() { for (TimedPosts post : posts) { long elapsedTimeInSec = (System.nanoTime() - post.getTime()) / 1000000000; if (elapsedTimeInSec < 60) { int elapsedTime = (int) elapsedTimeInSec; System.out.println(post.getPost() + "(" + elapsedTime + " seconds ago)"); } else { int elapsedTime = (int) (elapsedTimeInSec / 60); System.out.println(post.getPost() + "(" + elapsedTime + " minutes ago)"); } } }
98244daa-503c-4a09-967a-c81ac00dce7f
7
protected Node representData(Object data) { objectToRepresent = data; // check for identity if (representedObjects.containsKey(objectToRepresent)) { Node node = representedObjects.get(objectToRepresent); return node; } // } // check for null first if (data == null) { Node node = nullRepresenter.representData(data); return node; } // check the same class Node node; Class clazz = data.getClass(); if (representers.containsKey(clazz)) { Represent representer = representers.get(clazz); node = representer.representData(data); } else { // check the parents for (Class repr : multiRepresenters.keySet()) { if (repr.isInstance(data)) { Represent representer = multiRepresenters.get(repr); node = representer.representData(data); return node; } } // check array of primitives if (clazz.isArray()) { throw new YAMLException("Arrays of primitives are not fully supported."); } // check defaults if (multiRepresenters.containsKey(null)) { Represent representer = multiRepresenters.get(null); node = representer.representData(data); } else { Represent representer = representers.get(null); node = representer.representData(data); } } return node; }
ba1be49f-5635-4e9c-892d-24101e0a38a8
4
public void mouseDragged(MouseEvent e) { if(Global.isRunning) { return; } // block mouse input while simulating if(shiftStartPoint != null) { // shift the view pt.moveView((int) ((shiftStartPoint.x - e.getX()) / pt.getZoomPanelZoomFactor() * pt.getZoomFactor()), (int) ((shiftStartPoint.y - e.getY()) / pt.getZoomPanelZoomFactor() * pt.getZoomFactor())); shiftStartPoint = e.getPoint(); gui.redrawControl(); } else if(rotateStartPoint != null) { if(pt instanceof Transformation3D) { Transformation3D t3d = (Transformation3D) pt; t3d.rotate(e.getX() - rotateStartPoint.x, e.getY() - rotateStartPoint.y, !e.isControlDown(), true); // read keyboard - ctrl allows to freely rotate rotateStartPoint = e.getPoint(); gui.redrawControl(); } } }
79c728af-7b92-4564-9088-1f319eb78e4e
8
public void run() { PrintStream outOld = null; PrintStream outNew = null; String outFilename = null; // is the output redirected? if (m_CommandArgs.length > 2) { String action = m_CommandArgs[m_CommandArgs.length - 2]; if (action.equals(">")) { outOld = System.out; try { outFilename = m_CommandArgs[m_CommandArgs.length - 1]; // since file may not yet exist, command-line completion doesn't // work, hence replace "~" manually with home directory if (outFilename.startsWith("~")) outFilename = outFilename.replaceFirst("~", System.getProperty("user.home")); outNew = new PrintStream(new File(outFilename)); System.setOut(outNew); m_CommandArgs[m_CommandArgs.length - 2] = ""; m_CommandArgs[m_CommandArgs.length - 1] = ""; // some main methods check the length of the "args" array // -> removed the two empty elements at the end String[] newArgs = new String[m_CommandArgs.length - 2]; System.arraycopy(m_CommandArgs, 0, newArgs, 0, m_CommandArgs.length - 2); m_CommandArgs = newArgs; } catch (Exception e) { System.setOut(outOld); outOld = null; } } } try { Object[] args = {m_CommandArgs}; m_MainMethod.invoke(null, args); if (isInterrupted()) { System.err.println("[...Interrupted]"); } } catch (Exception ex) { if (ex.getMessage() == null) { System.err.println("[...Killed]"); } else { System.err.println("[Run exception] " + ex.getMessage()); } } finally { m_RunThread = null; } // restore old System.out stream if (outOld != null) { outNew.flush(); outNew.close(); System.setOut(outOld); System.out.println("Finished redirecting output to '" + outFilename + "'."); } }
403d7fdb-f60f-4817-a834-862141ddf8a0
5
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = ""; StringBuilder out = new StringBuilder(); int nCase = 1; while ((line = in.readLine()) != null) { if (line.trim().startsWith("#")) break; char[] a = line.toCharArray(); char[] b = in.readLine().toCharArray(); int[][] dp = new int[a.length + 1][b.length + 1]; for (int i = 0; i < a.length; i++) { for (int j = 0; j < b.length; j++) { if (a[i] == b[j]) dp[i + 1][j + 1] = dp[i][j] + 1; else dp[i + 1][j + 1] = Math.max(dp[i][j + 1], dp[i + 1][j]); } } out.append("Case #" + nCase++ + ": you can visit at most " + dp[a.length][b.length] + " cities.\n"); } System.out.print(out); }
c27b8a03-71b4-4107-b49e-9909b9a9979b
4
private void parse(JSONObject action) { // Initialize the keywords available for this Action keywords = new ArrayList<String>(); // Assign the name and execution code for this Action name = action.getString("name"); execute = action.getString("execute"); // Pull off the keywords from the JSONObject and store them in a JSONArray JSONArray keywordsjson = action.getJSONArray("keywords"); // Loop over the keywords for(int i = 0; i<keywordsjson.length(); i++) { // Add each keyword into the ArrayList keywords.add(keywordsjson.getString(i)); } // Initialize the parameters available for this Action parameters = new ArrayList<ArrayList<String>>(); // Try to load the JSONArray try { // Store the parameters as JSONArray JSONArray parametersjson = action.getJSONArray("parameters"); // Loop over the previously created array for(int i = 0; i<parametersjson.length(); i++) { // Initialize a temporary ArrayList ArrayList<String> temp = new ArrayList<String>(); // Fetch all possibilities for parameter i JSONArray parameterjson = parametersjson.getJSONArray(i); // Loop over all possibilities for(int j = 0; j<parameterjson.length(); j++) { // Write those into the temporary array temp.add(parameterjson.getString(j)); } // Add the array to the parameter storage parameters.add(temp); } // If no parameters are available just skip the assignment } catch(JSONException e) {} }
15f32b7b-005b-48a8-94a2-1aa5e6124652
9
public Rule cloneWithModeChange(final Mode toMode) throws RuleException { if ("".equals(toMode)) throw new RuleException("invalid mode [" + toMode + "] to convert"); boolean isModified = false; Rule newRule = clone(); List<Mode> modeUsedInBody = getModeUsedInBody(); if (modeUsedInBody.size() == 0) { } else { for (Literal literal : newRule.body) { if (!toMode.equals(literal.getMode())) throw new RuleModeConversionException("inconsistent mode found in rule body"); } } if (!toMode.equals(newRule.getMode())) { newRule.setMode(mode.clone()); isModified = true; } for (Literal literal : newRule.head) { if (!"".equals(literal.getMode().toString()) && !toMode.equals(literal.getMode())) { literal.setMode(toMode.clone()); isModified = true; } } if (!isModified) throw new RuleModeConversionException("no mode is modified"); return newRule; }
fed7ef78-5fd2-42bc-8a4c-a4d36058eb81
5
public int getBlockTypeIdFromPixel(int imagePixel) { int blockTypeId = -1; String[] line = (String[])groups.get(imagePixel); if(line != null) { int newBlockType = blockManager.getRandomIdByGroup(line[0]); if(newBlockType > 0) { blockTypeId = newBlockType; } } line = (String[])blockTypes.get(imagePixel); if(line != null) { int newBlockType = Integer.parseInt(line[line.length - 1]); if(newBlockType > 0) { blockTypeId = newBlockType; } } int blockTypeOverrideId = getBlockTypeOverrideIdFromPixel(imagePixel); if(blockTypeOverrideId > 0) { blockTypeId = blockTypeOverrideId; } return blockTypeId; }
05b28d9f-2bdc-402a-9cbe-49c6dfd03694
8
@Override public void onEnable() { loadConfig(); PluginManager pm = getServer().getPluginManager(); pSpout = pm.getPlugin("Spout"); pTag = pm.getPlugin("TagAPI"); formatTranslations(); setupDatabase(); pm.registerEvents(playerlistener, this); for (DNCCommands cmd : DNCCommands.values()) { getCommand(cmd.getName()).setExecutor(executor); } if (pSpout == null) { this.bUseSpout = false; log.info(DNCStrings.dnc_long + localization.getString(DNCStrings.INFO_NO_SPOUT)); } else { this.bUseSpout = true; log.info(DNCStrings.dnc_long + localization.getString(DNCStrings.INFO_SPOUT)); } if (pTag != null && !bUseSpout) { bUseTagAPI = true; tagListener = new TagListener(); pm.registerEvents(tagListener, this); log.info(DNCStrings.dnc_long + localization.getString(DNCStrings.INFO_TAGAPI)); } else if (pTag != null && bUseSpout) { bUseTagAPI = false; log.warning(DNCStrings.dnc_long + localization.getString(DNCStrings.INFO_TAGAPI_CONFLICT)); } else { bUseTagAPI = false; log.info(DNCStrings.dnc_long + localization.getString(DNCStrings.INFO_NO_TAGAPI)); } log.info(DNCStrings.dnc_long + localization.getString(DNCStrings.INFO_DNC_COMMANDS)); if (!isSaveOnQuit() && !isSaveOnRename()) { log.severe(DNCStrings.dnc_long + localization.getString(DNCStrings.INFO_SAVE_DISABLED)); } log.info(DNCStrings.dnc_long + localization.getString(DNCStrings.INFO_DNC_ENABLED)); }
dd155fed-f58e-4a30-992c-51ebabe61fb4
2
@Override public boolean subscribe(Client client, SubscribeMessage message) throws Exception { String[] topics = message.getTopics(); QoS[] qoses = message.getRequestedQoSes(); List<String> allowedTopics = new ArrayList<String>(); List<QoS> allowedQoses = new ArrayList<QoS>(); int index = 0; for (String topic : topics) { // Only allow topic subscriptions for topics that don't include country music. if (!topic.matches("^.*(?i:country).*$")) { allowedTopics.add(topic); allowedQoses.add(qoses[index]); } index++; } message = new SubscribeMessage(message.getMessageId(), allowedTopics.toArray(new String[0]), allowedQoses.toArray(new QoS[0])); return super.subscribe(client, message); }
dc03321b-23bd-499f-9138-abfcbe0f4805
6
public Element featureChange(Element element) { Game game = getGame(); Specification spec = game.getSpecification(); boolean add = "add".equalsIgnoreCase(element.getAttribute("add")); FreeColGameObject object = game.getFreeColGameObject(element.getAttribute("id")); NodeList nodes = element.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Element e = (Element) nodes.item(i); String tag = e.getTagName(); if (tag == null) { logger.warning("featureChange null tag"); } else if (tag == Modifier.getXMLElementTagName()) { Modifier m = new Modifier(spec); m.readFromXMLElement(e, spec); if (add) { object.addModifier(m); } else { object.removeModifier(m); } } else if (tag == Ability.getXMLElementTagName()) { Ability a = new Ability(""); a.readFromXMLElement(e, spec); if (add) { object.addAbility(a); } else { object.removeAbility(a); } } else { logger.warning("featureChange unrecognized: " + tag); } } return null; }
242191f2-a65c-4efb-b27a-1192414c7613
3
public boolean doSendPackage() { boolean result = false; try { synchronized (mOutPkgs) { while (mOutPkgs.size() > 0) { mBos.reset(); ObjectOutputStream out = new ObjectOutputStream(mBos); NetSystem.Package pkg = mOutPkgs.poll(); out.writeObject(pkg); byte[] data = mBos.toByteArray(); mBuffer.limit(data.length); mBuffer.put(data); mBuffer.flip(); // important while (mBuffer.hasRemaining()) mSocketChannel.write(mBuffer); mBuffer.clear(); result = true; }; } } catch (Exception e) { System.out.print(e.toString() + "\n"); } mKey.interestOps(mKey.interestOps() ^ SelectionKey.OP_WRITE); return result; }
0a3f2d1c-9436-48bb-9c83-0e4a4806ba27
5
private int selectRGBTransform(RGBTransformAvailable chanel,Color color){ int colorReturn=0; switch (chanel){ case GBR: colorReturn=super.colorRGBtoSRGB(new Color(color.getGreen(), color.getBlue(), color.getRed(),color.getAlpha())); break; case GRB: colorReturn=super.colorRGBtoSRGB(new Color(color.getGreen(), color.getRed(), color.getBlue(),color.getAlpha())); break; case BRG: colorReturn=super.colorRGBtoSRGB(new Color(color.getBlue(), color.getRed(), color.getGreen(),color.getAlpha())); break; case BGR: colorReturn=super.colorRGBtoSRGB(new Color(color.getBlue(), color.getGreen(), color.getRed(),color.getAlpha())); break; case RBG: colorReturn=super.colorRGBtoSRGB(new Color(color.getRed(), color.getBlue(), color.getGreen(),color.getAlpha())); break; } return colorReturn; }
e1fbb5ee-1b87-4aba-851f-23f1b8e805d4
0
private void printTotalScores(Player player, int count) { System.out.println(player.getName() + " wins " + player.getNumberOfWins() + " of " + count + " games."); }
fa70b6d6-3285-46f2-b57c-eecc78c75789
6
private static Entry[] merge(Entry[] list1, Entry[] list2) { Entry[] output = new Entry[list1.length + list2.length]; int p1 = 0, p2 = 0; for(int i = 0; i < output.length; i++) { if(p2 >= list2.length) { output[i] = list1[p1]; p1++; } else if(p1 >= list1.length || list1[p1].getScore() < list2[p2].getScore()) { output[i] = list2[p2]; p2++; } else if(list1[p1].getScore() > list2[p2].getScore()) { output[i] = list1[p1]; p1++; } else if(list1[p1].getScore() == list2[p2].getScore()) { Entry[] sortedByName = bubbleSort(new Entry[] {list1[p1], list2[p2]}); output[i] = sortedByName[0]; output[i+1] = sortedByName[1]; p1++; p2++; i++; } else { System.out.println("Error!"); break; // Something has gone horribly wrong. } } return output; }
ff34c64d-4999-4dc5-ae6b-343754ee1c65
2
protected void processCondCommentBlocks(List<String> condCommentBlocks) { if(generateStatistics) { for(String block : condCommentBlocks) { statistics.setPreservedSize(statistics.getPreservedSize() + block.length()); } } }
a2e1e999-7833-456c-9421-e8c1a5395cfb
2
private void showAboutPanel() { String html = MessageFormat.format(resources .getString("dialog.about.text"), new Object[] { resources.getString("version.id") }); String[] props = { "java.version", "java.vendor", "java.home", "os.name", "os.arch", "os.version", "user.name", "user.home", "user.dir" }; html += "<table border='1'>"; for (String prop : props) { try { String value = System.getProperty(prop); html += "<tr><td>" + prop + "</td><td>" + value + "</td></tr>"; } catch (SecurityException ex) { // oh well... } } html += "</table>"; html = "<html>" + html + "</html>"; JOptionPane.showMessageDialog(this, new JLabel(html), resources .getString("dialog.about.title"), JOptionPane.INFORMATION_MESSAGE); }
854f11e6-6d3c-4e97-ac14-73dc1f44c783
1
@Override public List<? extends DefaultModel> getObj(String campo) { return null; }
eb397f45-0968-48c9-a6a3-5efdd0e14838
9
public Address getAddresses(String content, String encodingString) throws UnsupportedEncodingException { // 这里调用pconline的接口 String urlStr = "http://ip.taobao.com/service/getIpInfo.php"; // 从http://whois.pconline.com.cn取得IP所在的省市区信息 String returnStr = this.getResult(urlStr, content, encodingString); if (returnStr != null) { // 处理返回的省市区信息 System.out.println(returnStr); String[] temp = returnStr.split(","); if (temp.length < 3) { return null;// 无效IP,局域网测试 } String region = (temp[5].split(":"))[1].replaceAll("\"", ""); region = decodeUnicode(region);// 省份 String country = ""; String area = ""; // String region = ""; String city = ""; String county = ""; String isp = ""; for (int i = 0;i < temp.length;i++) { switch (i) { case 1: country = (temp[i].split(":"))[2].replaceAll("\"", ""); country = decodeUnicode(country);// 国家 break; case 3: area = (temp[i].split(":"))[1].replaceAll("\"", ""); area = decodeUnicode(area);// 地区 break; case 5: region = (temp[i].split(":"))[1].replaceAll("\"", ""); region = decodeUnicode(region);// 省份 break; case 7: city = (temp[i].split(":"))[1].replaceAll("\"", ""); city = decodeUnicode(city);// 市区 break; case 9: county = (temp[i].split(":"))[1].replaceAll("\"", ""); county = decodeUnicode(county);// 地区 break; case 11: isp = (temp[i].split(":"))[1].replaceAll("\"", ""); isp = decodeUnicode(isp); // ISP公司 break; } } Address address = new Address(); address.setArea(area); address.setCity(city); address.setCountry(country); address.setCounty(county); address.setIsp(isp); address.setRegion(region); return address; } return null; }
05de0f84-8fd5-46dc-9a1c-e17e8be79e7a
4
public void enterParkedState(int parkingTime, int intendedDuration) throws VehicleException { exitTime = parkingTime + intendedDuration; this.parkingTime = parkingTime; // this.intendedDuration = intendedDuration; if (isParked() == true) { throw new VehicleException("Vehicle is already parked."); } if (isQueued() == true) { throw new VehicleException("Vehicle is queueing"); } if (parkingTime <= 0) { throw new VehicleException("Parking time must be positive."); } if (intendedDuration < Constants.MINIMUM_STAY) { throw new VehicleException( "Vehicle must park longer than minimum time limit."); } // Used for the isParked() method. parked = true; // Defines the vehicles state as parked. vehicleState = "parked"; }
e3fc4f40-4159-40e0-9f6e-6e90e3d044b9
7
public boolean isE(char c) { if ((c >= 'a' && c <= 'z')) { return true; } switch (c) { case '.': return true; case '-': return true; case '/': return true; case '#': return true; case '?': return true; } return false; }
b7e8d959-3dc4-4219-81cf-a1d00df02abe
5
public ProcessState execute(final CommandSender sender, final Command cmd, final String label, final String[] args) { ProcessState state = null; if ( sender instanceof Player ) { final IPlayerExecutor exec = this.playerExec.get(args.length); if ( exec != null ) state = exec.execPlayer((Player) sender, cmd, label, args); } else if ( sender instanceof ConsoleCommandSender ) { final IConsoleExecutor exec = this.consoleExec.get(args.length); if ( exec != null ) state = exec.execConsole((ConsoleCommandSender) sender, cmd, label, args); } if ( state == null ) state = new ProcessState("The ProcessState wasn't sent back or instanciated neither"); return state; }
c84fd711-5933-4e4b-a6a8-02a17b07b485
6
public int[][][] loadLevel(String levelName) { int[][][] level = new int[2][Constants.levelHeight][Constants.levelWidth]; try { Scanner scanner = new Scanner(this.getClass().getResourceAsStream("resources/levels/" + levelName + ".lvl")); while (scanner.hasNext()) { for (int i = 0; i < level[0].length; i++) { for (int j = 0; j < level[0][i].length; j++) { level[0][i][j] = scanner.nextInt(); } } for (int i = 0; i < level[1].length; i++) { for (int j = 0; j < level[1][i].length; j++) { level[1][i][j] = scanner.nextInt(); } } } scanner.close(); } catch (Exception e) { e.printStackTrace(); } return level; }