text
stringlengths
14
410k
label
int32
0
9
public void doDownload(HttpRequest request, long contentLength, OutputStream clientOut) { cout = clientOut; SpeedThread speedThread = new SpeedThread(this); buffer = new CircularDownloadBuffer(bufferSize); // Also write the request out to a file BufferedOutputStream fileOut = null; try { String outFile = request.getFileName(); if(outputDir != null) { outFile = outputDir + File.separator + request.getFileName(); fileOut = new BufferedOutputStream(new FileOutputStream(outFile)); } downloadThreads = new DownloadThread[downloadThreadCount]; for (int i = 0; i < downloadThreadCount; i++) { downloadThreads[i] = new DownloadThread(request, buffer, this); downloadThreads[i].start(); } speedThread.start(); // Whoa there boyo, give the server time to give us some data before we start sending it to the client Thread.sleep(2000); byte readBuffer[] = new byte[4096]; int readLength = 4096; while (bytesSent < contentLength - 1 && !downloadFinished) { // For the last set of bytes that we download we need to make sure we don't try and read too much // from the circular buffer, otherwise it will block waiting for more data if(readLength + bytesSent >= contentLength) readLength = (int) (contentLength - bytesSent - 1); int newBytes = buffer.read(readBuffer, readLength); clientOut.write(readBuffer, 0, newBytes); if(fileOut != null) { fileOut.write(readBuffer, 0, newBytes); } bytesSent += newBytes; } clientOut.flush(); } catch (Exception e) { e.printStackTrace(); } finally { downloadFinished = true; buffer.quit(); if(fileOut != null) try { fileOut.close(); } catch(IOException e) {} } log.debug("Manager - finished sent: " + bytesSent); }
9
public synchronized void makeimages () // create images and repaint, if ActiveImage is invalid. // uses parameters from the BoardInterface for coordinate layout. { Dim = getSize(); boolean c = GF.getParameter("coordinates", true); boolean ulc = GF.getParameter("upperleftcoordinates", true); boolean lrc = GF.getParameter("lowerrightcoordinates", false); D = Dim.height / (S + 1 + (c?(ulc?1:0) + (lrc?1:0):0)); OP = D / 4; O = D / 2 + OP; W = S * D + 2 * O; if (c) { if (lrc) OT = D; else OT = 0; if (ulc) OTU = D; else OTU = 0; } else OT = OTU = 0; W += OTU + OT; if ( !GF.boardShowing()) return; // create image and paint empty board synchronized (this) { Empty = createImage(W, W); EmptyShadow = createImage(W, W); } emptypaint(); ActiveImage = createImage(W, W); // update the emtpy board updateall(); repaint(); }
7
public ResultSet GrabRow() { try { ResultSet Result = Statement.executeQuery(ClassQuery); while(Result.next()) { return Result; } } catch(SQLException E) { Grizzly.WriteOut(E.getMessage()); return null; } return null; }
2
public static void shoot() { // pellet created if (gunRoll == 1){ if(Data.ammo > 0){ Data.p_list.add(new Pellet(x_gunpos + Data.x_adjust_gun, y_gunpos, 0, VELOCITY_Y)); Data.ammo -= 1; } } else if (gunRoll == 2){ if(Data.ammo > 0){ shootDouble(); Data.ammo -= 2; } } if (gunRoll == 3){ if(Data.ammoRockets > 0){ shootRocket(); Data.ammoRockets--; } } if(gunRoll == 4){ if(Data.ammoRockets > 0){ shootTakeOver(); Data.ammoRockets--; } } }
8
public void YCC_to_RGB(int count) { if((ncolors != 3)||parent.isRampNeeded()) { throw new IllegalStateException("YCC_to_RGB only legal with three colors"); } while(count-- > 0) { final int y = parent.data[offset]; final int b = parent.data[offset + 1]; final int r = parent.data[offset + 2]; final int t2 = r + (r >> 1); final int t3 = (y + 128) - (b >> 2); final int b0 = t3 + (b << 1); parent.data[offset++] = (byte)((b0 < 255) ? ((b0 > 0) ? b0 : 0) : 255); final int g0 = t3 - (t2 >> 1); parent.data[offset++] = (byte)((g0 < 255) ? ((g0 > 0) ? g0 : 0) : 255); final int r0 = y + 128 + t2; parent.data[offset++] = (byte)((r0 < 255) ? ((r0 > 0) ? r0 : 0) : 255); } }
9
private Genetics[] makeNewGenetics(Genetics oldGen) { System.out.println("makeNewGenetics() is running"); Genetics gen1 = new Genetics(oldGen); Genetics gen2 = new Genetics(oldGen); Random r = new Random(); // OBS inte s�ker p� att detta blir helt r�tt. // f�rst har vi ett tal mellan 0.0 och 1.0, dra ifr�n en halv f�r -0.5-0.5, multiplicera med 2*0.2 = 0.4 ger mellan -0.2 och 0.2 // r�tt? float offset = (2 * (r.nextFloat() -0.5f)) * (Constants.maxAttributeOffset); int attribute = r.nextInt(6); // NOTE: H�rdkodatat. Fyra olika attributes att �ndra. switch (attribute) { case 0: gen1.setAggression(gen1.getAggression()+offset); gen2.setAggression(gen2.getAggression()-offset); break; case 1: gen1.setPlantAttraction(gen1.getPlantAttraction()+offset); gen2.setPlantAttraction(gen2.getPlantAttraction()-offset); break; case 2: gen1.setHerbivoreAttraction(gen1.getHerbivoreAttraction()+offset); gen2.setHerbivoreAttraction(gen2.getHerbivoreAttraction()-offset); break; case 3: gen1.setCarnivoreAttraction(gen1.getCarnivoreAttraction()+offset); gen2.setCarnivoreAttraction(gen2.getCarnivoreAttraction()-offset); break; case 4: gen1.setDyingAttraction(gen1.getDyingAttraction()+offset); gen2.setDyingAttraction(gen2.getDyingAttraction()-offset); break; case 5: gen1.setOmnivoreAttraction(gen1.getOmnivoreAttraction()+offset); gen2.setOmnivoreAttraction(gen2.getOmnivoreAttraction()-offset); break; } return new Genetics[] {gen1, gen2}; }
6
public static void insertCommercial(int idservice, String nom, String prenom, String adresse1, String adresse2 ) throws SQLException { String query; try { query = "INSERT INTO COMMERCIAL (ID_VILLE,COMMNOM,COMMPRENOM,COMMADRESSE1,COMMADRESSE2) VALUES (?,?,?,?,?) "; PreparedStatement pStatement = ConnectionBDD.getInstance().getPreparedStatement(query); pStatement.setInt(1, idservice); pStatement.setString(2, nom); pStatement.setString(3, prenom); pStatement.setString(4, adresse1); pStatement.setString(5, adresse2); pStatement.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(RequetesCommercial.class.getName()).log(Level.SEVERE, null, ex); } }
1
public final void show() { StackPane parentRoot = (StackPane) ((Stage) stage.getOwner()) .getScene().getRoot(); parentRoot.getChildren().add(mask); stage.show(); }
0
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; StatefulContext other = (StatefulContext) obj; if (id != other.id) return false; return true; }
4
public void runGame() { WorldGUI view = new WorldGUI(world); for(int rounds=0; rounds<1000; rounds++){ for(int i = 0; i<127; i++){//127 ants per team in the game? step(i, Colour.RED); step(i, Colour.BLACK); } //refresh/update representation here if(rounds%15 == 0){ view.update(cellsToUpdateList); cellsToUpdateList.clear(); } } for(int x = 0; x<world.getRows(); x++){ for(int y = 0; y<world.getColumns(); y++){ Cell c = world.getCell(x,y); if(c.isAnt()){ c.removeAnt(); } } } view.endGame(); }
6
public void writeBoolean(boolean v) throws IOException { if (trace == API_TRACE_DETAILED) { Log.current.println("writeBoolean = " + v); } if (v) { writeSymbol(CycObjectFactory.t); } else { writeSymbol(CycObjectFactory.nil); } }
2
private static String hashPieces(File source) throws NoSuchAlgorithmException, IOException { MessageDigest md = MessageDigest.getInstance("SHA-1"); FileInputStream fis = new FileInputStream(source); StringBuffer pieces = new StringBuffer(); byte[] data = new byte[Torrent.PIECE_LENGTH]; int read; while ((read = fis.read(data)) > 0) { md.reset(); md.update(data, 0, read); pieces.append(new String(md.digest(), Torrent.BYTE_ENCODING)); } fis.close(); int n_pieces = new Double(Math.ceil((double)source.length() / Torrent.PIECE_LENGTH)).intValue(); logger.debug("Hashed " + source.getName() + " (" + source.length() + " bytes) in " + n_pieces + " pieces."); return pieces.toString(); }
1
protected void setUDPOptionsEnabled(boolean enabled) { lb_udpBufferSize.setEnabled(enabled); udpBufferSize.setEnabled(enabled && lb_udpBufferSize.isSelected()); udpBufferSizeUnit.setEnabled(enabled && lb_udpBufferSize.isSelected()); lb_udpPacketSize.setEnabled(enabled); udpPacketSize.setEnabled(enabled && lb_udpPacketSize.isSelected()); udpPacketSizeUnit.setEnabled(enabled && lb_udpPacketSize.isSelected()); lb_udpBandwidth.setEnabled(!serverModeRadioButton.isSelected() && enabled); udpBandwidth.setEnabled(!serverModeRadioButton.isSelected() && enabled); udpBandwidthUnit.setEnabled(!serverModeRadioButton.isSelected() && enabled); // other options lb_TTL.setEnabled(!serverModeRadioButton.isSelected() && enabled); TTL.setEnabled(!serverModeRadioButton.isSelected() && enabled); }
9
protected int countNeighbours(int col, int row) { int total = 0; total = getCell(col-1, row-1) ? total + 1 : total; total = getCell( col , row-1) ? total + 1 : total; total = getCell(col+1, row-1) ? total + 1 : total; total = getCell(col-1, row ) ? total + 1 : total; total = getCell(col+1, row ) ? total + 1 : total; total = getCell(col-1, row+1) ? total + 1 : total; total = getCell( col , row+1) ? total + 1 : total; total = getCell(col+1, row+1) ? total + 1 : total; return total; }
8
void setExampleWidgetAlignment () { int alignment = 0; if (leftButton.getSelection ()) alignment = SWT.LEFT; if (centerButton.getSelection ()) alignment = SWT.CENTER; if (rightButton.getSelection ()) alignment = SWT.RIGHT; label1.setAlignment (alignment); label2.setAlignment (alignment); label3.setAlignment (alignment); label4.setAlignment (alignment); label5.setAlignment (alignment); label6.setAlignment (alignment); }
3
public static void initialize(ParseMode mode) { System.out.println("started"); props = new Properties(); if (mode == ParseMode.POS) { props.put("annotators", "tokenize, ssplit, pos"); } else if (mode == ParseMode.WORD_TOKENIZE) { props.put("annotators", "tokenize, ssplit"); } else if (mode == ParseMode.NONE) { props.put("annotators", ""); } pipeline = new StanfordCoreNLP(props); }
3
@Override public boolean execute(SimpleTowns plugin, CommandSender sender, String commandLabel, String[] args) { final Localisation localisation = plugin.getLocalisation(); if (!(sender instanceof Player)) { sender.sendMessage(localisation.get(LocalisationEntry.ERR_PLAYER_ONLY_COMMAND)); return true; } if (args.length == 0) { sender.sendMessage(localisation.get(LocalisationEntry.ERR_SPECIFY_TOWN)); return false; } final Player player = (Player) sender; final Town town = plugin.getTown(args[0]); // Check town exists if (town == null) { sender.sendMessage(localisation.get(LocalisationEntry.ERR_TOWN_NOT_FOUND, args[0])); return true; } // Check they're a leader of that town. if (!(town.getLeaders().contains(sender.getName())) && !sender.hasPermission(STPermission.ADMIN.getPermission())) { sender.sendMessage(localisation.get(LocalisationEntry.ERR_NOT_LEADER, town.getName())); return true; } // Check there isn't already a town in that chunk final Chunk chunk = player.getLocation().getChunk(); final Town chunkOwner = plugin.getTown(chunk); if (chunkOwner != null) { sender.sendMessage(localisation.get(LocalisationEntry.MSG_CHUNK_ALREADY_CLAIMED, chunkOwner.getName())); return true; } //Create and call TownClaimEvent final TownClaimEvent event = new TownClaimEvent(town, chunk, sender); plugin.getServer().getPluginManager().callEvent(event); // Check event has not been cancelled by event listeners if (event.isCancelled()) { return true; } final int chunkX = chunk.getX(); final int chunkZ = chunk.getZ(); final String worldname = chunk.getWorld().getName(); final TownChunk townchunk = new TownChunk(chunk); final String path = "Towns."; // Add chunk to town final String chunkString = chunkX + "," + chunkZ; final List<String> chunks = plugin.getConfig().getStringList(path + town.getName() + ".Chunks." + worldname); chunks.add(chunkString); plugin.getConfig().set(path + town.getName() + ".Chunks." + worldname, chunks); town.getTownChunks().add(townchunk); // Log to file new Logger(plugin).log(localisation.get(LocalisationEntry.LOG_CHUNK_CLAIMED, town.getName(), sender.getName(), worldname, chunkX, chunkZ)); // Save config plugin.saveConfig(); // Send confimation message to sender sender.sendMessage(localisation.get(LocalisationEntry.MSG_CHUNK_CLAIMED, town.getName())); return true; }
7
private void scavenge() { Thread thread = Thread.currentThread(); ClassLoader old_loader = thread.getContextClassLoader(); try { if (_handler==null) return; ClassLoader loader = _handler.getClassLoader(); if (loader!=null) thread.setContextClassLoader(loader); long now = System.currentTimeMillis(); // Since Hashtable enumeration is not safe over deletes, // we build a list of stale sessions, then go back and invalidate them Object stale=null; synchronized(AbstractSessionManager.this) { // For each session for (Iterator i = _sessions.values().iterator(); i.hasNext(); ) { Session session = (Session)i.next(); long idleTime = session._maxIdleMs; if (idleTime > 0 && session._accessed + idleTime < now) { // Found a stale session, add it to the list stale=LazyList.add(stale,session); } } } // Remove the stale sessions for (int i = LazyList.size(stale); i-->0;) { // check it has not been accessed in the meantime Session session=(Session)LazyList.get(stale,i); long idleTime = session._maxIdleMs; if (idleTime > 0 && session._accessed + idleTime < System.currentTimeMillis()) { session.invalidate(); int nbsess = this._sessions.size(); if (nbsess < this._minSessions) this._minSessions = nbsess; } } } finally { thread.setContextClassLoader(old_loader); } }
9
@Override public void update(GameContainer gc, StateBasedGame game, int delta) throws SlickException { super.update(gc, game, delta); player.update(gc, game, delta); map.update(gc, game, delta); if(gc.getInput().isKeyPressed(Input.KEY_D)) { if(((Game) game).isDebug()) ((Game) game).setDebug(false); else ((Game) game).setDebug(true); } else if(gc.getInput().isKeyPressed(Input.KEY_ESCAPE)) { game.enterState(Game.PAUSE_STATE_ID, new FadeOutTransition(), new FadeInTransition()); } }
3
public void fillUnobstructedArea(Graphics g, int pixelsize) { g.setColor(Color.green); for (int i = 0; i < gui.getWidth(); i += pixelsize) for (int j = 0; j < gui.getHeight(); j += pixelsize) if (!AngleElimination.isObstructed(new Vertex(i+pixelsize/2, j+pixelsize/2))) g.fillRect(i, j, pixelsize, pixelsize); }
3
@Override public boolean show() { if (!getTab().open()) return false; final WidgetChild list = Widgets.get(EMOTE_WIDGET, EMOTE_LIST); if (list == null || !list.visible()) return false; final WidgetChild emote = list.getChild(childId); return Widgets.scroll(emote, Widgets.get(EMOTE_WIDGET, EMOTE_SCROLLBAR)) && emote.visible() && list.getBoundingRectangle().contains(emote.getBoundingRectangle()); }
5
private void handleAdjustShooterAngle(PlayerAdjustShooterAnglePacket packet) { ClientPlayer player = getPlayer(packet.name); if (player != null) { player.setShooterAngle(packet.angle); } }
1
public void mouseReleased(MouseEvent e) { if (!b.isEnabled()) return; if (b instanceof javax.swing.JButton) { b.setBorder(inactive); b.setBorderPainted(false); } }
2
public void updateSprite(int currentState) { switch (currentState) { case 0: currentSprite.set(new Sprite(Art.player[2][0])); currentSprite.flip(true, false); break; case 1: currentSprite.set(new Sprite(Art.player[2][0])); break; case 2: currentSprite.set(new Sprite(Art.player[1][0])); break; case 3: currentSprite.set(new Sprite(Art.player[0][0])); break; } }
4
public boolean isSelected(){ return selected; }
0
public void fecharConexao(){ try { if(c != null) c.close(); if(stmt != null) stmt.close(); if(rs != null) rs.close(); } catch (SQLException ex) { Logger.getLogger(TrackingNumberWatcherDBConn.class.getName()).log(Level.SEVERE, null, ex); } }
4
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; }
1
void notifyListeners(Object created, Page modified, Object deleted) { Page root = null; if (created != null) root = findRoot(created); else if (modified != null) root = findRoot(modified); else if (deleted != null) root = findRoot(deleted); else throw new RuntimeException("Root was not found"); List<TreeModelListener> listeners = root.modelListeners; for (TreeModelListener l : listeners) { if (created != null) { TreeModelEvent e = new TreeModelEvent(this, getPath(created)); l.treeNodesInserted(e); } if (modified != null) { TreeModelEvent e = new TreeModelEvent(this, getPath(modified)); l.treeNodesChanged(e); } if (deleted != null) { TreeModelEvent e = new TreeModelEvent(this, getPath(deleted)); l.treeNodesRemoved(e); l.treeStructureChanged(new TreeModelEvent(this, getPath(root))); } } }
7
@EventHandler public void PlayerPoison(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getPlayerConfig().getDouble("Player.Poison.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getPlayerConfig().getBoolean("Player.Poison.Enabled", true) && damager instanceof Player && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, plugin.getPlayerConfig().getInt("Player.Poison.Time"), plugin.getPlayerConfig().getInt("Player.Poison.Power"))); } }
6
public void neglectDeath(Player p, Entity animal ){ if(this.willDie && this.getAge() < 120){ p.getWorld().createExplosion(animal.getLocation().getX(), animal.getLocation().getY(), animal.getLocation().getZ(), (float)0, false, false); animal.remove(); animalUtility au = new animalUtility(plugin); this.animalNoise(animal, p); this.removeAnimalData(); Bukkit.broadcastMessage(ChatColor.RED + p.getName() + " has had an animal die of neglect!"); List<Entity> en = p.getNearbyEntities(10, 10, 10); for(Entity se : en){ if(au.isAnimal(se)){ if(au.isAnimalOwner(p, animal)){ Animals news = new Animals(plugin, se.getUniqueId().toString(), p.getUniqueId().toString()); news.addHeartPoint(-1); p.sendMessage(news.getAnimalName() + " doesn't look at you the same"); } } } } }
5
public Object getFieldValue(_Fields field) { switch (field) { case ID: return Long.valueOf(getId()); case NAME: return getName(); case PRICE: return Integer.valueOf(getPrice()); } throw new IllegalStateException(); }
3
public int getDistance(String after) { if (ignoreSize) after = StringSizeConverter.getFullString(after); int[][] cost = new int[before.length() + 1][after.length() + 1]; for (int i = 0; i < cost.length; i++) cost[i][0] = i; for (int i = 0; i < cost[0].length; i++) cost[0][i] = i; int eq; for (int i = 1; i < cost.length; i++) for (int j = 1; j < cost[i].length; j++) { eq = getCost(before.charAt(i - 1), after.charAt(j - 1)); cost[i][j] = minimum(cost[i - 1][j - 1] + eq, cost[i][j - 1] + a_r, cost[i - 1][j] + a_r); } return cost[cost.length - 1][cost[0].length - 1]; }
5
protected void fireTreeNodesInserted(Object source, TreePath path, int[] childIndices, Object[] children) { // Guaranteed to return a non-null array Object[] listeners = this.listenerList.getListenerList(); TreeModelEvent e = null; // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == TreeModelListener.class) { // Lazily create the event: if (e == null) { e = new TreeModelEvent(source, path, childIndices, children); } ((TreeModelListener) listeners[i + 1]).treeNodesInserted(e); } } }
3
public static void main(String args[]) throws java.io.IOException { char ch; char answer = 'K'; System.out.println("I'm thinking of a letter between A and Z."); System.out.print("Can you guess it?: "); ch = (char) System.in.read(); //read character from keyboard if(ch == answer) System.out.println("** Jou slim kind"); else { System.out.print("..try again you're "); if (ch < answer) System.out.println(" too low."); else System.out.println(" too high."); } }
2
private Inventory solveExhaustivelyRecursively(int indexOfNextItem, int remainingCapacity, ArrayList<Double> result, int value) { if (indexOfNextItem >= items.size()) { return new Inventory(this, result, value); } Item nextItem = items.get(indexOfNextItem); result.add(0.0); Inventory resultWhenExcluded = solveExhaustivelyRecursively(indexOfNextItem + 1, remainingCapacity, result, value); result.set(result.size() - 1, 1.0); Inventory resultWhenIncluded = solveExhaustivelyRecursively(indexOfNextItem + 1, remainingCapacity, result, value + nextItem.getValue()); result.remove(result.size() - 1); if (resultWhenIncluded.getTotalValue() >= resultWhenExcluded.getTotalValue() && resultWhenIncluded.getTotalWeight() <= remainingCapacity) { return resultWhenIncluded; } else { return resultWhenExcluded; } }
3
public void deleteUser(User user) { try { beginTransaction(); session.delete(user); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); } finally { closeSession(); } }
1
public static void main(String[] args) { System.out.println("Starting."); System.out.flush(); final Semaphore sem = new Semaphore(0); for (int i = 0; i < 10; i++) { System.out.println("Queing proc " + i); System.out.flush(); final int threadNum = i; getDefaultPool().execute(new Runnable() { public void run() { try { System.out.println("Starting proc " + threadNum); System.out.flush(); Thread.currentThread().sleep(threadNum + 5000); sem.release(); System.out.println("Finished proc " + threadNum); System.out.flush(); } catch (Exception e) {} // dont care } }); } try { sem.acquire(10); } catch (Exception e) {} // dont care System.out.println("Quitting."); System.exit(0); }
3
public Cuenta getDestino(){ return this.destino; }
0
public List validate() { String error; if(!isNameValidate()) { error = "Name is not valid."; validateErrors.add(error); } if(!isSurnameValidate()) { error = "Surname is not valid."; validateErrors.add(error); } if(!isBirthdayValidate()) { error = "Birthday is not valid."; validateErrors.add(error); } if(!isEmailValidate()) { error = "Email is not valid."; validateErrors.add(error); } if(!isPasswordValidate()) { error = "Password is not valid."; validateErrors.add(error); } if(!isPasswordAndConfirmEquals()) { error = "Password and password confirm not equals."; validateErrors.add(error); } return this.validateErrors; }
6
private String readStringUTF8(byte[] remainingData, int stringIdx) throws IOException { // skip the length, will usually be 0x1A1A // int strLen = readUInt16(remainingData, stringIdx); // the length here is somehow weird int strLen = readUInt8(remainingData, stringIdx + 1); stringIdx += 2; String str = new String(remainingData, stringIdx, strLen, "UTF-8"); return str; }
0
@Test public void testTimeStep_DAILY2_period() throws Exception { printDebug("----------------------------"); printDebug("DAILY with Period Range: " + this.toString()); printDebug("----------------------------"); CSTable t = DataIO.table(r, "obs"); Assert.assertNotNull(t); // 1 YEAR Date start = Conversions.convert("1981-1-01", Date.class); Date end = Conversions.convert("1981-2-14", Date.class); printDebug("Start = " + start.toString() + "; End = " + end.toString()); int periodStart=May; boolean[] periodMask = new boolean[12]; periodMask[Jan] = false; periodMask[Feb] = true; periodMask[Mar] = true; periodMask[Apr] = false; periodMask[May] = false; periodMask[Jun] = false; periodMask[Jul] = true; periodMask[Aug] = true; periodMask[Sep] = false; periodMask[Oct] = true; periodMask[Nov] = true; periodMask[Dec] = true; double[] obsval = DataIO.getColumnDoubleValuesInterval(start, end, t, "runoff[0]", DataIO.DAILY, periodStart, periodMask, null); printDebug("# values = " + obsval.length); Assert.assertTrue(obsval.length == 14); // Values directly from table double[] goldenVal = new double[14]; goldenVal[0] = 83; goldenVal[1] = 84; goldenVal[2] = 85; goldenVal[3] = 86; goldenVal[4] = 86; goldenVal[5] = 87; goldenVal[6] = 88; goldenVal[7] = 96; goldenVal[8] = 98; goldenVal[9] = 91; goldenVal[10] = 97; goldenVal[11] = 98; goldenVal[12] = 107; goldenVal[13] = 308; // goldenVal[14] = 75; for (int i = 0; i < obsval.length; i++) { printDebug("obs[" + i + "] = " + obsval[i] + ";\tGolden = " + goldenVal[i]); } Assert.assertArrayEquals(goldenVal, obsval, 0); }
1
@Override public void layoutContainer(final Container target) { final Dimension d = target.getSize(); final Insets insets = target.getInsets(); // preferred layout size for Image5dCanvas final Dimension prefCanvasSize = new Dimension(d); contentBounds.x = insets.left; contentBounds.y = insets.top; // Widths of canvasses contentBounds.width = d.width - (contentBounds.x + getVerticalControlsWidth() + insets.right); if (slice != null) { contentBounds.width = Math.max(contentBounds.width, slice.getMinimumSize().width + 2 * hgap); } if (frame != null) { contentBounds.width = Math.max(contentBounds.width, frame.getMinimumSize().width + 2 * hgap); } prefCanvasSize.width = (int) Math.floor((contentBounds.width - hgap) / (double) nCanvassesX) - hgap; // Heights of canvasses contentBounds.height = d.height - (contentBounds.y + insets.bottom); if (channel != null) { contentBounds.height = Math.max(contentBounds.height, channel.getMinimumSize().height + 2 * vgap); } contentBounds.height -= getHorizontalControlsHeight(); prefCanvasSize.height = (int) Math.floor((contentBounds.height - vgap) / (double) nCanvassesY) - vgap; // Resize the ImageCanvas5D. This also resizes its "satellite" canvasses // in montage display mode. final Dimension canvasDim = ic5d.resizeCanvasI5D(prefCanvasSize.width, prefCanvasSize.height); final int offsX = insets.left; final int offsY = insets.top; // Place canvasses in center of area spanned by the controls. final int mainOffsX = offsX + (d.width - offsX - getVerticalControlsWidth() - insets.right - canvasDim.width * nCanvassesX - hgap * (nCanvassesX - 1)) / 2; final int mainOffsY = offsY + (d.height - offsY - getHorizontalControlsHeight() - insets.bottom - canvasDim.height * nCanvassesY - hgap * (nCanvassesY - 1)) / 2; // Set location of canvasses and store location and size in // canvasRectangles. // Canvas #0 is in lower right corner for (int i = 0; i < nCanvassesX * nCanvassesY; i++) { // Canvas #0 is in lower right corner (overlay). The others start from top // left. int j = 0; if (i == 0) j = nCanvassesX * nCanvassesY - 1; else j = i - 1; final int nX = j % nCanvassesX; final int nY = j / nCanvassesX; final int tempOffsX = mainOffsX + nX * (canvasDim.width + hgap); final int tempOffsY = mainOffsY + nY * (canvasDim.height + vgap); if (i < imageCanvasses.size()) { ((Canvas) imageCanvasses.get(i)).setLocation(tempOffsX, tempOffsY); final Rectangle imageRect = imageRectangles.get(i); imageRect.x = tempOffsX; imageRect.y = tempOffsY; imageRect.width = canvasDim.width; imageRect.height = canvasDim.height; } // TODO: Add black Canvasses to locations up to n-1 (??) } // Set locations and sizes of controls. int y = d.height - insets.bottom - getHorizontalControlsHeight() - vgap; if (slice != null) { slice.setSize(contentBounds.width - 2 * hgap, slice.getPreferredSize().height); y += vgap; slice.setLocation(offsX + hgap, y); y += slice.getPreferredSize().height; } if (frame != null) { frame.setSize(contentBounds.width - 2 * hgap, frame.getPreferredSize().height); y += vgap; frame.setLocation(offsX + hgap, y); y += frame.getPreferredSize().height; } int x = d.width - insets.right - getVerticalControlsWidth() - vgap; if (channel != null) { channel.setSize(channel.getPreferredSize().width, d.height - insets.top - insets.bottom - 2 * vgap); x += hgap; channel.setLocation(x, offsY + vgap); x += channel.getPreferredSize().width; } }
9
public void lancer() { System.out.println("lancement du serveur ..."); String[] serveursIP = { "http://checkip.amazonaws.com/", "http://icanhazip.com/", "http://curlmyip.com/", "http://www.trackip.net/ip" }; for (String servIP : serveursIP) { try { URL whatismyip = new URL(servIP); BufferedReader in = new BufferedReader(new InputStreamReader(whatismyip.openStream())); String ip = in.readLine(); if (ip != null) { System.out.println("ip à indiquer : " + ip); break; } } catch (IOException e1) { e1.printStackTrace(); } } while (!this.quitter) { System.out.println("--- Attente de nouvelle connexion ---"); try { Socket clientSocket = serverSocket.accept(); InputStream is = clientSocket.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String ligne = br.readLine(); if (ligne == null) { System.out.println("--- Message null ---"); clientSocket.close(); } else if (ligne.startsWith("mouseClicker newclient")) { System.out.println("--- Demande de nouveau client ---"); String[] elementsLigne = ligne.split(" "); if (elementsLigne.length == 3) { String nom = elementsLigne[2]; System.out.println("--- Création client " + nom + " ---"); GestionClient gc = new GestionClient(clientSocket, nom); gc.getPlayer().addObserver(this); listeGestionClients.add(gc); Thread t = new Thread(gc); t.start(); } } else { System.out.println("--- Requete Invalide ---"); clientSocket.close(); } } catch (SocketException e) { System.out.println("--- Fin recherche de connexion ---"); } catch (IOException e) { e.printStackTrace(); } } System.out.println("--- Fin serveur ---"); }
9
@Override public void update(Stage stage) { updateFleeRange(); ArrayList<Actor> actors = new ArrayList<Actor>(); actors = PropQuad.get().getActors(fleeRange); if(!actors.isEmpty()) { if(actors.size() > 1) { Actor target = getClosestTarget(actors); if(target != null) { source.getAI().setTarget(target); source.getAI().sendAlert(AIAlert.THREATENED, 1f); } } actors = null; } }
3
public static int[] generateRandomIntArray(int size, boolean allowsDuplicate, int min, int max)throws ArrayIndexOutOfBoundsException { if(countNumbersInRange(min, max) < size) { throw new ArrayIndexOutOfBoundsException(); } int randArr[] = new int[size]; int randNum = MathUtils.generateRandomNumb(min, max); for(int i = 0; i < size; i++) { if(SearchAndSort.linearIntSearch(randArr, randNum) && !allowsDuplicate) { while(true) { randNum = MathUtils.generateRandomNumb(min, max); if(!SearchAndSort.linearIntSearch(randArr, randNum)) { randArr[i] = randNum; break; } } } randArr[i] = randNum; randNum = MathUtils.generateRandomNumb(min, max); } return randArr; }
6
public void encrypt(InputStream in, OutputStream out) throws IOException { byte inbuf[] = new byte[8]; byte outbuf[] = new byte[8]; boolean done = false; while (!done) { int n = readn(in, inbuf, 8); if (n < 8) { done = true; int m = n; while (n < 7) inbuf[n++] = 0; inbuf[n++] = (byte) (m & 0xff); } DES.des_ecb_encrypt(inbuf, outbuf, schedule, true); out.write(outbuf, 0, 8); } }
3
public static void quicksort(Comparable[] a, int lo, int hi) { if (lo < hi) { int pivotIndex = lo; Comparable pivot = a[pivotIndex]; a[pivotIndex] = a[hi]; a[hi] = pivot; int i = lo - 1; int j = hi; do { do { i++; } while (a[i].compareTo(pivot) < 0); do { j--; } while ((a[j].compareTo(pivot) > 0) && (j > lo)); if (i < j) { Comparable holder = a[i]; a[i]=a[j]; a[j] = holder; } } while (i < j); a[hi] = a[i]; a[i] = pivot; quicksort(a, lo, i - 1); quicksort(a, i + 1, hi); } }
6
@Override public void startSetup(Attributes atts) { String id = atts.getValue(A_ID); setCommand(id); Outliner.prefs.addPreference(id, this); }
0
public void enqueue(E e) { if (e == null) return; Node u = new Node(e); if (tail != null) tail.setNext(u); tail = u; if (isEmpty()) head = tail; size++; }
3
private void replacedata( boolean repl ) { if(isReadOnly()) return; try { fdbf.seek( recordpos() ); } catch (IOException e) {} writeChars(0,1,(repl && deleted ? "*" : " ")); for(int i=0;i<fcount;i++) replacefielddata(i); update_key(); getfieldsValues(); }
5
public boolean containsAttribute(String locationpath){ if (locationpath.contains("@") || locationpath.contains("attribute::")){ return true; }else{ return false; } }
2
public ArrayList<String> readFile(String arg) { String thisLine; ArrayList<String> fileToRead = new ArrayList<String>(); try { //BufferedReader to scan in the file BufferedReader buffy = new BufferedReader(new FileReader(arg)); while((thisLine = buffy.readLine()) != null && !thisLine.substring(0,7).trim().equals("ENDMDL")) { //while there are still lines in the document fileToRead.add(thisLine); } //end while } // end try catch (IOException ioe) { System.err.println("Error: " + ioe); fileToRead.clear(); } return fileToRead; }
3
protected static Ptg calcINTRATE( Ptg[] operands ) { if( operands.length < 4 ) { return new PtgErr( PtgErr.ERROR_NULL ); } debugOperands( operands, "calcINTRATE" ); try { GregorianCalendar sDate = (GregorianCalendar) DateConverter.getCalendarFromNumber( operands[0].getValue() ); GregorianCalendar mDate = (GregorianCalendar) DateConverter.getCalendarFromNumber( operands[1].getValue() ); double investment = operands[2].getDoubleVal(); double redemption = operands[3].getDoubleVal(); int basis = 0; if( operands.length > 4 ) { basis = operands[4].getIntVal(); } // TODO: if dates are not valid, return #VALUE! error if( (basis < 0) || (basis > 4) ) { return new PtgErr( PtgErr.ERROR_NUM ); } if( !sDate.before( mDate ) ) { return new PtgErr( PtgErr.ERROR_NUM ); } if( (investment <= 0) || (redemption <= 0) ) { return new PtgErr( PtgErr.ERROR_NUM ); } long settlementDate = (new Double( DateConverter.getXLSDateVal( sDate ) )).longValue(); long maturityDate = (new Double( DateConverter.getXLSDateVal( mDate ) )).longValue(); // double delta = maturityDate - settlementDate; // double result = ((redemption - investment) / investment) * ((getDaysInYearFromBasis(basis, settlementDate, maturityDate) / delta)); double result = ((redemption - investment) / investment) / yearFrac( basis, settlementDate, maturityDate ); PtgNumber pnum = new PtgNumber( result ); log.debug( "Result from calcINTRATE= " + result ); return pnum; } catch( Exception e ) { } return new PtgErr( PtgErr.ERROR_VALUE ); }
8
public int getProcessMode() { return processMode; }
0
@Override public String toString() { String name = getName(); String append = ""; if(name != null && !name.equals("")) { append = "(\"" + this.getName() + "\")"; } return "TAG_Float" + append + ": " + value; }
2
public void popEntriesSymbolTable(int numberToRemove) { symbolTable.popEntries(numberToRemove); }
0
@Override public void actionPerformed(ActionEvent e) { JTextField rowField = new JTextField("", 5); JTextField colField = new JTextField("", 5); JPanel myPanel = new JPanel(); myPanel.add(new JLabel("Rows:")); myPanel.add(rowField); myPanel.add(Box.createHorizontalStrut(15)); // a spacer myPanel.add(new JLabel("Columns:")); myPanel.add(colField); int result = JOptionPane.OK_OPTION; String rowInput = rowField.getText(); String colInput = colField.getText(); while ((result == JOptionPane.OK_OPTION) && (!rowInput.matches("[0-9]{1,3}") || (!colInput .matches("[0-9]{1,2}")))) { result = JOptionPane.showConfirmDialog(tabManager, myPanel, "Please Enter the Number of Rows and Columns", JOptionPane.OK_CANCEL_OPTION); rowInput = rowField.getText(); colInput = colField.getText(); } if (result == JOptionPane.OK_OPTION) { int numRows = Integer.parseInt(rowInput); int numCols = Integer.parseInt(colInput); String inputText = "<table>\n"; for (int row = 0; row < numRows; row++) { inputText += " <tr>\n"; for (int col = 0; col < numCols; col++) { inputText += " <td></td>\n"; } inputText += " </tr>\n"; } inputText += "</table>"; tabManager.InsertText(inputText); } }
6
private void swim(int k) { while (k > 1 && greater(k / 2, k)) { exch(k, k / 2); k = k / 2; } }
2
public float getY() { return y; }
0
public Model getRotatedModel() { if(desc == null) return null; Model model = method450(); if(model == null) return null; super.height = model.modelHeight; if(super.anInt1520 != -1 && super.anInt1521 != -1) { SpotAnim spotAnim = SpotAnim.cache[super.anInt1520]; Model model_1 = spotAnim.getModel(); if(model_1 != null) { int j = spotAnim.aAnimation_407.anIntArray353[super.anInt1521]; Model model_2 = new Model(true, Class36.method532(j), false, model_1); model_2.method475(0, -super.anInt1524, 0); model_2.method469(); model_2.method470(j); model_2.anIntArrayArray1658 = null; model_2.anIntArrayArray1657 = null; if(spotAnim.anInt410 != 128 || spotAnim.anInt411 != 128) model_2.method478(spotAnim.anInt410, spotAnim.anInt410, spotAnim.anInt411); model_2.method479(64 + spotAnim.anInt413, 850 + spotAnim.anInt414, -30, -50, -30, true); Model aModel[] = { model, model_2 }; model = new Model(aModel); } } if(desc.aByte68 == 1) model.aBoolean1659 = true; return model; }
8
boolean isMatch(String str, int i, String pat, int j, Map<Character, String> map, Set<String> set) { // base case if (i == str.length() && j == pat.length()) return true; if (i == str.length() || j == pat.length()) return false; // get current pattern character char c = pat.charAt(j); // if the pattern character exists if (map.containsKey(c)) { String s = map.get(c); // then check if we can use it to match str[i...i+s.length()] if (!str.startsWith(s, i)) { return false; } // if it can match, great, continue to match the rest return isMatch(str, i + s.length(), pat, j + 1, map, set); } // pattern character does not exist in the map for (int k = i; k < str.length(); k++) { String p = str.substring(i, k + 1); //!!! if (set.contains(p)) { continue; } // create or update it map.put(c, p); set.add(p); // continue to match the rest if (isMatch(str, k + 1, pat, j + 1, map, set)) { return true; } // backtracking map.remove(c); set.remove(p); } // we've tried our best but still no luck return false; }
9
public int getCount(ArrayList<FilterBean> hmFilter) throws Exception { int pages; try { oMysql.conexion(enumTipoConexion); pages = oMysql.getCount("empresa", hmFilter); oMysql.desconexion(); return pages; } catch (Exception e) { throw new Exception("EmpresaDao.getCount: Error: " + e.getMessage()); } }
1
public void keyPressed(KeyBindingEvent keyBindingEvent) { //Only toggle state when not on the gamescreen if (!keyBindingEvent.getScreenType().equals(ScreenType.GAME_SCREEN)) { return; } SpoutPlayer sPlayer = keyBindingEvent.getPlayer(); if(sPlayer.hasPermission("playerplus.use")) { new TextureChooser(PlayerPlus.getInstance(), keyBindingEvent.getPlayer()); } }
2
public DocumentAttributesPanel getDocumentAttributesPanel() { return this.attPanel; }
0
@EventHandler public void PlayerNausea(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getPlayerConfig().getDouble("Player.Nausea.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getPlayerConfig().getBoolean("Player.Nausea.Enabled", true) && damager instanceof Player && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, plugin.getPlayerConfig().getInt("Player.Nausea.Time"), plugin.getPlayerConfig().getInt("Player.Nausea.Power"))); } }
6
private void startSimulation() throws InterruptedException { start = System.currentTimeMillis(); SimpleDirectedWeightedGraph<Node, DefaultWeightedEdge> swg = createMapGraph(); Queue<Node> pathForVehicle = getPathForVehicle(vehicle, swg, null); if(pathForVehicle.isEmpty()) { removeTemporaryStreets(); throw new NoPathFoundExceptionException(vehicle.getName()); } Node n = pathForVehicle.poll(); //statistics if(n!=null){ vehicle.addNode(n); } while(!vehicle.getCurrentNode().equals(vehicle.getFinishNode())){ vehicle.setNextNode(pathForVehicle.poll()); Street currentStreet = null; for(int i = 0; i<simulationEditorModel.getMapEditorModel().getStreets().size(); i++) { Street street = simulationEditorModel.getMapEditorModel().getStreets().get(i); if(street.getStart().equals(vehicle.getCurrentNode()) && street.getEnd().equals(vehicle.getNextNode()) || street.getStart().equals(vehicle.getNextNode()) && street.getEnd().equals(vehicle.getCurrentNode())){ currentStreet = street; break; } } currentStreet.getVehicles().add(vehicle); driveFromTo(vehicle.getCurrentNode(), vehicle.getNextNode(), currentStreet); //statistics vehicle.addNode(vehicle.getNextNode()); vehicle.setCurrentNode(vehicle.getNextNode()); currentStreet.getVehicles().remove(vehicle); } //reinitialize the current Node so a new simulation can be performed vehicle.setCurrentNode(vehicle.getStartNode()); //statistics vehicle.addNode(vehicle.getFinishNode()); updateStatistics(); removeTemporaryStreets(); }
8
private void extractFile(String name) { File actual = new File(getDataFolder(), name); if (!actual.exists()) { InputStream input = getClass().getResourceAsStream("/Default_Files/" + name); if (input != null) { FileOutputStream output = null; try { output = new FileOutputStream(actual); byte[] buf = new byte[8192]; int length = 0; while ((length = input.read(buf)) > 0) { output.write(buf, 0, length); } System.out.println(pluginNameBracket() + " Default file written: " + name); } catch (Exception e) { e.printStackTrace(); } finally { try { if (input != null) input.close(); } catch (Exception e) { } try { if (output != null) output.close(); } catch (Exception e) { } } } } }
8
public static int[][] TerrainLoad() { int[][] map= new int[320][240]; String filePath = "src/map.lvl"; Scanner scanner = null; try { scanner = new Scanner(new File(filePath)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } int i=0; int j=0; while (scanner.hasNextInt()) { int nb = scanner.nextInt(); map[i][j]=nb; i++; if(i==15) { i=0; j++; } } scanner.close(); return map; }
3
private boolean verificaQteAulaHorario(String anoletivo, Date datageracao) { Boolean resp = false; int ocorrmath = 0; int idmat = 0; List<Integer> idmatprof = new ArrayList<>(); for (int i = 0; i < erroperiodo.size(); i++) { try { List<HorarioAulaBeans> lhorario = new HorarioAulaDao().BuscaHorarioPeriodo(idcurso, anoletivo, datageracao, erroperiodo.get(i)); for (int j = 0; j < lhorario.size(); j++) { idmatprof.add(lhorario.get(j).getSegunda()); idmatprof.add(lhorario.get(j).getTerca()); idmatprof.add(lhorario.get(j).getQuarta()); idmatprof.add(lhorario.get(j).getQuinta()); idmatprof.add(lhorario.get(j).getSexta()); idmatprof.add(lhorario.get(j).getSabado()); idmatprof.add(lhorario.get(j).getDomingo()); } //JOptionPane.showMessageDialog(null, erroperiodo.get(i)); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao Verifica Qtde Ocorrencia Materia\n" + ex, "Gerar Horario", JOptionPane.ERROR_MESSAGE); } } Collections.sort(idmatprof); int cont = 0; idmat = idmatprof.get(0); for (int i = 0; i < idmatprof.size(); i++) { try { if (idmat != idmatprof.get(i)) { ocorrmath = new ProfessorMateriaDao().buscaProfessorQtdeOcorrHorario(idmat); new LogsTxt().setTxt(new Date() + " Ocorrencia Materia: " + idmat + "|" + ocorrmath + "|" + cont); if (ocorrmath != cont) { resp = true; } idmat = idmatprof.get(i); cont = 0; } cont++; if (idmatprof.size() == i + 1) { ocorrmath = new ProfessorMateriaDao().buscaProfessorQtdeOcorrHorario(idmatprof.get(i)); new LogsTxt().setTxt(new Date() + " Ocorencia Materia: " + idmat + "|" + ocorrmath + "|" + cont); if (ocorrmath != cont) { resp = true; } } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao Verifica Qtde Ocorrencia Materia\n" + ex, "Gerar Horario", JOptionPane.ERROR_MESSAGE); } } return resp; }
9
private void callSetter(HashMap<String, String> headerToFieldMap, T instance, Method method, CSVMapperSetterMethod annotation, Class<?> parameterType) { Class<?> wrapperType; if (parameterType.isPrimitive()) { wrapperType = wrapperMap.get(parameterType); } else { wrapperType = parameterType; } try { Object fieldValue = headerToFieldMap.get(annotation.fieldName()); Object fieldValueAsCorrectType; fieldValueAsCorrectType = getFieldValueAsCorrectType(wrapperType, fieldValue); method.invoke(instance, fieldValueAsCorrectType); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } }
5
public Record findById(java.lang.Integer id) { log.debug("getting Record instance with id: " + id); try { Record instance = (Record) getSession().get( "com.oj.hibernate.daoNdo.Record", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } }
1
public static void saveImage(BufferedImage img, File output) throws IOException { output.delete(); final String formatName = "png"; for (Iterator<ImageWriter> iw = ImageIO.getImageWritersByFormatName(formatName); iw.hasNext();) { ImageWriter writer = iw.next(); ImageWriteParam writeParam = writer.getDefaultWriteParam(); ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB); IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, writeParam); if (metadata.isReadOnly() || !metadata.isStandardMetadataFormatSupported()) { continue; } setDPI(metadata, 300); final ImageOutputStream stream = ImageIO.createImageOutputStream(output); try { writer.setOutput(stream); writer.write(metadata, new IIOImage(img, null, metadata), writeParam); } finally { stream.close(); } break; } }
3
private static void createAndShowGUI() { //Check the SystemTray support if (!SystemTray.isSupported()) { System.out.println("SystemTray is not supported"); return; } final PopupMenu popup = new PopupMenu(); final TrayIcon trayIcon = new TrayIcon(createImage("bulb.gif", "tray icon")); final SystemTray tray = SystemTray.getSystemTray(); // Create a popup menu components MenuItem aboutItem = new MenuItem("About"); CheckboxMenuItem cb1 = new CheckboxMenuItem("Set auto size"); CheckboxMenuItem cb2 = new CheckboxMenuItem("Set tooltip"); Menu displayMenu = new Menu("Display"); MenuItem errorItem = new MenuItem("Error"); MenuItem warningItem = new MenuItem("Warning"); MenuItem infoItem = new MenuItem("Info"); MenuItem noneItem = new MenuItem("None"); MenuItem exitItem = new MenuItem("Exit"); //Add components to popup menu popup.add(aboutItem); popup.addSeparator(); popup.add(cb1); popup.add(cb2); popup.addSeparator(); popup.add(displayMenu); displayMenu.add(errorItem); displayMenu.add(warningItem); displayMenu.add(infoItem); displayMenu.add(noneItem); popup.add(exitItem); trayIcon.setPopupMenu(popup); try { tray.add(trayIcon); } catch (AWTException e) { System.out.println("TrayIcon could not be added."); return; } trayIcon.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "This dialog box is run from System Tray"); } }); aboutItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "This dialog box is run from the About menu item"); } }); cb1.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { int cb1Id = e.getStateChange(); if (cb1Id == ItemEvent.SELECTED){ trayIcon.setImageAutoSize(true); } else { trayIcon.setImageAutoSize(false); } } }); cb2.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { int cb2Id = e.getStateChange(); if (cb2Id == ItemEvent.SELECTED){ trayIcon.setToolTip("Sun TrayIcon"); } else { trayIcon.setToolTip(null); } } }); ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { MenuItem item = (MenuItem)e.getSource(); //TrayIcon.MessageType type = null; System.out.println(item.getLabel()); if ("Error".equals(item.getLabel())) { //type = TrayIcon.MessageType.ERROR; trayIcon.displayMessage("Sun TrayIcon Demo", "This is an error message", TrayIcon.MessageType.ERROR); } else if ("Warning".equals(item.getLabel())) { //type = TrayIcon.MessageType.WARNING; trayIcon.displayMessage("Sun TrayIcon Demo", "This is a warning message", TrayIcon.MessageType.WARNING); } else if ("Info".equals(item.getLabel())) { //type = TrayIcon.MessageType.INFO; trayIcon.displayMessage("Sun TrayIcon Demo", "This is an info message", TrayIcon.MessageType.INFO); } else if ("None".equals(item.getLabel())) { //type = TrayIcon.MessageType.NONE; trayIcon.displayMessage("Sun TrayIcon Demo", "This is an ordinary message", TrayIcon.MessageType.NONE); } } }; errorItem.addActionListener(listener); warningItem.addActionListener(listener); infoItem.addActionListener(listener); noneItem.addActionListener(listener); exitItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { tray.remove(trayIcon); System.exit(0); } }); }
8
public void generateNotes() throws InvalidChordException { // If this is the first chord of the song, treat it differently. if (prevBeat == null) { generateFirstChord(); return; } // Until all the rules are followed, continue generating combinations. int tries = 0; boolean notesFollowAllRules = false; while (!notesFollowAllRules) { // Generate notes for each voice. try { for (int voiceIndx = 0; voiceIndx < numVoices; voiceIndx++) { generateNote(voiceIndx); } } catch (InvalidChordException ex) { continue; } // Check to make sure this beat follows all the rules. notesFollowAllRules = containsAllChordTones(chordTones, chord); notesFollowAllRules &= noParallelFifths(prevBeat.getChordTones(), chordTones); // Keep track of the number of attempts. If it goes on for too // long, give up. tries++; if (tries >= 100) { System.out.println("Cannot find note combination for this chord"); throw new InvalidChordException( "Cannot find note combination for this chord"); } } for (int voiceIndx = 0; voiceIndx < numVoices; voiceIndx++) { setPlayedNotes(voiceIndx); addNonChordTones(voiceIndx); } }
6
protected boolean checkCoverage() { int i; int n; int[] count; Range r; String attrIndex; SubspaceClusterDefinition cl; // check whether all the attributes are covered count = new int[getNumAttributes()]; for (i = 0; i < getNumAttributes(); i++) { for (n = 0; n < getClusters().length; n++) { cl = (SubspaceClusterDefinition) getClusters()[n]; r = new Range(cl.getAttrIndexRange()); r.setUpper(getNumAttributes()); if (r.isInRange(i)) count[i]++; } } // list all indices that are not covered attrIndex = ""; for (i = 0; i < count.length; i++) { if (count[i] == 0) { if (attrIndex.length() != 0) attrIndex += ","; attrIndex += (i+1); } } if (attrIndex.length() != 0) throw new IllegalArgumentException( "The following attributes are not covered by a cluster " + "definition: " + attrIndex + "\n"); return true; }
7
@BeforeClass public static void setUpClass() { }
0
private void fixColUp() { turnLeft(); while (frontIsClear()) { if (noBeepersPresent()) { putBeeper(); } move(); } if (noBeepersPresent()) { putBeeper(); } turnRight(); }
3
public static String classPackageAsResourcePath(Class<?> clazz) { if (clazz == null) { return ""; } String className = clazz.getName(); int packageEndIndex = className.lastIndexOf('.'); if (packageEndIndex == -1) { return ""; } String packageName = className.substring(0, packageEndIndex); return packageName.replace('.', '/'); }
3
public static void main(String[] args) { if (args.length < 1 || args.length >1){ System.out.println("Error: incorrect arguments"); } else { //Object to hold word information for given web pages. WebPages webPage = new WebPages(); //Commands from input file ArrayList<String> commands = parseInputFile(args[0]); ArrayList<String> nonEmptyCommands = new ArrayList<String>(); for(String command: commands){ if(command.trim().compareTo("") != 0) nonEmptyCommands.add(command); } commands = nonEmptyCommands; if (commands.size() == 0) { System.out.println("Error: empty file"); } else { //Scan in files until *EOF* command boolean reachedEOF = false; for (String command : commands) { if (command.equals("*EOFs*")) { webPage.printTerms(); reachedEOF = true; System.out.println(); continue; } if (!reachedEOF) { webPage.addPage(command); } if (reachedEOF) { webPage.getTermIndex().get(command, true); } } } } }
9
@Override public String runMacro(HTTPRequest httpReq, String parm, HTTPResponse httpResp) { final java.util.Map<String,String> parms=parseParms(parm); final String last=httpReq.getUrlParameter("FACTION"); if(parms.containsKey("RESET")) { if(last!=null) httpReq.removeUrlParameter("FACTION"); return ""; } String lastID=""; Faction F; String factionID; for(final Enumeration q=CMLib.factions().factions();q.hasMoreElements();) { F=(Faction)q.nextElement(); factionID=F.factionID().toUpperCase().trim(); if((last==null)||((last.length()>0)&&(last.equals(lastID))&&(!factionID.equalsIgnoreCase(lastID)))) { httpReq.addFakeUrlParameter("FACTION",factionID); return ""; } lastID=factionID; } httpReq.addFakeUrlParameter("FACTION",""); if(parms.containsKey("EMPTYOK")) return "<!--EMPTY-->"; return " @break@"; }
8
@Override public void run() { while(true) { while(queueOfMessages.peekFirst() != null) { String s = queueOfMessages.removeFirst(); Iterator<Client> iteratorOfClients = listOfClients.iterator(); while(iteratorOfClients.hasNext()) { Client client = iteratorOfClients.next(); if(client.isConnected() && client.isLogged()) { client.println(s); } } } try { Thread.sleep(100); } catch(InterruptedException e) { System.err.println("InterruptedException"); } } }
6
@Override public ArrayList<Object> show(int id) { conn = new SQLconnect().getConnection(); ArrayList<Object> tns = new ArrayList<Object>(); try { String sql = "select * from eventnodes where display = 'true' and owner = "+ id + ";"; Statement st = (Statement) conn.createStatement(); // 创建用于执行静态sql语句的Statement对象 ResultSet rs = st.executeQuery(sql); // 执行查询操作的sql语句,并返回插入数据的个数 while (rs.next()) { int event_id = rs.getInt("id"); int owner = rs.getInt("owner"); String description = rs.getString("description"); Eventnode tmp = new Eventnode(owner, description); tmp.setId(event_id); tns.add(tmp); } conn.close(); } catch (Exception e) { e.printStackTrace(); } return tns; }
2
protected void appendLabel(final Label l) { String name = (String) labelNames.get(l); if (name == null) { name = "L" + labelNames.size(); labelNames.put(l, name); } buf.append(name); }
1
private void drawExits(Graphics g){ g.setColor(exitColor); //int size = this.getWidth() / 10; int xPos = 0; int yPos = 0; int width = 0; int height = 0; for (Relative_Direction dir: room.getAbsoluteExits()){ //Relative_Direction dir = room.convertAbsoluteDirectionToRoomRelativeDirection(exit); switch (dir){ case NORTH: height = 10; width = this.getWidth() / 2; yPos = 0; xPos = (this.getWidth() - width)/2; break; case SOUTH: height = 10; width = this.getWidth() / 2; yPos = this.getHeight()-height; xPos = (this.getWidth() - width)/2; break; case EAST: width = 10; height = this.getHeight() / 2; yPos = (this.getHeight() - height)/2; xPos = this.getWidth()-width; break; case WEST: width = 10; height = this.getHeight() / 2; yPos = (this.getHeight() - height)/2; xPos = 0; break; default: continue; } g.fillRect(xPos, yPos, width, height); } }
5
@Override public void setValue(Object o) { // TODO support setting (by pushing properties to parent) throw new UnsupportedOperationException("Not supported yet."); }
0
public boolean isOptOut() { synchronized (optOutLock) { try { // Reload the metrics file configuration.load(getConfigFile()); } catch (IOException ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); } return true; } catch (InvalidConfigurationException ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); } return true; } return configuration.getBoolean("opt-out", false); } }
4
public void learn(String learn) { char c; String name = ""; for (int i = 0; i < learn.length(); i++) { c = learn.charAt(i); switch (c) { case '(': if (name.length() > 0) startElement(name); name = ""; break; case ')': if (name.length() > 0) startElement(name); name = ""; oState = oState.getParent(); break; case '\n': case '\r': case '\t': case ' ': break; default: name += c; break; } } }
9
public String toString() { if (isFree) return "FREE"; else if (isInvalid) return "INVALID-CONSTANT"; else if (name != null) return name; else return "[CycConstant: " + guid.toString() + "]"; }
3
private Double calculateExpressionValue() throws MalformedParenthesisException, InvalidOperandException, MalformedTokenException, MalformedDecimalException { if(this.expressionList==null) { tokenize(); } //Magic happens here (i.e. PEMDAS) performParentheticalExpressionEvaluation(); performExponentiationSubstitution(); performMultiplicationAndDivisionSubstitution(); performSubtractionSubstitution(); performAdditionSubstitution(); Double value = Double.valueOf(this.expressionList.get(0).getUnderlyingObject().toString()); this.expressionValue = value; this.hasBeenEvaluated = true; //assume that we've burned it down to one object at this point return value; }
1
@Override public void onMoveTick(int x, int y, Game game) { SinglePlayerGame spg = (SinglePlayerGame) game; if (filterByID(spg.getSquareNeighbors(x, y, 1), juggernaut.id).isEmpty()) { Location loc = spg.getFirstSquareNeighborLocation(x, y, 2, zombie.id); spg.moveEntity(x, y, loc == null ? Location.wander(x, y, 1) : Location.away(x, y, loc, 2)); } }
2
private void dealtDamage(int getX, int getY, int getWidth, int getLength, int getTime, int getDelay, double getDamage, int applyForce) { if (character.equals("P1")) { if (direction) { getWorld().addObject(new P1AttackArea(getX + x, y + getY,getWidth,getLength,getTime,getDelay,getDamage,applyForce,direction),x + getX, y + getY); } else { getWorld().addObject(new P1AttackArea(getX - x, y + getY,getWidth,getLength,getTime,getDelay,getDamage,applyForce,direction), this.getX() - x, y + getY); } } else if (character.equals("P2")) { if (direction) { getWorld().addObject(new P2AttackArea(getX + x, y + getY,getWidth,getLength,getTime,getDelay,getDamage,applyForce,direction), x + getX, y + getY); } else { getWorld().addObject(new P2AttackArea(getX - x, y + getY,getWidth,getLength,getTime,getDelay,getDamage,applyForce,direction), this.getX() - x, y + getY); } } }
4
public Type getSubType() { if ((clazz == null && ifaces.length == 1) || ifaces.length == 0) return tRange(this, tNull); /* * We don't implement the set of types, that are castable to some of the * given classes or interfaces. */ throw new alterrs.jode.AssertError( "getSubType called on set of classes and interfaces!"); }
3
static CommandLine doCommandLineParsing(String[] args) { /* * Lese Kommandozeilenargumente ein */ Option sourceFileOpt = new Option("s", "sourceFile", true, "Die Ausgangsdatei"); sourceFileOpt.setRequired(true); Option destFileOpt = new Option("d", "destFile", true, "Die Zieldatei"); destFileOpt.setRequired(true); Option destColorDepth = new Option("c", "colorDepth", true, "Die Farbtiefe, auf die reduziert werden soll, in Bits"); destColorDepth.setRequired(true); destColorDepth.setType(Integer.class); Options options = new Options(); options.addOption(sourceFileOpt); options.addOption(destFileOpt); options.addOption(destColorDepth); // create the parser CommandLineParser parser = new BasicParser(); CommandLine line = null; try { // parse the command line arguments line = parser.parse(options, args); } catch (ParseException exception) { // oops, something went wrong System.err .println("Mit den Kommandozeilenargumenten stimmt etwas nicht: " + exception.getMessage()); } return line; }
1
public boolean isComplexNotOfMiddle() { return (truthTable[0] == true) && (truthTable[1] == true) && (truthTable[2] == false) && (truthTable[3] == false) && (truthTable[4] == true) && (truthTable[5] == true) && (truthTable[6] == false) && (truthTable[7] == false); }
7
private EncryptedCard encryptEncCard(EncryptedCard card) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException { if (e == null) { System.err .println("Cannot encrypt when using decrypting constructor RSAService(gp, gq, gd)"); return null; } EncryptedCard encCard = new EncryptedCard(); encCard.cardData = encrypt(card.cardData); return encCard; }
1
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { this.className = name; super.visit(version, access, remapper.mapType(name), remapper .mapSignature(signature, false), remapper.mapType(superName), interfaces == null ? null : remapper.mapTypes(interfaces)); }
1
private void resetElements() { // remove ParameterChangeListeners on editable elements to prevent memory leaks if (nt != null) nt.removeParameterChangeListener(this); if (pl != null) pl.removeParameterChangeListener(this); if (ws != null) ws.removeParameterChangeListener(this); if (ck != null) ck.removeParameterChangeListener(this); if (mo != null) mo.removeParameterChangeListener(this); if (affinity != null) affinity.destroy(); nt = new Element(ID_NT, 20.0 / 120.0, 7.0, 0.1); pl = new Element(ID_PL, 40.0 / 120.0, 14.0, 0.1); ws = new Element(ID_WS, 0.5, 21.0, 0.1); ck = new Element(ID_CK, 80.0 / 120.0, 28.0, 0.1); mo = new Element(ID_MO, 5.0, 12.0, 0.1); sp = new Element(ID_SP, 5.0, 16.0, 0.01); for (byte i = ID_ALA; i <= ID_VAL; i++) { if (aminoAcidElement[i - ID_ALA] == null) { Aminoacid aa = AminoAcidAdapter.getAminoAcid(i); aminoAcidElement[i - ID_ALA] = new Element(i, ((Float) aa.getProperty("mass")).floatValue(), ((Double) aa.getProperty("sigma")).doubleValue(), 0.1); } } for (int i = ID_A; i <= ID_U; i++) { nucleotideElement[i - ID_A] = new Element(i, 5.0, 12.0, 0.01); } nt.addParameterChangeListener(this); pl.addParameterChangeListener(this); ws.addParameterChangeListener(this); ck.addParameterChangeListener(this); mo.addParameterChangeListener(this); affinity = new Affinity(new Element[] { nt, pl, ws, ck, mo }); affinity.addParameterChangeListener(this); setCutOffMatrix(2.0f); setListMatrix(2.5f); }
9
private void meetingMenu(int meetingJoined) throws IOException, ClassNotFoundException { String opt = ""; while (!("0".equals(opt))) { System.out.println("Welcome to the meeting, " + username_logged + "!\n"); System.out.println("Please select one of the following options (0 to quit):\n"); System.out.println("1-List Agenda Items\n2-Add Agenda Items\n3-Modify Agenda Items\n4-Delete Agenda Items\n"); opt = scs.nextLine(); switch (opt) { //list case "1": Message listitems = new Message(username_logged, null, null, "listAgendaItems"); listitems.dataint = meetingJoined; sendOut(listitems); listitems = (Message) in.readObject(); System.out.println(listitems.data); System.out.println("Do you wish to enter any agenda item? Enter its ID. (or 0 to exit)\n"); int listop; listop = sci.nextInt(); if (listop != 0) { itemJoined = listop; agendaItemMenu(listop, meetingJoined); //voltar a colocar o itemJoined a 0 para quando sair itemJoined = 0; } break; //add case "2": Message additems = new Message(username_logged, null, null, "addAgendaItem"); additems.dataint = meetingJoined; System.out.println("Nome:"); additems.name = scs.nextLine(); System.out.println("Description:"); additems.description = scs.nextLine(); sendOut(additems); additems = (Message) in.readObject(); if (additems.result) { System.out.println("Item added to the agenda!"); } else { System.out.println("An error occured. Please try again."); } break; //modify case "3": Message listi = new Message(username_logged, null, null, "listAgendaItems"); listi.dataint = meetingJoined; sendOut(listi); listi = (Message) in.readObject(); System.out.println(listi.data); Message modifyitems = new Message(username_logged, null, null, "modifyagendaitem"); System.out.println("Which one do tou wish to modify?\n"); modifyitems.dataint = sci.nextInt(); System.out.println("(1)Name (2)Description"); modifyitems.dataint2 = sci.nextInt(); sendOut(modifyitems); modifyitems = (Message) in.readObject(); if (modifyitems.result) { System.out.println("Modified."); } else { System.out.println("An error occured. Please try again"); } break; //delete case "4": Message listToDelete = new Message(username_logged, null, null, "listAgendaItems"); listToDelete.dataint = meetingJoined; sendOut(listToDelete); listToDelete = (Message) in.readObject(); System.out.println(listToDelete.data); Message deleteItem = new Message(username_logged, null, null, "deleteagendaitem"); System.out.println("Which one do tou wish to delete?\n"); deleteItem.dataint = sci.nextInt(); sendOut(deleteItem); deleteItem = (Message) in.readObject(); if (deleteItem.result) { System.out.println("Deleted!\n"); } else { System.out.println("A problem occured. Someone else probably deleted it already. Please refresh\n"); } break; } } }
9
public static void main(String[] args) { Round round; do { round = new Round(); Square square = new Square(); round.hello(); IPlayer player1 = new Human(); IPlayer player2; if (round.getTypeOfGame() == '2') { player2 = new Computer(); } else { player2 = new Human(); } round.registration(player1,player2); round.setMarksForPlayers(player1, player2); if (round.start == 1) { player1.setMark(MARK_X); player2.setMark(MARK_O); } else { player1.setMark(MARK_O); player2.setMark(MARK_X); } square.showMatrix(); while (true) { if (round.start == 1) { player1.go(square,round); square.showMatrix(); if (square.winner(player1)) { square.winMessage(player1); break; } if (square.endWithoutWinner()) { square.endWithoutWinnerMessage(); break; } round.start = 2; } else { player2.go(square, round); square.showMatrix(); if (square.winner(player2)) { square.winMessage(player2); break; } if (square.endWithoutWinner()) { square.endWithoutWinnerMessage(); break; } round.start = 1; } } } while (round.restartGame()); }
9
private static void removeIsomorphicPieceOrientations() { for(int x = 0; x < p.size(); x++) { for(int y = 0; y < p.get(x).size(); y++) { if(p.get(x).get(y) != null) { for(int z = y+1; z < p.get(x).size(); z++) { if(p.get(x).get(z) != null) { if(p.get(x).get(y).equals(p.get(x).get(z))) { p.get(x).set(z, null); } } } } } } }
6