text
stringlengths
14
410k
label
int32
0
9
public int compareTo(Object o) { @SuppressWarnings("unchecked") Node<K> other = (Node<K>) o; return this.frequency - other.getFrequency(); }
0
@Override public boolean equals(Object object) { if (this == object) { return true; } if (object instanceof Map.Entry) { Map.Entry<?, ?> entry = (Map.Entry<?, ?>) object; return (key == null ? entry.getKey() == null : key.equals(entry .getKey())) && (value == null ? entry.getValue() == null : value .equals(entry.getValue())); } return false; }
9
public void testSet_Field() { MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); test.set(DurationFieldType.years(), 10); assertEquals(10, test.getYears()); test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8); try { test.set(null, 10); fail(); } catch (IllegalArgumentException ex) {} }
1
public void testCharacter() { System.out.println("\n*** testCharacter ***"); final Character[] testChars = {'a', 'A', '\t', ' '}; for (final Character character : testChars) { final boolean testResult = DefaultCycObject.isCycLObject(character); assertTrue("char test " + character, testResult); } for (final Character character : testChars) { final String cyclified = DefaultCycObject.cyclify(character); final boolean testResult = cyclified.startsWith("#\\"); assertTrue("char cyclify test " + character, testResult); } for (final Character character : testChars) { final String cyclified = DefaultCycObject.cyclifyWithEscapeChars(character, false); final boolean testResult = cyclified.startsWith("#\\\\"); assertTrue("char escaped cyclify test " + character, testResult); } System.out.println("*** testCharacter OK ***"); }
3
@Override public void mouseMoved(MouseEvent e) { }
0
public int removeDuplicates(int[] A) { if(A ==null || A.length ==0) return 0; else{ int length = A.length-1; int index =1; for(int i=0;i< length;i++){ if(A[i] != A[i+1]){ A[index++] = A[i+1]; } } return index; } }
4
public void keyReleased(KeyEvent e) { if ( e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_DOWN || e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_RIGHT ) { switch(e.getKeyCode()) { case KeyEvent.VK_LEFT: case KeyEvent.VK_RIGHT: _keyDeltaX = 0; break; case KeyEvent.VK_UP: case KeyEvent.VK_DOWN: _keyDeltaY = 0; break; } dropAllGraphicsUndoable(); } }
8
public boolean mainMenu() { System.out.println("City Connection"); System.out.println("Choose and option by typing the" + " corresponding number and pressing enter:"); System.out.println("1. Show Connecting Cities"); System.out.println("2. Get Shortest Path"); System.out.println("3. Exit"); int choice = scr.nextInt(); switch(choice) { case 1: this.showConnections(); break; case 2: this.getShortestPath(); break; case 3: System.out.println("Goodbye!!!"); return false; default: System.out.println("Invalid input restarting."); return true; } return true; }
3
public void dropCheck(int stateChange) { if(stateChange == ItemEvent.SELECTED){ shadow = true; }else{ shadow = false; } if(selectedDrawings != null){ for(int i=0;i<selectedDrawings.size();i++){ selectedDrawings.elementAt(i).setShadow(shadow); } } }
3
@FXML private void handleBtnRegisterAction(ActionEvent event) { if (mode == Mode.MODIFY) { String sql = "update Suppliers set name = ? where suppliercode = ?;"; getPersist().executeUpdate(sql, txtName.getText(), selected.getSuppliercode()); mode = Mode.ADD; } else { getPersist().executeUpdate("insert into Suppliers (name) values (?);", txtName.getText()); } updateTable(); txtName.clear(); txtName.requestFocus(); MainController.showMessageBar("登録しました"); }
1
public ReportWindow(String reportText){ new JFrame(); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); setSize(500,250); setResizable(false); setLocation(screenSize.width/2-getWidth()/2, screenSize.height/2-getHeight()/2); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); setResizable(true); initTextArea(reportText); initButton(); addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { super.componentResized(e); scrollPane.setBounds(10, 10, getWidth() - 25, getHeight() - 90); buttonOK.setLocation(getWidth()/2-buttonOK.getWidth()/2, getHeight()-65); } }); }
0
static void draw_sprites3(osd_bitmap bitmap, int c, int d) { int offs, mx, my, color, tile, i, bank, fx, fy; for (offs = 0x0000; offs < 0x800; offs += 0x40) { mx = spriteram.READ_WORD(offs + c); my = mx >> 8; mx = mx & 0xff; /* if ((my & 0x80) != 0) mx=(mx+0x100)&0x1ff; my=(my+0x100)&0x1ff; mx-=0x100; my-=0x100; my=0x200 - my; my-=0x200; */ for (i = 0; i < 0x40; i += 2) { tile = spriteram.READ_WORD(offs + d + i); color = 0; fy = tile & 0x1000; fx = 0; tile &= 0xfff; if (tile < 0x400) { bank = 0; } else if (tile < 0x800) { bank = 1; } else if (tile < 0xc00) { bank = 2; } else { bank = 3; } //check the exclusions if (tile != 0 && tile != 0x3000 && tile != 0x26) { drawgfx(bitmap, Machine.gfx[bank], tile & 0x3ff, color, fx, fy, mx, my, null, TRANSPARENCY_PEN, 0); } my += 8; if (my > 0x100) { my -= 0x200; } } } }
9
public String listarCuenta() throws SQLException { String Recorrertbl = ""; String colorEstado = ""; String iconoEstado = ""; String nomFuncion = ""; ResultSet listCuentaPro = Cuen.consultarCuentaPro(); ResultSet listCuentaest = Cuen.consultarCuentaEst(); try { while (listCuentaPro.next()) { Recorrertbl += "<tr>"; Recorrertbl += "<td Style='display:none'><center>" + listCuentaPro.getString("cu.Id_cuenta").toString().trim() + "</center></td>"; Recorrertbl += "<td><center>" + listCuentaPro.getString("Empleado").toString().trim() + "</center></td>"; Recorrertbl += "<td><center>" + listCuentaPro.getString("es.Identificacion").toString().trim() + "</center></td>"; Recorrertbl += "<td><center>" + listCuentaPro.getString("cu.Login").toString().trim() + "</center></td>"; Recorrertbl += "<td><center><button class='btn btn-primary glyphicon glyphicon-pencil' data-toggle='modal' data-target='#myModal' onclick='mapear.Cuenta(" + '\"' + listCuentaPro.getString("cu.Id_cuenta").toString().trim() + '\"' + "," + '\"' + listCuentaPro.getString("Empleado").toString().trim() + '\"' + "," + '\"' + listCuentaPro.getString("cu.Login").toString().trim() + '\"' + ")' ></button></center></td>"; if (listCuentaPro.getString("cu.Estado").toString().trim().equals("Habilitado")) { colorEstado = "success"; iconoEstado = "ok-circle"; nomFuncion = "Estado_habilitado(" + listCuentaPro.getString("cu.Id_cuenta").toString().trim() + ")"; } else if (listCuentaPro.getString("cu.Estado").toString().trim().equals("Inhabilitado")) { colorEstado = "danger"; iconoEstado = "remove-circle"; nomFuncion = "Estado_inhabilitado(" + listCuentaPro.getString("cu.Id_cuenta").toString().trim() + ")"; } Recorrertbl += "<td><center><div id='cambio_est'><button class='btn btn-" + colorEstado + " glyphicon glyphicon-" + iconoEstado + "' onclick =" + nomFuncion + "></button></center></div></center></td>"; Recorrertbl += "</tr>"; } while (listCuentaest.next()) { Recorrertbl += "<tr>"; Recorrertbl += "<td Style='display:none'><center>" + listCuentaest.getString("cu.Id_cuenta").toString().trim() + "</center></td>"; Recorrertbl += "<td><center>" + listCuentaest.getString("Estudiante").toString().trim() + "</center></td>"; Recorrertbl += "<td><center>" + listCuentaest.getString("es.Identificacion").toString().trim() + "</center></td>"; Recorrertbl += "<td><center>" + listCuentaest.getString("cu.Login").toString().trim() + "</center></td>"; Recorrertbl += "<td><center><button class='btn btn-primary glyphicon glyphicon-pencil' data-toggle='modal' data-target='#myModal' onclick='mapear.Cuenta(" + '\"' + listCuentaest.getString("cu.Id_cuenta").toString().trim() + '\"' + "," + '\"' + listCuentaest.getString("Estudiante").toString().trim() + '\"' + "," + '\"' + listCuentaest.getString("cu.Login").toString().trim() + '\"' + ")' ></button></center></td>"; if (listCuentaest.getString("cu.Estado").toString().trim().equals("Habilitado")) { colorEstado = "success"; iconoEstado = "ok-circle"; nomFuncion = "Estado_habilitado(" + listCuentaest.getString("cu.Id_cuenta").toString().trim() + ")"; } else if (listCuentaest.getString("cu.Estado").toString().trim().equals("Inhabilitado")) { colorEstado = "danger"; iconoEstado = "remove-circle"; nomFuncion = "Estado_inhabilitado(" + listCuentaest.getString("cu.Id_cuenta").toString().trim() + ")"; } Recorrertbl += "<td><center><div id='cambio_est'><button class='btn btn-" + colorEstado + " glyphicon glyphicon-" + iconoEstado + "' onclick =" + nomFuncion + "></button></center></div></center></td>"; Recorrertbl += "</tr>"; } } catch (Exception e) { Recorrertbl = "error" + e.getMessage(); } return Recorrertbl; }
7
@Override public void actionPerformed(ActionEvent e) { if (Start.getUserLogStatus()) { statusLbl.setText("You have logged in as " + user.getName()); } if (user.getName() != null && user.getName().length() > 0 && !Start.getUserLogStatus()) { Utils.changeUserLastLogDate(user); Start.setUserLoggedIn(); openMainMenuFrame(); return; } if (user.getName() != null && user.getName().length() > 0 && Start.getUserLogStatus()) { Utils.changeUserLastLogDate(user); openMainMenuFrame(); return; } else { statusLbl.setText("First of all, select user name and then log-in"); } System.out.println(user.getName()); }
7
public void interesting() { if (!this.interesting) { logger.trace("Telling " + this + " we're interested."); this.send(Message.InterestedMessage.craft()); this.interesting = true; } }
1
public Value execute(Interpreter machine) throws MyException { if (_operands != null && _operands.size() == 1) { if (_operands.get(0).isNumeral()) { double a = _operands.get(0).execute(machine).doubleValue(); if (a >= 0.0) { result = Math.sqrt(a); return new Number(result); } else { throw new MyException("Error: variable" + "isn't a Numeral"); } } else if (_operands.get(0).isSymbol()) { Symbol a = (Symbol) _operands.get(0); Value v = a.execute(machine); if (v.isNumber()) { result = Math.sqrt(v.doubleValue()); if (result >= 0.0) { return new Number(result); } else { throw new MyException("Error: variable" + "isn't a Numeral"); } } else { throw new MyException("Error: variable" + "isn't a Numeral"); } } else { throw new MyException("Error: operands" + "not numeral or symbol"); } } else { throw new MyException("Error: incorrect args squareroot"); } }
7
public boolean addBuddies(String user, String friend){ PreparedStatement st; Integer rs; String query; if(!checkFriendship(user,friend)){ query="INSERT INTO friends(friend1,friend2) VALUES('"+user+"','"+friend+"')"; try { st = conn.prepareStatement(query); rs = st.executeUpdate(); st.close(); } catch (SQLException e) { return false; } } return true; }
2
public String getColumnName(int spaltenNr) { switch (spaltenNr) { case 0: return "ID-Nr"; case 1: return "Username"; case 2: return "Rolle"; case 3: return "Password"; default: return null; } }
4
public void setPosition(double x, double y) { if (this.minX != 0.0 && this.minY != 0.0 && this.maxX != 0.0 && this.maxY != 0.0) { if(x < this.minX) { x = this.minX; } else if(x > this.maxX) { x = this.maxX; } if(y < this.minY) { y = this.minY; } else if(y > this.maxY) { y = this.maxY; } } this.x = x; this.y = y; }
8
@SuppressWarnings("unused") public Image scale(Image img) { // Offset the image by one pixel so there's a border around it. // This lets us avoid having to check that A-I are in range of the image before samping them sourceGraphics.drawImage(img, 1, 1, null); int line = width + 2; for (int y = 0; y < height; y++) { // Two lines of target pixel pointers int tp0 = y * width * 4 - 1; int tp1 = tp0 + width * 2; // Three lines of source pixel pointers int sp0 = (y) * line; int sp1 = (y + 1) * line; int sp2 = (y + 2) * line; // Fill the initial A-I values int A = sourcePixels[sp0]; int B = sourcePixels[++sp0]; int C = sourcePixels[++sp0]; int D = sourcePixels[sp1]; int E = sourcePixels[++sp1]; int F = sourcePixels[++sp1]; int G = sourcePixels[sp2]; int H = sourcePixels[++sp2]; int I = sourcePixels[++sp2]; for (int x = 0; x < width; x++) { if (B != H && D != F) { targetPixels[++tp0] = D == B ? D : E; targetPixels[++tp0] = B == F ? F : E; targetPixels[++tp1] = D == H ? D : E; targetPixels[++tp1] = H == F ? F : E; } else { targetPixels[++tp0] = E; targetPixels[++tp0] = E; targetPixels[++tp1] = E; targetPixels[++tp1] = E; } // Scroll A-I left A = B; B = C; D = E; E = F; G = H; H = I; // Resample rightmost edge C = sourcePixels[++sp0]; F = sourcePixels[++sp1]; I = sourcePixels[++sp2]; } } return targetImage; }
8
public List<Location> getAllCompatibleActors(Animal actor) { List<Location> allactors = new LinkedList<Location>(); for(int row = 0; row < depth; row++) { for(int col = 0; col < width; col++) { if(getObjectAt(row, col)!=null) { if(actor.getClass().equals(getObjectAt(row, col).getClass()) && actor.getSex()!=getObjectAt(row, col).getSex()) { allactors.add(new Location(row, col)); } } } } if(!allactors.isEmpty()) { return allactors; } else { return null; } }
6
public static void main(String[] args) { System.out.println(0.12345); System.out.println(1.2345E-1); System.out.println(1.2345e-1); }
0
public static List<Mensalidade> getListaMensalidade(String nome, Date data){ List<Mensalidade> lista = new ArrayList(); Connection conn = Conexao.getConexao(); PreparedStatement stmt = null; ResultSet rs = null; Mensalidade mens = null; try { String sql = "Select M.Codigo, M.Cliente, M.Descricao, M.DataPagto, M.ValorPago, M.DataRef from MensalidadesPagas M, Clientes C" + " where C.Codigo = M.Cliente"; if (nome != null) { sql += " and C.Nome like '%" + nome + "%'"; } if (data != null) { sql += " and M.DataRef = ?"; } sql += " Order by C.Nome"; stmt = conn.prepareStatement(sql); if (data != null) { stmt.setDate(1, new java.sql.Date(data.getTime())); } rs = stmt.executeQuery(); while (rs.next()) { mens = new Mensalidade(); mens.setCodigo(rs.getInt("Codigo")); mens.setCliente(ClienteDAO.getCliente(rs.getInt("Cliente"))); mens.setDescricao(rs.getString("Descricao")); mens.setDatapagto(rs.getDate("DataPagto")); mens.setValorpago(rs.getDouble("ValorPago")); mens.setDataRef(rs.getDate("DataRef")); lista.add(mens); } } catch (SQLException e) { System.out.println("ERRO: " + e.getMessage()); } finally { if(stmt != null) { try { stmt.close(); } catch (SQLException e) { System.out.println("ERRO: " + e.getMessage()); } } if(conn != null) { try { conn.close(); } catch (SQLException e) { System.out.println("ERRO: " + e.getMessage()); } } } return lista; }
9
public GeneralRegexNameExtractor(Params params) throws Exception { this.params = params; if (params.name == null) throw new Exception("Name muss definiert werden"); if (params.patterns == null || params.patterns.length == 0) throw new Exception("Es müssen Regex zum Extrahieren von Namen definiert werden"); }
3
public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); if (command.equals("Exit")) { view.dispose(); System.exit(0); } else if (command.equals("Pause/Continue")) { model.setPause(! model.getPause()); } else if (command.equals("Flip Vertically")) { view.setFlipVertical(! view.getFlipVertical()); } else if (command.equals("Reset")){ System.out.println("RESET"); model.resetLevel(); } }
4
public static void reset(Graphics g) throws IncorrectUsageException { Throwable t = new Throwable(); StackTraceElement[] elements = t.getStackTrace(); String className = elements[1].getClassName(); String methodName = elements[1].getMethodName(); //@formatter:off if (!className.equals("com.blp.gfxlib.Game") || !methodName.equals("draw")) throw new IncorrectUsageException("method reset(Graphics) called in " + className + " is used incorrectly"); //@formatter:on Gfx.g = g; g2d = (Graphics2D) g; }
2
public void actionPerformed(ActionEvent evt) { if (evt.getSource().equals(MENU_PRINCIPAL)) { ModelePanneau.getInstance().setChoix(MENU_PRINCIPAL); } if (evt.getSource() instanceof JButton) { JButton bouton = (JButton) evt.getSource() ; String texte = bouton.getText(); if (texte.equals("Valider")) { demarrerMatch(); try { traitementJeu(); } catch (WrongColorException e) { System.err.println("Erreur de mauvaise couleur dans les comboBox " + e); } } else if (texte.equals("Sauvegarder")) { Persistance.getInstance().sauvegarderPartie(); } else if (texte.equals("Reprendre")) { Persistance.getInstance().reprendrePartie(); } } }
6
@Override public int compareTo(OpenHouse o) { double dist = getSuccess() - o.getSuccess(); final SummoningTask summoningTask = script.summoningTask; if (summoningTask != null && summoningTask.branch()) { // Need to recharge pick house with obelisk if (hasObelisk) { if (!o.hasObelisk) { return 1; } } else if (o.hasObelisk) { return -1; } } if (dist == 0) { return 0; } else { return dist < 0 ? -1 : 1; } }
7
public static void About() { GUI.log("\nCorlanthia is a text adventure game\n\n" + "v" + Game.version + "\n" + "Type 'exit' to go back to the main menu"); }
0
public asset(String id){ super(id); }
0
private void pilotJListSelectionChanged(ListSelectionEvent listSelectionEvent) { if(pilotJList.getSelectedIndex() >= 0){ try{ Pilot thePilot = (Pilot)pilotJList.getSelectedValue(); currentData.setCurrentPilot(thePilot); firstNameField.setText((thePilot.getFirstName())); firstNameField.setBackground(Color.GREEN); firstNameField.setHorizontalAlignment(JTextField.RIGHT); lastNameField.setText((thePilot.getLastName())); lastNameField.setBackground(Color.GREEN); lastNameField.setHorizontalAlignment(JTextField.RIGHT); middleNameField.setText((thePilot.getMiddleName())); middleNameField.setBackground(Color.GREEN); middleNameField.setHorizontalAlignment(JTextField.RIGHT); String emergencyContact = thePilot.getEmergencyContact(); String emergencyContactName; String emergencyContactPhone; int p = emergencyContact.indexOf('%'); if (p >= 0) { emergencyContactName = emergencyContact.substring(0, p); emergencyContactPhone = emergencyContact.substring(p + 1); } else { emergencyContactName = ""; emergencyContactPhone = ""; } emergencyContactNameField.setText(emergencyContactName); emergencyContactNameField.setBackground(Color.GREEN); emergencyContactNameField.setHorizontalAlignment(JTextField.RIGHT); emergencyContactPhoneField.setText(emergencyContactPhone); emergencyContactPhoneField.setBackground(Color.GREEN); emergencyContactPhoneField.setHorizontalAlignment(JTextField.RIGHT); /*String medInfo = thePilot.getEmergencyContact(); String medInfoName; String medInfoPhone; int t = medInfo.indexOf('%'); if (t >= 0) { medInfoName = emergencyContact.substring(0, t); medInfoPhone = emergencyContact.substring(t + 1); } else { medInfoName = ""; medInfoPhone = ""; } medInfoNameField.setText(medInfoName); medInfoNameField.setBackground(Color.GREEN); medInfoPhoneField.setText(medInfoPhone); medInfoPhoneField.setBackground(Color.GREEN);*/ flightWeightField.setText(String.valueOf((thePilot.getWeight() * UnitConversionRate.convertWeightUnitIndexToFactor(flightWeightUnitsID)))); flightWeightField.setBackground(Color.GREEN); flightWeightField.setHorizontalAlignment(JTextField.RIGHT); if(thePilot.getCapability().equals("Student")) { studentLabel.setEnabled(true); proficientLabel.setEnabled(false); advancedLabel.setEnabled(false); } if(thePilot.getCapability().equals("Proficient")) { studentLabel.setEnabled(false); proficientLabel.setEnabled(true); advancedLabel.setEnabled(false); } if(thePilot.getCapability().equals("Advanced")) { studentLabel.setEnabled(false); proficientLabel.setEnabled(false); advancedLabel.setEnabled(true); } if(thePilot.getPreference().equals("Mild")) { mildLabel.setEnabled(true); nominalLabel.setEnabled(false); performanceLabel.setEnabled(false); } if(thePilot.getPreference().equals("Nominal")) { mildLabel.setEnabled(false); nominalLabel.setEnabled(true); performanceLabel.setEnabled(false); } if(thePilot.getPreference().equals("Performance")) { mildLabel.setEnabled(false); nominalLabel.setEnabled(false); performanceLabel.setEnabled(true); } optionalInfoField.setText((thePilot.getOptionalInfo())); } catch(Exception e) { //TODO respond to error } editButton.setEnabled(true); } }
9
public void fill(int i, int x, int y) { int orig = texture.getRGB(x, y); if(x < texture.getWidth() && y < texture.getHeight() && x >= 0 && y >= 0) { this.spread(i, orig, x, y); } this.repaint(); }
4
public static boolean isAlphaSpace(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if ((Character.isLetter(str.charAt(i)) == false) && (str.charAt(i) != ' ')) { return false; } } return true; }
4
public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) { text.add("\n"); AnnotationVisitor tav = super.visitAnnotation(desc, visible); if (cv != null) { ((TraceAnnotationVisitor) tav).av = cv.visitAnnotation(desc, visible); } return tav; }
1
public static void main(String[] args) { MainController coordinator = new MainController(); //set default values for the application boolean testRun = false; int timeBetweenTraces = 3; //check for existing args for(String arg : args){ //run with testdata ? if(arg.equals("testrun")){ testRun = true; } //look for a number for setting timeBetweenTraces else{ try{ int tmpTime = Integer.parseInt(arg); if(tmpTime > 0){ timeBetweenTraces = tmpTime; } } catch(NumberFormatException e){ //value was no number } } } //start the core of the analyzer coordinator.run(testRun, timeBetweenTraces); }
4
public static <E> int treeHeight(BinaryTreeNode<E> node) { if(node == null) { return 0; } int leftHeight = treeHeight(node.left); if(leftHeight == -1) { return -1; } int rightHeight = treeHeight(node.right); if(rightHeight == -1) { return -1; } if(leftHeight-rightHeight>1 || leftHeight-rightHeight<-1) { return -1; } else { return (leftHeight > rightHeight) ? (leftHeight + 1) : (rightHeight + 1); } }
6
@Override public String toString() { return String.format("%s[%s]", getClass().getSimpleName(), (getValue() == null) ? "null" : getValue().toString()); }
1
public void disableTicket(Ticket ticket) { if ( !existsTicket(ticket)) { throw new IllegalArgumentException("Ticket from another seance cannot be disabled"); } if (ticket.getStatus() != TicketStatus.ENABLE) { throw new IllegalArgumentException("Cannot disable ticket which is not ENABLED"); } ticket.changeStatus(TicketStatus.NOT_FOR_SALE); }
2
public Boolean cadastarNovos(List<Material> materiais) { Boolean sucesso = false; Connection connection = conexao.getConnection(); try { String valorDoComandoUm = comandos.get("cadastarNovos" + 1); String valorDoComandoDois = comandos.get("cadastarNovos" + 2); StringBuilder query = new StringBuilder(valorDoComandoUm); for (int i = 0; i < materiais.size(); i++) { query.append("\n").append(valorDoComandoDois); } connection.setAutoCommit(false); PreparedStatement preparedStatement = connection.prepareStatement(query.toString()); query.delete(0, query.length()); int indice = 1; DadoMaterial dadoMaterial = materiais.get(0).getDadoMaterial(); setString(indice++, dadoMaterial.getTitulo(), preparedStatement); setString(indice++, dadoMaterial.getDescricao(), preparedStatement); Edicao edicao = dadoMaterial.getEdicao(); setInt(indice++, edicao.getNumero(), preparedStatement); AnoPublicacao anoPublicacao = dadoMaterial.getAnoPublicacao(); setInt(indice++, anoPublicacao.getAno(), preparedStatement); Autor autor = dadoMaterial.getAutor(); setString(indice++, autor.getNome(), preparedStatement); Editora editora = dadoMaterial.getEditora(); setInt(indice++, editora.getCodigo(), preparedStatement); setString(indice++, editora.getNome(), preparedStatement); Categoria categoria = dadoMaterial.getCategoria(); setInt(indice++, categoria.getCodigo(), preparedStatement); setString(indice++, categoria.getNome(), preparedStatement); Publico publico = dadoMaterial.getPublico(); setInt(indice++, publico.getCodigo(), preparedStatement); setString(indice++, publico.getNome(), preparedStatement); Formato formato; for (Material material : materiais) { formato = material.getFormato(); setInt(indice++, formato.getCodigo(), preparedStatement); setString(indice++, formato.getNome(), preparedStatement); setString(indice++, material.getInformacao(), preparedStatement); } preparedStatement.execute(); connection.commit(); connection.setAutoCommit(true); sucesso = true; } catch (SQLException ex) { try { connection.rollback(); } catch (SQLException ex1) { } throw new RuntimeException(ex.getMessage()); } catch (NullPointerException ex) { throw new RuntimeException(ex.getMessage()); } catch (Exception ex) { throw new RuntimeException(ex.getMessage()); } finally { conexao.fecharConnection(); } return sucesso; }
6
public CryptoModuleInfoType getCryptoModuleInfo() { return cryptoModuleInfo; }
0
public Dodgeball(Plugin plug, Location minPoint, Location maxPoint, String name, DodgeballTeam team1, DodgeballTeam team2) { if(minPoint.equals(maxPoint)) { throw new IllegalArgumentException("Arena size is zero!"); } this.area = new CubeSerializable(minPoint, maxPoint); this.name = name; this.mm = plug.getMinigameManager(); mm.addMinigame(this); World w = minPoint.getWorld(); double minX1 = minPoint.getX() + .5D;//Block center = block position + 0.5 double minY1 = minPoint.getY() + .5D; double minZ1 = minPoint.getZ() + .5D; double maxX1 = (minX1 + maxPoint.getX() + .5D) / 2; double maxY1 = maxPoint.getY() + .5D; double maxZ1 = maxPoint.getZ() + .5D; TEAM_1_AREA = new CubeSerializable(new LocationSerializable(w, minX1, minY1, minZ1), new LocationSerializable(w, maxX1, maxY1, maxZ1)); double minX2 = maxX1; double minY2 = minY1; double minZ2 = minZ1; double maxX2 = maxPoint.getX() + .5D; double maxY2 = maxY1; double maxZ2 = maxZ1; TEAM_2_AREA = new CubeSerializable(new LocationSerializable(w, minX2, minY2, minZ2), new LocationSerializable(w, maxX2, maxY2, maxZ2)); this.TEAM_1 = team1; this.TEAM_2 = team2; TEAM_1_SPAWN_X = minX1 + 1 + 0.5D; TEAM_2_SPAWN_X = maxX2 - 1 + 0.5D; SPECTATE_AREA = new CubeSerializable(new LocationSerializable(minPoint).add(new Vector(0, 5, 0)).getLocation(), maxPoint); this.maxPlayers = (int)Math.abs(((maxPoint.getX() - minPoint.getX()) * (maxPoint.getZ() - minPoint.getZ()) / (8F + 1F / 3F))); }
1
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Email other = (Email) obj; if(!(this.getLocal().equals(other.getLocal()))) return false; else if(!this.getDomain().equals(other.getDomain())) return false; else return true; }
5
private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset, int options ) { // Lots of error checking and exception throwing if( source == null ){ throw new NullPointerException( "Source array was null." ); } // end if if( destination == null ){ throw new NullPointerException( "Destination array was null." ); } // end if if( srcOffset < 0 || srcOffset + 3 >= source.length ){ throw new IllegalArgumentException( String.format( "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) ); } // end if if( destOffset < 0 || destOffset +2 >= destination.length ){ throw new IllegalArgumentException( String.format( "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) ); } // end if byte[] DECODABET = getDecodabet( options ); // Example: Dk== if( source[ srcOffset + 2] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); return 1; } // Example: DkL= else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 ); return 2; } // Example: DkLE else { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6) | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) ); destination[ destOffset ] = (byte)( outBuff >> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); destination[ destOffset + 2 ] = (byte)( outBuff ); return 3; } } // end decodeToBytes
8
public int[][] initializePathTable(Tile current, int area) { Random r = new Random(); r.nextInt(); Tile tile = uncharted.setCoordinates(current, -area, -area); Tile newTile; int[][] pathTable; int[][] unchartedTable = uncharted.getUncharted(); pathTable = new int[area * 2 + 1][area * 2 + 1]; for (int i = 0; i < pathTable.length; i++) { for (int j = 0; j < pathTable[0].length; j++) { newTile = uncharted.setCoordinates(tile, j, i); if (ants.getIlk(newTile) == Ilk.WATER) { pathTable[i][j] = -1; } else if (unchartedTable[newTile.getRow()][newTile.getCol()] == 31) { pathTable[i][j] = -1; } else if (ants.getIlk(newTile) == Ilk.MY_ANT && !eat.antHasJob(newTile)) { pathTable[i][j] = -3; } else { pathTable[i][j] = -2; } } } return pathTable; }
6
private void remSongPLButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_remSongPLButtonActionPerformed //Get selected songs from Current Playlist int[] songs = currentPLList.getSelectedIndices(); //Use indices array to remove from currentList for(int i : songs){ currentList.removeSongFromPlaylist(i); } populatePlaylist(); ///^^^^Need to work on remove from database also. Thinking: get songid ///and search in songs db. Also, will need to search conjoined db once ///implemented. }//GEN-LAST:event_remSongPLButtonActionPerformed
1
public int maxOfMatrix(int row, int col, int N) { int case1=0, case2=0, case3=0, max; if(((col-1) >= 0)&&((row+1)<=N-1)) case1 = maxOfMatrix(row+1, col-1, N); if((row+1)<=N-1) case2 = maxOfMatrix(row+1, col, N); if(((col+1) <= N-1)&&((row+1)<=N-1)) case3 = maxOfMatrix(row+1, col+1, N); if((case1 >= case2)&&(case1 >= case3)) max = case1; else if((case2 >= case1)&&(case2>=case3)) max = case2; else max = case3; return max + matrix[row][col]; }
9
public static List<List<Double>> readData(String option, BufferedReader reader) throws IOException { List<List<Double>> datas = new ArrayList<List<Double>>(); System.out.println(option); String str = ""; while (!(str = reader.readLine()).equals("")) { StringTokenizer tokenizer = new StringTokenizer(str); ArrayList<Double> s = new ArrayList<Double>(); while (tokenizer.hasMoreTokens()) { s.add(Double.valueOf(tokenizer.nextToken())); } datas.add(s); } return datas; }
2
@Override public FactionChangeEvent[] findAbilityChangeEvents(Ability key) { if(key==null) return null; // Direct ability ID's if(abilChangeCache.containsKey(key.ID().toUpperCase())) return abilChangeCache.get(key.ID().toUpperCase()); if(changes.containsKey(key.ID().toUpperCase())) { abilChangeCache.put(key.ID().toUpperCase(), changes.get(key.ID().toUpperCase())); return abilChangeCache.get(key.ID().toUpperCase()); } // By TYPE or FLAGS FactionChangeEvent[] Cs =null; final Vector<FactionChangeEvent> events=new Vector<FactionChangeEvent>(); for (final Enumeration<FactionChangeEvent[]> e=changes.elements();e.hasMoreElements();) { Cs=e.nextElement(); for(final FactionChangeEvent C : Cs) { if((key.classificationCode()&Ability.ALL_ACODES)==C.IDclassFilter()) events.addElement(C); else if((key.classificationCode()&Ability.ALL_DOMAINS)==C.IDdomainFilter()) events.addElement(C); else if((C.IDflagFilter()>0)&&(CMath.bset(key.flags(),C.IDflagFilter()))) events.addElement(C); } } final FactionChangeEvent[] evs = events.toArray(new FactionChangeEvent[0]); abilChangeCache.put(key.ID().toUpperCase(), evs); return evs; }
9
private boolean parseExits(Document doc) { NodeList nodes = doc.getElementsByTagName(XmlTag.EDGE_SECTION.toString()); NodeList exits = ((Element)nodes.item(0)).getElementsByTagName(XmlTag.EDGE.toString()); for(int exit_num = 0; exit_num < exits.getLength(); exit_num++) { Item key = null; int x1=-1, y1=-1, x2=-1, y2=-1; boolean crossable = false; String dir1="", dir2=""; Element exit = (Element) exits.item(exit_num); NodeList tiles = exit.getElementsByTagName(XmlTag.TILE.toString()); String type = exit.getAttribute(XmlTag.TYPE.toString()); if(type.equalsIgnoreCase(XmlTag.BOUNDRIES.toString())) { if(!parseBoundaries(exit)) return false; } else { //get tile1 Element tile1 = (Element) tiles.item(0); x1 = Integer.parseInt(tile1.getAttribute(XmlTag.X.toString())); y1 = Integer.parseInt(tile1.getAttribute(XmlTag.Y.toString())); dir1 = tile1.getAttribute(XmlTag.DIRECTION.toString()); //get tile2 Element tile2 = (Element) tiles.item(1); x2 = Integer.parseInt(tile2.getAttribute(XmlTag.X.toString())); y2 = Integer.parseInt(tile2.getAttribute(XmlTag.Y.toString())); dir2 = tile2.getAttribute(XmlTag.DIRECTION.toString()); String crossableString = exit.getAttribute(XmlTag.CROSSABLE.toString()); if(crossableString.equalsIgnoreCase("true")) crossable = true; else crossable = false; if(type.equalsIgnoreCase(XmlTag.EXIT.toString())) { String locked = exit.getAttribute(XmlTag.LOCKED.toString()); if(locked.equalsIgnoreCase("true")) { //if so what is the key NodeList items = exit.getElementsByTagName(XmlTag.ITEM.toString()); Element item = (Element) items.item(0); String keyname = item.getAttribute(XmlTag.NAME.toString()); int keyweight = Integer.parseInt(item.getAttribute(XmlTag.WEIGHT.toString())); key = new Item(keyname, keyweight); crossable = false; } else crossable = true; } if(!level.addEdge(level.getTile(x1,y1),level.getTile(x2,y2),dir1, dir2, key, crossable)) return false; } } return true; }
7
public static Digraph rootedOutDAG(int V, int E) { if (E > (long) V * (V - 1) / 2) throw new IllegalArgumentException("Too many edges"); if (E < V - 1) throw new IllegalArgumentException("Too few edges"); Digraph G = new Digraph(V); SET<Edge> set = new SET<Edge>(); // fix a topological order int[] vertices = new int[V]; for (int i = 0; i < V; i++) vertices[i] = i; StdRandom.shuffle(vertices); // one edge pointing from each vertex, other than the root = // vertices[V-1] for (int v = 0; v < V - 1; v++) { int w = StdRandom.uniform(v + 1, V); Edge e = new Edge(v, w); set.add(e); G.addEdge(vertices[w], vertices[v]); } while (G.E() < E) { int v = StdRandom.uniform(V); int w = StdRandom.uniform(V); Edge e = new Edge(v, w); if ((v < w) && !set.contains(e)) { set.add(e); G.addEdge(vertices[w], vertices[v]); } } return G; }
7
private boolean IsSampleValid(double[] sample) { int paras = parameterNames.length; for (int i = 0; i < paras; i++) { if (sample[i] < lowBound[i] || sample[i] > upBound[i]) { return false; } } return true; }
3
public boolean insertaEquipo(int numeroInveInterInfo, int numInvUnam, String descrip, String modelo, String marca, String serie, String familia, String tipo, String prove, String clase, String uso, String nivel, String edoFisico, String area, String institu, String fecha, String responsable) { boolean res = false; Statement statement; ResultSet resultSet; try { Connection con = DriverManager.getConnection(connectString, user, password); statement = con.createStatement(); resultSet = statement.executeQuery("SELECT * from agregaEquipo(" + numeroInveInterInfo + " , " + numInvUnam + "," + "'" + descrip + "','" + modelo + "','" + marca + "','" + serie + "','" + familia + "','" + tipo + "','" + prove + "','" + clase + "','" + uso + "','" + nivel + "','" + edoFisico + "','" + area + "','" + institu + "','" + fecha + "','" + responsable + "');"); while (resultSet.next()) { res = resultSet.getBoolean(1); } } catch (SQLException ex) { System.err.println(ex.getMessage()); } return res; }
2
public void analyzeXPathExpressions(String xpathExpr1, String xpathExpr2){ XPathParser xpathParser = new XPathParser(); Expr transitionExpr1 = xpathParser.parseExpression(xpathExpr1); Expr transitionExpr2 = xpathParser.parseExpression(xpathExpr2); //zeigt an, dass hier kein BPEL-Prozess analysiert wird bpelTest = false; boolean result = handleFirstExpression(transitionExpr1, transitionExpr2); //Ausgabe System.out.println("XPathExpr1: "+transitionExpr1.getText()); System.out.println("XPathExpr2: "+transitionExpr2.getText()); System.out.println(""); if (result){ System.out.println("XPathExpr1 || XPathExpr2 = "+result); System.out.println("Die XPath-Ausdruecke koennen gleichzeitig zutreffen."); }else{ System.out.println("XPathExpr1 || XPathExpr2 = "+result); System.out.println("Die XPath-Ausdruecke koennen nicht gleichzeitig zutreffen."); } }
1
static public void main(String args[]) { double x, y; String prefix = null; OSGB osgb = new OSGB(); if (args.length < 2) { /* * Caister Water Tower */ x = 651409.903; y = 313177.271; } else { if (args.length == 2) { Double d; d = new Double(args[0]); x = d.doubleValue(); d = new Double(args[1]); y = d.doubleValue(); } else { Double d; prefix = args[0]; d = new Double(args[1]); x = d.doubleValue(); d = new Double(args[2]); y = d.doubleValue(); } } DPoint p0 = new DPoint(x, y); if (prefix != null && prefix.length() == 2) { DPoint dp = osgb.GridSquareToOffset(prefix.charAt(0), prefix .charAt(1)); System.out.println("Applying offset [" + dp.getX() + ", " + dp.getY() + "]"); p0.offsetBy(dp); } char[] pfx = osgb.GridToGridSquare(p0); String pfxs = new String(pfx); DPoint p = osgb.GridToLongitudeAndLatitude(p0); double phi, lambda; lambda = (180.0 / Math.PI) * p.getX(); phi = (180.0 / Math.PI) * p.getY(); System.out.println("Grid coordinates (" + p0.getX() + ", " + p0.getY() + ") map to:"); double ls = Math.abs(lambda); double ps = Math.abs(phi); int ld, lm, pd, pm; ld = (int) ls; ls = 60.0 * (ls - ld); lm = (int) ls; ls = 60.0 * (ls - lm); pd = (int) ps; ps = 60.0 * (ps - pd); pm = (int) ps; ps = 60.0 * (ps - pm); System.out.print((lambda < 0.0) ? "West " : "East "); System.out.println(ld + "\u00b0 " + lm + "\' " + ls + "\""); System.out.print((phi < 0.0) ? "South " : "North "); System.out.println(pd + "\u00b0 " + pm + "\' " + ps + "\""); System.out.println("Grid letters are " + pfxs); p = osgb.LatitudeAndLongitudeToGrid(p); System.out.println("Reverse transform:"); System.out.println(" Easting = " + p.getX()); System.out.println(" Northing = " + p.getY()); }
6
public static String convertMoveToServerNotation(Board b, Move m) { String serverNotation = ""; try { // Get the piece's letter notation and add it to the return string serverNotation += convertIntToServerChar(b.board[m.start.rank][m.start.file]); // Get the file notation for the start row serverNotation += fileIntegerToFile.get(m.start.file); serverNotation += convertRowToServerRow(m.start.rank); serverNotation += fileIntegerToFile.get(m.end.file); serverNotation += convertRowToServerRow(m.end.rank); // For promotion stuff int color = MoveHandler.getColorOfPiece(b, m.start); if (Board.isPawnPromotion(b, m, color)) { // Just assume that we want to promote to the queen. // Can tweak later if we feel inclined to do so. if (color == Board.white) { serverNotation += convertIntToServerChar(Board.whiteQueen); } else if (color == Board.black) { serverNotation += convertIntToServerChar(Board.blackQueen); } } } catch (NullPointerException e) { e.printStackTrace(); } return serverNotation; }
4
public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed) throws PacketRejectedException { if (!processed && packet != null && packet instanceof Message) { if (Configuration.switchPostmanMessage) { String target = packet.getTo().getNode(); if (!userManager.isRegisteredUser(target) || target.equalsIgnoreCase(Configuration.userPostman)) { Message message = (Message)packet; try { IMessageHandler handler = MessageHandler.getHandler(MessageType.POSTMAN); if (!handler.validate(message)) { Utils.debug(String.format("Invalid postman message detected, %1$s", message.toXML())); return; } handler.process(message); Utils.debug(String.format("Postman message processed, %1$s", message.toXML())); } catch (Exception ex) { Utils.error(String.format("Fail to process postman message, %1$s, %2$s", ex.getMessage(), message.toXML()), ex); } } } } }
8
public Collection<CollectionAndArtist> extractNames(PageInfo info) { String pageHTML = info.getContent(); if (pageHTML == null) { System.out.println("## ERROR could not download '" + info.getURL() + "'"); return new LinkedList<CollectionAndArtist>(); } // Nur bei Zieldokument anwenden, ansonsten hier aussteigen if (!pageHTML.contains("STAATLICHE GRAPHISCHE SAMMLUNG")) { return new LinkedList<CollectionAndArtist>(); } // Reguläre Ausdrücke zum Finden der Namen Pattern[] patterns = new Pattern[]{ /* // Monogramm A Pattern.compile("<SPAN[^>]+?>([^,]+?)-[^<>]*?</SPAN", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL), // Monogramm B Pattern.compile("<SPAN[^>]+?>([^,]+?)siehe[^<>]*?</SPAN", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL), */ // Normaler Name Pattern.compile("<SPAN[^>]+?>([^,<>]+),([^<>,]+?)-[^<>]*?</SPAN", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL) }; List<CollectionAndArtist> names = new ArrayList<CollectionAndArtist>(); // Fügt jeden Treffer als Name zur aktuellen Seite hinzu for (Pattern p : patterns) { Matcher m = p.matcher(pageHTML); while (m.find()) { String name = null; if (m.groupCount() == 1) { name = m.group(1).trim(); } else if (m.groupCount() == 2) { name = m.group(2).trim() + " " + m.group(1).trim(); } CollectionAndArtist item = new CollectionAndArtist(info.getCollection(), name); item.crawler = CRAWLER_TAG; item.url = info.getURL().toString(); item.collection = "STAATLICHE GRAPHISCHE SAMMLUNG"; if (m.groupCount() == 2) { item.fname = m.group(2); item.lname = m.group(1); } names.add(item); } } return names; }
7
public boolean canPlayMonopoly(int playerIndex) { //Checks status, players turn, has player already played dev card, and if the player has a monopoly card if (generalDevCardPreconditions(playerIndex) && serverModel.getPlayers().get(playerIndex).getOldDevCards().getMonopoly() > 0) { return true; } else { return false; } }
2
boolean SetDictionarySize(int dictionarySize) { if (dictionarySize < 0) return false; if (m_DictionarySize != dictionarySize) { m_DictionarySize = dictionarySize; m_DictionarySizeCheck = Math.max(m_DictionarySize, 1); m_OutWindow.Create(Math.max(m_DictionarySizeCheck, 4096)); } return true; }
2
public void run() { try { String link = "http://xkcd.com/" + Integer.toString(index); File file = new File("XKCD/" + Integer.toString(index) + ".html"); if(file.exists()) return; URL xkcd = new URL(link); BufferedReader reader = new BufferedReader(new InputStreamReader(xkcd.openStream())); PrintWriter writer = new PrintWriter(new FileOutputStream(file)); String str = ""; while((str = reader.readLine()) != null) { writer.write(str + "\n"); writer.flush(); } } catch(Exception ex) {} System.out.println("Saved " + Integer.toString(index)); }
3
public void run() { try { boolean running = true; while (running) { try { String line = null; while ((line = _breader.readLine()) != null) { try { _bot.handleLine(line); } catch (Throwable t) { // Stick the whole stack trace into a String so we can output it nicely. StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.flush(); StringTokenizer tokenizer = new StringTokenizer(sw.toString(), "\r\n"); synchronized (_bot) { _bot.log("### Your implementation of PircBot is faulty and you have"); _bot.log("### allowed an uncaught Exception or Error to propagate in your"); _bot.log("### code. It may be possible for PircBot to continue operating"); _bot.log("### normally. Here is the stack trace that was produced: -"); _bot.log("### "); while (tokenizer.hasMoreTokens()) { _bot.log("### " + tokenizer.nextToken()); } } } } if (line == null) { // The server must have disconnected us. running = false; } } catch (InterruptedIOException iioe) { // This will happen if we haven't received anything from the server for a while. // So we shall send it a ping to check that we are still connected. this.sendRawLine("PING " + (System.currentTimeMillis() / 1000)); // Now we go back to listening for stuff from the server... } } } catch (Exception e) { // Do nothing. } // If we reach this point, then we must have disconnected. try { _socket.close(); } catch (Exception e) { // Just assume the socket was already closed. } if (!_disposed) { _bot.log("*** Disconnected."); _isConnected = false; _bot.onDisconnect(); } }
9
private JPopupMenu createToolMenu() { final JPopupMenu ret = new JPopupMenu(); ImageIcon publicImg = null, protectImg = null, privateImg = null, packageImg = null, upImg = null, downImg = null; ImageIcon addItemImg = null, delItemImg = null; try { addItemImg = new ImageIcon(ImageIO.read(this.getClass() .getResource("images/addItem.png"))); delItemImg = new ImageIcon(ImageIO.read(this.getClass() .getResource("images/delItem.png"))); publicImg = new ImageIcon(ImageIO.read(this.getClass().getResource( "images/public.png"))); protectImg = new ImageIcon(ImageIO.read(this.getClass() .getResource("images/protected.png"))); privateImg = new ImageIcon(ImageIO.read(this.getClass() .getResource("images/private.png"))); packageImg = new ImageIcon(ImageIO.read(this.getClass() .getResource("images/package.png"))); upImg = new ImageIcon(ImageIO.read(this.getClass().getResource( "images/upitem.png"))); downImg = new ImageIcon(ImageIO.read(this.getClass().getResource( "images/downitem.png"))); } catch (Exception ee) { } JButton btnAdd = new JButton(addItemImg); JButton btnDel = new JButton(delItemImg); JButton btnPublic = new JButton(publicImg); JButton btnProtect = new JButton(protectImg); JButton btnPrivate = new JButton(privateImg); JButton btnPackage = new JButton(packageImg); JButton btnUp = new JButton(upImg); JButton btnDown = new JButton(downImg); btnAdd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { MethodTable.this.clearSelection(); attributeModel.addRow("+", "Method" + MethodTable.this.getRowCount()); updateUI(); } }); btnAdd.setContentAreaFilled(false); btnDel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int delIdx; delIdx = MethodTable.this.getSelectedRow(); if (delIdx < 0) return; MethodTable.this.attributeModel.removeRow(delIdx); MethodTable.this.clearSelection(); updateUI(); } }); btnDel.setContentAreaFilled(false); btnPublic.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (MethodTable.this.getSelectedRow() >= 0) { int rowIdx = MethodTable.this.getSelectedRow(); attributeModel.setValueAt("+", rowIdx, 0); } } }); btnPublic.setContentAreaFilled(false); btnProtect.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (MethodTable.this.getSelectedRow() >= 0) { int rowIdx = MethodTable.this.getSelectedRow(); attributeModel.setValueAt("#", rowIdx, 0); } } }); btnProtect.setContentAreaFilled(false); btnPrivate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (MethodTable.this.getSelectedRow() >= 0) { int rowIdx = MethodTable.this.getSelectedRow(); attributeModel.setValueAt("-", rowIdx, 0); } } }); btnPrivate.setContentAreaFilled(false); btnPackage.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (MethodTable.this.getSelectedRow() >= 0) { int rowIdx = MethodTable.this.getSelectedRow(); attributeModel.setValueAt("~", rowIdx, 0); } } }); btnPackage.setContentAreaFilled(false); btnUp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (MethodTable.this.getSelectedRow() > 0) { int rowIdx = MethodTable.this.getSelectedRow(); Object obj0, obj1; obj0 = attributeModel.getValueAt(rowIdx, 0); obj1 = attributeModel.getValueAt(rowIdx, 1); attributeModel.removeRow(rowIdx); attributeModel.insertRow(rowIdx - 1, obj0, obj1); MethodTable.this.setRowSelectionInterval(rowIdx - 1, rowIdx - 1); } updateUI(); } }); btnUp.setContentAreaFilled(false); btnDown.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (MethodTable.this.getSelectedRow() < MethodTable.this .getRowCount() - 1) { int rowIdx = MethodTable.this.getSelectedRow(); if (rowIdx >= 0) { Object obj0, obj1; obj0 = attributeModel.getValueAt(rowIdx, 0); obj1 = attributeModel.getValueAt(rowIdx, 1); attributeModel.removeRow(rowIdx); attributeModel.insertRow(rowIdx + 1, obj0, obj1); MethodTable.this.setRowSelectionInterval(rowIdx + 1, rowIdx + 1); } } updateUI(); } }); btnDown.setContentAreaFilled(false); ret.add(btnAdd); ret.add(btnDel); ret.add(btnPublic); ret.add(btnProtect); ret.add(btnPrivate); ret.add(btnPackage); ret.add(btnUp); ret.add(btnDown); ret.setBackground(null); ret.setVisible(false); return ret; }
9
@Override public void actionPerformed(ActionEvent e) { // Extracts the type of source by typecasting it to JMenuItem. JMenuItem source = (JMenuItem) (e.getSource()); // If menu is selected is the Clear Canvas, // this will clear the canvas and updates status bar. if (source.getText().equals("Clear Canvas")) { this.theCanvas.clearCanvas(); this.theCanvas.repaint(); this.theCanvas.setStatus( " Canvas is now cleared. Ready to draw.. "); } // If menu is selected is New // this will destroy all line objects created and clear canvas. if (source.getText().equals("New")) { this.theCanvas.startANew(); this.theCanvas.repaint(); this.theCanvas.setStatus(" New Canvas created. Ready to draw.."); } // If menu is selected is About Application // this will show a pane describing about the application. if (source.getText().equals("About Application")) { String pt1 = "<html><body width='"; String pt2 = "'><h1>J-PAINTER</h1>" + "<p>Written in Java 1.7 using AWT and SWING API." + " Look And Feel design by Mikle Garin (WebLaF 1.28) " + "http://weblookandfeel.com" + " " + "<br><br>" + "<p>All Rights Reserved 2014 <br>Ryan Gilera" + ""; int width = 175; String s = pt1 + width + pt2; JOptionPane.showMessageDialog(null, s); } }
3
private void buy(String command) { currentCommand = "buy"; String[] commandComps = command.split("\\s+"); if (commandComps.length != 3) { sendToUser("Invalid command"); return; } if (commandComps[0].equalsIgnoreCase("BUY") && commandComps[1].startsWith("<") && commandComps[1].endsWith(">") && commandComps[2].startsWith("<") && commandComps[2].endsWith(">")) { String tickername = commandComps[1].substring(1, commandComps[1].length() - 1).toUpperCase(); int no = 0; try { no = Integer.valueOf(commandComps[2].substring(1, commandComps[2].length() - 1)); } catch (Exception e) { sendToUser("Invalid amount entered. Please enter an integer"); return; } Collection results = Writer.purchaseStock(tickername, user, no, users, stocks); if (results != null) { userStocks = DataReader.getUserStocks(); stocks = DataReader.getStocks(); users = DataReader.getUsers(); // (ArrayList<User>) list.get(2); user = DataReader.getUserByUsername(user.getUsername(), users); this.sendToUser("Purchase successful."); } else { this.sendToUser("Purchase unsuccessful."); } } else { this.sendToUser("Invalid command"); } }
8
public boolean setINodeParams(String resource_id, String inode_id, Map<String,String> paramMap) { boolean isUpdated = false; int count = 0; try { while((!isUpdated) && (count != retryCount)) { if(count > 0) { //System.out.println("iNODEUPDATE RETRY : region=" + region + " agent=" + agent + " plugin" + plugin); Thread.sleep((long)(Math.random() * 1000)); //random wait to prevent sync error } isUpdated = IsetINodeParams(resource_id,inode_id, paramMap); count++; } if((!isUpdated) && (count == retryCount)) { System.out.println("GraphDBEngine : setINodeParams : Failed to add node in " + count + " retrys"); } } catch(Exception ex) { System.out.println("GraphDBEngine : setINodeParams : Error " + ex.toString()); } return isUpdated; }
6
@Override public void putCell(CellState state) { if (this.sealed) { throw new IllegalStateException("sealed memento cannot be altered"); } this.states.add(state); }
1
public void perform(HttpServletRequest request, HttpServletResponse response) throws ServletException { String jsp = null; UserVO user; String username = request.getParameter("username"); request.setAttribute("username", username); String password = request.getParameter("password"); request.setAttribute("password", password); databaseAccess = new DatabaseAccess(); user = databaseAccess.login(username, password); try { if (user == null) { request.setAttribute("message", "Der Benutzername und das Passwort sind falsch."); Logger.getInstance().logWarning(new StringBuffer("Unbekannter Benutzer '"+username+"' hat sich mit Password '"+password+"' versucht anzumelden.")); jsp = "res/jsp/error/errorLogin.jsp"; } else if (user.getRole() == null) { request.setAttribute("message", "Das Passwort ist falsch."); Logger.getInstance().logWarning(new StringBuffer("Der Benutzer '"+user.getUsername()+"' konnte sich mit dem Password '"+password+"' nicht anmelden.")); jsp = "res/jsp/error/errorLogin.jsp"; } else { request.setAttribute("user", user); request.setAttribute("path", Logger.getInstance().getPath()); Logger.getInstance().logInfo(new StringBuffer("Der Benutzer '"+user.getUsername()+"' hat sich erfolgreich angemeldet mit dem Password: "+user.getPassword())); jsp = "res/jsp/secret.jsp"; } forward(request, response, jsp); } catch (IOException e) { e.printStackTrace(); System.out.println("Foward file '"+jsp+"' was not found."); } catch (NullPointerException e) { e.printStackTrace(); } }
4
@Override public List<Order> load(Criteria criteria, GenericLoadQuery loadGeneric, Connection conn) throws DaoQueryException { int pageSize = 50; List paramList = new ArrayList<>(); StringBuilder sb = new StringBuilder(WHERE); String queryStr = new QueryMapper() { @Override public String mapQuery() { Appender.append(DAO_ID_ORDER, DB_ORDER_ID_ORDER, criteria, paramList, sb, AND); Appender.append(DAO_ID_USER, DB_ORDER_ID_USER, criteria, paramList, sb, AND); Appender.append(DAO_ID_TOUR, DB_ORDER_ID_TOUR, criteria, paramList, sb, AND); Appender.append(DAO_ORDER_SEATS, DB_ORDER_SEATS, criteria, paramList, sb, AND); Appender.append(DAO_ORDER_CURR_PRICE, DB_ORDER_CURR_PRICE, criteria, paramList, sb, AND); Appender.append(DAO_ORDER_CURR_DISCOUNT, DB_ORDER_CURR_DISCOUNT, criteria, paramList, sb, AND); Appender.append(DAO_ORDER_USER_DISCOUNT, DB_ORDER_USER_DISCOUNT, criteria, paramList, sb, AND); Appender.append(DAO_ORDER_FINAL_PRICE, DB_ORDER_FINAL_PRICE, criteria, paramList, sb, AND); Appender.append(DAO_ORDER_DATE, DB_ORDER_DATE, criteria, paramList, sb, AND); Appender.append(DAO_ORDER_STATUS, DB_ORDER_STATUS, criteria, paramList, sb, AND); if (paramList.isEmpty()) { return LOAD_QUERY; } else { return sb.insert(0, LOAD_QUERY).toString(); } } }.mapQuery(); try { return loadGeneric.sendQuery(queryStr, paramList.toArray(), pageSize, conn, (ResultSet rs, int rowNum) -> { Order bean = new Order(); bean.setIdOrder(rs.getInt(DB_ORDER_ID_ORDER)); bean.setUser(new User(rs.getInt(DB_ORDER_ID_USER))); bean.setTour(new Tour(rs.getInt(DB_ORDER_ID_TOUR))); bean.setSeats(rs.getInt(DB_ORDER_SEATS)); bean.setCurrentPrice(rs.getFloat(DB_ORDER_CURR_PRICE)); bean.setCurrentDiscount(rs.getInt(DB_ORDER_CURR_DISCOUNT)); bean.setCurrentUserDiscount(rs.getInt(DB_ORDER_USER_DISCOUNT)); bean.setFinalPrice(rs.getFloat(DB_ORDER_FINAL_PRICE)); bean.setOrderDate(rs.getDate(DB_ORDER_DATE)); bean.setStatus(rs.getShort(DB_ORDER_STATUS)); return bean; }); } catch (DaoException ex) { throw new DaoQueryException(ERR_ORDER_LOAD, ex); } }
2
public void testDajSveZaposlenike(){ Zaposlenik zaposlenik = new Zaposlenik(); Osoba osoba = new Osoba(); osoba.setImePrezime("TestZaposl Test"); osoba.setAdresa("adr"); osoba.setDatumRodjenja(new Date()); zaposlenik.setOsoba(osoba); zaposlenik.setDrzavljanstvo("BiH"); zaposlenik.setEmail("zap@etf.ba"); zaposlenik.setIsAdministrator(true); zaposlenik.setObrazovanje("SSS"); zaposlenik.setUsername("zaposl"); zaposlenik.setMobitel("987456123"); zaposlenik.setPassword("passwd"); zaposlenik.setJMB("1234567890789"); zaposlenik.setUloga("Cistacica"); zaposlenik.setTitula("titula"); zaposlenik.setTelefon("123456789"); Session session = HibernateUtil.getSessionFactory().openSession(); Transaction t = session.beginTransaction(); session.save(osoba); session.save(zaposlenik); t.commit(); List<Zaposlenik> zaposlenici = DBManager.dajSveZaposlenike(); Transaction t1 = session.beginTransaction(); session.delete(zaposlenik); session.delete(osoba); t1.commit(); boolean ispit = false; for(Zaposlenik z : zaposlenici){ if(z.getOsoba().getImePrezime().equals(zaposlenik.getOsoba().getImePrezime()) && z.getIsAdministrator() == zaposlenik.getIsAdministrator() && z.getObrazovanje().equals(zaposlenik.getObrazovanje())){ ispit = true; break; } } assertTrue(ispit); }
4
public static void circle( double x, double y, double r ) { if ( filling ) { pane.setColor( fillColor ); if ( ellipseMode == 0 ) pane.fillOval( (int) x, (int) y, (int) r, (int) r ); else pane.fillOval( (int) ( x - r / 2 ), (int) ( y - r / 2 ), (int) r, (int) r ); } if ( stroking ) { Graphics2D g2d = (Graphics2D) pane; g2d.setStroke( new BasicStroke( (float) strokeWeight ) ); pane.setColor( strokeColor ); if ( ellipseMode == 0 ) pane.drawOval( (int) x, (int) y, (int) r, (int) r ); else pane.drawOval( (int) ( x - r / 2 ), (int) ( y - r / 2 ), (int) r, (int) r ); } }
4
protected void calcDIR_Attr() { byte[] bTemp = new byte[1]; for (int i = 11;i < 12; i++) { bTemp[i-11] = bytesOfFAT32Element[i]; } DIR_Attr = byteArrayToInt(bTemp); }
1
private boolean selectInterface(){ for (BAPointsPluginInterface pi : pis){ if(pi!=null){ if(pi.getPointPlugin()!=null){ if(pi.getPointPlugin().getName().equalsIgnoreCase(pp)){ this.pi=pi; return true; } } } } return false; }
4
void formatBuf( int formatPass, HBuffer fmtBuf) throws HdfException { setFormatEntry( formatPass, true, fmtBuf); // BaseBlk: set blkPos, buf pos // We need to use version 2 to support the // messages: link, link info, group info // Write it out if (formatPass == 1) { if (! isVariable) { hdrMsgList.add( new MsgGroupInfo( this, hdfFile)); hdrMsgList.add( new MsgLinkInfo( this, hdfFile)); } if (subGroupList != null) { for (HdfGroup subGroup : subGroupList) { hdrMsgList.add( new MsgLinkit( linkCreationOrder++, subGroup, this, hdfFile)); } } if (subVariableList != null) { for (HdfGroup subGroup : subVariableList) { hdrMsgList.add( new MsgLinkit( linkCreationOrder++, subGroup, this, hdfFile)); } } } // There is some needlessly twisted code // in the HDF5 H5Odbg.c. // It requires that the length of the chunklen field // be "appropriate" for the chunk0Len value, meaning // if 0 <= chunk0Len <= 255 the chunklen field must be // exactly 1 byte, if chunk0Len <= 65535 the field must be // exactly 2 bytes, etc. // // So we cannot always specify that the chunklen field size = 8. // This implies we must know chunk0Len before laying out // chunk0 ... as I said, a bit twisted. // // So we lay out the HdfGroup twice on each formatPass. // The first layout uses a temp HBuffer and just gets // us the chunk0Len. // The second layout is for real and uses fmtBuf. HBuffer tempHbuf = new HBuffer( null, // outChannel 0, // compressionLevel hdfFile); int svIndent = hdfFile.indent; hdfFile.indent += 6; if (hdfFile.bugs >= 5) prtIndent("Start HdfGroup temp layout"); // Find chunk0Len // Use formatPass = 0 so MsgLayout and MsgLinkit don't call addWork. long chunk0Len = 0; chunk0Len = layoutVersion2( 0, chunk0Len, tempHbuf); // formatPass = 0 if (hdfFile.bugs >= 5) prtIndent("End HdfGroup temp layout"); hdfFile.indent = svIndent; // Layout for real layoutVersion2( formatPass, chunk0Len, fmtBuf); noteFormatExit( fmtBuf); // BaseBlk: print debug } // end formatBuf
8
@Override public void mouseReleased(MouseEvent e) { if(e.getSource()==recordBut){ recordBut.setIcon(recordOverIcon); }else if(e.getSource()==playBut){ playBut.setIcon(playOverIcon); }else if(e.getSource()==stopBut){ stopBut.setIcon(stopOverIcon); }else if(e.getSource()==saveBut){ saveBut.setIcon(saveOverIcon); }else if(e.getSource()==openBut){ openBut.setIcon(openOverIcon); }else if(e.getSource()==saveAllBut){ saveAllBut.setIcon(saveOverIcon); } }
6
@Override public void deserialize(Buffer buf) { super.deserialize(buf); paddockId = buf.readInt(); worldX = buf.readShort(); if (worldX < -255 || worldX > 255) throw new RuntimeException("Forbidden value on worldX = " + worldX + ", it doesn't respect the following condition : worldX < -255 || worldX > 255"); worldY = buf.readShort(); if (worldY < -255 || worldY > 255) throw new RuntimeException("Forbidden value on worldY = " + worldY + ", it doesn't respect the following condition : worldY < -255 || worldY > 255"); mapId = buf.readInt(); subAreaId = buf.readShort(); if (subAreaId < 0) throw new RuntimeException("Forbidden value on subAreaId = " + subAreaId + ", it doesn't respect the following condition : subAreaId < 0"); abandonned = buf.readBoolean(); int limit = buf.readUShort(); mountsInformations = new MountInformationsForPaddock[limit]; for (int i = 0; i < limit; i++) { mountsInformations[i] = new MountInformationsForPaddock(); mountsInformations[i].deserialize(buf); } }
6
private int assignValue(T item) { int value; switch((String)item) { case "+": value = 1; break; case "-": value = 1; break; case "/": value = 2; break; case "*": value = 2; break; default: value = 0; } return value; }
4
private static int generateWrapArg(ClassFileWriter cfw, int paramOffset, Class argType) { int size = 1; if (!argType.isPrimitive()) { cfw.add(ByteCode.ALOAD, paramOffset); } else if (argType == Boolean.TYPE) { // wrap boolean values with java.lang.Boolean. cfw.add(ByteCode.NEW, "java/lang/Boolean"); cfw.add(ByteCode.DUP); cfw.add(ByteCode.ILOAD, paramOffset); cfw.addInvoke(ByteCode.INVOKESPECIAL, "java/lang/Boolean", "<init>", "(Z)V"); } else if (argType == Character.TYPE) { // Create a string of length 1 using the character parameter. cfw.add(ByteCode.ILOAD, paramOffset); cfw.addInvoke(ByteCode.INVOKESTATIC, "java/lang/String", "valueOf", "(C)Ljava/lang/String;"); } else { // convert all numeric values to java.lang.Double. cfw.add(ByteCode.NEW, "java/lang/Double"); cfw.add(ByteCode.DUP); String typeName = argType.getName(); switch (typeName.charAt(0)) { case 'b': case 's': case 'i': // load an int value, convert to double. cfw.add(ByteCode.ILOAD, paramOffset); cfw.add(ByteCode.I2D); break; case 'l': // load a long, convert to double. cfw.add(ByteCode.LLOAD, paramOffset); cfw.add(ByteCode.L2D); size = 2; break; case 'f': // load a float, convert to double. cfw.add(ByteCode.FLOAD, paramOffset); cfw.add(ByteCode.F2D); break; case 'd': cfw.add(ByteCode.DLOAD, paramOffset); size = 2; break; } cfw.addInvoke(ByteCode.INVOKESPECIAL, "java/lang/Double", "<init>", "(D)V"); } return size; }
9
protected void getCounterEvidenceDetail(String title) { if (title != null) { selfCounterevidenceResultList = evidence.getSelfCounterevidence(fileName); for (int i = 0; i < selfCounterevidenceResultList.size(); i++) { if (selfCounterevidenceResultList.get(i).getTitle().equals(title)) { if (!(selfCounterevidenceResultList.get(i).getDescription() == null || selfCounterevidenceResultList.get(i).getDescription().equals("null"))) { descriptionJtxa.setText(selfCounterevidenceResultList.get(i).getDescription()); } evidenceCurrent = selfCounterevidenceResultList.get(i); if (evidenceCurrent.getParentClaim() != null) { parentContentJlbl.setText(evidenceCurrent.getParentClaim().getTitle()); // Store parent title parentIdJlbl.setText(evidenceCurrent.getParentClaim().getId()); // Store Parent id } else { parentContentJlbl.setText("None"); } dialogContentJlbl.setText(evidenceCurrent.getDialogState()); playerContentJlbl.setText(evidenceCurrent.getName()); if (evidenceCurrent.getName().equals(userLogin.getName()) && evidenceCurrent.getDialogState().equals("Private")) { editDetailsJbtn.setEnabled(true); deleteActionJbtn.setEnabled(true); } else { editDetailsJbtn.setEnabled(false); deleteActionJbtn.setEnabled(false); } break; } } } }
8
public double[] NewtonIterate(double i, double j, int mode) { int n = 0; Complex z = new Complex(i, j); Complex old = new Complex(i, j); z = Newt(z, i, j, mode); double hue = 0; double w = 0; while (n < depth && distance(old, z) > rootBoundry) { old = z; z = Newt(z, i, j, mode); if (mandelbrotAddition) z = z.add(new Complex(i / 2, j / 2)); n++; // normal smoothing w = 1.0 / z.sub(old).abs(); hue += Math.pow(1.05, -w); } double[] vals = new double[4]; if (n != depth) { vals[0] = hue; vals[1] = addRoot(z); } else { vals[0] = n; vals[1] = 0; } vals[2] = z.re; vals[3] = z.im; return vals; }
4
public void setCurColor(CPColor color) { if (!curColor.isEqual(color)) { artwork.setForegroundColor(color.getRgb()); curColor.copyFrom(color); for (Object l : colorListeners) { ((ICPColorListener) l).newColor(color); } } }
2
public final long getTime() { if(_onlineModus) { return System.currentTimeMillis(); } if(_time == -1) { long waitingTime = 0, startTime = System.currentTimeMillis(); long sleepTime = 10; while(waitingTime < CommunicationConstant.MAX_WAITING_TIME_FOR_SYNC_RESPONCE) { try { synchronized(_timeNotification) { _timeNotification.wait(sleepTime); if(sleepTime < 1000) sleepTime *= 2; } if(_time != -1) { break; } waitingTime = System.currentTimeMillis() - startTime; } catch(InterruptedException e) { e.printStackTrace(); break; } } } if(_time == -1) { throw new IllegalStateException("Die Zeit kann nicht bestimmt werden."); } return _time; }
7
public boolean unpublishCoverage(String workspace, String storename, String layerName) { try { final String fqLayerName; // this null check is here only for backward compatibility. // workspace // shall be mandatory. if (workspace == null) { fqLayerName = layerName; if (LOGGER.isWarnEnabled()) { LOGGER.warn("Null workspace while configuring layer : " + layerName + " -- This behavior is deprecated."); } } else { fqLayerName = workspace + ":" + layerName; } // delete related layer URL deleteLayerUrl = new URL(restURL + "/rest/layers/" + fqLayerName); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Going to delete " + "/rest/layers/" + fqLayerName); } boolean layerDeleted = HTTPUtils .delete(deleteLayerUrl.toExternalForm(), gsuser, gspass); if (!layerDeleted) { LOGGER.warn("Could not delete layer '" + fqLayerName + "'"); return false; } // delete the coverage URL deleteCovUrl = new URL(restURL + "/rest/workspaces/" + workspace + "/coveragestores/" + storename + "/coverages/" + layerName); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Going to delete " + "/rest/workspaces/" + workspace + "/coveragestores/" + storename + "/coverages/" + layerName); } boolean covDeleted = HTTPUtils.delete(deleteCovUrl.toExternalForm(), gsuser, gspass); if (!covDeleted) { LOGGER.warn("Could not delete coverage " + workspace + ":" + storename + "/" + layerName + ", but layer was deleted."); } else { LOGGER.info("Coverage successfully deleted " + workspace + ":" + storename + "/" + layerName); } return covDeleted; // the covstore is still there: should we delete it? } catch (MalformedURLException ex) { if (LOGGER.isErrorEnabled()) LOGGER.error(ex.getLocalizedMessage(), ex); return false; } }
8
@Override public Class<?> getColumnClass(int sarakeIndeksi) { return tyypit[sarakeIndeksi]; }
1
public static int generate(int[] result, int N) { int res = 0; if (result.length == N) { return 1; } else { for (int i=0; i<result.length; i++) { result[N] = i; if (isConsistent(result, N)) res += generate(result, N+1); } } return res; }
3
private boolean shouldIgnoreLine(String line) { if (fluxStack.empty()) return false; Matcher loopMatcher = loopIdentifier.matcher(line); Matcher ifMatcher = ifIdentifier.matcher(line); Matcher endFluxMatcher = (fluxStack.peek().getEndFluxPattern().matcher(line)); Matcher elseMatcher = elseIdentifier.matcher(line); // Enquanto o último resultado de Loop for falso if (fluxStack.peek().result() == false) { if (loopMatcher.find()) { fluxStack.push(new BlankFlux(0, endloopIdentifier, false)); } if (ifMatcher.find()) { fluxStack.push(new BlankFlux(0, endifIdentifier, false)); } if (elseMatcher.find()) { fluxStack.peek().setResult(!fluxStack.peek().result()); } if (endFluxMatcher.find()) { fluxStack.pop(); } return true; } return false; }
6
private int[][] left() {//all numbers will go left and combine when possible int[][] egrid = clone2DArray(grid); for (int yIndex = 0; yIndex < 4; yIndex++) { for (int xIndex = 3; xIndex > 0; xIndex--) { if (egrid[yIndex][xIndex - 1] == 0) { for (int a = xIndex - 1; a < 3; a++) { egrid[yIndex][a] = egrid[yIndex][a + 1]; } egrid[yIndex][3] = 0; } } for (int xIndex = 0; xIndex < 3; xIndex++) { if (egrid[yIndex][xIndex] == egrid[yIndex][xIndex + 1]) { score += egrid[yIndex][xIndex]; egrid[yIndex][xIndex + 1] += egrid[yIndex][xIndex]; egrid[yIndex][xIndex] = 0; } } for (int xIndex = 3; xIndex > 0; xIndex--) { if (egrid[yIndex][xIndex - 1] == 0) { for (int a = xIndex - 1; a < 3; a++) { egrid[yIndex][a] = egrid[yIndex][a + 1]; } egrid[yIndex][3] = 0; } } } return egrid; }
9
public void deleteElement(String value) { ListElement previous = head; ListElement current = head.next(); if (previous.getValue().equals(value)) { head = head.next(); count--; } else { while (current != tail.next()) { if (current.getValue().equals(value)) { ListElement help = current.next(); previous.connectNext(help); previous = help; current = help.next(); count--; } else { previous = current; current = current.next(); } } } }
3
public static String getNextEmail(BufferedReader br) throws Exception { StringBuffer email = new StringBuffer(1024); String nextLine = br.readLine(); if(nextLine == null) { return nextLine; } if(nextLine != null && nextLine.contains("::new email::")) { nextLine = br.readLine(); } while( nextLine != null && !nextLine.contains("::new email::") ) { email.append(nextLine + "\n"); nextLine = br.readLine(); } return email.toString(); }
5
public void setWaiting(int c){ lblWaiting.setText(String.valueOf(c)); if(c>0){ lblWaiting.setForeground(Color.RED); }else{ lblWaiting.setForeground(Color.GREEN); } }
1
public void divyScore(ScoreTracker score) { if (score.isComplete || !gameOn) { boolean[] owners = new boolean[5]; int max = 1; for (int i = 0; i < score.followers.length; i++) { if (score.followers[i] == max) { owners[i] = true; } else if (score.followers[i] > max) { max = score.followers[i]; for (int j = 0; j < owners.length; j++) { owners[j] = false; } owners[i] = true; } } for (int i = 0; i < owners.length; i++) { if (owners[i]) { addPlayerScore(i, score.score); } } // Not sure if this is a good algorithm } }
8
public void run() { T current; while (!isInterrupted()) { /* select next thread */ current = queue.getNext(); if ((current != null) && (current.isAlive())) { // moved this to after the priority changes to get complete and relevant readings: // /* Print Log */ // reportThreadState(); //Max priority for the first thread in the list to increase likelihood of execution current.setPriority(Thread.MAX_PRIORITY); System.err.println("********* New High Priority: " + current.getName()); /* wait until time slice is over */ schedulerSleep(); //Resetting the priority for the first thread in the list to min, as the scheduler doesn't work when it's not running current.setPriority(Thread.MIN_PRIORITY); /* Print Log */ reportThreadState(); } } }
3
public void propertyChange(PropertyChangeEvent evt) { if(evt.getSource().equals(giocatoriPanel)){ if(evt.getPropertyName().equals("SELEZIONATO")){ attivitaPanel.aggiorna(mioTurno(ultimoAggiornamento, TipoFaseGiocoFamily.F_S_ORARIA), mioTurno(ultimoAggiornamento,TipoFaseGiocoFamily.F_S_ALTERAZIONE_GARA), mioTurno(ultimoAggiornamento, TipoFaseGiocoFamily.F_S_ANTIORARIA), ultimoAggiornamento.getGiocatori()); attivitaPanel.showManoPanel((GiocatoreView)evt.getNewValue()); } } if(evt.getSource().equals(tabellonePanel)){ if(evt.getPropertyName().equals("SELEZIONATO")){ attivitaPanel.aggiorna(mioTurno(ultimoAggiornamento, TipoFaseGiocoFamily.F_S_ORARIA), mioTurno(ultimoAggiornamento,TipoFaseGiocoFamily.F_S_ALTERAZIONE_GARA), mioTurno(ultimoAggiornamento, TipoFaseGiocoFamily.F_S_ANTIORARIA), ultimoAggiornamento.getGiocatori()); attivitaPanel.showScuderiePanel(ultimoAggiornamento.getScuderiaDalColore((Colore)evt.getNewValue())); } } if(evt.getSource().equals(attivitaPanel)){ if(evt.getPropertyName().equals("SCOMMESSA")){ scomessaFatta((Scommessa)evt.getNewValue()); } if(evt.getPropertyName().equals("INIZIO_TRUCCAMENTO")){ attivitaPanel.showSelezionaCarta(ultimoAggiornamento.getMioGiocatore()); } if(evt.getPropertyName().equals("FINE_TRUCCAMENTO")){ cartaGiocata((CartaAzione)evt.getNewValue(), tabellonePanel.getScuderiaSelezionata()); } } }
8
private void removeSoldOutProducts() { Iterator<Product> iterator = products.iterator(); while (iterator.hasNext()) { if (iterator.next().getStock() == 0) iterator.remove(); } }
2
public void setArmor(String armor) { this.armor = armor; if (armor.compareTo("Light") == 0) CharInfo[3] = 0; else if (armor.compareTo("Medium") == 0) CharInfo[3] = 1; else if (armor.compareTo("Heavy") == 0) CharInfo[3] = 2; else if (armor.compareTo("Advanced") == 0) CharInfo[3] = 3; else if (trait.compareTo("Random") == 0) CharInfo[4] = (int) (Math.random()*4); else this.code.setValid(false); }
5
public void run() { int answer = 0; ArrayList<Integer> listOfAbundants= new ArrayList<Integer>(); ArrayList<Integer> listOfSumOfAllAbundants= new ArrayList<Integer>(); //make an arraylist of all abundant numbers between 1 and 28123 inclusive for (int i = 1; i < 28124; i++){ if (MathFunctions.isAbundantNumber(i)){ listOfAbundants.add(i); } } //for all integers in arraylist listOfAbundants, add them to each other and include the sum //in arraylist listOfSumOfAllAbundants if: a. the sum is not already in the list, and //b. if the sum is less than 28124(any number larger than 28123 is defined as the sum of two abundants, //per the problem description) for (int i = 0; i < listOfAbundants.size(); i++){ outerloop: for (int j = 0; j < listOfAbundants.size(); j++){ int sum = listOfAbundants.get(i) + listOfAbundants.get(j); if (sum > 28123){ break outerloop; } if (!listOfSumOfAllAbundants.contains(sum)) { listOfSumOfAllAbundants.add(sum); } } } //for all integers between 1 and 28123 (inclusive), if the number is NOT in the arraylist //listOfSumOfAllAbundants then add it to the answer for (int i = 1; i < 28124; i++){ if (!listOfSumOfAllAbundants.contains(i)){ answer += i; } } this.answer = answer; }
8
public String toString() { String chaine = "this.ensemble_cartes.put(\""+Partie.NOM_CARTE+"\", new Carte(new Tile[][] {{"; int indexCase; Position position; for (int ligne = 0; ligne < this.obtenirHauteur(); ligne++) { for (int colonne = 0; colonne < this.obtenirLargeur(); colonne++) { position = new Position(ligne,colonne); indexCase = position.obtenirColonne()+(this.largeur*(position.obtenirLigne())); chaine += "Tile."+this.cases[0][indexCase].name(); if(indexCase+1!=this.largeur*this.hauteur) chaine+=","; } } chaine += "},{"; for (int ligne = 0; ligne < this.obtenirHauteur(); ligne++) { for (int colonne = 0; colonne < this.obtenirLargeur(); colonne++) { position = new Position(ligne,colonne); indexCase = position.obtenirColonne()+(this.largeur*(position.obtenirLigne())); if(this.cases[1][indexCase] != null) chaine += "Tile."+this.cases[1][indexCase].name(); else chaine += "null"; if(indexCase+1!=this.largeur*this.hauteur) chaine+=","; } } chaine += "}},"+this.obtenirLargeur()+","+this.obtenirHauteur()+","+Partie.COMBAT_ALEATOIRES+"));"; return chaine; }
7
private void checkReminder(Calendar cal) { Reminder[] reminders = DBHandler.getAllRiminders(); for (Reminder reminder : reminders) { if (!reminder.isWas_handled()) { if (cal.getTime().after((reminder.getDue_date()))) { sendReminder(reminder); reminder.setWas_handled(true); DBHandler.addReminder(reminder); } } } }
3
private void fillFlag(Flag annotation, Parameter parameter) { String shortName = annotation.name(); String longName = annotation.longName(); if (shortName.isEmpty() && longName.isEmpty()) { LabelProvider labelProvider = parameter.getProperty(Properties.LABEL_PROVIDER); longName = labelProvider.getLabel(); shortName = longName.substring(0, 1); } parameter.offer(Properties.FLAG_LONGNAME, longName); parameter.offer(Properties.FLAG_NAME, shortName); parameter.offer(Properties.PARSER, new FlagParser(parameter)); parameter.offer(Properties.REQUIREMENT, Requirement.OPTIONAL); parameter.offer(Properties.DEFAULT_PROVIDER, FlagReader.class); parameter.offer(Properties.VALUE_READER, new FlagReader(shortName, longName)); }
2
@Override public void run(){ ImageIcon iconLogo = new ImageIcon(IMG.getImage(this.mainImg)); this.refLabel.setIcon(iconLogo); while(!super.detener){ try{ if(!this.defensaColaAtaques.isEmpty()&&this.getOcupado()) recibirdaño(); if(ejercito.size() > 0) atacar(); int segundos = 100; sleep(segundos); }catch (InterruptedException ex){} } }
5
public void visitNewMultiArrayExpr(final NewMultiArrayExpr expr) { for (int i = 0; i < expr.dimensions.length; i++) { if (expr.dimensions[i] == from) { expr.dimensions[i] = (Expr) to; ((Expr) to).setParent(expr); return; } } expr.visitChildren(this); }
2