method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
5a86ef25-2818-41b9-98aa-f2414699a67d
7
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()); } } } }
9acc4d7a-96c8-432e-90b4-f2474f341358
2
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); } }
3d11a0c4-2ee8-4692-9da2-ff45584161d6
3
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(); } } }
49786937-15f6-4a31-ab22-2f484c05212b
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()]); }
4bee4b4e-8005-49a0-9f82-59d1ddd1f466
9
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); } } }
a72a69fc-d8b4-438c-9108-fa69d2cb1c03
0
protected int getMaxAge() { return MAX_AGE; }
5f9903ea-6838-4130-92ea-6de3a0703c40
2
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; }
acca4422-451f-4dcf-a6bd-feafc5198756
6
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; } }
d6307c8a-4fa0-4aca-939a-8475839f90b6
0
public Knight(boolean isWhite, ImageIcon imgIcon) { super(isWhite, imgIcon); this.setIcon(); }
f2869eb1-9382-4217-95b3-b108be62abe7
4
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(); } } } }
c6ff8d65-7175-4c39-aeb3-6024231df3f5
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; }
39e26fdc-acb3-47c4-adc9-8f1e09905be7
8
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); } } }
346047fe-7240-4bff-9838-be6273c5376e
3
public void run() { while (true) { if (year!=w.year) { year=w.year; } synchronized (this) { repaint(); } try { Thread.sleep(50); } catch (InterruptedException e) { } } }
f9cb7715-4887-41c4-a50c-217d8f8dfdfb
2
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); }
152d44f6-929c-49ef-ba50-472a0cd79b76
7
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(); }
c71de067-d7cd-42e0-ac09-14479b4c8dff
8
@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(); } }
6793f804-f1ec-49b3-8eb8-79452484a155
1
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) {} }
7f30aa79-d44b-41bf-93b1-0a72b24ac333
5
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; }
f5a5892e-2dad-4b5c-8d57-e6ab0b87af1d
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(); }
be07a175-2ba4-4c2a-a5ca-2f44707e7034
2
/* */ @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); /* */ } /* */ }
e3977bfb-084b-49ec-8972-82aefa2976ff
2
public void updateButtons(LinkedList<ClickableObject> selection) { for(ClickableObject selectable : selection) { for(Ability ability : selectable.getAbilities()) { addHability(ability); } } }
abc3145c-87a4-4252-afae-ccbcabdaa366
8
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() ); } }
e86372f3-cb4a-438d-acd6-fec86f6ee2da
1
public void run() { // The following line nullifies timestamp-diff-cache. if (!useTimestampDiffCache){ apicaCommunicator.checkResultTimeStamps.clear(); } apicaCommunicator.populate(metrics); DumpToStdOut(metrics); writeAllMetrics(); metrics.clear(); }
85de4cba-7b70-49a9-a6f5-9a3e0ad2b9a0
0
public void setBlockSheet(int[][] blockSheet) { this.blockSheet = blockSheet; }
81325920-7fc2-4e81-99d3-d45c2cbd862d
8
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; }
16fedbb6-59e7-4f5e-9715-95d2fbe48a5a
7
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; }
b2a5568d-bc6a-4b57-935e-dfebf2f16b1f
4
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); } }
fd56e4c6-0ef9-4627-926b-32b8a5e07d5d
8
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()); } } }
05825bff-6ece-4aed-908c-a33ad393a309
4
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; } } }
b26a1853-177f-4c70-96c8-98426fcd3ed2
8
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; }
4fd8bf35-fbf3-4de8-ba48-eaeab9b554b4
2
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); }
be77bbfe-5039-4382-8514-f6bc04c83a43
5
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; }
54fc5b33-ed22-4349-b3c1-5e44f0d2c3d6
0
public InPackage( String targetPackage ) { this.targetPackage = targetPackage; }
46fe8be3-a1c3-4ddd-b8db-30230c8c00d6
7
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); }
7cd75524-b5e3-4349-89fc-bfd20410b812
1
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; } }
e67df3bf-2da0-4a9f-a337-35b1bde5e0ee
1
public boolean ModificarProducto(Producto p){ if (p!=null) { cx.Modificar(p); return true; }else { return false; } }
0c05016b-22fa-489f-8c6f-876594aa1575
8
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); } }
ecf21487-3051-4c5b-ae7d-0bf7edc9bdad
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()); } }
d84c14dc-fb1f-4722-8ded-224490198264
4
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); } } } }
ceb23474-03dc-42ba-9097-68a5a5b348b4
3
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; }
a11a2200-fcae-4e7c-8fbf-1c186a3b7d72
9
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; }
e0de6413-09cf-4568-a47f-b5119b5ba4e4
7
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; } } }
fe609a62-8a1a-433b-9262-a6631d385edf
2
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(); } } }); }
9cd3e27f-9ddf-4215-836b-c2fca6ee5cfe
7
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; }
2f218a1a-2844-4258-8cf8-08bf3276c069
0
protected void onMode(String channel, String sourceNick, String sourceLogin, String sourceHostname, String mode) {}
7d4526d6-fe51-40af-8281-949d552b9fef
3
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; }
46e1cc85-6738-4605-acff-d52e6af49820
9
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; }
9cabd4a1-1292-4e45-9869-0a6aa276a792
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); } }
72d3ba4f-f512-42f1-8508-e7cfbd86a929
7
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(); }
f7026b15-fab2-4dcf-a49a-5b14e25de320
2
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."); }
151e91c4-75f4-4c29-9fb7-c1ae17c0ca07
0
public void setSkillName(String skillName) { this.skillName = skillName; }
c191429d-787a-4692-bc0a-3c431d94bf35
0
public Serializable getObject() { return theMainObject; }
509fe733-828f-4bab-81d6-795420087c0a
4
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); } }
fd6a92a6-bbc5-45dd-9c8e-16debec97fbb
2
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; }
5ca5ccf8-daf5-49d2-82b7-7e3e7e009a94
4
private void check() { synchronized (ui) { if (tgt && !wrapped.hasfs()) wrapped.setfs(); if (!tgt && wrapped.hasfs()) wrapped.setwnd(); } }
ace50de4-2e5e-4ff4-a050-fbf18019c1d1
6
@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; }
53b13d28-26aa-4ccf-8a5c-72cb90e9a478
8
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(); } }
9ee88142-1b43-4f9b-a76c-7565ffb6542a
9
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(); }
b42d912c-9952-426f-b109-fcea341c51ff
8
@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; }
2aaf11cf-9673-4829-9d88-69ad9d89c1aa
1
public List<ReferenceType> getReference() { if (reference == null) { reference = new ArrayList<ReferenceType>(); } return this.reference; }
151d7ea0-67bc-4e17-b894-217892235c45
7
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
deb00377-1cb6-4ddb-bc7b-a6c0f78a6d6d
3
@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)); }
e8df2c82-88ca-4398-9b26-7362b8f4353f
7
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(); } }); }} }); } }
88aba317-8790-4203-b5b0-00489e36c39b
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; }
30aa7fd0-e3c6-488f-9c98-052d6c896f32
9
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(); }
9d9c6912-7f29-4fe6-a322-75f356d9fa90
7
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(); } }
0dc89219-5948-47f9-a836-1a880a707875
9
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 = ""; }
3e0532df-9e1b-4f84-b274-91d37e6dfd1a
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); } }
c3dd5a49-f5a8-4e11-af7f-a336af02e2be
1
@Override public void stop(int objectId) { AudioChannel channel = channels.get(objectId); if (channel != null) { alSourceStop(channel.source); } }
47ce73b8-d51a-4852-be7e-36175133872e
0
public boolean isCompleted() { return PeerState.COMPLETED.equals(this.state); }
9871ffae-9147-4622-b73f-27739a3abf4e
6
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; } }
b805d922-dd41-4d41-bb87-7d2b0aecc27e
7
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; } }
2421a97a-6bcf-48de-9559-6324ffd5e4a3
4
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; }
f84827bf-29cd-4552-aacb-ef6fc687da90
5
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; }
8d1eff9d-f307-4f17-b360-17139ff2678c
9
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()]); }
a796205b-79ed-40c4-9603-c474d2cba98b
3
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; }
fc389317-a5fe-4206-898a-206061367b17
7
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; }
0c1b8fa6-e85b-47f4-913a-ba625ba79009
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();
a8ff1466-2a7c-43fe-b622-0b01d43c5a2a
9
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; } }
1fafa232-fd82-472f-8516-93bb7df3773c
3
@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"; }
5eba6e57-5c6a-480b-8a33-6085fd4c2301
2
public BESong getById(int id) throws SQLException { for (BESong aSong : getAll()) { if (aSong.getId() == id) { return aSong; } } return null; }
87885972-0189-41bd-a39e-51e1554315e6
4
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); }
bbcfed59-74b2-4ad5-84f5-415102da36ff
8
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()); } } }
a65fefc6-3fc0-4010-ae90-496a37e01401
7
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; }
db1d76fa-a096-42b2-b445-81c45a807413
6
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(); } }
82f5451a-4989-46ae-948e-b5e605026e48
2
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; }
22ea4afa-70be-4317-9d10-170ea60091fa
4
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; }
76a8c60d-e759-41ba-95ce-d6aa8389e862
0
public Group(GoGame game1) { game = game1; pieces = new HashSet<Piece>(); liberties = new HashSet<Square>(); }
e9ff414d-44c0-4fa9-985f-e0869e927ac3
1
public boolean hasPathTo(Node to) { if (edgeTo.containsKey(to)) { return true; } else { return false; } }
7dc65ad9-cd62-43da-8faf-5824634106f4
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; }
20fa9450-6270-49ca-8f64-6a885a05b067
8
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; } } }
bff316ee-3dd9-4c15-bf76-dd9f87386c8a
9
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); }
651f1c39-0c42-4995-aec4-8e1fa57ef045
8
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; }
96693ad1-9d32-44fd-be69-2cbe96d5573e
1
public boolean isBlack() { if (myColor.equals(BLACK)) return true; return false; }
d29ddbe8-e597-4add-a54d-9d9f1d3bc3a0
1
public CtMethod[] getMethods() { try { return getSuperclass().getMethods(); } catch (NotFoundException e) { return super.getMethods(); } }
e7e4327a-6ddb-436c-91a6-76bf4002adf2
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); } }
fc324eed-9b32-4737-b710-47378e43dca8
0
public int getWildCardRank() { return wildCardRank; }
28cf5ffb-9445-41de-8ea1-e9c0edadaf60
5
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
26d3bd03-058e-4b74-9389-79a35cbacbb0
4
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); }
a5330a4c-112b-4cd4-88e1-901b0f9e5821
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; }