method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
70ca726a-80f0-4c60-9e63-15b6f6a6ce0f
6
private void addTargetControlsToPanel(JPanel panel, final IntValueHolder targetTypeValueSource, final IntValueHolder targetNumberValueSource) { Integer validTargetTypes[] = Event_3_46.getTargetTypes(); Integer targetTypes[] = new Integer[validTargetTypes.length + 1]; targetTypes[0] = new Integer(Integer.MIN_VALUE); for (int index = 0; index < validTargetTypes.length; ++index) { targetTypes[1 + index] = validTargetTypes[index]; } final JComboBox targetTypeList = new JComboBox(targetTypes); targetTypeList.setSelectedItem(new Integer(targetTypeValueSource.getValue())); final JFormattedTextField targetTypeTextField = new JFormattedTextField(new Integer(targetTypeValueSource.getValue())); targetTypeTextField.setColumns(3); if (0 == targetTypeList.getSelectedIndex()) { targetTypeTextField.setEnabled(true); } else { targetTypeTextField.setEnabled(false); } ListCellRenderer targetTypeRenderer = new AbstractStringListCellRenderer() { protected String getStringForValue(Object value) { Integer valueNumber = (Integer)value; if ((null == valueNumber) || (Integer.MIN_VALUE == valueNumber.intValue())) return "UNKNOWN"; return Event_3_46.getTargetTypeName(valueNumber.intValue()); } }; targetTypeList.setRenderer(targetTypeRenderer); targetTypeList.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Object selectedItem = ((JComboBox)e.getSource()).getSelectedItem(); int value; if (null == selectedItem) value = Integer.MIN_VALUE; else value = ((Number)selectedItem).intValue(); if (Integer.MIN_VALUE == value) { targetTypeTextField.setEnabled(true); targetTypeValueSource.setValue(((Number)targetTypeTextField.getValue()).intValue()); return; } targetTypeTextField.setEnabled(false); targetTypeValueSource.setValue(value); targetTypeTextField.setValue(new Integer(targetTypeValueSource.getValue())); } } ); targetTypeTextField.addPropertyChangeListener("value", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { targetTypeValueSource.setValue(((Number)((JFormattedTextField)e.getSource()).getValue()).intValue()); targetTypeList.setSelectedItem(null); targetTypeList.setSelectedItem(new Integer(targetTypeValueSource.getValue())); } }); JFormattedTextField targetNumberTextField = new JFormattedTextField(new Integer(targetNumberValueSource.getValue())); targetNumberTextField.setColumns(5); targetNumberTextField.addPropertyChangeListener("value", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { targetNumberValueSource.setValue(((Number)((JFormattedTextField)e.getSource()).getValue()).intValue()); } }); panel.add(targetTypeList); panel.add(targetTypeTextField); panel.add(targetNumberTextField); }
e8ccbe1c-3797-408a-bad0-d7324deb6c9d
2
public boolean hasRelWithSubsection(int question_ID) { boolean hasRel=false; try { StringBuffer sql = new StringBuffer(); sql.append("select Subsection_ID "); sql.append("from subsectionquestion_ID "); sql.append("where Question_ID=" + question_ID); SQLHelper sQLHelper = new SQLHelper(); sQLHelper.sqlConnect(); ResultSet rs = sQLHelper.runQuery(sql.toString()); if (rs.next()) { hasRel=true; } } catch (SQLException ex) { Logger.getLogger(Question_DAO.class.getName()).log(Level.SEVERE, null, ex); } return hasRel; }
fb9d6c4a-bfc4-4b0f-858a-e23cbd48b319
8
public String toString() { StringBuffer sb = new StringBuffer(); // balanced or ordinary OSDL if (m_balanced) { sb.append("Balanced OSDL\n=============\n\n"); } else { sb.append("Ordinary OSDL\n=============\n\n"); } if (m_weighted) { sb.append("Weighted variant\n"); } // classification type used sb.append("Classification type: " + getClassificationType() + "\n"); // parameter s if (!m_weighted) { sb.append("Interpolation parameter: " + m_s + "\n"); if (m_tuneInterpolationParameter) { sb.append("Bounds and stepsize: " + m_sLower + " " + m_sUpper + " " + m_sNrParts + "\n"); if (!m_interpolationParameterValid) { sb.append("Interpolation parameter is not valid"); } } } if(m_Debug) { if (m_estimatedCumulativeDistributions != null) { /* * Cycle through all the map of cumulative distribution functions * and print each cumulative distribution function */ for (Iterator i = m_estimatedCumulativeDistributions.keySet().iterator(); i.hasNext(); ) { Coordinates yc = (Coordinates) i.next(); CumulativeDiscreteDistribution cdf = (CumulativeDiscreteDistribution) m_estimatedCumulativeDistributions.get(yc); sb.append( "[" + yc.hashCode() + "] " + yc.toString() + " --> " + cdf.toString() + "\n"); } } } return sb.toString(); }
971c7cf0-08a6-4503-a992-c96c71c401b4
1
public String getValue(String key) { if(containsKey(key)) { return getKeyValuePair(key).getValue(); } else { return null; } }
ead1fe7c-1217-44b8-9f26-4ec9bac86929
5
private void transmitText(String text) { if (byteJRadioButton.isSelected()) { boolean ready = false; Scanner scanner = new Scanner(text); while (! ready) { try { outputStream.write(scanner.nextInt()); } catch (NoSuchElementException e) { ready = true; } catch (IOException e) { JOptionPane.showMessageDialog(this, e.toString(), "Port error", JOptionPane.ERROR_MESSAGE); ready = true; } } } else { try { text += CR; outputStream.write(text.getBytes()); sendText.setText(""); } catch (Throwable t) { System.out.println(t); JOptionPane.showMessageDialog(this, t.toString(), "Port error", JOptionPane.ERROR_MESSAGE); } } }
c3926112-7ab5-4b82-885d-e3475ba30707
5
public double mean_as_double() { double mean = 0.0D; switch (type) { case 1: double[] dd = this.getArray_as_double(); for (int i = 0; i < length; i++) { mean += dd[i]; } mean /= length; break; case 12: BigDecimal[] bd = this.getArray_as_BigDecimal(); BigDecimal meanbd = BigDecimal.ZERO; for (int i = 0; i < length; i++) meanbd = meanbd.add(bd[i]); meanbd = meanbd.divide(new BigDecimal((double) length), BigDecimal.ROUND_HALF_UP); mean = meanbd.doubleValue(); bd = null; meanbd = null; break; case 14: throw new IllegalArgumentException("Complex cannot be converted to double"); default: throw new IllegalArgumentException("This type number, " + type + ", should not be possible here!!!!"); } return mean; }
b7eb7798-3da0-46b0-892a-ccf730303674
3
private boolean whiteCanEnPassantLeft( int position ) { return ( this.previousMove != null && pieceTypeAt( position - 1 ) == PAWN && this.previousMove.from() == ( position + 31 ) ) && this.previousMove.to() == ( position - 1 ); }
e669e1d3-c843-440e-acdd-e52b374a5052
2
private static void enchantedBag() { System.out.println("enchantedBag"); for (int i = 0; i < enchantedBag.length; ++i) { if (enchantedBag[i] != null) { System.out.println(i + ":" + enchantedBag[i]); } } }
326fdd6e-1399-4ed7-a55f-44791731ef3e
1
private boolean isRed(Node node) { if (node == null) return false; return node.color == RED; }
9190c09a-2649-49bf-8ffa-16149bde39e0
8
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { final Item target=getTarget(mob,null,givenTarget,commands,Wearable.FILTER_ANY); if(target==null) return false; if(!target.subjectToWearAndTear()) { mob.tell(L("@x1 cannot be reinforced.",target.name(mob))); return false;} else if(target.usesRemaining()<100) { mob.tell(L("@x1 must be repaired before it can be reinforced.",target.name(mob))); return false;} if(!super.invoke(mob,commands, givenTarget, auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,(((mob.phyStats().level()+(2*getXLEVELLevel(mob)))-target.phyStats().level())*5),auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto), (auto?"<T-NAME> begins to shimmer!" :"^S<S-NAME> incant(s) at <T-NAMESELF>!^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); if(target.usesRemaining()>=150) mob.tell(L("@x1 cannot be reinforced further.",target.name(mob))); else { mob.location().show(mob,target,CMMsg.MSG_OK_VISUAL,L("<T-NAME> begin(s) to glow and harden!")); target.setUsesRemaining(target.usesRemaining()+50); target.recoverPhyStats(); mob.location().recoverRoomStats(); } } } else beneficialWordsFizzle(mob,target,L("<S-NAME> incant(s) at <T-NAMESELF>, but nothing happens.")); // return whether it worked return success; }
2a81552e-14ab-4613-a811-392951b30281
3
@Override public boolean logoutClient(final String name) throws RemoteException { ServerManager.invokeLater(new Runnable() { @Override public void run() { _connectedClients.remove(name); _spiel.meldeSpielerAb(name); if(name.equals(_hostName)) { for(ClientInterface client : _connectedClients.values()) { try { client.serverBeendet(); } catch(RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } } beendeServer(); } //if(_connectedClients.isEmpty()) // beendeServer(); } }); return true; }
5d6959ef-d8e7-4d64-8df2-4dc0c13e72bf
8
public void build() { FileConfiguration fc = new YamlConfiguration(); File f = new File(plugin.getDataFolder(), "custom.yml"); if (f.exists()) { try { fc.load(f); } catch (Exception e) { if (plugin.getDebug()) plugin.log.warning(e.getMessage()); } } for (String name : fc.getKeys(false)) { ConfigurationSection cs = fc.getConfigurationSection(name); Material mat = Material.matchMaterial(cs.getString("Material")); ChatColor color = ChatColor.valueOf(cs.getString("Color") .toUpperCase()); List<String> lore = cs.getStringList("Lore"); ItemStack tool = new ItemStack(mat); List<String> list = new ArrayList<String>(); for (String s : lore) { list.add(ChatColor.translateAlternateColorCodes( "&".toCharArray()[0], s)); } ConfigurationSection cs1 = cs .getConfigurationSection("Enchantments"); if (cs1 != null) { for (String ench : cs1.getKeys(false)) { Enchantment encha = Enchantment.getByName(ench .toUpperCase()); if (encha == null) continue; tool.addUnsafeEnchantment(encha, cs1.getInt(ench)); } } ItemMeta meta = tool.getItemMeta(); meta.setDisplayName(color + name); meta.setLore(list); tool.setItemMeta(meta); plugin.custom.add(tool); } }
b2f38c54-07e7-4710-a5a3-0606791bf8bb
7
@Override public int[] getInts(int par1, int par2, int par3, int par4) { int[] aint = this.biomePatternGeneratorChain.getInts(par1, par2, par3, par4); int[] aint1 = this.riverPatternGeneratorChain.getInts(par1, par2, par3, par4); int[] aint2 = IntCache.getIntCache(par3 * par4); for (int i1 = 0; i1 < par3 * par4; ++i1) { if (aint[i1] != BiomeGenBase.ocean.biomeID && aint[i1] != BiomeGenBase.deepOcean.biomeID) { if (aint1[i1] == BiomeGenBase.river.biomeID) { if (aint[i1] == BiomeGenBase.icePlains.biomeID) { aint2[i1] = BiomeGenBase.frozenRiver.biomeID; } else if (aint[i1] != BiomeGenBase.mushroomIsland.biomeID && aint[i1] != BiomeGenBase.mushroomIslandShore.biomeID) { aint2[i1] = aint1[i1] & 255; } else { aint2[i1] = BiomeGenBase.mushroomIslandShore.biomeID; } } else { aint2[i1] = aint[i1]; } } else { aint2[i1] = aint[i1]; } } return aint2; }
5490c5a4-c103-4f61-b665-b9be4cf8993c
3
static double[] spawnAveragesArrayFromPricePair(String ticker, int neighborsToCount) { double[] priceData = spawnTimeSeriesForFFT(ticker); double[] avgPriceData = new double[priceData.length]; for (int J = neighborsToCount; J < (priceData.length - neighborsToCount); J++) { float sum = 0; int n = 0; for (int L = J - neighborsToCount; L <= J + 1 + 2 * neighborsToCount && L < priceData.length; L++) { n++; sum += priceData[L]; } float average = sum / n; avgPriceData[(J)] = average; } return avgPriceData; }
5cdd26c1-6238-4a5d-a7e3-00c3c3b59b55
5
public void drawEntitiesOnMap(Renderer r) { Graphics g = r.getGraphics(); for (EntityXML e : entities) { if (e.getPos().x >= mapDisplayStart.x && e.getPos().x < mapDisplayStart.x + MAP_DISPLAY_NB_TILE_X && e.getPos().y >= mapDisplayStart.y && e.getPos().y < mapDisplayStart.y + MAP_DISPLAY_NB_TILE_Y) { int x = e.getPos().x - mapDisplayStart.x; int y = e.getPos().y - mapDisplayStart.y; g.setColor(new Color(0,0,0, 0.75f)); g.fillRect(boxMap.x + x * Tile.SIZE,boxMap.y + y * Tile.SIZE, Tile.SIZE, Tile.SIZE); g.setColor(new Color(255,255,255)); r.drawCenteredText(e.getEnemyType().toString().substring(0, 2), boxMap.x + x * Tile.SIZE, boxMap.y + y * Tile.SIZE + 6, Tile.SIZE); } } }
9c789292-7103-40d3-9bbe-ac39d8d62708
5
public static void dump(File f) throws IOException { try (BTXParser p = new BTXParser(f)) { String indent = ""; l: while (true) { switch (p.next()) { case ATTRIBUTE : { BTXAttribute at = p.getEventData().getAttribute(); byte[] buf = new byte[at.getLength()]; at.fill(buf); System.out.println(indent + at.getName() + "=" + new String(buf)); break; } case END_OBJECT : indent = indent.substring(2); break; case EOF : break l; case START_OBJECT : System.out.println(indent + p.getEventData().objName); indent += " "; break; default : break; } } } }
101859ca-622c-4ae1-8a9e-5052dbbea311
1
public final int getInt(int index) throws JSONException { Object o = get(index); return o instanceof Number ? ((Number)o).intValue() : (int)getDouble(index); }
766f3948-119c-42b6-81b4-5e8b3bb5c1b6
1
@Override public void run() { if(Thread.currentThread().getId() % 2 == 0) init("Achtung Die Kurve"); else init("TicTacToe"); }
2a25d691-2cc1-458f-bc68-218790489456
9
public static String getSeptaServiceID() { String servid = null; String strDateFormat = "EEEE"; SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat); sdf.setTimeZone(TimeZone.getTimeZone("America/New_York")); String weekday = sdf.format(date); Format formatter; String s; // TODO check cal date for exceptions Boolean reverse; String myHours; formatter = new SimpleDateFormat("hh:mm:ss"); s = formatter.format(date); String[] tokens = s.split(":"); // Making sure that the right service day comes up myHours = tokens[0]; if (myHours.equals("24") || myHours.equals("25") || myHours.equals("26")) { reverse = true; } else { reverse = false; } weekday = weekday.trim(); if (weekday.equals("Sunday")) { if (reverse == false) { servid = "S3"; } else { servid = "S2"; } } else if (weekday.equalsIgnoreCase("Saturday")) { if (reverse == false) { servid = "S2"; } else { servid = "S1"; // Log.d("NOOOO",weekday + "-" + reverse.toString() + "-" + // myHours.toString()); } } else if (weekday.equals("Monday")) { if (reverse == false) { servid = "S1"; } else { servid = "S3"; } } else { servid = "S1"; // Log.d("NOOOO",weekday + "-" + reverse.toString()); } return servid; }
b537c1ac-19f2-4c47-9fea-fd7b6e49509a
5
public void random(){ if(leafNode != null){ this.randomNumber = (int)(Math.random()*RANDOM_SINCOS); }else{ this.randomNumber = (int)(Math.random()*RANDOM_XY+RANDOM_SINCOS); } if(this.randomNumber == 0){ this.textFunction = "sin(PI*x*"; }else if(this.randomNumber ==1){ this.textFunction = "cos(PI*y*"; }else if(this.randomNumber ==2){ this.textFunction = "abs(PI*"; }else if(this.randomNumber ==3){ this.textFunction = "x"; }else{ this.textFunction = "y"; } }
858bbb99-bae9-4e81-91c3-db176da7d0a7
1
private void bootToRecoveryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bootToRecoveryButtonActionPerformed try { device.reboot(DeviceState.RECOVERY); adbController.executeADBCommand(false, false, device, new String[]{"wait-for-device"}); } catch (IOException | InvalidModeException ex) { logger.log(Level.ERROR, "An error occurred while rebooting the device (" + device.toString() + "): " + ex.toString() + "\n" + "The error stack trace will be printed to the console..."); ex.printStackTrace(System.err); } }//GEN-LAST:event_bootToRecoveryButtonActionPerformed
f6d82537-bfec-4803-ae8a-a112ef35c913
3
public Point[] getCorners() { Point[] corners = new Point[4]; switch(orientation) { case X_AXIS: corners[0] = center.add(new Point(0, 0.5f, 0.5f, 1)); corners[1] = center.add(new Point(0, 0.5f, -0.5f, 1)); corners[2] = center.add(new Point(0, -0.5f, -0.5f, 1)); corners[3] = center.add(new Point(0, -0.5f, 0.5f, 1)); return corners; case Y_AXIS: corners[0] = center.add(new Point(0.5f, 0, 0.5f, 1)); corners[1] = center.add(new Point(0.5f, 0, -0.5f, 1)); corners[2] = center.add(new Point(-0.5f, 0, -0.5f, 1)); corners[3] = center.add(new Point(-0.5f, 0, 0.5f, 1)); return corners; case Z_AXIS: corners[0] = center.add(new Point(0.5f, 0.5f, 0, 1)); corners[1] = center.add(new Point(0.5f, -0.5f, 0, 1)); corners[2] = center.add(new Point(-0.5f, -0.5f, 0, 1)); corners[3] = center.add(new Point(-0.5f, 0.5f, 0, 1)); return corners; } return null; }
9c54ad91-eef4-479a-b888-31e3d7b1e12e
6
static public boolean hasImageFileExtension(File cl_f) { String lstr_ext = getFileExtension(cl_f); lstr_ext = lstr_ext.toLowerCase(); if (lstr_ext.equals("jpg") || lstr_ext.equals("jpeg") || lstr_ext.equals("png") || lstr_ext.equals("bmp") || lstr_ext.equals("tga") || lstr_ext.equals("gif")) { return true; } return false; }
8dac3309-cc61-443b-9082-b574bfa2905a
3
public void loadPlayers() throws BadConfigFormatException { //This needs way way way more error checking try { FileReader reader = new FileReader("people.txt"); Scanner in = new Scanner(reader); // set a marker that is true only for the first line boolean marker = true; // loop through all the lines while (in.hasNextLine()) { String line = in.nextLine(); String[] parts = line.split(","); // get the different fields from the file, could do some error checking here. String name = parts[0]; String color = parts[1]; String rowStr = parts[2]; String colStr = parts[3]; // turn the row and col strings into a walkway cell int col = Integer.parseInt(colStr); int row = Integer.parseInt(rowStr); BoardCell location = (BoardCell)board.getCellAt(board.calcIndex(row, col)); // if its the first person, initialize the human player if (marker) { Player human = new HumanPlayer(name, color, location); players.add(human); marker = false; } // otherwise initialize a computer player else { Player computer = new ComputerPlayer(name, color, location); players.add(computer); } } } catch(FileNotFoundException e) { System.out.println(e.getMessage()); } }
2fe09485-2fca-4865-ae1f-d1d335c9edd4
3
public void registerValueVisitor(Class<?> targetClass, ValueVisitor visitor) { if (visitors == null) { visitors = new HashMap<Class<?>, ValueVisitor>(4); } visitors.put(targetClass, visitor); }
aad520e1-fab9-44d6-af8d-1bd2d312e9a8
1
@Override protected void processFocusEvent(FocusEvent event) { super.processFocusEvent(event); if (event.getID() == FocusEvent.FOCUS_GAINED) { selectAll(); } }
12bae2af-451c-46e7-8e75-545ca3f8379c
5
public AnimatedSprite getAnimatedSprite(String imageURL, int rows, int columns) { /*Get the animated sprite (load it if nescessary)*/ AnimatedSprite sprite = sprites.get(imageURL); if(sprite == null) { BufferedImage image = getTransparentImage(imageURL); if(image == null) { System.err.println("Breakout: Could not load sprite sheet\n"); return null; } BufferedImage[] images = new BufferedImage[rows * columns]; int count = 0; for(int i = 0; i < rows; i++) { for(int j = 0; j < columns; j++) { if(!imageURL.endsWith("BORDER.bmp")) { images[count] = image.getSubimage(j * image.getWidth() / columns, i * image.getHeight() / rows, image.getWidth() / columns, image.getHeight() / rows ); } else { images[count] = image.getSubimage(j * image.getWidth() / columns + 1, i * image.getHeight() / rows + 1, image.getWidth() / columns - (columns + 1), image.getHeight() / rows - (rows + 1) ); } //images[count] = image; //BufferedImage img = new BufferedImage(images[count].getWidth(), images[count].getHeight(), BufferedImage.TYPE_INT_ARGB); //img.setData(images[count].getData()); //images[count] = img; //System.out.println(images[count].getType()); //images[count] = new BufferedImage() //images[count] = Transparency.makeColorTransparent(ImageCache.ImageToBufferedImage(BufferedImage., images[count].getWidth(), images[count].getHeight()), new Color(TRANS_RED, TRANS_GREEN, TRANS_BLUE)); count++; } } sprite = new AnimatedSprite(images, rows * columns); sprites.put(imageURL, sprite); } return sprite; /*BufferedImage image = getTransparentImage(imageURL); ImageProducer source = image.getSource(); Image crop_image; for(int i = 0; i < rows; i++) { for(int j = 0; j < columns; j++) { sprites[i] = image.getSubimage(j * image.getWidth(), i * image.getHeight(), image.getWidth(), image.getHeight()); ImageFilter extractFilter = new CropImageFilter(j * image.getWidth(), i * image.getHeight(), image.getWidth(), image.getHeight()); ImageProducer producer = new FilteredImageSource(source,extractFilter); crop_image = Toolkit.getDefaultToolkit().createImage(producer); sprites[i] = ImageToBufferedImage(crop_image, crop_image.getWidth(null), crop_image.getHeight(null)); } }*/ }
8947528e-08d6-48d8-8352-25eccbe9c76f
0
private void jCheckBoxQuitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxQuitActionPerformed //Récupération de la méthode contrôleur 'close' this.getCtrlM().close(); }//GEN-LAST:event_jCheckBoxQuitActionPerformed
367e98e3-b726-4ac1-9f6e-588b5040f3d6
8
public Date ceil(Date date, int field) { Calendar cal = Calendar.getInstance(); cal.setTime(date); for (int currentField : fields) { if (currentField > field) { if (currentField == Calendar.DAY_OF_MONTH && (field == Calendar.WEEK_OF_MONTH || field == Calendar.WEEK_OF_YEAR)) { continue; } cal.set(currentField, cal.getActualMaximum(currentField)); } } if (field == Calendar.WEEK_OF_MONTH || field == Calendar.WEEK_OF_YEAR) { if (cal.getFirstDayOfWeek() == Calendar.MONDAY) { cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); cal.add(Calendar.DAY_OF_WEEK, 6); } } return cal.getTime(); }
b3e4fb68-7d29-493a-b811-3dd6adb8ce30
3
public static void main(String[] args){ Date now = new Date(); LinkedList<Room> rooms = new LinkedList<Room>(); rooms.add(new Room("chilloutRoom",Property.Dim,Property.Private,Property.Sitting)); rooms.add(new Room("officeRoom",Property.Bright,Property.Public,Property.Sitting)); Constraint c = new Constraint(); c.constrain(Property.Bright); c.constrain(Property.Public); c.constrainStart(new Date(now.getTime()+10*60*1000)); //in ten minutes c.constrainDuration(60*15); //15minutes c.constrainEnd(new Date(now.getTime()+26*60*1000)); //in 26 minutes HashMap<Room,LinkedList<Booking>> possibleBookings = new HashMap<Room, LinkedList<Booking>>(); for(Room r : rooms){ possibleBookings.put(r,r.getPossibleBookings(c)); System.out.println(r.toString()+possibleBookings.get(r).toString()); System.out.println("book them!"); for(Booking b : possibleBookings.get(r)){ b.book(); } } System.out.println("check whats still free:"); for(Room r : rooms){ possibleBookings.put(r,r.getPossibleBookings(c)); System.out.println(possibleBookings.get(r)); } }
18990993-f446-46cc-a430-3d85eee500e5
6
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed try { //cargo Parametros del Reporte generarTabla(); Map parametros = new HashMap(); parametros.put("name_empresa", r_con.getRazon_social()); parametros.put("desde", campoFecha.getText()); parametros.put("hasta", campoFecha1.getText()); //localizo el reporte para usarlo JasperReport report = JasperCompileManager.compileReport("src/Reportes/"+nombre_reporte); r_con.Connection(); //cargo los datos JasperPrint print = JasperFillManager.fillReport(report, parametros, r_con.getConn()); System.out.println(print.getPages().size()); //vector con las impresoras del modulo de la base de datos Vector<Vector<String>>v = r_con.getContenidoTabla("SELECT * FROM impresoras WHERE imp_id_modulo = "+id_modulo_imp); //total impresoras disponibles PrintService [] impresoras = PrintServiceLookup.lookupPrintServices(null, null); //vector con las impresoras del modulo como objeto impresora (PrintService) Vector<PrintService>impresoras_modulo = new Vector(); //objeto impresora en el que se imprime PrintService impresora = null; if (v.size()>0){ String nombre_imp; //caso en que haya mas de una impresora por modulo if (v.size()>=1){ //localizo con el simple nombre de la base de dato, el objeto impresora y los cargo for (int i = 0; i < v.size(); i++) { nombre_imp=v.elementAt(i).firstElement(); AttributeSet aset = new HashAttributeSet(); aset.add(new PrinterName(nombre_imp, null)); impresoras = PrintServiceLookup.lookupPrintServices(null, aset); impresora = impresoras[0]; impresoras_modulo.add(impresora); } //paso las impresoras del modulo a un arreglo para poder mostrarlo en el Dialog PrintService [] listado_impresoras = new PrintService[impresoras_modulo.size()]; for (int i = 0; i < impresoras_modulo.size(); i++) { listado_impresoras[i]=impresoras_modulo.elementAt(i); } //muestro el listado de impresoras como objeto y se la asigno a la impresora a imprimir impresora = (PrintService) JOptionPane.showInputDialog(null, "Seleccione una impresora asignada a este módulo:", "Imprimir Reporte", JOptionPane.QUESTION_MESSAGE, null, listado_impresoras, listado_impresoras[0]); } //mando a imprimir el reporte en la impresora if (impresora != null){ JRPrintServiceExporter jrprintServiceExporter = new JRPrintServiceExporter(); jrprintServiceExporter.setParameter(JRExporterParameter.JASPER_PRINT, print ); jrprintServiceExporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE, impresora ); jrprintServiceExporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG, Boolean.TRUE); jrprintServiceExporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, Boolean.FALSE); jrprintServiceExporter.exportReport(); } } else{ JOptionPane.showMessageDialog(null, "No hay Impresoras asignadas a este Modulo, " + "\npóngase en contacto con el Administrador de Impresoras.","Atención",JOptionPane.WARNING_MESSAGE); } r_con.cierraConexion(); } catch (JRException ex) { r_con.cierraConexion(); Logger.getLogger(GUI_Imprimir_Mayor.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButton3ActionPerformed
0f589288-5c79-46f7-bb11-8f65dab35e18
8
public ImageConfig getCurrentConfig(SurfaceSelection selection) { Node ancestor = selection.getSelection().getRange().getCommonAncestorContainer(); if (ancestor != null && ancestor.getNodeType() == Node.ELEMENT_NODE) { ImageElement img = (ImageElement) DOMUtil.getFirstChildOfType((Element) ancestor, "img"); if (img != null) { ImageConfig config = new ImageConfig(img.getSrc()); try { if (img.getStyle().getWidth() != null && !img.getStyle().getWidth().isEmpty()) { String width = img.getStyle().getWidth().replaceAll("px", ""); config.setWidth(Integer.parseInt(width)); } if (img.getStyle().getHeight() != null && !img.getStyle().getHeight().isEmpty()) { String height = img.getStyle().getHeight().replaceAll("px", ""); config.setHeight(Integer.parseInt(height)); } } catch (NumberFormatException nfe) { GWT.log("Error while retrieving img size", nfe); } return config; } } return null; }
eb4cbeb8-a826-4792-b79c-d09e9322ac27
1
private static String convertParameter(Object parameter) { if (QueryBuilder.isBsonPrimitives(parameter.getClass())) { return convertWithDriver(parameter); } String message = "无法将非BSON基本类型(non-bson-primitive)参数[" + parameter + "]绑定到查询json字符串中"; throw new IllegalMongoShellException(message); }
36a28d1a-6fec-418d-a45b-2c8e16d28582
2
public Exon queryExon(Marker interval) { for (Exon ei : this) if (ei.intersects(interval)) return ei; return null; }
c5ba8ece-08f2-4610-9655-ab847da1cd73
3
private synchronized void insert(Packet np, double time) { if ( timeList.isEmpty() ) { timeList.add( new Double(time) ); pktList.add(np); return; } for (int i = 0; i < timeList.size(); i++) { double next = ( (Double) timeList.get(i) ).doubleValue(); if (next > time) { timeList.add(i, new Double(time)); pktList.add(i, np); return; } } // add to end timeList.add( new Double(time) ); pktList.add(np); return; }
60f6b761-8713-4db7-8157-c83852978e34
3
public void crossing(ArrayList<Solve> population) { ArrayList<Integer> tmp = new ArrayList(); Random rand = new Random(); int ind1, ind2; for (int i = 0; i < populationsize; i++) { tmp.add(i); } int k = populationsize; while (k >= 2) { ind1 = getNum(tmp, k); k--; ind2 = getNum(tmp, k); k--; if (rand.nextDouble() < crossingindex) { //c.newSolve(population.get(ind1), population.get(ind2)); newSolve(population, ind1, ind2); //population.add(c); //populationsize++; } } }
1c2b1746-62b1-44d7-b759-4be03b01849c
4
@SuppressWarnings("unchecked") public <T extends Object> T createProxyWithType(Class<T> Interface, InvocationHandler handler, Class<?> TYPE){ if(Interface.isInterface() == false || TYPE.isInterface() == false) throw new RuntimeException("Class is not an Interface"); ClassLoader sysLoader = ClassLoader.getSystemClassLoader(); Class<?>[] Interfaces = new Class[]{ Interface, TYPE }; return (T) Proxy.newProxyInstance(sysLoader, Interfaces, handler); }
93410323-0e8f-454e-a0e7-748fd1f9685d
9
private void jump(int S) { jumps.clear(); jumps.push(S); while (!jumps.isEmpty()) { if (getWinner() != null) { return; } int nxt = jumps.pop(); if (getSquare(nxt).spots() > neighbors(nxt)) { getSquare(nxt).setSpots(getSquare(nxt).spots() - neighbors(nxt)); if (exists(nxt - size())) { addSpot(whoseMove(), nxt - size()); jumps.push(nxt - size()); } if (exists(nxt - 1) && nxt % size() != 0) { addSpot(whoseMove(), nxt - 1); jumps.push(nxt - 1); } if (exists(nxt + 1) && (nxt + 1) % size() != 0) { addSpot(whoseMove(), nxt + 1); jumps.push(nxt + 1); } if (exists(nxt + size())) { addSpot(whoseMove(), nxt + size()); jumps.push(nxt + size()); } } } }
6ed59a11-9ebc-4e2d-9252-0a8961971b01
8
public LevelOneQueue(Integer maxSize) { queue = new PriorityQueue<Aircraft>(100, new Comparator<Aircraft>() { @Override public int compare(Aircraft x, Aircraft y) { if( x == null || y == null ) { throw new IllegalArgumentException(""); } //Default to having max fuel (closest to "infinite" as reasonable) //This will move Unfuelled aircraft to the back of the queue int x_fuel = Integer.MAX_VALUE; int y_fuel = Integer.MAX_VALUE; //If the aircraft is a Fuelled Aircraft, it will have its own fuel level if ( x instanceof FuelledAircraft ) { x_fuel = ((FuelledAircraft) x).getFuelRemaining(); } if ( y instanceof FuelledAircraft ) { y_fuel = ((FuelledAircraft) x).getFuelRemaining(); } // Assume neither string is null. Real code should // probably be more robust if (x_fuel < y_fuel) { return -1; } if (x_fuel > y_fuel) { return 1; } return 0; } } ); if(maxSize == null) { throw new IllegalArgumentException("You must provide a maximum size for the queue."); } if(maxSize == 0) { this.maxSize = Integer.MAX_VALUE; } else { this.maxSize = maxSize; } }
50046615-3bca-471a-8acd-d899a1114778
7
private ConcurrentLinkedDeque<String> merge(ConcurrentLinkedDeque<String> left, ConcurrentLinkedDeque<String> right) { ConcurrentLinkedDeque<String> result = new ConcurrentLinkedDeque<String>(); while (left.size() > 0 || right.size() > 0) { if (left.size() > 0 && right.size() > 0) { if (left.peek().compareTo(right.peek()) <= 0) { result.addLast(left.remove()); } else { result.addLast(right.remove()); } } else if (left.size() > 0) { result.addLast(left.remove()); } else if (right.size() > 0) { result.addLast(right.remove()); } } return result; }
d4ecbd58-4c73-4b7a-ae42-39bd7ff50bc2
3
private int compileShader(String source, int type) { int shader = glCreateShader(type); glShaderSource(shader, source); glCompileShader(shader); String infoLog = glGetShaderInfoLog(shader, glGetShader(shader, GL_INFO_LOG_LENGTH)); if(glGetShader(shader, GL_COMPILE_STATUS) == GL_FALSE) throw new RuntimeException("Failure in compiling " + getName(type) + " shader. Error log:\n" + infoLog); else { System.out.print("Compiling " + getName(type) + " shader successful."); if(infoLog != null && !(infoLog = infoLog.trim()).isEmpty()) System.out.println(" Log:\n" + infoLog); else System.out.println(); } return shader; }
97e279da-77be-4be7-9657-e1d738e48e3c
4
void begin() { while(true){ if(toDo.isEmpty() == true){ toDo.addAll(done); toDo.add(new DefaultState(as)); done.clear(); } if(toDo.peek() == null){ toDo.remove(); } else{ toDo.peek().show(); try{ done.add(toDo.poll().next()); } catch(Exception e){ } } } }
28c1c380-6955-4cea-9db6-d8ee84cd97b0
1
public StructuredBlock appendBlock(StructuredBlock block) { if (block instanceof EmptyBlock) { moveJump(block.jump); return this; } else { SequentialBlock sequBlock = new SequentialBlock(); sequBlock.replace(this); sequBlock.setFirst(this); sequBlock.setSecond(block); return sequBlock; } }
5d5e6425-99ce-45b2-9d66-b62c94a7a7d2
3
private void showDir(){ String dirPath = tf.getText(); File dir = new File(dirPath); if(dir.exists() && dir.isDirectory()){ tf.setText(""); String[] names = dir.list(); for(String name:names){ ta.append(name+"\r\n"); } }else{ String info = "Ya directory "+"\'"+dirPath+"\'"+" is wrong"; lab.setText(info); d.setVisible(true); } }
ded0ae05-33d2-4aee-aee5-13ee4f331605
8
public Map<String, List<String>> askQuery(String property, String target, String... otherProperties) throws IOException { // Build the query (relying on the SMWAskAPI extension to be installed StringBuilder prop = new StringBuilder("[["+property+"::"+target+"]]"); StringBuilder url = new StringBuilder(query); url.append("action=ask&q=").append(prop).append("&po="); for (String op : otherProperties) { op = op.toLowerCase(); url.append(op).append("|"); } // Submit it and receive XML String xml = fetch(url.toString(), "askQuery", false); // Check the returned SML for errors try { checkErrors(xml, ""); } catch (LoginException e) { throw new IOException("User error."); } // Create the XML document parser and read the XML Document doc = null; try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); doc = builder.parse(is); } catch (ParserConfigurationException e) { e.printStackTrace(); throw new IOException("Could not create XML parser."); } catch (SAXException e) { e.printStackTrace(); throw new IOException("Error parsing XML."); } // iterate through the results and build the map that will eventually be returned Map<String, List<String>> results = new HashMap<String, List<String>>(); NodeList nodes = doc.getElementsByTagName("list-item"); for (int i=0; i < nodes.getLength(); i++) { Element result = (Element) nodes.item(i); String title = result.getAttribute("title"); Element propertiesNode = (Element) result.getFirstChild(); List<String> properties = new ArrayList<String>(); // Attempt to retrieve the properties try { // Get the type, which is always defined, and then get the optional ones specified String type = propertiesNode.getAttribute("type"); properties.add(type); for (String op : otherProperties) { op = op.toLowerCase(); String _prop = propertiesNode.getAttribute(op); properties.add(_prop); } } catch (NullPointerException e) { log(Level.WARNING, "Could not parse properties.", "askQuery"); } if (!title.equals("")) results.put(title, properties); } return results; }
82609133-6971-438b-9ac2-77f929d9a692
9
public static String toJSONString(final String value) { final StringBuilder strBldr = new StringBuilder(""); for(final char c : value.toCharArray()) { switch (c) { case '\"': case '\\': case '/': strBldr.append('\\').append(c); break; case '\b': strBldr.append('\\').append('b'); break; case '\f': strBldr.append('\\').append('f'); break; case '\n': strBldr.append('\\').append('n'); break; case '\r': strBldr.append('\\').append('r'); break; case '\t': strBldr.append('\\').append('t'); break; default: strBldr.append(c); break; } } return strBldr.toString(); }
0b4b0e8c-2dff-48c7-b8ce-9c185a56ad97
2
private static boolean isLocationInScreenBounds(Point location) { GraphicsDevice[] graphicsDevices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices(); for (int j = 0; j < graphicsDevices.length; j++) { if (graphicsDevices[j].getDefaultConfiguration().getBounds().contains(location)) { return true; } } return false; }
28b4ad8c-50c2-4c51-a4e2-7760a879a148
4
public void editArena() { if (this.arenastate == ArenaState.STAT_READY || this.arenastate == ArenaState.STAT_STARTED) this.endGame(EndReason.END_REASON_ARENAEDIT); else if (this.arenastate == ArenaState.STAT_OPEN) { for (Player p : players) { this.removeplayer(p); p.sendMessage(ChatColor.RED + "༭ģʽ!"); } } }
be677eb3-e15f-4136-bf15-52c1d819bad2
4
public boolean equals(BoundingBox other) { if (min_x == other.minX() && min_y == other.minY() && max_x == other.maxX() && max_y == other.maxY()) { return true; } else { return false; } }
44e29ce6-b20f-4039-8487-8ddd7126a84f
2
public static void checkChatYAML() { File file = new File(path + "Chat.yml"); if(!file.exists()){ try{ file.createNewFile(); FileConfiguration f = YamlConfiguration.loadConfiguration(file); f.set("Format", "&f+channel &7[+world&7]&f +name&7:&f +message"); f.set("World.defaultPrefix", "&4&lX"); f.set("World.Port", "&fP"); f.set("World.Creative", "&eC"); f.set("World.Video", "&9V"); f.set("World.Survival", "&aS"); f.set("World.Survival_nether", "&cS"); f.set("World.Survival_the_end", "&8S"); f.set("World.Minigames", "&dM"); f.set("Channels.Global.Prefix", "&2[G]"); f.set("Channels.Local.Prefix", "&f[L]"); f.set("Channels.Local.Radius", 150); f.set("Channels.Help.Prefix", "&9[H]"); f.set("Channels.World.Prefix", "&3[W]"); f.set("Channels.Staff.Prefix", "&4[S]"); f.set("Channels.Staff.Color", "&e"); f.save(file); } catch(Exception e) { e.printStackTrace(); } } }
4fd37737-2c5b-48f0-bdd4-9b1119e93d61
5
@Override public void update(Task task) { try { connection = getConnection(); ptmt = connection.prepareStatement("UPDATE Task SET description=? title=? id_executor=?" + " active=? done=? WHERE idtask=?;"); ptmt.setString(1, task.getDescription()); ptmt.setString(2, task.getTitle()); ptmt.setInt(3, task.getIdExecutor()); ptmt.setBoolean(4, task.getActive()); ptmt.setBoolean(5, task.getDone()); ptmt.setInt(6, task.getIdtask()); ptmt.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (ptmt != null) { ptmt.close(); } if (connection != null) { connection.close(); } if (resultSet != null) { resultSet.close(); } } catch (SQLException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } } }
aa0c3f6a-f9c9-42f1-add7-e3bd4fcd1fef
9
public int[] merger(int[] a , int[] b){ int curA=0,curB=0,curResult=0; int[] result=new int[a.length+b.length]; while (curA<a.length && curB<b.length){ if(a[curA]>b[curB]){ result[curResult++]=a[curA++]; }else if(a[curA]<b[curB]){ result[curResult++]=b[curB++]; }else{ if(max(a,curA,b,curB)){ result[curResult++]=a[curA++]; }else{ result[curResult++]=b[curB++]; } } } if(curA<a.length){ while (curA<a.length) result[curResult++]=a[curA++]; } if(curB<b.length){ while (curB<b.length) result[curResult++]=b[curB++]; } return result; }
deb2464c-e972-44df-bfef-340149345433
7
public boolean equals(Object object) { if (this == object) { return true; } if (object == null || object.getClass() != getClass()) { return false; } Slope other = (Slope) object; if (isVertical() && other.isVertical()) { return true; } if (isVertical() || other.isVertical()) { return false; } return (asDouble()) == (other.asDouble()); }
0da2554a-6fa4-4cb0-bc43-e195e0a8bc51
7
public static void main(String[] args) { int searchForEach = 10; int warmup = 100000; int count = 1000000; int length = UUID.randomUUID().toString().getBytes().length; System.out.println("length: " + length); // prepare warmup data System.out.print("preparing warmup data..."); List<byte[]> warmupData = new ArrayList<byte[]>(warmup); for (int i = 0; i < warmup; i++) { warmupData.add(UUID.randomUUID().toString().getBytes()); } System.out.println("done"); // prepare main data System.out.print("preparing main data..."); List<byte[]> srcData = new ArrayList<byte[]>(count); List<byte[]> searchData = new ArrayList<byte[]>((count / searchForEach) * 2); for (int i = warmup; i < warmup + count; i++) { byte[] e = UUID.randomUUID().toString().getBytes(); srcData.add(e); if (i % searchForEach == 0) { searchData.add(e); searchData.add(UUID.randomUUID().toString().getBytes()); } } System.out.println("done"); FixedByteSliceOpenHashSet set = new FixedByteSliceOpenHashSet(length); System.gc(); // warmup System.out.print("warming up..."); for (byte[] bs : warmupData) { set.add(bs); } System.out.println("done"); { // start the addition test System.out.print("testing addition..."); long start = System.currentTimeMillis(); for (byte[] bs : srcData) { set.add(bs); } long time = System.currentTimeMillis() - start; System.out.println("done. time: " + time + "ms"); } { // start the searching test System.out.print("testing searching..."); int found = 0; int notFound = 0; long start = System.currentTimeMillis(); for (byte[] bs : searchData) { if (set.contains(bs)) { found++; } else { notFound++; } } long time = System.currentTimeMillis() - start; System.out.println("done. found: " + found + ", not found: " + notFound + ", time: " + time + "ms"); } }
9bf5eeb6-7700-478b-a5f8-ffb3e22a418f
0
static public int getDefaultTypeId() { return Id3PictureType.defaultTypeId; }
3251827a-29f3-4b72-a203-f54de2306394
2
public ArrayList get_PatientMRN(MsgParse mp) throws SQLException { ArrayList<String> arr = new ArrayList<String>(); try { ResultSet rs = stmt.executeQuery("SELECT last_name, first_name, mrn, admission_type FROM Patient JOIN VISIT " + "ON patient.pid = visit.patient_pid WHERE admission_type <> 'D' "); while(rs.next()) { String val = rs.getString("last_name"); val += " "; val += rs.getString("first_name"); val += " "; val += rs.getString("mrn"); arr.add(val); } }catch (SQLException se) { System.out.println("Error in DBLoader.set_LabOrder: " + se); } return arr; }
4815d1ab-6feb-4411-826e-2d62cff00647
7
public static void netToUai(BeliefNetwork bn, List vars, String filename) { System.err.println("Saving network : " + filename); java.io.PrintWriter pw = getPrintWriter(filename); // preamble Map<FiniteVariable,Integer> var2index = getVarToIndexMap(vars); pw.println("BAYES"); pw.println(vars.size()); for (int i = 0; i < vars.size(); i++) { FiniteVariable var = (FiniteVariable)vars.get(i); pw.print((i==0?"":" ") + var.size()); } pw.println(); pw.println(vars.size()); for (int i = 0; i < vars.size(); i++) { FiniteVariable var = (FiniteVariable)vars.get(i); Table t = var.getCPTShell().getCPT(); List tvars = t.variables(); pw.print(tvars.size()); for (int j = 0; j < tvars.size(); j++) { FiniteVariable tvar = (FiniteVariable)tvars.get(j); pw.print(" " + var2index.get(tvar)); } pw.println(); } // function tables pw.println(); for (int i = 0; i < vars.size(); i++) { FiniteVariable var = (FiniteVariable)vars.get(i); int size = var.size(); double[] values = var.getCPTShell().getCPT().dataclone(); pw.println(values.length); for (int row = 0; row < values.length/size; row++) { for (int col = 0; col < size; col++) pw.print(" " + values[row*size+col]); pw.println(); } pw.println(); } pw.close(); }
6c6331b8-f501-4e1f-9f01-4c1c0268007d
9
private boolean isValidPhone(){ if(phone.length()!=12){ JOptionPane.showMessageDialog(null,"Invalid phone number entered. Must be 12 digits.","Error",JOptionPane.WARNING_MESSAGE); return false; } if(phone.charAt(3)!='-'||phone.charAt(7)!='-'){ JOptionPane.showMessageDialog(null,"Invalid phone number entered. Don't forget dashes.","Error",JOptionPane.WARNING_MESSAGE); return false; } for(int i=0; i<3; i++){ if(!Character.isDigit(phone.charAt(i))){ JOptionPane.showMessageDialog(null,"Phone numbers can only contain digits.","Error",JOptionPane.WARNING_MESSAGE); return false; } } for(int i=4; i<7; i++){ if(!Character.isDigit(phone.charAt(i))){ JOptionPane.showMessageDialog(null,"Phone numbers can only contain digits.","Error",JOptionPane.WARNING_MESSAGE); return false; } } for(int i=8; i<phone.length(); i++){ if(!Character.isDigit(phone.charAt(i))){ JOptionPane.showMessageDialog(null,"Phone numbers can only contain digits.","Error",JOptionPane.WARNING_MESSAGE); return false; } } return true; }
3e758c01-4832-4f80-a482-3028e5dff177
1
public void upkeep(){ level+=(Empous.Gov.getStat("infrastructure")-7)*repair_rate; if (level>max_level) level=max_level; }
27beee29-34dd-4faa-bc74-6da5f0564833
7
public Node ceiling(int x){ Node cur = root; while(true){ if(cur.value==x) return cur; if(x<cur.value){ if(cur.left==null){ return cur; } cur = cur.left; } else{ if(cur.right==null){ while(cur.parent!=null && cur==cur.parent.right) cur=cur.parent; return cur.parent; } cur = cur.right; } } }
06dffdef-594a-4992-a9f4-f767bd8a760c
0
public static String getQualifiedMethodName(Method method) { Assert.notNull(method, "Method must not be null"); return method.getDeclaringClass().getName() + "." + method.getName(); }
a9e5a53c-99da-4e86-b519-40dad8f9799f
3
public static boolean promptQuestion(String question, boolean warning, String yes, String no) { boolean answer = false; Object[] options = { yes, no }; int choice = JOptionPane.showOptionDialog( null, question, warning ? "Waarschuwing!" : "Gebruikersinteractie vereist", JOptionPane.YES_NO_OPTION, warning ? JOptionPane.WARNING_MESSAGE : JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (choice == JOptionPane.YES_OPTION) { answer = true; } return answer; }
adc07201-3a04-4bb8-b32d-e239835d1b83
4
private static String getMessage(Field field) { Localize[] annotations = field.getAnnotationsByType(Localize.class); if (annotations.length > 0) { for (String locale : LOCALES) { for (Localize one : annotations) { if (locale.equals(one.locale())) { return one.value(); } } } } return "*!*" + field.getName() + "*!*"; }
de15499d-db50-4491-99d7-dc4be9d51426
8
public void paint(Graphics graphics) { if (tree == null) return; final Graphics2D g2 = (Graphics2D) graphics; if (!calibrated) calibrate(g2, getWidth(), getHeight()); Paint oldPaint = g2.getPaint(); Stroke oldStroke = g2.getStroke(); for (Node selectedNode : selectedNodes) { Shape branchPath = treeLayoutCache.getBranchPath(selectedNode); if (branchPath != null) { Shape transPath = transform.createTransformedShape(branchPath); g2.setPaint(selectionPaint); g2.setStroke(selectionStroke); g2.draw(transPath); } Shape collapsedShape = treeLayoutCache.getCollapsedShape(selectedNode); if (collapsedShape != null) { Shape transPath = transform.createTransformedShape(collapsedShape); g2.setPaint(selectionPaint); g2.setStroke(selectionStroke); g2.draw(transPath); } } for (Node selectedTip : selectedTips) { g2.setPaint(selectionPaint); Shape labelBounds = tipLabelBounds.get(selectedTip); if (labelBounds != null) { g2.fill(labelBounds); } } g2.setPaint(oldPaint); g2.setStroke(oldStroke); drawTree(g2, getWidth(), getHeight()); if (dragRectangle != null) { g2.setPaint(new Color(128, 128, 128, 128)); g2.fill(dragRectangle); g2.setStroke(new BasicStroke(2.0F)); g2.setPaint(new Color(255, 255, 255, 128)); g2.draw(dragRectangle); g2.setPaint(oldPaint); g2.setStroke(oldStroke); } }
3c986511-4976-49c3-a087-55815925d3b7
5
public static boolean handleOption(int option, int longind, String arg) { if (arg == null) options ^= 1 << option; else if ("yes".startsWith(arg) || arg.equals("on")) options |= 1 << option; else if ("no".startsWith(arg) || arg.equals("off")) options &= ~(1 << option); else { GlobalOptions.err.println("jode.decompiler.Main: option --" + longOptions[longind].getName() + " takes one of `yes', `no', `on', `off' as parameter"); return false; } return true; }
514f56a1-bfcf-4938-97ef-2fd5de80e6cd
6
*/ public void moveOnAxisX(Direction direction) { if (direction.equals(Direction.RIGHT)) { if (this.position.x + moveStep <= desert.length && !isHurdle(this.position.x + moveStep, this.position.y)) { this.position.x += moveStep; } else { move(); } } else if (direction.equals(Direction.LEFT)) { if (this.position.x - moveStep >= 0 && !isHurdle(this.position.x - moveStep, this.position.y)) { this.position.x -= moveStep; } else { move(); } } }
c6df934e-8221-4d67-b76d-e24802af940d
4
public SpinnerTimeEditor(JSpinner spinner) { super(spinner); if (!(spinner.getModel() instanceof SpinnerNumberModel)) { throw new IllegalArgumentException(); } final Pattern pattern = Pattern.compile("([0-9]+)((:|.|h)([0-5]?[0-9]))?"); DefaultFormatter formatter = new DefaultFormatter() { @Override public String valueToString(Object value) throws ParseException { return StringValueTimer.INSTANCE.getString(value); } @Override public Object stringToValue(String text) throws ParseException { Matcher matcher = pattern.matcher(text); if (!matcher.find()) { throw new ParseException("Pattern did not match", 0); } int hour = 0; int minute = 0; if (matcher.group(4) == null) { minute = Integer.parseInt(matcher.group(1)); } else if (matcher.groupCount() == 4) { hour = Integer.parseInt(matcher.group(1)); minute = Integer.parseInt(matcher.group(4)); } return (hour * 60) + minute; } }; DefaultFormatterFactory factory = new DefaultFormatterFactory(formatter); JFormattedTextField ftf = this.getTextField(); ftf.setEditable(true); ftf.setFormatterFactory(factory); }
e4a026b7-7e94-4ad2-8c2a-253f03112eca
3
public int getLabelIdx(String label) throws IOException { if (labels == null) setLabels(); if (labelMap == null) return -1; if (!labelMap.containsKey(label)) return -1; return (labelMap.get(label)).intValue(); }
08bc2166-09d3-4e7e-acf7-a5c5160a9f4b
6
private HashMap<String,byte[]> readChars(byte[] d) { // skip thru data until we find "/"+key HashMap<String,byte[]> hm = new HashMap<String,byte[]>(); int i = findSlashName(d, "CharStrings"); if (i < 0) { // not found return hm; } PSParser psp = new PSParser(d, i); // read /name len -| [len bytes] |- // until "end" while (true) { String s = psp.readThing(); char c = s.charAt(0); if (c == '/') { int len = Integer.parseInt(psp.readThing()); String go = psp.readThing(); // it's -| or RD if (go.equals("-|") || go.equals("RD")) { psp.setLoc(psp.getLoc() + 1); byte[] line = psp.getNEncodedBytes(len, password, lenIV); hm.put(s.substring(1), line); } } else if (s.equals("end")) { break; } } return hm; }
8b6f0137-293a-4459-9843-192a7ecc40fe
3
public boolean jumpMayBeChanged() { for (int i = 0; i < subBlocks.length; i++) { if (subBlocks[i].jump == null && !subBlocks[i].jumpMayBeChanged()) return false; } return true; }
83d0c14a-6036-4f9e-a419-3252412c7348
4
void lpc_to_curve(float[] curve, float[] lpc, float amp){ for(int i=0; i<ln*2; i++) curve[i]=0.0f; if(amp==0) return; for(int i=0; i<m; i++){ curve[i*2+1]=lpc[i]/(4*amp); curve[i*2+2]=-lpc[i]/(4*amp); } fft.backward(curve); { int l2=ln*2; float unit=(float)(1./amp); curve[0]=(float)(1./(curve[0]*2+unit)); for(int i=1; i<ln; i++){ float real=(curve[i]+curve[l2-i]); float imag=(curve[i]-curve[l2-i]); float a=real+unit; curve[i]=(float)(1.0/FAST_HYPOT(a, imag)); } } }
f77ba440-b782-424b-a317-82964b8ebfe9
0
public Worker () { //initial settings results = new ArrayList<String>(); this.keyboard = new BufferedReader(new InputStreamReader(System.in)); System.out.println(MSG_WELCOME); //start this.lifeCycle(); }
ff2bf009-8610-4a78-9eaf-0ac93d499355
2
public static Collection<BufferedImage> getFromSpritesheet(BufferedImage spritesheet, int width, int height, int spacing, int border) { // GET THE NUMBER OF TILES VERTICALLY AND HORIZONTALLY int horizCount = (spritesheet.getWidth() - 2 * border + spacing) / (width + spacing); int vertCount = (spritesheet.getHeight() - 2 * border + spacing) / (height + spacing); // MAKE A NEW ARRAYLIST TO HOLD IT ALL Collection<BufferedImage> images = new ArrayList(horizCount * vertCount); // AND ITERATE THROUGH ALL THE TILES for (int tileY = 0; tileY < vertCount; tileY++) { for (int tileX = 0; tileX < horizCount; tileX++) { // GET THE SUBIMAGE AND ADD IT TO THE COLLECTION int xLoc = border + tileX * (width + spacing); int yLoc = border + tileY * (height + spacing); images.add(spritesheet.getSubimage(xLoc, yLoc, width, height)); } } return images; }
8f1ed1e7-0729-4772-ad60-7a9412c18baa
9
final public SimpleNode Start() throws ParseException { /*@bgen(jjtree) START */ SimpleNode jjtn000 = new SimpleNode(JJTSTART); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); jjtn000.jjtSetFirstToken(getToken(1));Token t = token; try { Program_declaration(); jj_consume_token(0); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.jjtSetLastToken(getToken(0)); jjtn000.value = t.image; {if (true) return jjtn000;} } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); jjtn000.jjtSetLastToken(getToken(0)); } } throw new Error("Missing return statement in function"); }
74346c8c-0211-4e05-8452-845f768ad5dd
9
public static void main(String[] args) { try { Experiment exp = null; // get options from XML? String xmlOption = Utils.getOption("xml", args); if (!xmlOption.equals("")) args = new XMLOptions(xmlOption).toArray(); String expFile = Utils.getOption('l', args); String saveFile = Utils.getOption('s', args); boolean runExp = Utils.getFlag('r', args); if (expFile.length() == 0) { exp = new Experiment(); try { exp.setOptions(args); Utils.checkForRemainingOptions(args); } catch (Exception ex) { ex.printStackTrace(); String result = "Usage:\n\n" + "-l <exp|xml file>\n" + "\tLoad experiment from file (default use cli options).\n" + "\tThe type is determined, based on the extension (" + FILE_EXTENSION + " or .xml)\n" + "-s <exp|xml file>\n" + "\tSave experiment to file after setting other options.\n" + "\tThe type is determined, based on the extension (" + FILE_EXTENSION + " or .xml)\n" + "\t(default don't save)\n" + "-r\n" + "\tRun experiment (default don't run)\n" + "-xml <filename | xml-string>\n" + "\tget options from XML-Data instead from parameters\n" + "\n"; Enumeration enm = ((OptionHandler)exp).listOptions(); while (enm.hasMoreElements()) { Option option = (Option) enm.nextElement(); result += option.synopsis() + "\n"; result += option.description() + "\n"; } throw new Exception(result + "\n" + ex.getMessage()); } } else { exp = read(expFile); // allow extra datasets to be added to pre-loaded experiment from command line String dataName; do { dataName = Utils.getOption('T', args); if (dataName.length() != 0) { File dataset = new File(dataName); exp.getDatasets().addElement(dataset); } } while (dataName.length() != 0); } System.err.println("Experiment:\n" + exp.toString()); if (saveFile.length() != 0) write(saveFile, exp); if (runExp) { System.err.println("Initializing..."); exp.initialize(); System.err.println("Iterating..."); exp.runExperiment(); System.err.println("Postprocessing..."); exp.postProcess(); } } catch (Exception ex) { System.err.println(ex.getMessage()); } }
7ec605d1-fa2f-488d-8c68-b04a5960928d
5
public static void main(String[] args){ User user = new User(); List<User> userList = new ArrayList<User>(); int minSize = 5; int maxSize = 10; user.setNick(getRandomString(minSize, maxSize)); user.setSessionKey(getRandomString(30, 50)); for (int i = 0; i < 10; i++) { User u = new User(); u.setNick(getRandomString(minSize, maxSize)); u.setSessionKey(getRandomString(30, 50)); userList.add(u); } int result=0; //Dao 接口 DaoFunc userDao = null; try { //建立Dao Dao作为默认类 userDao = Dao.getInstance(User.class); // 插入实体 // result = userDao.insert(user); //插入集合 // System.out.println(SqlC.insert(User.class)); // result = userDao.insert(userList); //当前实体搜索 SqlC sqlC = SqlC.select(User.class).orderBy(Orders.sortAsc("nick")); System.out.println(sqlC); List<User> resultList = userDao.query(sqlC); for(User u:resultList){ System.out.println(new JSONObject(u)); } //count测试 // Long count = userDao.count(); // System.out.println("count : "+count); //模糊count测试 // Long fuzzyCount = 0L; // fuzzyCount = userDao.fuzzyCount(); // System.out.println("fuzzyCount : "+fuzzyCount); //快速count测试 // Long fastCount = 0L; // fastCount = userDao.fastCount(10000, 100); // System.out.println("fastCount : "+fastCount); // //快速count测试2 // Dao categoryPropValueDao = Dao.getIntance(CategoryPropValue.class); // Long cpvFastCount = categoryPropValueDao.fastCount(50000, 3000); // System.out.println("CategroyPropValueFastCount : "+cpvFastCount); //更新实体 // user = resultList.get(0); // System.out.println(new JSONObject(user)); // user.setNick(getRandomString(minSize, maxSize)); // user.setSessionKey(getRandomString(30, 50)); // result = userDao.update(user); //更新集合 // for (User u:resultList) { // u.setNick(getRandomString(minSize, maxSize)); // u.setSessionKey(getRandomString(30, 50)); // } // result = userDao.update(userList); //删除实实体 // result = userDao.delete(user); //删除集合 // result = userDao.delete(resultList); System.out.println("result:"+result); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
771971f8-3cdb-4c0a-8c37-561040a03120
1
private void leave() { if(!oldLoc.containsKey(player)){ player.sendMessage(ChatColor.AQUA+"[CopsAndRobbers]"+ChatColor.DARK_RED+"You are not in a game!"); }else{ team.removePlayer(player); player.teleport(oldLoc.get(player)); } }
4ac4f283-2f78-4807-b08a-bf0493afa3f0
4
@Override public E peek() { // This ensures a previous wakeup has ended. E item = queue.peek(); if (blocking && item == null) { synchronized (lock) { // Only block if the item is null, else return it. item = queue.peek(); if (item == null) { try { lock.wait(timeout); } catch (InterruptedException e) { } item = queue.peek(); } } } return item; }
cb0460e2-cc7b-435a-83c0-c47a728aad46
6
public void destroy(ItItemHasEmpleadoPK id) throws NonexistentEntityException, RollbackFailureException, Exception { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); ItItemHasEmpleado itItemHasEmpleado; try { itItemHasEmpleado = em.getReference(ItItemHasEmpleado.class, id); itItemHasEmpleado.getItItemHasEmpleadoPK(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException("The itItemHasEmpleado with id " + id + " no longer exists.", enfe); } Empleado empleado = itItemHasEmpleado.getEmpleado(); if (empleado != null) { empleado.getItItemHasEmpleadoCollection().remove(itItemHasEmpleado); empleado = em.merge(empleado); } ItItem itItem = itItemHasEmpleado.getItItem(); if (itItem != null) { itItem.getItItemHasEmpleadoCollection().remove(itItemHasEmpleado); itItem = em.merge(itItem); } em.remove(itItemHasEmpleado); em.getTransaction().commit(); } catch (Exception ex) { try { em.getTransaction().rollback(); } catch (Exception re) { throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re); } throw ex; } finally { if (em != null) { em.close(); } } }
c5815a8e-06ac-4e57-adbd-3d76d13c507a
6
public static Task getSelectedTask() { if (DEBUG) log("Attempting to determine selected task"); Task selectedTask = null; if (tasks != null) { for(Task t : tasks) { if (t.isSelected()) { selectedTask = t; break; } } } if (DEBUG) { if (selectedTask != null) { log("Found selected task to be: " + selectedTask.getName()); } else { log("There was no selected task."); } } return selectedTask; }
ea37c6bf-2375-474e-b421-109becdddc4e
6
public static void main(String[] args) { base db = new base(); db.create("/SAMPLE1.DBF", "Npk N(10), Name C(20), Rating F(5,2), Birth D, Notes M, ieee B(8,4), Id I, Salary Y"); db.Field[0].setByLong(1); db.Field[1].setByString("Mickey"); db.Field[2].setByDouble( 3.15 ); db.Field[3].setByString("20050328"); db.Field[4].setByString("Some notes about."); db.Field[5].setByDouble( -9.1678 ); db.Field[6].setByLong( -2999999 ); db.Field[7].setByDouble( 3000.25 ); db.insert_from_memory(); // replace all fields in database db.DOS_FOX = true; db.create("/SAMPLE2.DBF", "Npk N(10), Name C(20), Rating F(5,2), Birth D, Notes M"); db.Field[0].setByLong(1); db.Field[1].setByString("Billy"); db.Field[2].setByDouble( 8.15 ); db.Field[3].setByString("20150101"); db.Field[4].setByString("This is for DOS FOXPRO 2.6x"); db.insert_from_memory(); // replace all fields in database db = new base(); db.create("/I.DBF", "Numb N(10)"); db.create_idx("/I.IDX","Numb"); // INDEX ON Numb without re-indexing records for(int k=0;k<100;k++) // append 100 indexed records { db.Field[0].setByLong(k); db.insert_from_memory(); } for(int k=99;k>=0;k--) // find them all by key and replace with (5000-value) { db.Field[0].setByLong(k); if(db.SEEK()) { db.Field[0].setByLong(5000-k); db.replace_from_memory(); } else { System.out.print("Not found?! Should be.\n"); // db.Idx.sRecno contains nearest record, so go to this and skip } } for(int k=4901;k<=5000;k++) // find new values to verify index { db.Field[0].setByLong(k); db.SEEK(); if(!db.eof) System.out.print("Seek " + String.valueOf(k) + ", record " + String.valueOf(db.recno) + "\n"); else System.out.print("Not found?! Should be.\n"); } db.use(); db.READ_ONLY = true; // to be sure for reading only db.use("/I.DBF"); db.set_order_to_idx("/I.IDX"); db.go_top(); // scan them sorted all and print values and record numbers while(!db.eof) // should be numbers in descending order { long V = db.Field[ db.FieldI("Numb") ].longValue(); System.out.print( "Numb = " + String.valueOf(V) + ", record " + String.valueOf(db.recno) + "\n"); db.skip(1); } db.use(); db.READ_ONLY = true; // set writing mode on // Verify in FoxPro by commands // USE C:\I // SET INDEX TO C:\I.IDX // BROW };
faffdd5e-77bf-4373-9387-403aeb227660
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Frm_CadAplicativo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Frm_CadAplicativo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Frm_CadAplicativo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Frm_CadAplicativo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Frm_CadAplicativo().setVisible(true); } }); }
c546f555-35e5-4e23-884c-9935dc6b021f
0
public void setCost(double value) { this.cost = value; }
dbf316b1-3ca5-4c6a-9f8f-28f8ff14a8f2
6
private static String unescape(String in, String escChars) { if (in == null) return null; if (in.length() == 0) return ""; //can't be any escapes in 1-char String, and we need to guarentee one pass through the loop escChars = escChars.concat("\\"); StringBuffer out = new StringBuffer(in.length()); char c=' ', next=in.charAt(0); //fix it so the last line will do the right thing if we don't enter the loop int end = in.length()-1; int i; for (i=0; i<end; i++) { c = in.charAt(i); if (c == '\\') { next = in.charAt(i+1); if (escChars.indexOf(next) < 0) out.append(c); else {out.append(next); i++;} } else { out.append(c); } } /* if (c == '\\') { if (escChars.indexOf(next) < 0) out.append(next); } else out.append(in.charAt(i)); */ if (i==end) out.append(in.charAt(i)); return out.toString().trim(); }
276614f3-bc80-4ef5-b9ea-99e82e9f5e2c
5
public String toDiffString(String jobId) { String f1 = "%1$-3.0f"; String f2 = "%1$-3.1f"; float xOUdf = exOU - rxOU; float mNGUdf = exNGU - rmNGU; float xNGUdf = exNGU - rxNGU; float xHeapUdf = exHeapU - rxHeapU; float RSSdf = exHeapU - rxRSS; float xOUrt = rxOU == 0 ? 100 : Math.abs(xOUdf) * 100 / rxOU; float mNGUrt = rmNGU == 0 ? 100 : Math.abs(mNGUdf) * 100 / rmNGU; float xNGUrt = rxNGU == 0 ? 100 : Math.abs(xNGUdf) * 100 / rxNGU; float xHeapUrt = rxHeapU == 0 ? 100 : Math.abs(xHeapUdf) * 100 / rxHeapU; float RSSrt = rxRSS == 0 ? 100 : Math.abs(RSSdf) * 100 / rxRSS; return xmx + "\t" + xms + "\t" + ismb + "\t" + RN + "\t" + String.format(f1, xOUdf) + "\t" + String.format(f1, mNGUdf) + "\t" + String.format(f1, xNGUdf) + "\t" + String.format(f1, xHeapUdf) + "\t" + String.format(f1, RSSdf) + "\t" + String.format(f2, xOUrt) + "\t" + String.format(f2, mNGUrt) + "\t" + String.format(f2, xNGUrt) + "\t" + String.format(f2, xHeapUrt) + "\t" + String.format(f2, RSSrt) + "\t" + jobId + "\t" + rJobId + "\t" + String.format(f1, rxOU) + "\t" + String.format(f1, exOU) + "\t" + String.format(f1, rmNGU) + "\t" + String.format(f1, rxNGU) + "\t" + String.format(f1, exNGU) + "\t" + String.format(f1, rxHeapU) + "\t" + String.format("%1$-3d", rxRSS) + "\t" + String.format(f1, exHeapU); }
f3fac0b3-2178-4a14-a46f-fa1bfef880f7
1
@Test public void tokenize_allTokenTypes() throws Exception { // given final String code = "+-<>[]rw"; // when final List<Token> tokens = tokenizer.tokenize(code); // then final List<Token> expectedTokens = new LinkedList<>(); for (char c : code.toCharArray()) { expectedTokens.add(new Token(c, mapping.getType(c))); } assertEquals(expectedTokens, tokens); }
7b6180df-04ba-4845-a48e-153ee75fd6ff
7
public void removeEdge(Vertex v1, Vertex v2) { for (int i = 0; i < edges.size(); i++) { //if this edge connects v1 and v2 if (((MyEdge) edges.get(i)).contains(v1, v2)) { //find vertices of this edge and remove them for (int j = 0; j < vertices.size(); j++ ) { if (v1.getElement().getX() == vertices.get(j).getElement().getX() && v1.getElement().getY() == vertices.get(j).getElement().getY() || v2.getElement().getX() == vertices.get(j).getElement().getX() && v2.getElement().getY() == vertices.get(j).getElement().getY()) vertices.remove(j); } edges.remove(i); } } }
81bc548e-1307-469f-a66a-b956ae3cd636
1
public void kill(Player p) { if(p.setStackInNextAvailableSlot(getDrops()[rand.nextInt(drops.length)])){ this.remove = true; }else{ health = maxHealth; } }
9ce50d00-3ac7-4231-bb32-4e35d288962b
6
public String toString() { switch(subtype){ case 'B': {si = 0; break;} case 'N': {si = 1; break;} case 'P': {si = 2; break;} case 'A': {si = 3; break;} case 'R': {si = 4; break;} case 'D': {si = 5; break;} } return "Group: "+group+"\n"+ "Address: "+address+"\n"+ "Nickname: "+nickname+"\n"+ "Presence: "+(p[presence])+"\n"+ "Type: "+type+"\n"+ "Mood: "+(m[mood])+"\n"+ "Flags: "+flags+"\n"+ "Subtype: "+s[si]+"\n"; }
6acaee59-958a-414c-ba59-d2ba1ae2e5e7
3
public BufferedImage getIdleImage(EnumDirection dir) { BufferedImage[] idleImages = TransformImage.splitAnimation(idleStrip, 3); switch(dir) { case EAST: return idleImages[1]; case WEST: return TransformImage.flipHorizontally(idleImages[1]); case NORTH: return idleImages[2]; default: return idleImages[0]; } }
7ae18edb-ba9b-4ba8-8932-204cc3079d85
4
String toSmallest(String in) { char minChar = 'z' + 1; int minIndex = in.length(); boolean refresh = true; for (int i = 0; i < in.length(); i++) { if (in.charAt(i) < minChar) { minIndex = i; refresh = false; minChar = in.charAt(i); } else if (in.charAt(i) == minChar) { if (refresh) { minIndex = i; refresh = false; } } else { refresh = true; } } return in.substring(minIndex) + in.substring(0, minIndex); }
21641ef4-8555-4cca-82b5-3cc2aab95dcc
0
protected final Logger getLogger() { return LoggerFactory.getLogger(this.getClass()); }
c8ce19cc-84c2-4019-b181-b73683832d0f
5
@Test public void testInfixToPostfix3() throws DAIllegalArgumentException, DAIndexOutOfBoundsException, ShouldNotBeHereException, BadNextValueException, UnmatchingParenthesisException { try { infix.addLast("*"); infix.addLast("5"); infix.addLast("+"); infix.addLast("3"); QueueInterface<String> postFix = calc.infixToPostfix(infix); String result = "245*+3+"; assertEquals(result, calc.stringTrans(postFix)); } catch (DAIllegalArgumentException e) { throw new DAIllegalArgumentException(); } catch (DAIndexOutOfBoundsException e) { throw new DAIndexOutOfBoundsException(); } catch (ShouldNotBeHereException e) { throw new ShouldNotBeHereException(); } catch (BadNextValueException e) { throw new BadNextValueException(); } catch (UnmatchingParenthesisException e) { throw new UnmatchingParenthesisException(); } }
e7e2e32e-a8da-4d7f-ac8c-b5be0e0dc336
1
@Override public void refresh(Camera camera) { if(!VerifySelectedObject()) setSelectObject(); primitives.get(namePrimitives[1]).calcCoordinates(this, camera, null); }
debc147a-173f-41f8-b157-5556dc803046
4
private static TimeSpan interval(double value, int scale) { if (Double.isNaN(value)) { throw new IllegalArgumentException("Arg_CannotBeNaN"); } double num = value * scale; double num2 = num + ((value >= 0.0) ? 0.5 : -0.5); if ((num2 > 922337203685477L) || (num2 < -922337203685477L)) { throw new IllegalArgumentException("Overflow TimeSpanTooLong"); } return new TimeSpan(((long) num2) * 0x2710L); }
2b3ef8e2-a559-44c5-9b96-282af7e7d416
1
public String viewToken() { String s = ""; for (Token token : this.listaToken) { s = s + token.getLexema() + " => " + dt.getLista().get(token.getValor_token()).getMatch() + "\n"; } return s; }
bc9aa546-dd85-4943-a084-663f0ccee200
7
@Test public void placeFiguresKingQueenBishop() { HashMap<String, Integer> figureQuantityMap = new HashMap<>(); figureQuantityMap.put(KING.toString(), 1); figureQuantityMap.put(QUEEN.toString(), 1); figureQuantityMap.put(BISHOP.toString(), 1); FiguresChain kingChain = new King(figureQuantityMap); FiguresChain queenChain = new Queen(figureQuantityMap); FiguresChain bishopChain = new Bishop(figureQuantityMap); kingChain.setNextFigure(queenChain); queenChain.setNextFigure(bishopChain); HashSet<String> strings = new HashSet<>(); strings.add(EMPTY_BOARD_SIZE_6); // int sum = kingChain.placeFigures(strings.stream()).parallel().map(e -> 1).mapToInt(Integer::new).sum(); assertThat("all elements are not present on each board", kingChain.placeFigures(strings.stream()) .parallel() .filter(board -> board.contains(KING.getFigureAsString()) && board.contains(QUEEN.getFigureAsString()) && board.contains(BISHOP.getFigureAsString()) && !board.contains(ROOK.getFigureAsString()) && !board.contains(KNIGHT.getFigureAsString()) && board.contains(FIELD_UNDER_ATTACK_STRING) && board.contains(EMPTY_FIELD_STRING) && leftOnlyFigures(board).length() == 3) .map(e -> 1) .reduce(0, (x, y) -> x + y), is(8768)); }
ccecb75c-7a2a-499e-847e-b36664d58380
3
public static String getName(StringBuilder sourceCode) { String name = ""; int index = sourceCode.indexOf("<title>"); int edge = sourceCode.indexOf(" filmography - Wikipedia, the free encyclopedia</title>"); if (edge == -1) { edge = sourceCode.indexOf(" - Wikipedia, the free encyclopedia</title>"); } for (index += 7; index < edge && sourceCode.charAt(index) != '('; index++) { name += sourceCode.charAt(index); } return name; }
1ff3b4c8-0127-4763-845d-3f16ecea5685
9
public ArrayList<Float> countSentenceLengths(String post) { ArrayList<Float> tmpCounter = new ArrayList<>(Collections.nCopies(6, 0.0f)); // Where 6 corresponds to the number of sentence lengths of interest // Split the post into a number of sentences List<String> sentences = splitIntoSentences(post); int nrOfWords = 0; for (String sentence : sentences) { // Get number of words in the sentence List<String> words = extractWords(sentence); nrOfWords = words.size(); if (nrOfWords > 0 && nrOfWords <= 10) { tmpCounter.set(0, tmpCounter.get(0) + 1); } else if (nrOfWords <= 20) { tmpCounter.set(1, tmpCounter.get(1) + 1); } else if (nrOfWords <= 30) { tmpCounter.set(2, tmpCounter.get(2) + 1); } else if (nrOfWords <= 40) { tmpCounter.set(3, tmpCounter.get(3) + 1); } else if (nrOfWords <= 50) { tmpCounter.set(4, tmpCounter.get(4) + 1); } else if (nrOfWords >= 51) { tmpCounter.set(5, tmpCounter.get(5) + 1); } } // "Normalize" the values by dividing with nr of sentences in the post for (int i = 0; i < tmpCounter.size(); i++) { tmpCounter.set(i, tmpCounter.get(i) / (float) sentences.size()); } return tmpCounter; }
9fdc35c7-18ac-4015-9a4a-c93646e27ded
4
@Override public boolean equals(Object obj) { boolean equal = false; if (obj instanceof Host) { Host host = (Host) obj; Map<String, String> otherHostProps = host.getProperties(); boolean areAllEqual = true; if (otherHostProps.size() == hostProperties.size()) { for (String prop : hostProperties.keySet()) { areAllEqual = areAllEqual && hostProperties.get(prop).equals( otherHostProps.get(prop)); } equal = areAllEqual; } } return equal; }