text
stringlengths
14
410k
label
int32
0
9
public static void main(String [] argumentos) { ObjectInputStream objeto =null; try { borrarPantalla(); objeto = new ObjectInputStream(new FileInputStream("ficheros/personasModificadas.dat")); try { Persona var=(Persona)objeto.readObject(); while (var != null) { System.out.println(var.toString()); var=(Persona)objeto.readObject(); } } catch (EOFException e) { System.out.println("\n\n\n CONTINUAR --> pulsar return "); try { char c =(char)teclado.read(); } catch (IOException e1) {} } catch (ClassNotFoundException e) { System.out.println("error --> " + e.toString()); } } catch (IOException e) { System.out.println("error --> " + e.toString()); } finally { if (objeto != null) { try { objeto.close(); } catch (IOException error) { System.out.println("ERROR : " + error.toString()); } } } }
7
private static String encode(final String content, final String encoding) { try { return URLEncoder.encode(content, encoding != null ? encoding : HTTP.DEFAULT_CONTENT_CHARSET); } catch (UnsupportedEncodingException problem) { throw new IllegalArgumentException(problem); } }
2
public static void updateCompte(Compte compte) { PreparedStatement stat; try { stat = ConnexionDB.getConnection().prepareStatement("select * from compte where id_compte=?",ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); stat.setInt(1, compte.getId_compte()); ResultSet res = stat.executeQuery(); if (res.next()) { res.updateString("typeCompte", compte.getTypeCompte()); res.updateDouble("solde", compte.getSolde()); res.updateString("dateCreation", compte.getDateCreation()); res.updateInt("fk_id_utilisateur", compte.getFk_id_utilisateur()); res.updateRow(); } } catch (SQLException e) { while (e != null) { System.out.println(e.getErrorCode()); System.out.println(e.getMessage()); System.out.println(e.getSQLState()); e.printStackTrace(); e = e.getNextException(); } } }
3
public static String[] arrangeAnagram (String[] aos) { // 1. arrange the input date in a HashMap HashMap<String, List<String>> hm = new HashMap<>(); for ( String ss : aos) { String key = getKey(ss); if ( !hm.containsKey(key) ) { hm.put(key, new LinkedList<String>()); } List<String> bucket = hm.get(key); bucket.add(ss); } /* 2. retrieve the bucket date from the HashMap * and form a new array */ List<String> los = new LinkedList<>(); for ( List<String> ll : hm.values()) { los.addAll(ll); } return los.toArray(new String[los.size()]); }
3
protected void plan() { isFinished = false; //cancel already finished subgoals first //most of the time, we won't get any units back from this Iterator<Goal> git = subGoalList.iterator(); while (git.hasNext()) { Goal g = git.next(); if (g.isFinished()) { List<AIUnit> units = g.cancelGoal(); availableUnitsList.addAll(units); git.remove(); } } //check whether our unit references are still valid, //so that we can use them in the following step validateOwnedUnits(); //Run through available units. If it's a missionary, create a subgoal //for it. If not, return unit to AIPlayer. Iterator<AIUnit> uit = availableUnitsList.iterator(); while (uit.hasNext()) { AIUnit u = uit.next(); uit.remove(); if (u.getUnit().getRole() == Role.MISSIONARY) { IndianSettlement i = findSettlement(u.getUnit().getTile()); if (i != null) { PathNode pathNode = u.getUnit().findPath(i.getTile()); if (pathNode != null) { logger.info("Creating subgoal CreateMissionAtSettlementGoal."); CreateMissionAtSettlementGoal g = new CreateMissionAtSettlementGoal(player,this,1,u,i); subGoalList.add(g); } } } else { //Setting goal=null will make the unit appear in the unit iterator next turn. //TODO: What about this turn? u.setGoal(null); } } if (availableUnitsList.size()==0 && subGoalList.size()==0) { //we don't have any units to deal with, and no active subgoals //signal that we may safely be cancelled now isFinished = true; } else { //set subgoal weights in case their number has changed float newWeight = 1f/subGoalList.size(); git = subGoalList.iterator(); while (git.hasNext()) { Goal g = git.next(); g.setWeight(newWeight); } } }
9
protected int getMaxAge() { return MAX_AGE; }
0
private static TPoint[] parsePoints(String string) { List<TPoint> points = new ArrayList<TPoint>(); StringTokenizer tok = new StringTokenizer(string); try { while(tok.hasMoreTokens()) { int x = Integer.parseInt(tok.nextToken()); int y = Integer.parseInt(tok.nextToken()); points.add(new TPoint(x, y)); } } catch (NumberFormatException e) { throw new RuntimeException("Could not parse x,y string:" + string); } // Make an array out of the collection TPoint[] array = points.toArray(new TPoint[0]); return array; }
2
public int hasVariable(Variable v){ // If this predicate has no variables we can directly return -1. if(varNum == 0){ return -1; } boolean found = false; int i = 0; while(i < varList.size() && !found){ boolean this_isDef = (varList.get(i) instanceof DefaultVariable); boolean v_isDef = (v instanceof DefaultVariable); // If they belong to the same class and have the same name, then we found it. if((this_isDef == v_isDef) && varList.get(i).isName(v.getName())){ found = true; } i++; } if(found){ return i-1; } else { return -1; } }
6
public Knight(boolean isWhite, ImageIcon imgIcon) { super(isWhite, imgIcon); this.setIcon(); }
0
public void generateCode(String fileLocation){ //Make a list of Strings and populate it with the generated code //from the generator. Vector<String> output = CodeGenerator.generateCodeForVectorOfClasses(components); //for each string in the list (which is a file) for (String file:output){ //find out the name of the file from the comment on the //top line of the string. String topline = file.split("\\n")[0]; String file_name = topline.split("/")[2]; //reference a file with the selected path and name: File writeFile = new File(fileLocation + "\\" + file_name); //check if it exists already boolean exist = true; try { exist = writeFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } if (!exist) { System.out.println("File already exists."); } else { //If it doesn't exist, then proceed with writing to it. //try catch in case it doesn't work here. FileWriter fstream = null; try { fstream = new FileWriter(fileLocation + "\\" + file_name); BufferedWriter out = new BufferedWriter(fstream); out.write(file); //output the file out.close(); } catch (IOException e) { //catch any errors here. e.printStackTrace(); } } } }
4
private boolean doesWordContainLetter(String selection) { int loc = -1; int letterCount = -1; // Check if the random word contains the selection if (randomWord.contains(selection)) { // If word was passed in check if it is right if (randomWord.equals(selection)) { isWinner = true; displayWord = selection; return true; } else { do { // Location of the selection loc = randomWord.indexOf(selection, letterCount+1); if (loc != -1) { correctLetters ++; letterCount = loc; letterLocation.add(loc); } }while (loc != -1); return true; } } return false; }
4
private void buildRuleList(String[] readedHolder) { for (int y = 0; y < valueArray.length; y++) { if (readedHolder[y].contains("*")) { ruleList[y] = new Rule(1); } else if (readedHolder[y].contains("\"R")) { if (readedHolder[y].contains(",.")) { ruleList[y] = new Rule(6); } else if (readedHolder[y].contains(",,")) { ruleList[y] = new Rule(5); } } else if (readedHolder[y].contains(",,")) { ruleList[y] = new Rule(2); } else if (readedHolder[y].contains(",;")) { ruleList[y] = new Rule(3); } else if (readedHolder[y].contains(",.")) { ruleList[y] = new Rule(4); } } }
8
public void run() { while (true) { if (year!=w.year) { year=w.year; } synchronized (this) { repaint(); } try { Thread.sleep(50); } catch (InterruptedException e) { } } }
3
public void stats(){ int[] cycleLengths = new int[bucket.size()]; double[] activities = new double[bucket.size()]; double cycleLengthMean, activityMean; int cycleLengthMedian, cycleLengthUQ, cycleLengthLQ; double activityMedian, activityUQ, activityLQ, activityVar, activityStdDev, cycleLengthVar, cycleLengthStdDev; System.out.printf("\n\t=========================================="); System.out.printf("\n\t STATISTICS "); System.out.printf("\n\t==========================================\n"); System.out.printf("\n\tCalculating averages...\n"); cycleLengthMean=0; activityMean=0; for(int i=0; i<bucket.size(); i++){ cycleLengths[i] = getCycleLength(i); cycleLengthMean += (double)cycleLengths[i]; activities[i] = getActivity(i); activityMean += activities[i]; } cycleLengthMean = cycleLengthMean/bucket.size(); activityMean = activityMean/bucket.size(); System.out.printf("\tSorting arrays...\n"); Arrays.sort(cycleLengths); Arrays.sort(activities); cycleLengthLQ = cycleLengths[(int) bucket.size()/4]; cycleLengthMedian = cycleLengths[(int) bucket.size()/2]; cycleLengthUQ = cycleLengths[(int) 3*bucket.size()/4]; activityLQ = activities[(int) bucket.size()/4]; activityMedian = activities[(int) bucket.size()/2]; activityUQ = activities[(int) 3*bucket.size()/4]; System.out.printf("\tCalculating variance..."); activityVar=0; cycleLengthVar=0; cycleLengthStdDev=0; activityStdDev=0; for(int i=0; i<bucket.size(); i++){ activityVar += (getActivity(i) - activityMean)*(getActivity(i) - activityMean); cycleLengthVar += ((double)getCycleLength(i) - cycleLengthMean)*((double)getCycleLength(i) - cycleLengthMean); } activityVar = activityVar/(bucket.size()-1); cycleLengthVar = cycleLengthVar/(bucket.size()-1); activityStdDev = Math.sqrt(activityVar); cycleLengthStdDev = Math.sqrt(cycleLengthVar); System.out.printf("\n\n\t\t\tCyclelength\tActivity\n"); System.out.printf("\t==========================================\n"); System.out.printf("\tMean\t\t%.2f\t\t%.2f\n", cycleLengthMean, activityMean); System.out.printf("\tMedian\t\t%d\t\t%.2f\n", cycleLengthMedian, activityMedian); System.out.printf("\tUpper Q\t\t%d\t\t%.2f\n", cycleLengthUQ, activityUQ); System.out.printf("\tLower Q\t\t%d\t\t%.2f\n", cycleLengthLQ, activityLQ); System.out.printf("\tVariance\t%.2f\t\t%.2f\n", cycleLengthVar, activityVar); System.out.printf("\tStd. Dev.\t%.2f\t\t%.2f\n\n", cycleLengthStdDev, activityStdDev); }
2
public void delayRebirth() { final Element element = this; new Thread(new Runnable() { public void run() { try { if (!active) { Thread.sleep(rebirth_delay); List<Integer> positions = Server.getPlayersPositions(); Element board_element = Server.board.getElement(index); if (!positions.contains(index) && !Server.board.isSquareOnFire(index) && (element.equals(board_element) || board_element == null)) { if (board_element == null) { Server.board.setElement(element); } setActive(true); Server.sendAll("add_element", Element.export(element)); } else { element.delayRebirth(); } } } catch (Exception e) { System.out.println(e.getMessage()); } } }).start(); }
7
@SuppressWarnings("unchecked") private void load() { try { Project lastProject = null; Date lastEntryDate = new Date(0); Object o = null; if (new File(SAVE_FILE).exists()) { ObjectInputStream ois = new ObjectInputStream( new FileInputStream(SAVE_FILE)); o = ois.readObject(); ois.close(); } if (o == null) { projects = new ArrayList<Project>(); addProject(); changeProject(projects.get(0)); return; } if (o instanceof List) { projects = (List<Project>) o; } for (Project p : projects) { projectSelector.addItem(p); for (Entry e : p.getEntries()) { if (e.getDate().after(lastEntryDate)) { lastProject = p; lastEntryDate = e.getDate(); } } } if (lastProject != null) { changeProject(lastProject); } } catch (Exception e) { e.printStackTrace(); } }
8
public void testToStandardHours() { Period test = new Period(0, 0, 0, 0, 5, 6, 7, 8); assertEquals(5, test.toStandardHours().getHours()); test = new Period(0, 0, 0, 1, 5, 0, 0, 0); assertEquals(29, test.toStandardHours().getHours()); test = new Period(0, 0, 0, 0, 0, 59, 59, 1000); assertEquals(1, test.toStandardHours().getHours()); test = new Period(0, 0, 0, 0, Integer.MAX_VALUE, 0, 0, 0); assertEquals(Integer.MAX_VALUE, test.toStandardHours().getHours()); test = new Period(0, 0, 0, 0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); long intMax = Integer.MAX_VALUE; BigInteger expected = BigInteger.valueOf(intMax); expected = expected.add(BigInteger.valueOf(intMax * DateTimeConstants.MILLIS_PER_SECOND)); expected = expected.add(BigInteger.valueOf(intMax * DateTimeConstants.MILLIS_PER_MINUTE)); expected = expected.divide(BigInteger.valueOf(DateTimeConstants.MILLIS_PER_HOUR)); assertTrue(expected.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) < 0); assertEquals(expected.longValue(), test.toStandardHours().getHours()); test = new Period(0, 0, 0, 0, Integer.MAX_VALUE, 60, 0, 0); try { test.toStandardHours(); fail(); } catch (ArithmeticException ex) {} }
1
public Customer getCustomerForPallet(Pallet pallet) { String sql = "Select name, address "+ "from Orders,Customers "+ "where Orders.customerName = name and Orders.id = ? "; PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); ps.setLong(1, pallet.orderId); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } Customer rtn = null; try { ResultSet rs = ps.executeQuery(); while (rs.next()) { rtn = new Customer(rs.getString("name"),rs.getString("address")); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } finally { if(ps != null) try { ps.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return rtn; }
5
public void fireAddnewDestroyerPressed() { destroyerType = null; String id = txtId.getText(); if (id.isEmpty()) { JOptionPane.showMessageDialog(null, "You must fill a name first!"); return; } if (ironDomeRadioButton.isSelected()) { destroyerType = ironDomeRadioButton.getText(); } else if (shipRadioButton.isSelected()) { destroyerType = shipRadioButton.getText(); } else if (planeDomeRadioButton.isSelected()) { destroyerType = planeDomeRadioButton.getText(); } for (WarUIEventsListener l : allListeners) { l.addDestructorToUI(id,destroyerType); } dispose(); }
5
/* */ @EventHandler /* */ public void onInventoryClick(InventoryClickEvent event) /* */ { /* 342 */ if (!(event.getWhoClicked() instanceof Player)) /* */ { /* 344 */ return; /* */ } /* */ /* 348 */ Player p = (Player)event.getWhoClicked(); /* */ /* 350 */ if (Main.getAPI().isSpectating(p)) /* */ { /* 352 */ event.setCancelled(true); /* */ } /* */ }
2
public void updateButtons(LinkedList<ClickableObject> selection) { for(ClickableObject selectable : selection) { for(Ability ability : selectable.getAbilities()) { addHability(ability); } } }
2
public void putAll( Map<? extends Double, ? extends Float> map ) { Iterator<? extends Entry<? extends Double,? extends Float>> it = map.entrySet().iterator(); for ( int i = map.size(); i-- > 0; ) { Entry<? extends Double,? extends Float> e = it.next(); this.put( e.getKey(), e.getValue() ); } }
8
public void run() { // The following line nullifies timestamp-diff-cache. if (!useTimestampDiffCache){ apicaCommunicator.checkResultTimeStamps.clear(); } apicaCommunicator.populate(metrics); DumpToStdOut(metrics); writeAllMetrics(); metrics.clear(); }
1
public void setBlockSheet(int[][] blockSheet) { this.blockSheet = blockSheet; }
0
private boolean[] attsTestedBelow() { boolean[] attsBelow = new boolean[m_numAttributes]; boolean[] attsBelowLeft = null; boolean[] attsBelowRight = null; if (m_right != null) { attsBelowRight = m_right.attsTestedBelow(); } if (m_left != null) { attsBelowLeft = m_left.attsTestedBelow(); } for (int i = 0; i < m_numAttributes; i++) { if (attsBelowLeft != null) { attsBelow[i] = (attsBelow[i] || attsBelowLeft[i]); } if (attsBelowRight != null) { attsBelow[i] = (attsBelow[i] || attsBelowRight[i]); } } if (!m_isLeaf) { attsBelow[m_splitAtt] = true; } return attsBelow; }
8
private boolean confirm() { if (!checkAndSetUid(uidField.getText(), pageTextBox, dialog)) return false; pageTextBox.setBorderType((String) borderComboBox.getSelectedItem()); pageTextBox.putClientProperty("border", pageTextBox.getBorderType()); pageTextBox.setBackground(bgComboBox.getSelectedColor()); pageTextBox.setTransparent(transparentCheckBox.isSelected()); String text = textArea.getText(); if (text.trim().length() >= 6 && text.trim().substring(0, 6).toLowerCase().equals("<html>")) { pageTextBox.setContentType("text/html"); } else { pageTextBox.setContentType("text/plain"); } pageTextBox.setText(text); double w = widthField.getValue(); double h = heightField.getValue(); if (w > 0 && w < 1.05) { pageTextBox.setWidthRatio((float) w); w *= pageTextBox.page.getWidth(); pageTextBox.setWidthRelative(true); } else { pageTextBox.setWidthRelative(false); } if (h > 0 && h < 1.05) { pageTextBox.setHeightRatio((float) h); h *= pageTextBox.page.getHeight(); pageTextBox.setHeightRelative(true); } else { pageTextBox.setHeightRelative(false); } pageTextBox.setPreferredSize(new Dimension((int) w, (int) h)); ((HTMLPane) pageTextBox.getTextComponent()).removeLinkMonitor(); pageTextBox.showBoundary(pageTextBox.page.isEditable()); pageTextBox.page.getSaveReminder().setChanged(true); pageTextBox.page.settleComponentSize(); EventQueue.invokeLater(new Runnable() { public void run() { pageTextBox.setEmbeddedComponentAttributes(); } }); return true; }
7
private void indicateSelection(JPanel panel) { if (panel == this.pnlDashboard) { this.mntmDashboard.setEnabled(false); } else { this.mntmDashboard.setEnabled(true); } if (panel == this.pnlProducts) { this.mntmProducts.setEnabled(false); } else { this.mntmProducts.setEnabled(true); } if (panel == this.pnlStatisticsAveragePickingTimes) { this.mntmAveragePickingTimes.setEnabled(false); } else { this.mntmAveragePickingTimes.setEnabled(true); } if (panel == this.pnlStatisticsPercentageOfWaste) { this.mntmPercentageOfWaste.setEnabled(false); } else { this.mntmPercentageOfWaste.setEnabled(true); } }
4
public void pushSolution(String failedPath, Host[] updatedHosts, Host... failedHosts) { ArgumentCheck.checkNotNull(failedPath, "Cannot broadcast a null failed path."); ArgumentCheck.checkNotNull(updatedHosts, "Cannot broadcast a null list of updated hosts."); ArgumentCheck.checkNotNull(failedHosts, "Cannot broadcast a null list of failed hosts."); if (routingTable_.uniqueHostsNumber() == 0) { return; } logger_.info("Broadcasting the solution for path {}.", failedPath); RepairSolution solution = new RepairSolution(); solution.failedPath = failedPath; solution.updatedHosts = new PeerReference[updatedHosts.length]; for (int i = 0; i < updatedHosts.length; i++) { solution.updatedHosts[i] = Serializer.serializeHost(updatedHosts[i]); } solution.failedHosts = new PeerReference[failedHosts.length]; for (int i = 0; i < failedHosts.length; i++) { solution.failedHosts[i] = Serializer.serializeHost(failedHosts[i]); if (registry_.containsHost(failedHosts[i].getUUID())) { registry_.removeIssue(failedHosts[i].getUUID()); } routingTable_.removeReference(failedHosts[i]); // sanity } routingTable_.refresh(maxRef_); PGridPath localPath = routingTable_.getLocalhost().getHostPath(); for (int i = 0; i < localPath.length(); i++) { Host[] level = routingTable_.getLevelArray(i); if (level.length == 0) { return; } Random r = new Random(System.currentTimeMillis()); Host host = level[r.nextInt(level.length)]; PGridPath responsibility = new PGridPath(localPath.subPath(0, i > 0 ? (i - 1) : 0)); responsibility.revertAndAppend(localPath.value(i)); solution.levelPrefix = responsibility.toString(); try { RepairHandle repairHandle = getRemoteHandle(host); repairHandle.pushSolution(solution); } catch (CommunicationException e) { // Ignore the failure. The broadcasting becomes really // complicated if a new repair session will start. What // will happen with all the host that already got the // solution? logger_.debug("{}:{} is not reachable.", host, host.getPort()); } } }
8
public void compare(HashSet<Area> aAreas) { for (Area area : aAreas) { if (area == this) continue; if (contains(area)) { for (int tile : area.getTiles()) mTiles.remove(tile); mBombs -= area.mBombs; } } }
4
public boolean crear(Object[] estructura) throws SecurityException{ String dir[]= (String[])estructura[0]; String dublin[]= (String[])estructura[1]; //try{ // crear un log GregorianCalendar hoy = new GregorianCalendar(); Ejecutable.getControl().imprimirLogFisico("-------------------------------"); Ejecutable.getControl().imprimirLogFisico("LOG DE IMPORTACIÓN"); Ejecutable.getControl().imprimirLogFisico("Fecha"+ GregorianCalendar.getInstance().getTime()); // seguir el proceso por cada archivo int cont = 10; //crear directorio de la coleccion File newDir = new File(directorio.getAbsolutePath()+"/"+coleccion); //borrar remanentes si existen if(newDir.exists()){ Ejecutable.getControl().deleteDir(newDir); } //Crea el directorio de la coleccion boolean success = newDir.mkdir(); if (success) { for (int i = 0; i < dir.length; i++) { // creacion de estructura para dspace //String url = dir[i]; String nombre= dir[i]; String dublinCore = dublin[i].trim(); //comentar para producción // tener en cuenta que la URL debe ser web o fisica y debe terminar en .pdf /*StringTokenizer token = new StringTokenizer(url,"/\\"); int val = token.countTokens(); String nombre = ""; while(val != 0){ nombre = token.nextToken().trim(); val--; }*/ File elPdf = new File(directorio+"/"+nombre); if(elPdf.exists()){ //Ejecutable.getControl().imprimirLogFisico("- Archivo "+elPdf.getName()+" encontrado"); newDir = new File(directorio.getAbsolutePath()+"/"+coleccion+"/"+cont++); //Crea el directorio success = newDir.mkdir(); if (success) { Ejecutable.getControl().imprimirLogFisico("- Creando carpeta No."+(cont-1)); //Mueve el archivo al directorio //success = elPdf.renameTo(new File(newDir, elPdf.getName())); success = Ejecutable.getControl().copy(elPdf,new File(newDir.getAbsolutePath()+"/"+elPdf.getName())); if (success) { //crea el archivo contents success = escribe(newDir.getPath()+"/contents",elPdf.getName()/*url*/); if (success) { Ejecutable.getControl().imprimirLogFisico("- El archivo contents fue creado."); //crea eldublin_core.xml success = escribe(newDir.getPath()+"/dublin_core.xml",dublinCore); if(success){ Ejecutable.getControl().imprimirLogFisico("- EL archivo dublin_core fue creado."); } else { Ejecutable.getControl().imprimirLog("\nERROR: EL archivo dublin_core no fue creado."); Ejecutable.getControl().imprimirLogFisico("ERROR: EL archivo dublin_core no fue creado."); return false; }//if del dublin core } else { Ejecutable.getControl().imprimirLog("\nERROR: un archivo contents no fue creado."); Ejecutable.getControl().imprimirLogFisico("ERROR: un archivo contents no fue creado."); return false; }//if del contents }else{ Ejecutable.getControl().imprimirLog("\nERROR: El archivo "+elPdf.getName()+" no pudo ser movido."); Ejecutable.getControl().imprimirLogFisico("ERROR: El archivo "+elPdf.getName()+" no pudo ser movido."); return false; }//if de mover el archivo }else{ Ejecutable.getControl().imprimirLog("\nERROR: El Directorio "+(cont-1)+" no pudo ser creado."); Ejecutable.getControl().imprimirLogFisico("ERROR: El Directorio "+(cont-1)+" no pudo ser creado."); return false; }//if de la creacion del directorio }else{ Ejecutable.getControl().imprimirLog("\nERROR: El archivo "+elPdf.getName()+" no existe."); Ejecutable.getControl().imprimirLogFisico("ERROR: El archivo "+elPdf.getName()+" no existe."); return false; }// if de buscar el pdf }//for }else{ Ejecutable.getControl().imprimirLog("\nERROR: El Directorio "+coleccion+" no pudo ser creado. Verifique que tiene permisos sobre esa carpeta o que su disco no este lleno."); Ejecutable.getControl().imprimirLogFisico("ERROR: El Directorio "+coleccion+" no pudo ser creado. Verifique que tiene permisos sobre esa carpeta o que su disco no este lleno."); return false; } return true; }
8
public void testPropertyAddToCopyYear() { LocalDate test = new LocalDate(1972, 6, 9); LocalDate copy = test.year().addToCopy(9); check(test, 1972, 6, 9); check(copy, 1981, 6, 9); copy = test.year().addToCopy(0); check(copy, 1972, 6, 9); copy = test.year().addToCopy(292278993 - 1972); check(copy, 292278993, 6, 9); try { test.year().addToCopy(292278993 - 1972 + 1); fail(); } catch (IllegalArgumentException ex) {} check(test, 1972, 6, 9); copy = test.year().addToCopy(-1972); check(copy, 0, 6, 9); copy = test.year().addToCopy(-1973); check(copy, -1, 6, 9); try { test.year().addToCopy(-292275054 - 1972 - 1); fail(); } catch (IllegalArgumentException ex) {} check(test, 1972, 6, 9); }
2
private static int getMeasure(final String stem) { List<Letter> letters = PorterStemmer.getLetters(stem); int m = 0; int start = 0; int length = letters.size(); if (length == 0) { return 0; } // if the last element is a vowel, skip it if (letters.get(length - 1) instanceof Vowel) { length -= 1; } // Skip leeding consonant if (letters.get(0) instanceof Consonant) { start = 1; length -= 1; } for (int i = start; i < start + length; i++) { if (letters.get(i) instanceof Consonant) { m++; } } return m; }
5
public InPackage( String targetPackage ) { this.targetPackage = targetPackage; }
0
private void findMaxMinCB(boolean max) { double maxMin = (max) ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; Instances cBCurve = m_costBenefit.getPlotInstances(); int maxMinIndex = 0; for (int i = 0; i < cBCurve.numInstances(); i++) { Instance current = cBCurve.instance(i); if (max) { if (current.value(1) > maxMin) { maxMin = current.value(1); maxMinIndex = i; } } else { if (current.value(1) < maxMin) { maxMin = current.value(1); maxMinIndex = i; } } } // set the slider to the correct position int indexOfSampleSize = m_masterPlot.getPlotInstances().attribute(ThresholdCurve.SAMPLE_SIZE_NAME).index(); int indexOfPercOfTarget = m_masterPlot.getPlotInstances().attribute(ThresholdCurve.RECALL_NAME).index(); int indexOfThreshold = m_masterPlot.getPlotInstances().attribute(ThresholdCurve.THRESHOLD_NAME).index(); int indexOfMetric; if (m_percPop.isSelected()) { indexOfMetric = indexOfSampleSize; } else if (m_percOfTarget.isSelected()) { indexOfMetric = indexOfPercOfTarget; } else { indexOfMetric = indexOfThreshold; } double valueOfMetric = m_masterPlot.getPlotInstances().instance(maxMinIndex).value(indexOfMetric); valueOfMetric *= 100.0; // set the approximate location of the slider m_thresholdSlider.setValue((int)valueOfMetric); // make sure the actual values relate to the true min/max rather // than being off due to slider location error. updateInfoGivenIndex(maxMinIndex); }
7
public Integer fetchInteger() throws InputMismatchException, NumberFormatException { if(peek().isEmpty()) throw new InputMismatchException("There are no integer arguments to fetch from."); else { Integer i = Integer.valueOf(pop()); return i; } }
1
public boolean ModificarProducto(Producto p){ if (p!=null) { cx.Modificar(p); return true; }else { return false; } }
1
void setVisibilityFlags(BitSet bs) { /* * set all fixed objects visible; others based on model being displayed note * that this is NOT done with atoms and bonds, because they have mads. When * you say "frame 0" it is just turning on all the mads. */ for (int i = 0; i < meshCount; i++) { Mesh m = meshes[i]; m.visibilityFlags = (m.isValid && m.visible ? myVisibilityFlag : 0); if (m.modelIndex >=0 && !bs.get(m.modelIndex)) { m.visibilityFlags = 0; continue; } if (m.modelFlags == null) continue; for (int iModel = modelCount; --iModel >= 0;) m.modelFlags[iModel] = (bs.get(iModel) ? 1 : 0); } }
8
@Test public void testSubgroupsOrder(){ Collection<? extends Symmetry<Point4D>> subgroups; Collection<? extends Symmetry<Point4D>> rotationsymsub; Reflection4D extEl; int subgroupCounter; for (Symmetry4DReflection g : Symmetry4DReflection.getSymmetries()) { subgroupCounter = 0; subgroups = g.subgroups(); rotationsymsub = g.getRotationsym().subgroups(); extEl = g.getExtendingElem(); for (Symmetry4D sym : Symmetry4D.getSymmetries()) { if (rotationsymsub.contains(sym)) { assertTrue(subgroups.contains(sym)); subgroupCounter ++; } } for (Symmetry4DReflection sym : Symmetry4DReflection.getSymmetries()) { if (rotationsymsub.contains(sym.getRotationsym()) && extEl.equals(sym.getExtendingElem())) { assertTrue(subgroups.contains(sym)); subgroupCounter ++; } } assertEquals(subgroupCounter, subgroups.size()); } }
8
private void teleportToMine() { if (Util.inAuburyShop()) { NPC aubury = NPCs.getNearest(Util.auburyId); if (aubury.interact("teleport")) { int time = 0; while (!Util.inEssenceMine() && time <= 4000) { time += 50; Time.sleep(50); } } } }
4
public static String display(char[][] array){ int k = 4; String format = "%-3s"; String limit = " +"+new String(new char[array.length]).replace("\0","---+"); String deca = new String(new char[k]).replace("\0"," "); String res = deca; char row = 'A'; int line = 1; //loop to display row letter for(int i = 0; i<array.length;i++){ res+= " "+row+" "; row++; } res+= System.getProperty("line.separator"); res+= limit; //loop to display line number and each character for(int i = 0; i<array.length;i++){ res+= System.getProperty("line.separator"); res += " "+String.format(format, line); for(int j = 0; j<array[i].length;j++) { res+= "| "; res += array[i][j]+" "; } res+= "|"; res+= System.getProperty("line.separator"); res+= limit; line++; } // Word wrap res+= System.getProperty("line.separator"); return res; }
3
public void setQueue2(FloatQueue t) throws MismatchException { if (t == null) throw new NullPointerException("the arg cannot be null"); if (q1 != null) { if (t.getLength() != q1.getLength()) throw new MismatchException("queue 1 and 2 have different lengths!"); if (t.getPointer() != q1.getPointer()) throw new MismatchException("queue 1 and 2 have different pointer indices!"); if (t.getInterval() != q1.getInterval()) throw new MismatchException("queue 1 and 2 have different intervals!"); } if (q3 != null) { if (t.getLength() != q3.getLength()) throw new MismatchException("queue 2 and 3 have different lengths!"); if (t.getPointer() != q3.getPointer()) throw new MismatchException("queue 2 and 3 have different pointer indices!"); if (t.getInterval() != q3.getInterval()) throw new MismatchException("queue 2 and 3 have different intervals!"); } q2 = t; }
9
public void keyPressed(KeyEvent e) { super.keyPressed(e); // ctrl key if (e.getModifiersEx() == 128) { switch (e.getKeyCode()) { // s key case 83 : file.promptSave(); break; // o key case 79 : if (file.promptOpen()) { undoManager.discardAllEdits(); } break; // n key case 78 : file.promptNew(); break; } } // shift + ctrl if (e.getModifiersEx() == 192) { switch (e.getKeyCode()) { // s key case 83 : file.promptSaveAs(); break; } } }
7
public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { Spel spel = new Spel(); List<logic.Onderwerp> onderwerpen = spel.getOnderwerpen(); spel.setOnderwerp(onderwerpen.get(1)); List<logic.Onderdeel> ondrln = spel.getOnderdelen(); List<logic.Onderdeel> ondrln2 = new ArrayList<logic.Onderdeel>(); ondrln2.add(ondrln.get(0)); // 0 ondrln2.add(ondrln.get(1)); // 1 ondrln2.add(ondrln.get(2)); // 2 ondrln2.add(ondrln.get(3)); // 3 ondrln2.add(ondrln.get(4)); // 4 ondrln2.add(ondrln.get(8)); // 5 ondrln2.add(ondrln.get(7)); // 6 ondrln2.add(ondrln.get(6)); // 7 ondrln2.add(ondrln.get(5)); // 8 for (logic.Onderdeel o : ondrln2) { spel.volgendeOnderdeel(); spel.kiesOnderdeel(o); } SpeelScherm speelscherm = new SpeelScherm(spel); spel.openPanel(speelscherm); speelscherm.openJokerscherm(); spel.getTimer().stop(); } catch (Exception e) { e.printStackTrace(); } } }); }
2
public BitSet diversify(List<Subset> neighborhood){ if(neighborhood == null) return m_Sbest.subset; BitSet result = new BitSet(m_numAttribs); double [] counts = new double[m_numAttribs]; int numNeighborhood = neighborhood.size (); for (int i = 0; i < m_numAttribs; i++) { if(i == m_classIndex) continue; int counter = 0; for (int j = 0; j < numNeighborhood; j++) { if(((Subset)neighborhood.get (j)).subset.get (i)) counter ++; } counts [i] = counter/(double)numNeighborhood; } for (int i = 0; i < m_numAttribs; i++) { double randomNumber = m_random.nextDouble (); double ocurrenceAndRank = counts [i] * (m_diversificationProb) + doubleRank (i) * (1 - m_diversificationProb); if(randomNumber > ocurrenceAndRank) result.set (i); } return result; }
7
protected void onMode(String channel, String sourceNick, String sourceLogin, String sourceHostname, String mode) {}
0
public double getTFIDF(String termName, String document){ Term searchTerm = null; for(Term term: tree){ if(term.getName().compareTo(termName.toLowerCase().trim()) == 0){ searchTerm = term; } } if(searchTerm != null) { termFrequency = searchTerm.getInDocumentFrequency(document); //System.out.println("termFrequency: " + termFrequency); totalDocs = totalDocuments; //System.out.println("totalDocs: " + totalDocs); documentFrequency = searchTerm.getDocFrequency(); //System.out.println("documentFrequency: " + documentFrequency); double IDF = Math.log(totalDocs / documentFrequency); return (termFrequency * IDF); } return -1; }
3
public boolean stageOne() { int smallest = 0, index = -1; ArrayList<Node> tempNodeList = new ArrayList<Node>(4); ArrayList<Integer> distance = new ArrayList<Integer>(4); // Initialise 4 slots in distance ArrayList to -1 for (int i=0; i<4; i++) { distance.add(-1); tempNodeList.add(new Node(-1, -1)); } this.closedNodes.add(this.currentNode); if(this.checkerObject.getUp()==1) { // Able to move to up tempNodeList.set(0, new Node((this.currentNode.getX()-1), (this.currentNode.getY()))); distance.set(0, calculateDistance(tempNodeList.get(0))); } if (this.checkerObject.getLeft()==1) { // Able to move to left tempNodeList.set(1, new Node((this.currentNode.getX()), (this.currentNode.getY()-1))); distance.set(1, calculateDistance(tempNodeList.get(1))); } if (this.checkerObject.getDown()==1) { // Able to move to down tempNodeList.set(2, new Node((this.currentNode.getX()+1), (this.currentNode.getY()))); distance.set(2, calculateDistance(tempNodeList.get(2))); } if (this.checkerObject.getRight()==1) { // Able to move to right tempNodeList.set(3, new Node((this.currentNode.getX()), (this.currentNode.getY()+1))); distance.set(3, calculateDistance(tempNodeList.get(3))); } // Make sure smallest variable starts out as biggest value smallest = distance.get(0) + distance.get(1) + distance.get(2) + distance.get(3) + 999; for(int i = 0; i < 4; i++) { if((distance.get(i) >= 0) && (distance.get(i) < smallest)) { smallest = distance.get(i); index = i; } } // Hit dead end if(index==-1) { super.verifyDeadEnd(); } else { this.currentNode = tempNodeList.get(index); } return true; }
9
public void keyReleased(KeyEvent ke) { try { if (ke.getKeyCode() == 38) { if ((ke.getSource() == this.jtfCommand_Broadcast) || (ke.getSource() == this.jtfCommand_Private) || (ke.getSource() == this.jtfTerminalCommand)) { moveCommandUp(); } } else if (ke.getKeyCode() == 40) { if ((ke.getSource() == this.jtfCommand_Broadcast) || (ke.getSource() == this.jtfCommand_Private) || (ke.getSource() == this.jtfTerminalCommand)) { moveCommandDown(); } } } catch (Exception e) { Drivers.eop("keyReleased", this.strMyClassName, e, e.getLocalizedMessage(), false); } }
9
protected void encodePacket(OutputStream out, String sharedSecret, RadiusPacket request) throws IOException { // check shared secret if (sharedSecret == null || sharedSecret.length() == 0) throw new RuntimeException("no shared secret has been set"); // check request authenticator if (request != null && request.getAuthenticator() == null) throw new RuntimeException("request authenticator not set"); // request packet authenticator if (request == null) { // first create authenticator, then encode attributes // (User-Password attribute needs the authenticator) authenticator = createRequestAuthenticator(sharedSecret); encodeRequestAttributes(sharedSecret); } byte[] attributes = getAttributeBytes(); int packetLength = RADIUS_HEADER_LENGTH + attributes.length; if (packetLength > MAX_PACKET_LENGTH) throw new RuntimeException("packet too long"); // response packet authenticator if (request != null) { // after encoding attributes, create authenticator authenticator = createResponseAuthenticator(sharedSecret, packetLength, attributes, request.getAuthenticator()); } else { // update authenticator after encoding attributes authenticator = updateRequestAuthenticator(sharedSecret, packetLength, attributes); } DataOutputStream dos = new DataOutputStream(out); dos.writeByte(getPacketType()); dos.writeByte(getPacketIdentifier()); dos.writeShort(packetLength); dos.write(getAuthenticator()); dos.write(attributes); dos.flush(); }
7
public static void main(String args[]) { NewThread3 ob1 = new NewThread3("One"); NewThread3 ob2 = new NewThread3("Two"); try { Thread.sleep(1000); ob1.t.suspend(); System.out.println("Suspending thread One"); Thread.sleep(1000); ob1.t.resume(); System.out.println("Resuming thread One"); ob2.t.suspend(); System.out.println("Suspending thread Two"); Thread.sleep(1000); ob2.t.resume(); System.out.println("Resuming thread Two"); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } // wait for threads to finish try { System.out.println("Waiting for threads to finish."); ob1.t.join(); ob2.t.join(); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } System.out.println("Main thread exiting."); }
2
public void setSkillName(String skillName) { this.skillName = skillName; }
0
public Serializable getObject() { return theMainObject; }
0
private void postProduct() throws IOException { if (!getTextArea().getText().isEmpty() && getTextField_name().getText().length() > 0) { JSONObject postData = ApiUtil.fetchObject("products", getTextField().getText()); JSONObject result = postData.getJSONObject("result"); String name = result.get("name").toString(); JSONObject new_product = new JSONObject(postData.toString().replace(name, getTextField_name().getText())); ApiUtil.postData(ApiProperties.get().getUrl() + "/products/save/", new_product.getJSONObject("result")); } else { if (getTextField_name().getText().length() == 0) throwPopup("Sie müssen einen neuen Produktnamen eingaben", JOptionPane.ERROR_MESSAGE); if (getTextArea().getText().isEmpty()) throwPopup("Sie müssen zuerst ein Produkt auswählen", JOptionPane.ERROR_MESSAGE); } }
4
private static int getTrackerId(Statement statement, String trackerName) throws SQLException { int id = -1; ResultSet resultSet = statement.executeQuery("select id from " + Settings.DB_TABLE_TRACKER + " where name like '" + trackerName + "' limit 1"); // SQL injection ? if (resultSet.next()) { id = resultSet.getInt(1); } else { statement.executeUpdate("insert into " + Settings.DB_TABLE_TRACKER + " (name) values ('" + trackerName + "')"); //Now there is a field resultSet = statement.executeQuery("select id from " + Settings.DB_TABLE_TRACKER + " where name like '" + trackerName + "'"); // SQL injection ? if (resultSet.next()) id = resultSet.getInt(1); } return id; }
2
private void check() { synchronized (ui) { if (tgt && !wrapped.hasfs()) wrapped.setfs(); if (!tgt && wrapped.hasfs()) wrapped.setwnd(); } }
4
@Override public String printStorage() { String print = new String(); for (int i = 1; i <= aisleCount; i++) { System.out.println(i); Aisle aisle = (Aisle) manager.get("A" + i); if (aisle == null) { i++; aisle = (Aisle) manager.get("A" + i); } print += "<p>" + aisle.getCode() + " :<br>"; List<Rack> racks = null; try { racks = aisle.getRacks(); } catch (Exception ex) { Logger.getLogger(Storage.class.getName()).log(Level.SEVERE, null, ex); } for (int j = 0; j < racks.size(); j++) { Rack rack = racks.get(j); List<IShelf> lst = null; print += rack.getCode() + ": "; try { lst = rack.getShelfs(); } catch (Exception ex) { Logger.getLogger(Storage.class.getName()).log(Level.SEVERE, null, ex); } for (int k = 0; k < lst.size(); k++) { IShelf proxyS = lst.get(k); print += proxyS.getID() + " "; } print += "</br>"; } print += "</p>"; } return print; }
6
public void init(File ff) { try { JarFile jf = new JarFile(ff); System.out.println("------------------------------------------------------------"); String name = jf.getManifest().getMainAttributes().getValue("plugin-name"); String verStr = jf.getManifest().getMainAttributes().getValue("plugin-version"); String dependsStr = jf.getManifest().getMainAttributes().getValue("plugin-depends"); if (name == null || verStr == null) { System.out.println("Skipping " + name + "(" + verStr + ")"); return; } Long ver = Long.parseLong(verStr); System.out.println("Detected " + name + "(" + ver + ") ..."); for (Entry<Object, Object> s : jf.getManifest().getMainAttributes().entrySet()) { if (!"plugin-name".equals(s.getKey()) && !"plugin-version".equals(s.getKey())) System.out.println(s.getKey() + " : " + s.getValue()); } ArrayList<Object[]> dependsArray = new ArrayList<Object[]>(); if (dependsStr != null) { StringTokenizer st = new StringTokenizer(dependsStr); while (st.hasMoreElements()) { String depName = st.nextToken(); String depVerStr = st.nextToken(); Long depVer = Long.parseLong(depVerStr); dependsArray.add(new Object[]{depName, depVer}); } } versions.put(name, ver); mark.put(name, -1); files.put(name, ff); childs.put(name, new ArrayList<String>()); depends.put(name, dependsArray); initializer.put(name, jf.getManifest().getMainAttributes().getValue("plugin-initializer")); configxml.put(name, jf.getManifest().getMainAttributes().getValue("plugin-configxml")); } catch (Exception ex) { ex.printStackTrace(); } }
8
public static synchronized BufferedImage layoutAndRender(OdeAccess access) { // Init sizes for layout generations initSizes(access); lindex++; Graph conn = GraphIO.readGraph("graph-" + lindex + ".txt"); Visode[] vert = GraphIO.readVisodes("vishy-" + lindex + ".txt"); OdeAccess copy = null; if (conn != null && vert != null && false) { copy = new OdeManager(vert, conn); } else { copy = new OdeManager(access); OdeLayout layout = new GansnerLayout(copy, true); layout.doLayout(); energyMinimize(copy); // Stick original display names back in for (String v : copy.getOdes()) { Visode cv = copy.find(v); Visode ov = access.find(v); if (ov == null || cv == null) { continue; } cv.setDisplayName(ov.getDisplayName()); cv.setLongName(ov.getLongName()); } try { GraphIO.saveGraph("graph-"+lindex+".txt", copy.copyGraph()); GraphIO.saveVisodes("vishy-" + lindex + ".txt", copy.getVisodes()); GraphIO.saveJson("json-" + lindex + ".js", copy); } catch (Exception e) { System.err.println("Error caching graphs: " + e); } } // Sizes might have changed due to virtual nodes initSizes(copy); for (Visode o : copy.getVisodes()) { if (o.getType() == Visode.TYPE_LINK) o.setRadius(0); } GraphRenderer renderer = new GraphRenderer(copy); return renderer.render(); }
9
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { MOB target=mob; if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB)) target=(MOB)givenTarget; if(target.fetchEffect(this.ID())!=null) { mob.tell(target,null,null,L("<S-NAME> <S-IS-ARE> already protected from fire.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("A cool field of protection appears around <T-NAME>."):L("^S<S-NAME> @x1 for a cool field of protection around <T-NAMESELF>.^?",prayWord(mob))); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); beneficialAffect(mob,target,asLevel,0); } } else beneficialWordsFizzle(mob,target,L("<S-NAME> @x1 for fire protection, but fail(s).",prayWord(mob))); return success; }
8
public List<ReferenceType> getReference() { if (reference == null) { reference = new ArrayList<ReferenceType>(); } return this.reference; }
1
private void btnCrearOfertaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCrearOfertaActionPerformed if(tbxMonto.getText().trim().length() != 0 && tbxTipoCambio.getText().trim().length() != 0 && cmbTipoOferta.getSelectedItem() != null) { try { DAOFactory sqlserverFactory = DAOFactory.getDAOFactory(DAOFactory.SQLSERVER); OfertaDAO ofertaDAO = sqlserverFactory.getOfertaDAO(); // Obtener valores boolean isCompra = false; if (cmbTipoOferta.getSelectedIndex() == 0) isCompra = true; BigDecimal monto = BigDecimal.valueOf(Float.parseFloat(tbxMonto.getText())); BigDecimal tipoCambio = BigDecimal.valueOf(Float.parseFloat(tbxTipoCambio.getText())); // Sesion actual SesionDAO sesionDAO = sqlserverFactory.getSesionDAO(); int idSesion = sesionDAO.obtenerSesionActual(); // Congelar Monto CuentaDAO cuentaDAO = sqlserverFactory.getCuentaDAO(); int resultCong = cuentaDAO.congelarMonto(tipoCambio, Integer.parseInt(id), monto, isCompra); if(resultCong > 0) { // Crear Oferta Oferta oferta; oferta = new Oferta(isCompra, monto, tipoCambio, true, Integer.parseInt(id), idSesion); int result = ofertaDAO.crearOferta(oferta); if(result > 0) JOptionPane.showMessageDialog(null, "Oferta creada correctamente."); else JOptionPane.showMessageDialog(null, "Ha ocurrido un error al crear la oferta," + " favor intente de nuevo."); } else JOptionPane.showMessageDialog(null, "No hay suficientes fondos en la cuenta."); } catch(HeadlessException e) { JOptionPane.showMessageDialog(rootPane, e.getMessage()); } } }//GEN-LAST:event_btnCrearOfertaActionPerformed
7
@Test public void testRemoveClient() { BlockingQueue<Client> currentObjectsList = null; Client client1 = new Client("Diego", "111", "diego.sousa@dce.ufpb.br", 18, 11, 1988); Client client3 = new Client("Kawe", "333", "kawe.ramon@dce.ufpb.br", 18, 11, 1988); facade.addClient(client1); facade.addClient(client3); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } facade.getListOfClient(copyListOfAllClient); try { currentObjectsList = copyListOfAllClient.take(); } catch (InterruptedException e) { e.printStackTrace(); } assertEquals(2, currentObjectsList.size()); assertTrue(currentObjectsList.contains(client1)); facade.removeClient(client1); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } assertEquals(1, currentObjectsList.size()); assertFalse(currentObjectsList.contains(client1)); }
3
public void listenerButtonVideau() { if (!session.getParametreSession().isUtiliseVideau()) { vuePartie.getPaneldroitencours().getVideau().setEnabled(false); } else { vuePartie.getPaneldroitencours().getVideau().addMouseListener(new MouseListener(){ @Override public void mouseClicked(MouseEvent arg0) { } @Override public void mouseEntered(MouseEvent arg0) {} @Override public void mouseExited(MouseEvent arg0) {} @Override public void mousePressed(MouseEvent arg0) {} @Override public void mouseReleased(MouseEvent arg0) { if ((couleurVideau == CouleurCase.VIDE || session.getPartieEnCours().getJoueurEnCour() != couleurVideau)&& (session.getPartieEnCours().isTourFini() && !session.getPartieEnCours().isPartieFini())) { SortedSet<String> hs = new ConcurrentSkipListSet<>(); hs.add("Non"); hs.add("Oui"); vuePartie.afficherFenetreDemande("Accepter vous le videau ?", hs).addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String action = e.getActionCommand(); if (action == "Oui") { couleurVideau = session.getPartieEnCours().getJoueurEnCour() ; session.getPartieEnCours().doublerVideau(); } else if (action == "Non") { finPartie(); //if (!session.isSessionFini()) //controleurPartie.nouvellePartie(); } vuePartie.getPaneldroitencours().updateVideau(); } }); }} }); } }
7
private boolean mtChecker(LinkedList<String>left,LinkedList<String>middle, LinkedList<String>consequent) { /* * assume ~~~c * assume ~~(b=>c) * mt 1 2 ~~~b * * */ /* * Potential Problems: * - c * - ~(b=>c) * - ~b * * assert size at bottom of method might break things * * */ filterTildas(left); filterTildas(middle); filterTildas(consequent); /* System.out.println(left.toString()); System.out.println(middle.toString()); System.out.println(consequent.toString()); */ LinkedList<String> fullExpression; LinkedList<String> predicate; if (left.size() > middle.size()) { fullExpression = left; predicate = middle; } else { fullExpression = middle; predicate = left; } //System.out.println(fullExpression.toArray().toString()); //System.out.println(predicate.toArray().toString()); if (fullExpression.pop().equals("=>")) { String fullBuff = ""; //check consequent matches left side of full expression, but has tilda assert consequent.peek().equals("~"); consequent.pop(); for(int i=0; i < consequent.size();i++) { try { fullBuff = fullExpression.pop(); assert consequent.pop().equals(fullBuff); } catch (Exception e) { return false; } } //check predicate matches right side of full expression, but has tilda assert predicate.peek().equals("~"); predicate.pop(); for(int i=0; i < predicate.size();i++) { try { fullBuff = fullExpression.pop(); assert predicate.pop().equals(fullBuff); } catch (Exception e) { return false; } } try { assert fullExpression.size()==0; return true; } catch (Exception e) { return false; } } return false; }
7
public String string2Json(String s) { StringBuffer sb = new StringBuffer(); for (int i=0; i<s.length(); i++) { char c = s.charAt(i); switch (c){ case '\"': sb.append("\\\""); break; case '\\': sb.append("\\\\"); break; case '/': sb.append("\\/"); break; case '\b': sb.append("\\b"); break; case '\f': sb.append("\\f"); break; case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; default: sb.append(c); } } return sb.toString(); }
9
public void paint(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHints(rh); g2d.drawImage(backgroundBuff, null, 0, 0); if (backgroundBuff == null) createBackground(); if (initDone && !participants.isEmpty()) { //Here we did such an awesome thing, that no comment can describe it! //Ok ok i will try //Here we can scale size with a help of setting -> resultsNumber! int paintOffset = 0; /*if (participantsSorted.size() > resultsNumber){ paintOffset = (getHeight() - ((entryHeight+entryTopSpacing) * resultsNumber))/2; }*/ if (participantsSorted.size() < resultsNumber) { paintOffset = (getHeight() - ((entryHeight+entryTopSpacing) * participantsSorted.size()))/2; } //Here we go through the list of the participants and draw them on screen //We use shallow sorted copy to index them for (int i = 0; i < participantsSorted.size(); i++) { if (i == resultsNumber) break; if (participantsSorted.get(i).getBuffImage() != null) { g2d.drawImage(participantsSorted.get(i).getBuffImage(), null, entrySideSpacing, participantsSorted.get(i).getY() + paintOffset); } } Toolkit.getDefaultToolkit().sync(); g.dispose(); } }
7
private void setfnames( String filename ) { if( used() ) use(); // close previous files String f = filename; int l = f.length(); ext = (( l>4 && f.charAt(l-4) == '.' ) ? f.substring(l-3) : "" ); if( ext.toLowerCase().equals("dbf") ) { dbfname = f; f = f.substring(0,l-4); } else { ext = "DBF" ; dbfname = f + "." + ext; } boolean sm = ext.equals("dbf"); fptname = f + "." + ( sm ? "fpt" : "FPT" ); cdxname = f + "." + ( sm ? "cdx" : "CDX" ); for(int i=f.length(); i>0;) { char c = f.charAt(--i); if(c=='/' || c=='\\') { f=f.substring(i+1); break; } } alias = f.toUpperCase(); order = ""; }
9
@Override public void keyTyped(KeyEvent e) { if (e.getKeyChar() == 'w') { selectedItem = (selectedItem + 1) % items; } if (e.getKeyChar() == 's') { if (selectedItem > 0) { selectedItem--; } else { selectedItem = items - 1; } } if (e.getKeyChar() == ' ') { SoundManager.stop("chiptune"); try { Thread.sleep(250); } catch (InterruptedException e1) { e1.printStackTrace(); } SoundManager.play("hit"); try { Thread.sleep(10); } catch (InterruptedException e1) { e1.printStackTrace(); } pressedItem = selectedItem; switch (selectedItem) { case 0: getStageManager().setStatge(StageManager.STAGE_SHOP, null); break; case 1: Main.frame.setVisible(false); getStageManager().close(); break; } } if (e.getKeyChar() == 'e') { getStageManager().setStatge(StageManager.STAGE_LEVELEDITOR, null); } }
9
@Override public void stop(int objectId) { AudioChannel channel = channels.get(objectId); if (channel != null) { alSourceStop(channel.source); } }
1
public boolean isCompleted() { return PeerState.COMPLETED.equals(this.state); }
0
public static boolean save() { if (KeyList.values().size() == 0) { //If queue is empty OR economy is disabled. KeysFile.delete(); return true; } ColorKeys.Log(Level.INFO, "Saving keys..."); try { if (!KeysFile.exists()) { if (!KeysFile.createNewFile()) { ColorKeys.Log(Level.SEVERE, "Error creating keys file."); return false; } } DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element fileVersionElement = doc.createElement("file"); fileVersionElement.setAttribute("version", "1.0"); doc.appendChild(fileVersionElement); for (String player : KeyList.keySet()) { Element playerElement = doc.createElement("player"); playerElement.setAttribute("name", player); fileVersionElement.appendChild(playerElement); for (CKKey key : KeyList.get(player)) { Element keyElement = doc.createElement("key"); keyElement.setAttribute("world", key.world.getName()); keyElement.setAttribute("location", key.location); keyElement.setAttribute("color", key.color + ""); keyElement.setAttribute("uses", key.uses + ""); keyElement.setAttribute("initialUses", key.initialUses + ""); keyElement.setAttribute("price", key.price + ""); playerElement.appendChild(keyElement); } } TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); //trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(doc); trans.transform(source, result); FileOutputStream OUT = new FileOutputStream(KeysFile); OUT.write(result.getWriter().toString().getBytes()); OUT.flush(); OUT.close(); ColorKeys.Log(Level.INFO, "Keys saved successfully."); return true; } catch (Exception e) { ColorKeys.Log(Level.SEVERE, "Unknown error saving Keys."); e.printStackTrace(); return false; } }
6
public Direction hitObj(GameObj other) { if (this.willIntersect(other)) { double dx = other.pos_x + other.width /2 - (pos_x + width /2); double dy = other.pos_y + other.height/2 - (pos_y + height/2); double theta = Math.atan2(dy, dx); double diagTheta = Math.atan2(height, width); if ( -diagTheta <= theta && theta <= diagTheta ) { return Direction.RIGHT; } else if ( diagTheta <= theta && theta <= Math.PI - diagTheta ) { return Direction.DOWN; } else if ( Math.PI - diagTheta <= theta || theta <= diagTheta - Math.PI ) { return Direction.LEFT; } else { return Direction.UP; } } else { return null; } }
7
public boolean onCommand(CommandSender s, Command command, String label, String[] args) { if (args.length == 0 || getCommands(args[0]) == null) { s.sendMessage(ChatColor.DARK_GRAY + "" + ChatColor.BOLD + "------------------[" + ChatColor.AQUA + ChatColor.BOLD + " Hubber " + ChatColor.DARK_GRAY + ChatColor.BOLD + "]------------------"); for (BaseCmd cmd : cmds) { if (Util.hp(s, cmd.cmdName)) s.sendMessage(ChatColor.GRAY + " - " + cmd.helper()); } s.sendMessage(ChatColor.DARK_GRAY + "" + ChatColor.BOLD + "---------------------------------------------------"); } else getCommands(args[0]).processCmd(s, args); return true; }
4
public Transition parseTransition(Id leftId, Id rightId, String transitionExpr) { Transition transition = new Transition(leftId, rightId); String[] leftAndRight; if(transitionExpr.contains("-.-")) { transition.usingLineStyle(Styles.LineStyle.Dashed); leftAndRight = transitionExpr.split(Pattern.quote("-.-")); } else if(transitionExpr.contains("...")) { transition.usingLineStyle(Styles.LineStyle.Dotted); leftAndRight = transitionExpr.split(Pattern.quote("...")); } else if(transitionExpr.contains("===")) { transition.usingLineStyle(Styles.LineStyle.Bold); leftAndRight = transitionExpr.split(Pattern.quote("===")); } else { transition.usingLineStyle(Styles.LineStyle.Solid); leftAndRight = transitionExpr.split("\\-"); } if(leftAndRight.length>1) { parseTransitionEndPoint(transition.leftEndPoint(), leftAndRight[0]); parseTransitionEndPoint(transition.rightEndPoint(), leftAndRight[1]); } else if(leftAndRight.length>0) { parseTransitionEndPoint(transition.leftEndPoint(), leftAndRight[0]); } return transition; }
5
protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption) { init(); this.options = options; // an iterator for the command line tokens Iterator iter = Arrays.asList(arguments).iterator(); // process each command line token while (iter.hasNext()) { // get the next command line token String token = (String) iter.next(); // handle long option --foo or --foo=bar if (token.startsWith("--")) { int pos = token.indexOf('='); String opt = pos == -1 ? token : token.substring(0, pos); // --foo if (!options.hasOption(opt)) { processNonOptionToken(token, stopAtNonOption); } else { currentOption = options.getOption(opt); tokens.add(opt); if (pos != -1) { tokens.add(token.substring(pos + 1)); } } } // single hyphen else if ("-".equals(token)) { tokens.add(token); } else if (token.startsWith("-")) { if (token.length() == 2 || options.hasOption(token)) { processOptionToken(token, stopAtNonOption); } // requires bursting else { burstToken(token, stopAtNonOption); } } else { processNonOptionToken(token, stopAtNonOption); } gobble(iter); } return (String[]) tokens.toArray(new String[tokens.size()]); }
9
public Command getCommand(String inputLine) { //String inputLine = ""; // will hold the full input line String word1; String word2; StringTokenizer tokenizer = new StringTokenizer(inputLine); if(tokenizer.hasMoreTokens()) word1 = tokenizer.nextToken(); // get first word else word1 = null; if(tokenizer.hasMoreTokens()) word2 = tokenizer.nextToken(); // get second word else word2 = null; // note: we just ignore the rest of the input line. // Now check whether this word is known. If so, create a command // with it. If not, create a "null" command (for unknown command). Command command = commands.getCommand(word1); if(command != null) { command.setSecondWord(word2); } return command; }
3
public ArrayList<GeoEvent> eventDataGenerator(JsonObject jsonObject){ ArrayList<GeoEvent> events = new ArrayList<GeoEvent>(); try { JsonObject jobject = (JsonObject) jsonObject.getAsJsonObject("events"); JsonArray eventOb = jobject.getAsJsonArray("event"); for(JsonElement s : eventOb){ JsonObject event = s.getAsJsonObject(); String eventName = event.get("title").getAsString(); String eventID = event.get("id").getAsString(); /** * Getting headliner, and support bands */ JsonObject artists = event.getAsJsonObject("artists"); JsonPrimitive headliner = (JsonPrimitive)artists.getAsJsonPrimitive("headliner"); String Headliner = headliner.getAsString(); ArrayList<String> support = new ArrayList<String>(); String eventUrl = event.get("url").getAsString(); if(artists.get("artist").isJsonArray()){ JsonElement supList = artists.get("artist"); JsonArray list = supList.getAsJsonArray(); for(JsonElement c : list){ support.add(c.getAsString()); } } /** * getting venue data. */ JsonObject venue = event.getAsJsonObject("venue"); JsonElement venuID = venue.get("id"); String StringID = venuID.getAsString(); String VenueName = venue.get("name").getAsString(); JsonObject location = venue.getAsJsonObject("location"); /** * Address and location */ JsonObject getPoint = location.getAsJsonObject("geo:point"); double geoLat = getPoint.get("geo:lat").getAsDouble(); double geoLong = getPoint.get("geo:long").getAsDouble(); String city = location.get("city").getAsString(); String country = location.get("country").getAsString(); String street = location.get("street").getAsString(); String postalCode = "0000"; try{ postalCode = location.get("postalcode").getAsString(); } catch (Exception e) { e.printStackTrace(); postalCode = "0000"; } String url = venue.get("url").getAsString(); String website = venue.get("website").getAsString(); String phone = venue.get("phonenumber").getAsString(); String date; try{ Date jdate = StringUtilities.getDateFromString(event.get("startDate").getAsString()); date = StringUtilities.getXSD(jdate); } catch (Exception e) { e.printStackTrace(); date = "010101"; } Result jsonArtist = Artist.getInfo(Headliner, "64ecb66631fd1570172e9c44108b96d4"); if(!jsonArtist.isSuccessful()){ } else{ GeoEvent geoEvent = new GeoEvent(eventName, eventID, Headliner,date, VenueName, StringID, geoLat, geoLong, city, country, street, postalCode, url, website, eventUrl, phone); events.add(geoEvent); } } } catch (Exception e) { return null; // e.printStackTrace(); // System.out.println("LOL"); } return events; }
7
public void run() { try{ System.out.println("Connecting on port: " +port); InetAddress server = InetAddress.getByName(ip); sConn = new Socket (server, port); conInf=("Connected to: "+sConn.getInetAddress().getHostName() +" on port"+port); mp.chat.append(conInf+"\n"); //System.out.println(conInf); out = new ObjectOutputStream(sConn.getOutputStream()); out.flush(); in = new ObjectInputStream(sConn.getInputStream()); do{ try{ msg = (String)in.readObject(); //System.out.println("Server sent:> "+msg); //for recieving the player hand if(msg.contains("ph=")) { String[] tmp = msg.split("="); String ph = tmp[1]; mp.hand.append(ph+"\n"); } //for recieving the player total if(msg.contains("pt=")) { String[] tmp = msg.split("="); String pt = tmp[1]; mp.pTotal.setText(pt+"\n"); } if(msg.contains("bust=")) { String[] tmp = msg.split(("=")); String pt = tmp[1]; mp.hand.setForeground(Color.red); mp.hand.append(pt); mp.twist.setEnabled(false); mp.stick.setEnabled(false); } }catch(ClassNotFoundException e){ System.out.println("Client data received in " + "unknown format"); } } while(!msg.equals("serverpls")); } catch(IOException e) { System.out.println("IOException in player " + "connect: "+e); e.printStackTrace(); } finally{ //Closing connection try{ in.close(); out.close(); sConn.close(); } catch(IOException e){ e.printStackTrace(); } } } //end of run();
7
public static String getRelativePath(PackageDoc packDoc, PathType eparamssource) { String pkgPath = packDoc.name().replace('.', '/') + "/"; switch(eparamssource) { case eInterfaceHeader: return pkgPath + "interfaces.h"; case eProxyHeader: return pkgPath + "proxys.h"; case eProxySource: return pkgPath + "proxys.cc"; case eParamsHeader: return pkgPath + "params.h"; case eParamsSource: return pkgPath + "params.cc"; case eStubBaseHeader: return pkgPath + "stub_base.h"; case eStubBaseSource: return pkgPath + "stub_base.cc"; case eApiFolder: case eImplFolder: return pkgPath; default: return null; } }
9
@RequestMapping(value = {"/search"}) public String findDepartments(@RequestParam(value = "name", required = false) String name, @RequestParam(value = "page", required = false) Integer page, Model model) { if (name == null) { name = ""; } if (page == null) { page = 0; } List<Department> findDepartments = departmentService.findDepartments(name, page); if (findDepartments == null) { return "notFound"; } int pages = departmentService.pageCount(name); model.addAttribute("name", name); model.addAttribute("pages", pages); model.addAttribute("departments", findDepartments); return "deparmentSearchResult"; }
3
public BESong getById(int id) throws SQLException { for (BESong aSong : getAll()) { if (aSong.getId() == id) { return aSong; } } return null; }
2
protected void effect() { if (radius > 1) { for (int x = -radius; x <= radius; ++x) { for (int y = -radius; y <= radius; ++x) { for (int z = -radius; z <= radius; ++z) { Location loc = world.getBlockAt(X + x, Y + y, Z + z).getLocation(); world.playEffect(loc, effect, direction); } } } } else world.playEffect(center, effect, direction); }
4
static void handleUpdate(UpdateSet update) { ArrayList vmUpdates = new ArrayList(); ArrayList hostUpdates = new ArrayList(); PropertyFilterUpdate[] pfus = update.getFilterSet(); for(int i=0; i<pfus.length; i++) { ObjectUpdate[] ous = pfus[i].getObjectSet(); for(int j=0; j<ous.length; ++j) { if(ous[j].getObj().getType().equals("VirtualMachine")) { vmUpdates.add(ous[j]); } else if(ous[j].getObj().getType().equals("HostSystem")) { hostUpdates.add(ous[j]); } } } if(vmUpdates.size() > 0) { System.out.println("Virtual Machine updates:"); for(Iterator vmi = vmUpdates.iterator(); vmi.hasNext();) { handleObjectUpdate((ObjectUpdate)vmi.next()); } } if(hostUpdates.size() > 0) { System.out.println("Host updates:"); for(Iterator vmi = hostUpdates.iterator(); vmi.hasNext();) { handleObjectUpdate((ObjectUpdate)vmi.next()); } } }
8
public Animation getAnim() { Animation anim = null; switch(state) { case IDLE: anim = idleAnimation; break; case WALK: anim = walkAnimation; break; case JUMP: anim = jumpAnimation; break; case FALL: anim = fallAnimation; break; case LAND: anim = landAnimation; break; } if(anim != null) anim.flippedX = spriteFacesRight ? (facing == FacingState.LEFT) : (facing == FacingState.RIGHT); return anim; }
7
public void removeTask(Task task) { if (DEBUG) log("Find the taskWidget that contains the desired task"); TaskWidget target = null; for (TaskWidget tw : taskWidgets) { if (tw.getTask() == task) { target = tw; } } if (target == null) { if (DEBUG) log("Failed to find desired taskWidget"); } else { if (DEBUG) log("Found the desired taskWidget...now just remove it"); taskWidgets.remove(target); unPlannedContent.remove(target); repaint(); } }
6
public Map<String, Object> getAllTypes() { Map<String, Object> types = new HashMap<String, Object>(); // Cr�ation de la requ�te java.sql.Statement query; try { // create connection connection = java.sql.DriverManager.getConnection("jdbc:mysql://" + dB_HOST + ":" + dB_PORT + "/" + dB_NAME, dB_USER, dB_PWD); // Creation de l'�l�ment de requ�te query = connection.createStatement(); // Executer puis parcourir les r�sultats java.sql.ResultSet rs = query .executeQuery("SELECT distinct type FROM Recipe;"); while (rs.next()) { types.put(rs.getString("type"), rs.getString("type")); } rs.close(); query.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } return types; }
2
private static int[][] calculateDistances2(double[][] points,int N) { int[][] distanceMatrix= new int[N][N]; for(int i=0; i<N;i++){ for(int j=0;j<N;j++){ if(j==i){ distanceMatrix[i][j]=0; } else if(i<j){ distanceMatrix[i][j]=distance(points[0][i],points[0][j],points[1][i],points[1][j]); } else {//i>j distanceMatrix[i][j]=distanceMatrix[j][i]; } } } return distanceMatrix; }
4
public Group(GoGame game1) { game = game1; pieces = new HashSet<Piece>(); liberties = new HashSet<Square>(); }
0
public boolean hasPathTo(Node to) { if (edgeTo.containsKey(to)) { return true; } else { return false; } }
1
public static String changeExtension(String a){ int cnt = 0; String tempo = ""; while(cnt < (a.length() - 5)){ tempo = tempo + a.charAt(cnt); cnt++; } tempo = tempo + ".jpg"; return tempo; }
1
static void calculate_sprites_areas() { //UINT8 sx,sy; int[] sx=new int[1]; int[] sy=new int[1]; int i,minx,miny,maxx,maxy; for (i = 0x00; i < 0x20; i++) { if ((i >= 0x10) && (i <= 0x17)) continue; /* no sprites here */ if (get_sprite_xy(i, sx, sy)!=0) { minx = sx[0]; miny = sy[0]; maxx = minx+15; maxy = miny+15; /* check for bitmap bounds to avoid illegal memory access */ if (minx < 0) minx = 0; if (miny < 0) miny = 0; if (maxx >= Machine.drv.screen_width - 1) maxx = Machine.drv.screen_width - 1; if (maxy >= Machine.drv.screen_height - 1) maxy = Machine.drv.screen_height - 1; spritearea[i]=new rectangle(); spritearea[i].min_x = minx; spritearea[i].max_x = maxx; spritearea[i].min_y = miny; spritearea[i].max_y = maxy; spriteon[i] = 1; } else /* sprite is off */ { spriteon[i] = 0; } } }
8
boolean whitelisted(String page, String user, String summary, String project) { if (config.whitelistModel.contains(user + "#" + project) || config.tempwhitelistModel.contains(user + "#" + project)) return (true); else { int size = config.regexpwhiteModel.getSize(), i; for (i = 0; i < size; i++) if ((config.getBooleanProp("rwhiteuser") && user .matches((String) config.regexpwhiteModel.getElementAt(i))) || (config.getBooleanProp("rwhitepage") && page .matches((String) config.regexpwhiteModel.getElementAt(i))) || (config.getBooleanProp("rwhitesummary") && summary .matches((String) config.regexpwhiteModel.getElementAt(i)))) return (true); } return (false); }
9
public static boolean isValid(final List<S2Loop> loops) { // If a loop contains an edge AB, then no other loop may contain AB or BA. // We only need this test if there are at least two loops, assuming that // each loop has already been validated. if (loops.size() > 1) { Map<UndirectedEdge, LoopVertexIndexPair> edges = Maps.newHashMap(); for (int i = 0; i < loops.size(); ++i) { S2Loop lp = loops.get(i); for (int j = 0; j < lp.numVertices(); ++j) { UndirectedEdge key = new UndirectedEdge(lp.vertex(j), lp.vertex(j + 1)); LoopVertexIndexPair value = new LoopVertexIndexPair(i, j); if (edges.containsKey(key)) { LoopVertexIndexPair other = edges.get(key); log.info( "Duplicate edge: loop " + i + ", edge " + j + " and loop " + other.getLoopIndex() + ", edge " + other.getVertexIndex()); return false; } else { edges.put(key, value); } } } } // Verify that no loop covers more than half of the sphere, and that no // two loops cross. for (int i = 0; i < loops.size(); ++i) { if (!loops.get(i).isNormalized()) { log.info("Loop " + i + " encloses more than half the sphere"); return false; } for (int j = i + 1; j < loops.size(); ++j) { // This test not only checks for edge crossings, it also detects // cases where the two boundaries cross at a shared vertex. if (loops.get(i).containsOrCrosses(loops.get(j)) < 0) { log.info("Loop " + i + " crosses loop " + j); return false; } } } return true; }
8
public boolean isBlack() { if (myColor.equals(BLACK)) return true; return false; }
1
public CtMethod[] getMethods() { try { return getSuperclass().getMethods(); } catch (NotFoundException e) { return super.getMethods(); } }
1
private void getTourCollection(List<Direction> directions, AbstractDao dao, Criteria criteria) throws DaoException { for (Direction dir : directions) { Criteria crit = new Criteria(); crit.addParam(DAO_ID_DIRECTION, dir.getIdDirection()); crit.addParam(DAO_TOUR_STATUS, criteria.getParam(DAO_TOUR_STATUS)); crit.addParam(DAO_TOUR_DATE_FROM, criteria.getParam(DAO_TOUR_DATE_FROM)); crit.addParam(DAO_TOUR_DATE_TO, criteria.getParam(DAO_TOUR_DATE_TO)); List<Tour> list = dao.findTours(crit); Tour.DateComparator comparator = new Tour.DateComparator(); Collections.sort(list, comparator); dir.setTourCollection(list); } }
1
public int getWildCardRank() { return wildCardRank; }
0
private void botonAniadirCompraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonAniadirCompraActionPerformed // Esto sólo añade a la lista, NO al map, para que se añada al map se debe guardar DefaultTableModel modeloCompra = ((DefaultTableModel) jTableCompras.getModel()); String articulo = jTextFieldArticulo.getText();//nombre del articulo String idtext = jTextFieldCantidad.getText(); boolean relleno = false; int cantidad = 0; if (!idtext.isEmpty()) { try { cantidad = Integer.parseInt(jTextFieldCantidad.getText()); relleno = true; } catch (NumberFormatException numberFormatException) { relleno = false; } } //el id va a ser autogenerado int id = modeloCompra.getRowCount() + 1; //comprobamos que se ha introducido algo y que la cantidad es positiva if (!articulo.isEmpty() && cantidad > 0 && relleno) { modeloCompra.addRow(new Object[]{id, cantidad, articulo}); } else { JOptionPane.showMessageDialog(this, "Rellena los campos Concepto y Cantidad"); } }//GEN-LAST:event_botonAniadirCompraActionPerformed
5
private void removeHighlight(int start, int end) { Highlighter.Highlight remove = null; for (Highlighter.Highlight h : editor.getHighlighter().getHighlights()) { if (h.getStartOffset() == start && h.getEndOffset() == end) { remove = h; break; } } if (remove != null) editor.getHighlighter().removeHighlight(remove); }
4
int[] loadIntArray() throws IOException { int n = loadInt(); if (n == 0) return NOINTS; // read all data at once int m = n << 2; if (buf.length < m) buf = new byte[m]; is.readFully(buf, 0, m); int[] array = new int[n]; for (int i = 0, j = 0; i < n; ++i, j += 4) array[i] = luacLittleEndian ? (buf[j + 3] << 24) | ((0xff & buf[j + 2]) << 16) | ((0xff & buf[j + 1]) << 8) | (0xff & buf[j + 0]) : (buf[j + 0] << 24) | ((0xff & buf[j + 1]) << 16) | ((0xff & buf[j + 2]) << 8) | (0xff & buf[j + 3]); return array; }
4