text
stringlengths
14
410k
label
int32
0
9
public void guardarSQLite(){ Connection con = null; PreparedStatement state = null; try{ Class.forName("org.sqlite.JDBC"); String dir = System.getProperty("user.dir"); System.out.println(dir); con = DriverManager.getConnection("jdbc:sqlite:"+dir+"/pokedex.db"); con.setAutoCommit(false); try{ String sql = "CREATE TABLE IF NOT EXISTS POKEMON" + "(ID INT PRIMARY KEY NOT NULL," + "NAME TEXT NOT NULL," + "TYPE1 TEXT NOT NULL," + "TYPE2 TEXT," + "HP INT NOT NULL," + "ATK INT NOT NULL," + "DEF INT NOT NULL," + "SPATK INT NOT NULL," + "SPDEF INT NOT NULL," + "SPEED INT NOT NULL," + "AVG REAL NOT NULL," + "DESCR TEXT);"; state = con.prepareStatement(sql); state.executeUpdate(); }catch(Exception e){ System.out.println(e+" Debug 1"); } try{ for(int i = 0; i<pokeId.length; i++){ String sql1 = "INSERT INTO POKEMON (ID, NAME, TYPE1, TYPE2, HP, ATK, DEF, SPATK, SPDEF, SPEED, AVG, DESCR) " + "VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"; state = con.prepareStatement(sql1); state.setInt(1, pokeId[i].numero); state.setString(2, pokeId[i].nombre); state.setString(3, pokeId[i].type1); state.setString(4, pokeId[i].type2); state.setInt(5, pokeId[i].stats[0]); state.setInt(6, pokeId[i].stats[1]); state.setInt(7, pokeId[i].stats[2]); state.setInt(8, pokeId[i].stats[3]); state.setInt(9, pokeId[i].stats[4]); state.setInt(10, pokeId[i].stats[5]); state.setDouble(11, pokeId[i].avg); state.setString(12, pokeId[i].descripcion); state.executeUpdate(); } }catch(Exception e){ System.out.println(e+" Debug 2"); } con.commit(); }catch(Exception e){ System.out.println(e); } }
4
public void mergeUnhandledException(TypeBinding newException){ if (this.extendedExceptions == null){ this.extendedExceptions = new ArrayList(5); for (int i = 0; i < this.handledExceptions.length; i++){ this.extendedExceptions.add(this.handledExceptions[i]); } } boolean isRedundant = false; for(int i = this.extendedExceptions.size()-1; i >= 0; i--){ switch(Scope.compareTypes(newException, (TypeBinding)this.extendedExceptions.get(i))){ case Scope.MORE_GENERIC : this.extendedExceptions.remove(i); break; case Scope.EQUAL_OR_MORE_SPECIFIC : isRedundant = true; break; case Scope.NOT_RELATED : break; } } if (!isRedundant){ this.extendedExceptions.add(newException); } }
7
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Ticket ticket = (Ticket) o; if (id != ticket.id) return false; if (Double.compare(ticket.price, price) != 0) return false; return true; }
5
public void redo(){ myKeeper.redo(); }
0
@Override public ParserResult specialCheckAndGetParserResult(ParserResult result, SyntaxAnalyser analyser) throws GrammarCheckException { Map<String, String> dimensionLevelInfo = result.getDimensionLevelInfo(); boolean conditionIsOk = dimensionLevelInfo.size() >= 3; int nullValueNumber = 0; for (Iterator<String> iterator = dimensionLevelInfo.keySet().iterator(); iterator .hasNext();) { String key = iterator.next(); String value = dimensionLevelInfo.get(key); if (value == null) { nullValueNumber++; } } if (nullValueNumber != 2) { conditionIsOk = conditionIsOk && false; } boolean theOtherConditionIsOk = result.getAggregateFunctionName() == null && result.getConditions().size() == 0 && result.getDimensionNicknames().size() == 0 && result.getResultCube() == null; if (!(conditionIsOk && theOtherConditionIsOk)) { this.throwException(result.getOperationName(), null, analyser); } return result; }
9
String fileSizeStr(long s) { if (s < K) return String.format("%dbytes", s); if (s < M) return String.format("%.1fKb", (1.0 * s / K)); if (s < G) return String.format("%.1fMb", (1.0 * s / M)); if (s < T) return String.format("%.1fGb", (1.0 * s / G)); if (s < P) return String.format("%.1fTb", (1.0 * s / T)); return String.format("%.1fPb", (1.0 * s / P)); }
5
private String getLoginUserIP(){ HttpServletRequest req=(HttpServletRequest)ServletActionContext.getRequest(); String lastLoginIP = req.getHeader("x-forwarded-for"); if(lastLoginIP == null || lastLoginIP.length() == 0 || "unknown".equalsIgnoreCase(lastLoginIP)) { lastLoginIP = req.getHeader("Proxy-Client-IP"); } if(lastLoginIP == null || lastLoginIP.length() == 0 || "unknown".equalsIgnoreCase(lastLoginIP)) { lastLoginIP = req.getHeader("WL-Proxy-Client-IP"); } if(lastLoginIP == null || lastLoginIP.length() == 0 || "unknown".equalsIgnoreCase(lastLoginIP)) { lastLoginIP = req.getRemoteAddr(); } return lastLoginIP; }
9
public EditButtonsListener(final MenuItem menuItem) throws IllegalParametrs { this.menuItem = menuItem; switch (menuItem) { case ADD: listener = new AddButtonActionListener(); break; case DELETE: listener = new DeleteButtonActionListener(); break; case FIND: listener = new FindButtonActionListener(); break; case LANGUAGE_ENGLISH: listener = new EnglishLanguageButtonActionListener(); break; case LANGUAGE_RUSSIAN: listener = new RussianLanguageButtonActionListener(); break; case CONNECT: listener = new ConnectButtonActionListener(); break; case DISCONNECT: listener = new DisconnectButtonActionListener(); break; default: throw new IllegalParametrs(); } }
7
private void initGroupCreation() { driver.findElement(By.name("new")).click(); }
0
public static boolean isHappy(int n) { Map<Integer, Boolean> traverseMap = new HashMap<Integer, Boolean>(); int res = n; while (true) { res = assistIsHappy(res); if (1 == res) return true; if (traverseMap.containsKey(res)) return false; traverseMap.put(res, true); } }
3
private boolean isLegalNameChar(char ch) { return ((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z')) || ((ch >= '0') && (ch <= '9')) || (ch == '.') || (ch == '_') || (ch == '$'); }
8
private void powrotDoOknaGlownego() { widokOpisTworcow.setVisible(false); if(oknoMacierzyste.equals("OknoGlowne")) widokOpisTworcow.widokGlowny.setVisible(true); if(oknoMacierzyste.equals("OknoDolacz")) widokOpisTworcow.widokGlowny.widokDolacz.setVisible(true); if(oknoMacierzyste.equals("OknoUtworz")) widokOpisTworcow.widokGlowny.widokUtworz.setVisible(true); if(oknoMacierzyste.equals("OknoOpisAplikacji")) widokOpisTworcow.widokGlowny.widokOpisAplikacji.setVisible(true); if(oknoMacierzyste.equals("OknoUstawieniaLokalne")) widokOpisTworcow.widokGlowny.widokUstawien.setVisible(true); if(oknoMacierzyste.equals("OknoRozmiesc")) widokOpisTworcow.widokGlowny.widokDolacz.widokRozmiesc.setVisible(true); if(oknoMacierzyste.equals("OknoGry")) widokOpisTworcow.widokGlowny.widokDolacz.widokRozmiesc.widokGry.setVisible(true); if(oknoMacierzyste.equals("OknoWynikow")) widokOpisTworcow.widokGlowny.widokDolacz.widokRozmiesc.widokGry.widokGryZdarzenia.widokWynikow.setVisible(true); }
8
public static int findRowByDate(Date date, int dateColumn, CSTable table) { String type = table.getColumnInfo(dateColumn).get(KEY_TYPE); if ((type == null) || !type.equalsIgnoreCase(VAL_DATE)) { throw new IllegalArgumentException(); } DateFormat fmt = lookupDateFormat(table, dateColumn); int rowNo = 0; for (String[] row : table.rows()) { try { Date d = fmt.parse(row[dateColumn]); if (d.equals(date)) { return rowNo; } rowNo++; } catch (ParseException ex) { throw new RuntimeException(ex); } } throw new IllegalArgumentException(date.toString()); }
5
public void keyPressed(KeyEvent e) { // Packet sent for any type of key event. So create the packet first Packet event = null; // Create event packet according to key event // If the user pressed Q, invoke the cleanup code and quit. if((e.getKeyChar() == 'q') || (e.getKeyChar() == 'Q')) { event = new Packet(Packet.Type.QUIT, use_packet().intValue(), getID()); // Up-arrow moves forward. } else if(e.getKeyCode() == KeyEvent.VK_UP) { event = new Packet(Packet.Type.FWD, use_packet().intValue(), getID()); // Down-arrow moves backward. } else if(e.getKeyCode() == KeyEvent.VK_DOWN) { event = new Packet(Packet.Type.BACK, use_packet().intValue(), getID()); // Left-arrow turns left. } else if(e.getKeyCode() == KeyEvent.VK_LEFT) { event = new Packet(Packet.Type.LEFT, use_packet().intValue(), getID()); // Right-arrow turns right. } else if(e.getKeyCode() == KeyEvent.VK_RIGHT) { event = new Packet(Packet.Type.RIGHT, use_packet().intValue(), getID()); // Spacebar fires. } else if(e.getKeyCode() == KeyEvent.VK_SPACE) { event = new Packet(Packet.Type.FIRE, use_packet().intValue(), getID()); } else { // Unhandeled key event. Simply ignored return; } assert(event != null); // Send request to server try{ System.out.println(this.getName() + ": requesting action " + event.type); out.writeObject(event); } catch (IOException ex){ System.err.println("GUIClient: Failed to send movement request."); ex.printStackTrace(); } catch (Exception ex) { System.err.println("GUIClient: Failed to send movement request"); ex.printStackTrace(); } }
9
private boolean moveTowards(int tx, int ty) { if(x < tx && move(x+1, y)) return true; if(x > tx && move(x-1, y)) return true; if(y < ty && move(x, y+1)) return true; if(y > ty && move(x, y-1)) return true; return false; }
8
public void multiplyPay(int multiplier) { if(multiplier == 1) return; this.win *= multiplier; for(WinResult winResult : this.nonReelWinResults) { winResult.Win *= multiplier; } for(ReelGridEvalResult reelGridEvalResult : this.reelGridEvalResults) { reelGridEvalResult.win *= multiplier; for(PatternSetEvalResult patternSetEvalResult : reelGridEvalResult.patternSetEvalResults) { patternSetEvalResult.win *= multiplier; for(PatternEvalResult patternEvalResult : patternSetEvalResult.patternEvalResults) { patternEvalResult.Win *= multiplier; for(WinResult winResult : patternEvalResult.WinResults) { winResult.Win *= multiplier; } } } } }
6
public static Config getInstance() { if (instance == null) { new Config(); } return instance; }
1
protected void ShowMainScreen(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // set the encoding, otherwise database is encoded wrongly request.setCharacterEncoding("UTF-8"); // so, 2 ways to be here - there is session with our data (then it was // post), // or there isnt - then its get // there are two ways to arrive here through get method // either with id already set (validate it!) for editing or id=new or // id=0 // get the session HttpSession session = request.getSession(); // get the viewmodel data from session AdminUnitTypeVM formData = (AdminUnitTypeVM) session .getAttribute("formData"); // if no viewmodel in session, then normally this is first call through // get // so check get parameters and populate viewmodel with data from dao if (formData == null) { session.removeAttribute("errors"); formData = processGET(request, response); } else { // formData was there, so this is post. lets update the viewmodel // with changes the user wants to make // maybe it was cancel? if (cancelWasPressed(request, response)) { return; } // fill out viewmodel with first data formData = updateViewModelFieldsForDB(request, formData); // do some simple validation - so at least code and name are set // (and should be unique) List<String> errors = getValidationErrors(request); if (!errors.isEmpty()) { session.setAttribute("errors", errors); } else { session.removeAttribute("errors"); } // AdminUnitTypeMaster (0-"---": no master) System.out .println("AdminUnitTypeMaster_adminUnitTypeID:" + request .getParameter("AdminUnitTypeMaster_adminUnitTypeID")); // was AdminUnitTypeMaster dropdown changed? formData = updateUnitTypeMaster(request, formData); // now the tricky part - scan through several possible submit // buttons // which button was clicked? Enumeration<String> paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String paramName = paramNames.nextElement(); // table of subordinates for this adminUnitType // every line has separate submit button, with item sequence no // added to each button name. if (paramName.startsWith("RemoveButton_")) { formData = removeSubordinate(formData, paramName); } // add new subordinate if (paramName.equals("AddSubordinateButton")) { formData = addSubordinate(formData, request); } // global save and exit, no validation errors if (paramName.equals("SubmitButton") && errors.isEmpty()) { submitToDataBase(formData, response); return; } } } // save the viewmodel for jsp dispatcher into session session.setAttribute("formData", formData); // call the dispatcher request.getRequestDispatcher("AdminUnitTypeScreen.jsp").forward( request, response); }
8
public static void displayOpponentPlayerExpeditions(Player player) { List<String> lines = new ArrayList<String>(); int rowCount = 0; List<List<String>> cardsStrings = new ArrayList<List<String>>(); for (ExpeditionCardStack expeditionCardStack : player.getExpeditions()) { List<String> expeditionStrings = buildReverseExpedition(expeditionCardStack); cardsStrings.add(expeditionStrings); if (expeditionStrings.size() > rowCount) { rowCount = expeditionStrings.size(); } } for (int i = 0; i < rowCount; i++) { StringBuilder str = new StringBuilder(); str.append(" "); for (List<String> expeditionStrings : cardsStrings) { int offset = rowCount - expeditionStrings.size(); if (offset == 0 && i < expeditionStrings.size()) { str.append(expeditionStrings.get(i)); } else if (i < offset) { str.append(" "); } else { str.append(expeditionStrings.get(i - offset)); } str.append(" "); } lines.add(str.toString()); } for (String line : lines) { System.out.println(line); } }
8
Point2D randomGoal(Game game, Point2D pt){ Point2D candidatePt = pt; Tile fTile = game.getMap().getTileAt(pt); Rectangle2D fRect = fTile.getArea(); double fwidth = fRect.getWidth(); double fheight = fRect.getHeight(); int n = 50; boolean notFound = true; if (fwidth >= fheight){ while (n > 0 && ! notFound){ double x = fRect.getX() + (fwidth * fRandom.nextDouble()); candidatePt = new Point2D.Double(x, fRect.getCenterY()); if (CollisionDetection.canOccupy(game, fCreature, candidatePt)){ notFound = false; } n = n--; } } else { while (n > 0 && ! notFound){ double y = fRect.getY() + (fheight * fRandom.nextDouble()); candidatePt = new Point2D.Double(fRect.getCenterX(), y); if (CollisionDetection.canOccupy(game, fCreature, candidatePt)){ notFound = false; } n = n--; } } if (notFound){ candidatePt = pt; } return candidatePt; }
8
private void makeFire() { final Tile playerTile = ctx.players.local().tile(); if (ctx.objects.select().at(playerTile).select(ObjectDefinition.name(ctx, "Fire")).isEmpty()) { if (ctx.inventory.itemOnItem(TINDERBOX, LOGS)) { Condition.wait(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return ctx.chat.visible("Click on the flashing bar graph icon"); } }, 200, 20); } } else { LogicailArea area = new LogicailArea(playerTile.derive(-3, -3), playerTile.derive(4, 4)); final ArrayList<Tile> tiles = new ArrayList<Tile>(area.getReachable(ctx)); Collections.shuffle(tiles); for (final Tile tile : tiles) { if (!ctx.objects.select().at(tile).select(ObjectDefinition.name(ctx, "Fire")).isEmpty()) { continue; } if (ctx.movement.myWalk(tile)) { Condition.wait(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return !ctx.players.local().inMotion() || ctx.players.local().tile().equals(tile); } }, 200, 10); } return; } } }
6
public String Add(BigInteger a) { String output = ""; ArrayList<Integer> lawl2 = new ArrayList<Integer>(); ArrayList<Integer> second = a.getNum(); //Returns the BigInteger objects ArrayList int z = 0; for(int i=0; i < input.length(); i++) { if((second.get(i) + this.lawl.get(i) + z) >= 10) { lawl2.add(second.get(i) + this.lawl.get(i) + z - 10); z = 1; if(i == input.length()-1) lawl2.add(1); } else { lawl2.add(second.get(i) + this.lawl.get(i) + z); z = 0; } } for(int i=lawl2.size() - 1; i >=0; i--) output += lawl2.get(i).toString(); return output; }
4
void parseNotationDecl() throws java.lang.Exception { String nname, ids[]; requireWhitespace(); nname = readNmtoken(true); requireWhitespace(); // Read the external identifiers. ids = readExternalIds(true); if (ids[0] == null && ids[1] == null) { error("external identifer missing", nname, null); } // Register the notation. setNotation(nname, ids[0], ids[1]); skipWhitespace(); require('>'); }
2
public void abrir() throws Exception { if(id.length() > 0 && id != "0"){ long cod = Long.parseLong(id); if(produto == null || (produto != null && produto.getId() != cod ) ) setProduto(ejb.Open(cod)); } }
5
public void initTransient() { if (blocks == null) { throw new RuntimeException("The level is corrupt!"); } else { listeners.clear(); blockers = new int[width * length]; Arrays.fill(blockers, height); calcLightDepths(0, 0, width, length); random = new Random(); randId = random.nextInt(); tickList.clear(); if (waterLevel == 0) { waterLevel = height / 2; } if (skyColor == 0) { skyColor = DEFAULT_SKY_COLOR; } if (fogColor == 0) { fogColor = DEFAULT_FOG_COLOR; } if (cloudColor == 0) { cloudColor = DEFAULT_CLOUD_COLOR; } if (xSpawn == 0 && ySpawn == 0 && zSpawn == 0) { findSpawn(); } if (blockMap == null) { blockMap = new BlockMap(width, height, length); } } }
9
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(MenuPrincipalViews.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MenuPrincipalViews.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MenuPrincipalViews.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MenuPrincipalViews.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MenuPrincipalViews().setVisible(true); } }); }
6
public void setLook(int i){ switch(i){ case 0: this.look = 0; /*look.N; */ break; case 1: this.look = 1; /*look.NE; */ break; case 2: this.look = 2; /*look.E; */ break; case 3: this.look = 3; /*look.SE; */ break; case 4: this.look = 4; /*look.S; */ break; case 5: this.look = 5; /*look.SW; */ break; case 6: this.look = 6; /*look.W; */ break; case 7: this.look = 7; /*look.NW; */ break; } }
8
@Override public boolean execute(WorldChannels plugin, CommandSender sender, Command command, String label, String[] args) { final Map<Flag, String> info = new EnumMap<Flag, String>(Flag.class); info.put(Flag.TAG, WorldChannels.TAG); if(!(sender instanceof Player)) { sender.sendMessage(Localizer.parseString(LocalString.NO_CONSOLE, info)); } else { try { final Channel channel = parseChannel(sender, args[0], plugin.getModuleForClass(ConfigHandler.class)); final String playerName = expandName(args[1]); if(playerName != null) { final Player target = plugin.getServer().getPlayer( playerName); if(target != null) { if(channel != null) { if(sender .hasPermission(channel.getPermissionKick())) { channel.removeListener(target.getName()); final String channelId = channel.getWorld() + channel.getName(); ChannelManager manager = plugin.getModuleForClass(ChannelManager.class); if(manager.getCurrentChannelId(target.getName()).equals(channelId)) { manager.removeCurrentChannel(target.getName()); } target.sendMessage(ChatColor.RED + WorldChannels.TAG + " You have been kicked from channel '" + channel.getName() + "' by " + sender.getName()); sender.sendMessage(ChatColor.GREEN + WorldChannels.TAG + " Kicked " + target.getName() + " from channel " + channel.getName()); } else { info.put(Flag.EXTRA, channel.getPermissionKick()); sender.sendMessage(Localizer.parseString( LocalString.PERMISSION_DENY, info)); } } else { info.put(Flag.EXTRA, args[0]); info.put(Flag.REASON, "channel"); sender.sendMessage(Localizer.parseString( LocalString.UNKNOWN, info)); } } else { info.put(Flag.EXTRA, args[1]); info.put(Flag.REASON, "player"); sender.sendMessage(Localizer.parseString( LocalString.UNKNOWN, info)); } } else { info.put(Flag.EXTRA, args[1]); info.put(Flag.REASON, "player"); sender.sendMessage(Localizer.parseString( LocalString.UNKNOWN, info)); } } catch(ArrayIndexOutOfBoundsException e) { info.put(Flag.EXTRA, "channel name"); sender.sendMessage(Localizer.parseString( LocalString.MISSING_PARAM, info)); } } return true; }
7
DisguiseSound(Sound... sounds) { for (int i = 0; i < sounds.length; i++) { Sound s = sounds[i]; if (i == 0) disguiseSounds.put(SoundType.HURT, s); else if (i == 1) disguiseSounds.put(SoundType.STEP, s); else if (i == 2) disguiseSounds.put(SoundType.DEATH, s); else if (i == 3) disguiseSounds.put(SoundType.IDLE, s); else cancelSounds.add(s); } }
5
public boolean validMove(int dir) { boolean valid = true; int[][] key = screen[row][col].key(); if (col+dir < 0 || col+dir >= NUM_COLS || dead[row][col+dir] == true) valid = false; for (int i=0; i<3; i++) { int r = row+key[i][0]; int c = col+key[i][1]; if (c+dir < 0 || c+dir >= NUM_COLS || dead[r][c+dir] == true) valid = false; } return valid; }
7
public void setPassengerCurCount(int passengerCount) throws CarriageException { if ((passengerCount >= 0) && (passengerCount <= this.passengerMaxCount)) { this.passengerCurCount = passengerCount; } else { throw new CarriageException( "Current passenger count is out of range [0," + this.passengerMaxCount + "]"); } }
2
private static ArrayList<Integer> obtenerTiempos(String etiqueta, Element elemento) { ArrayList<Integer> t = null; /*Desgloza los tiempos en funcion de la etiqueda deseada*/ NodeList e = elemento.getElementsByTagName(etiqueta); int n = e.getLength(); if (e.getLength() > 0 && e != null) { t = new ArrayList<Integer>(); /*Toma todos los tiempos que fueron desglozados anteriormente*/ for (int i = 0; i < e.getLength(); i++) { Element eletmp = (Element) e.item(i); NodeList listatmp = eletmp.getChildNodes(); t.add(Integer.parseInt(listatmp.item(0).getNodeValue())); } } return t; }
3
public String getMessage() { if (!specialConstructor) { return super.getMessage(); } StringBuffer expected = new StringBuffer(); int maxSize = 0; for (int i = 0; i < expectedTokenSequences.length; i++) { if (maxSize < expectedTokenSequences[i].length) { maxSize = expectedTokenSequences[i].length; } for (int j = 0; j < expectedTokenSequences[i].length; j++) { expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' '); } if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { expected.append("..."); } expected.append(eol).append(" "); } String retval = "Encountered \""; Token tok = currentToken.next; for (int i = 0; i < maxSize; i++) { if (i != 0) retval += " "; if (tok.kind == 0) { retval += tokenImage[0]; break; } retval += " " + tokenImage[tok.kind]; retval += " \""; retval += add_escapes(tok.image); retval += " \""; tok = tok.next; } retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; retval += "." + eol; if (expectedTokenSequences.length == 1) { retval += "Was expecting:" + eol + " "; } else { retval += "Was expecting one of:" + eol + " "; } retval += expected.toString(); return retval; }
9
@Test public void nodeTests(){ Node db = null; try{ ConfigParser cp = ConfigParser.getParser("resources/config.xml"); cp.getElementAt("wookie", 0); db = (Node)cp.getElementAt("databases", 0); } catch(Exception e){ assertTrue(false); } Connection con = ConnectionFactory.createConnection(db); assertTrue(con instanceof ImplConnection); con.close(); con = ConnectionFactory.createConnection(db, "curl"); assertTrue(con instanceof CurlConnection); con.close(); // con = ConnectionFactory.createConnection(db, "implcurl"); // assertTrue(con instanceof ImplCurlConnection); // con.close(); con = ConnectionFactory.createConnection(db, "impl"); assertTrue(con instanceof ImplConnection); con.close(); }
1
public String getDefaultName() { ClassInfo type; if (clazz != null) type = clazz; else if (ifaces.length > 0) type = ifaces[0]; else type = ClassInfo.javaLangObject; String name = type.getName(); int dot = Math.max(name.lastIndexOf('.'), name.lastIndexOf('$')); if (dot >= 0) name = name.substring(dot + 1); if (Character.isUpperCase(name.charAt(0))) { name = name.toLowerCase(); if (keywords.get(name) != null) return "var_" + name; return name; } else return "var_" + name; }
5
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerItemPickup(PlayerPickupItemEvent event) { // CAUTION:This event fires, BEFORE the picked up item is added to the inventory! // therefore, delay all checks for 1 tick because "itemInHand()" is needed for checks // this event can be potentially fired every tick, so make sure the handling (with schedulers...) is as // efficient as possible for normal players // check if this player is already scheduled for a pickup check (must be happened last tick) and if so, // if the check has not yet been executed. // if so, cancel the scheduler and re-schedule the check // otherwise do some preconditions checks and if successful, schedule the check for next tick if(playersScheduledForDelayedServiceModeCheck.containsKey(event.getPlayer().getName()) && (null != playersScheduledForDelayedServiceModeCheck.get(event.getPlayer().getName()))) { // a new itemPickUpEvent has fired while the check routine that is scheduled for the // current tick has not yet been called for this player // so cancel the task and re-schedule it for the next tick playersScheduledForDelayedServiceModeCheck.get(event.getPlayer().getName()).cancel(); } if(preconditionsOK(event.getPlayer())) // may player use MG at all in current situation? { if(!playersInSM.contains(event.getPlayer().getName()) && !playersInGracePeriod.containsKey(event.getPlayer().getName()) && !playersOnWarmup.containsKey(event.getPlayer().getName())) // check only if player is NOT in SM and not already handled by any check timer { playersScheduledForDelayedServiceModeCheck.put(event.getPlayer().getName(), plugin.startDelayedServiceModeCheckTimer_Task(event.getPlayer())); // this will schedule the check handling for next tick } } }
6
protected User() { super(User.class.getSimpleName()); }
0
public void Draw(Graphics2D g2d) { //******************************************* //text coordinates g2d.setColor(Color.white); g2d.drawString("Car coordinates: " + x + " : " + y, 5, 15); g2d.drawString("Frame size, height " + Framework.frameHeight + ", width " + Framework.frameWidth, 5, 30); g2d.drawString("Car coordinates: " + x + " : " + y, 5, 50); g2d.drawString("The car speed is currently: " + speedY, 5, 65); // If the car is raceWin. //image for winnging if (raceWin) { g2d.drawImage(carWonImg, x, y, null); } // If the car is crashed. else if (crashed) { g2d.drawImage(carCrashedImg, x, y + carImgHeight - carCrashedImg.getHeight(), null); } // If the car is still in the space. else { // If player hold down a W key we draw car fire. //removed because it isn't a car car // if(Canvas.keyboardKeyState(KeyEvent.VK_W)) // g2d.drawImage(carFireImg, x + 12, y + 66, null); g2d.drawImage(carImg, x, y, null); } }
2
private void stopButtonAction() { text.append(String.format("Stopping current action.%s", newline)); // Remember the state before stopping State state = currentState; // Set to initial this.setStateInitial(); //remove buttons if (!results.isEmpty()) { text.append(String.format("Removing results.%s", newline)); results.clear(); showTimes(); } if (state == State.PROCESSING) { if (!this.mediator.stopVideoProcessing()) { text.append(String.format("Failed to stop the processing.%s", newline)); return; } text.append(String.format("Video processing stopped.%s", newline)); } if (state == State.FINISHING) { if (!this.mediator.stopCuttingAds()) { text.append(String.format("Failed to stop the ads cutting.%s", newline)); return; } text.append(String.format("Ads cutting stopped.%s", newline)); } text.append(String.format("--------------------------%s", newline)); }
5
public void setAccountNumber(String accountNumber) { this.accountNumber = accountNumber; }
0
private void refreshClipboardList() { Transferable[] copiedItems = CopyPasteManager.getInstance().getAllContents(); int amountItems = UtilsClipboard.getAmountStringItemsInTransferables(copiedItems); String[] itemsUnique = null; boolean hasClipboardContent= UtilsClipboard.hasContent(); String[] copyItemsList = new String[amountItems]; if( amountItems > 0 || hasClipboardContent ) { // Add copied string items, historic and current int index = 0; for( Transferable currentItem : copiedItems) { if( currentItem.isDataFlavorSupported( DataFlavor.stringFlavor ) ) { try { String itemStr = currentItem.getTransferData( DataFlavor.stringFlavor ).toString(); if( !itemStr.trim().isEmpty() ) { copyItemsList[index] = itemStr; index++; } } catch(Exception e) { e.printStackTrace(); } } } // Tidy items: distinct items, none empty String[] copyItemsPref = Preferences.getItems(); Object[] allItems = (copyItemsPref.length > 0) ? ArrayUtils.addAll(copyItemsList, copyItemsPref) : copyItemsList; itemsUnique = UtilsArray.tidy(allItems); if( itemsUnique.length > 0 ) { this.setClipboardListData(itemsUnique, false); this.sortClipboardListByTags(this.form.checkboxKeepSorted.isSelected()); Preferences.saveCopyItems(itemsUnique); } } initStatusLabel(itemsUnique == null ? 0 : itemsUnique.length); }
9
@Override public void execute() { Player receiver = getReceiver(); for (String playerName : players) { Ban ban = new Ban(playerName, until, reason); TimeBanBanEvent event; if (receiver != null) { event = new TimeBanBanEvent(receiver, ban); } else { event = new TimeBanBanEvent(ban); } Bukkit.getServer().getPluginManager().callEvent(event); } }
2
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { MOB target=mob; if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB)) target=(MOB)givenTarget; if(target.fetchEffect(this.ID())!=null) { mob.tell(target,null,null,L("<S-YOUPOSS> can already "+canSpeakWithWhat()+".")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; boolean success=proficiencyCheck(mob,0,auto); if(success) { invoker=mob; final CMMsg msg=CMClass.getMsg(mob,null,this,verbalCastCode(mob,null,auto),auto?L("<T-NAME> attain(s) the ability to "+canSpeakWithWhat()+"!"):L("^S<S-NAME> chant(s) to <S-NAMESELF>, becoming one with the "+canSpeakWithWhatNoun()+"!^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); success=beneficialAffect(mob,target,asLevel,0)!=null; target.location().recoverRoomStats(); } } else return beneficialWordsFizzle(mob,null,L("<S-NAME> chant(s) to <S-NAMESELF>, but nothing happens")); // return whether it worked return success; }
8
public void unpack(String filename1) { String filename = filename1; File srcFile = new File(filename); String zipPath = filename.substring(0, filename.length()-4); File temp = new File(zipPath); temp.mkdir(); ZipFile zipFile = null; try { zipFile = new ZipFile(srcFile); Enumeration<? extends ZipEntry> e = zipFile.entries(); while(e.hasMoreElements()) { ZipEntry entry = e.nextElement(); File destinationPath = new File(zipPath, entry.getName()); destinationPath.getParentFile().mkdirs(); if(entry.isDirectory()) { continue; } else { System.out.println("Extracting file: " + destinationPath); BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); int b; byte buffer[] = new byte[1024]; FileOutputStream fos = new FileOutputStream(destinationPath); BufferedOutputStream bos = new BufferedOutputStream(fos, 1024); while ((b = bis.read(buffer, 0, 1024)) != -1) { bos.write(buffer, 0, b); } bos.close(); bis.close(); } } } catch (IOException e1) { System.out.println("Error opening zip file" + e1); } finally { try { if(zipFile != null) { zipFile.close(); } } catch (IOException e2) { System.out.println("Error while closing zip file" + e2); } } }
7
private boolean checkIfStuck(){ // bottom of the board if(myPieceLocation.y == 0){ return true; } // check if crashed into another piece Point[] points = getPoints(myPieceLocation, myPiece, myOrientation); for(int i = 0; i < points.length; i++){ Point p = points[i]; if(p.y - 1 > 0 && p.y - 1 < getGridHeight() && p.x >= 0 && p.x < getGridHeight()) if(isSpotOccupied(p.y - 1, p.x)){ return true; } } return false; }
7
public static void goToManageMenu() { alphabetize(); System.out.println("\nEmployee List:"); for (Prototype p : employeeList) { System.out .println(employeeList.indexOf(p) + 1 + ") " + p.getName()); } System.out .print("\n~Management Menu~\nA) Remove Employee\nB) Edit Employee\nC) View Employee Information\nPick Letter: "); String choice1 = scString.nextLine().toLowerCase(); System.out.println(); switch (choice1) { case "a": removeEmployee(); break; case "b": editEmployee(); break; case "c": viewEmployee(); break; default: System.err.println("Fatal Error!"); System.exit(1); } }
4
public void switchDoors(Gameboard gameboard) { Field[][] fields = gameboard.getFields(); for(int i = 0; i < fields.length; i++) { for(int j = 0; j < fields[i].length; j++) { if(fields[i][j].getType() == 2 && Math.random() < GlobalGameboard.doorSwitchFrequency) { if(fields[i][j].isDoorOpen()) fields[i][j].setDoorOpen(false); else fields[i][j].setDoorOpen(true); if(!fields[i][j].isDoorOpen() && fields[i][j].getAnt() != null) { killAnt(gameboard, fields[i][j].getAnt()); } } } } }
7
public void parse(String sentence, ParserReceiver receiver, Console console) throws EvaluationException { String normalized = sentence.trim().toLowerCase(); // Check if sentence is a known magic phrase String magicPhrase = vocabulary.getMagicPhrases().get(normalized); if (magicPhrase != null) { receiver.magicPhrase(magicPhrase); return; } // Tokenize String[] tokens = StringUtils.split(normalized); // Lookup verb WordNode verb = vocabulary.getVerbTree().find(tokens); if (verb == null) { console.display(vocabulary.getMessages().get("didntUnderstand")); return; } // Identify subject if (verb.depth() < tokens.length) { List<String> subject = new ArrayList<String>(); int i = verb.depth(); // Add first token, only if it's not an article String token = tokens[i]; if (!vocabulary.getArticles().contains(token)) { subject.add(token); } // Add the remaining tokens until a preposition is found String preposition = null; for (i++; i < tokens.length; ++i) { token = tokens[i]; // Preposition found if (vocabulary.getPrepositions().contains(token)) { preposition = token; i++; break; } subject.add(token); } // Get Modifier if (i < tokens.length) { String modifier = ""; modifier = tokens[i++]; for (; i < tokens.length; ++i) { modifier += " " + tokens[i]; } receiver.doActionOnObjectWithModifier(verb.toString(), StringUtils.join(subject, ' '), preposition, modifier); } else { receiver.doActionOnObject(verb.toString(), StringUtils.join(subject, ' ')); } } else { receiver.doAction(verb.toString()); } }
8
private static Object evaluate(final Object problem, final String expression) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { final StringTokenizer tok = new StringTokenizer(expression, "."); Object result = problem; if (tok.hasMoreTokens()) { final String problemToken = tok.nextToken(); if ("problem".equals(problemToken)) { while (tok.hasMoreTokens()) { final String nextMethodName = tok.nextToken(); final Class<?> clazz = result.getClass(); final Method method = clazz.getMethod(nextMethodName, NO_ARGS); if (method != null) { result = ReflectionUtils.getValueOfMethod(method, result); } else { break; } } } } return result; }
5
private void buyButtonActionPerformed(java.awt.event.ActionEvent evt) { if (road == -1 && settlement == -1) { return; } Request toSend = new Request(); toSend.setRequest(road == -1 ? 7 : 8); toSend.setHexagonSelected(hexagon); if (road == -1) { toSend.setOnSpotSelected(settlement); } else if (settlement == -1) { toSend.setRoadsSpotSelected(road); } sendRequest(toSend); road = -1; settlement = -1; // TODO add your handling code here: }
5
private void write(){ //Writing to OutputStream try { try { transferUsePermit.acquire(); } catch (InterruptedException e){ } //never thrown if (transfer==null) transfer=new NullTransfer(); //To ensure memory space and that the objects are properly serialised oos.reset(); oos.writeObject(transfer); } catch (IOException e){ conn.exceptionEncountered(e,this); try { close(); } catch (IOException ioe){ } } finally { //Reset transfer to NullTransfer transfer=null; transferUsePermit.release(); //allow transfer to get Changed now if it was changed if (transferChangePermit.availablePermits()==0) transferChangePermit.release(); } }
5
private void generateStereogram() { try { if (this.dottedRadioButton.isSelected()) { if (batchMode) { //todo } else { BufferedImage depthMap = null; if (this.textRadioButton.isSelected()) { depthMap = ImageManipulator.generateTextDepthMap(getMapText(), getFontSize(), getStereogramWidth(), getStereogramHeight()); } else { depthMap = getImage(this.mapFileChooser.getSelectedFile()); } Color c1 = getColor1(); Color c2 = getColor2(); Color c3 = getColor3(); float intensity = getIntensity(); float obsDistance = getObservationDistance(); float eyeSep = getEyeSeparation(); float maxDepth = getMaxDepth(); float minDepth = getMinDepth(); int width = getStereogramWidth(); int height = getStereogramHeight(); int horizPPI = getHorizontalPPI(); BufferedImage stereogram = StereogramGenerator.generateSIRD( depthMap, c1, c2, c3, intensity, width, height, obsDistance, eyeSep, maxDepth, minDepth, horizPPI); if (this.stereogramWindow != null) { this.stereogramWindow.dispose(); } this.stereogramWindow = new StereogramWindow(stereogram); this.stereogramWindow.setVisible(true); } } else { //Texture pattern selected: if (batchMode) { //todo } else { BufferedImage depthMap = null; if (this.textRadioButton.isSelected()) { depthMap = ImageManipulator.generateTextDepthMap(getMapText(), getFontSize(), getStereogramWidth(), getStereogramHeight()); } else { depthMap = getImage(this.mapFileChooser.getSelectedFile()); } BufferedImage texturePattern = getImage(this.patternFileChooser.getSelectedFile()); float obsDistance = getObservationDistance(); float eyeSep = getEyeSeparation(); float maxDepth = getMaxDepth(); float minDepth = getMinDepth(); int width = getStereogramWidth(); int height = getStereogramHeight(); int vertPPI = getVerticalPPI(); int horizPPI = getHorizontalPPI(); BufferedImage stereogram = StereogramGenerator.generateTexturedSIRD( depthMap, texturePattern, width, height, obsDistance, eyeSep, maxDepth, minDepth, horizPPI, vertPPI); if (this.stereogramWindow != null) { this.stereogramWindow.dispose(); } this.stereogramWindow = new StereogramWindow(stereogram); this.stereogramWindow.setVisible(true); } } } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error generating stereogram." + System.getProperty("line.separator") + "ERROR: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } }
8
public JLabel getjLabelNumeroRapport() { return jLabelNumeroRapport; }
0
protected static PreparedStatement prepareStatement(String query, Object... args) throws SQLException { String[] splitedQuery = (query + " ").split("\\?"); int count = splitedQuery.length - 1; String resultQuery = ""; List<Object> resultArgs = new ArrayList<Object>(); if (count != args.length) { throw new SQLException("Invalid arguments count for query " + query + ". Expected " + count + " Actual " + args.length); } else { int counterArgiments = -1; String q; for (String queryPart : splitedQuery) { q = "?"; if (counterArgiments == -1) { resultQuery = queryPart; } else { int counterList = 0; if (args[counterArgiments] instanceof Collection) { if (((Collection) args[counterArgiments]).isEmpty()) { throw new SQLException("Invalid argument. Collection is Empty."); } for (Object object : (Collection) args[counterArgiments]) { q = (counterList++ == 0 ? "" : q + ",") + "?"; resultArgs.add(object); } } else { resultArgs.add(args[counterArgiments]); } resultQuery = resultQuery + q + queryPart; } counterArgiments++; } PreparedStatement statement = Query.getConnection().prepareStatement(resultQuery, Statement.RETURN_GENERATED_KEYS); if (!resultArgs.isEmpty()) { int index = 0; for (Object param : resultArgs) { Query.processValue(statement, ++index, param); } } return statement; } }
9
public String getLabel() { return label; }
0
private void occurrencesCharacter(char ... c) { MyIterator<String> forward = list.getForwardIterator(); int[] counts = new int[c.length]; while (forward.hasMoreElements()) { String temp = (String)forward.nextElement(); for (int i = 0; i < temp.length(); i++) for (int j = 0; j < c.length; j++) { if (temp.charAt(i) == c[j]) counts[j]++; } } for (int i = 0; i < c.length; i++) System.out.println("\nOccurrences of " + c[i] + ": " + counts[i]); }
5
public static String readDodgyXML(String filename) throws IOException { InputStream in = new FileInputStream(new File(filename)); StringBuffer sb = new StringBuffer(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line = br.readLine(); // Ignore first line and replace it with the utf-8 one. sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); while ((line = br.readLine()) != null) { byte[] b = line.getBytes(); for (int i = 0; i < b.length; i++) { if (b[i] != 0) { sb.append((char) b[i]); } } sb.append("\n"); } return sb.toString(); }
3
public Member findById(java.lang.Integer id) { log.debug("getting Member instance with id: " + id); try { Member instance = (Member) getSession().get( "com.oj.hibernate.daoNdo.Member", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } }
1
public static void main(String[] args) { try (InputStreamReader isr = new FileReader(System.getProperty("user.dir") + "/file/tmp"); BufferedReader br = new BufferedReader(isr)) { String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } try (OutputStreamWriter osw = new FileWriter(System.getProperty("user.dir") + "/file/write_new");) { for (int i = 0; i < 100; i++) { osw.write(Integer.toString(i) + "\n"); } } catch (IOException e) { e.printStackTrace(); } }
4
public static void main(String args[]) { 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(ApplicationInvoices.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ApplicationInvoices.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ApplicationInvoices.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ApplicationInvoices.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> File guard = new File(".guard"); if(guard.exists()){ JOptionPane.showMessageDialog(null, "Er is al een andere instantie van het programma actief.", "Melding", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } else { try { guard.createNewFile(); guard.deleteOnExit(); } catch (IOException ex) { Logger.getLogger(ApplicationInvoices.class.getName()).log(Level.SEVERE, null, ex); } } database.Database.driver(); UIManager.getLookAndFeelDefaults().put("defaultFont", new Font("Arial", Font.PLAIN, Utilities.fontSize())); /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new ApplicationInvoices().setVisible(true); } }); System.out.println(Configuration.center().getDB_URL()); }
8
private boolean ValidPetNameChars(String inputStr,int HardCodedLen) { for(int i=0;i<HardCodedLen;i++) { if(i==0) { if(inputStr.charAt(0) == ' ') { return false; } } if((inputStr.charAt(i) < 'a' || inputStr.charAt(i) > 'z') && (inputStr.charAt(i) < '0' || inputStr.charAt(i) > '9')) { return false; } } return true; }
7
public GlobalParams withLocalParams(Collection<ParamsType> params) { GlobalParams p = copy(); for (ParamsType t: params) { p.put(t.name, t.value); } return p; }
1
public static IntNode listSearch(IntNode head, int target) { IntNode cursor; for (cursor = head; cursor != null; cursor = cursor.link) if (target == cursor.data) return cursor; return null; }
2
protected void getNodeTexts(TreeMap<String, LinkedList<ParseTopiaryNode>> map, boolean includeNamedNodes) { // System.out.format("names.size()=%d\n",names.size()); if ( (text!=null) && !text.isEmpty() ) { if (names.size() == 0 || includeNamedNodes ) { LinkedList<ParseTopiaryNode> ll = map.get(text); if (ll == null) { ll = new LinkedList<ParseTopiaryNode>(); map.put(text, ll); } ll.add(this); } } for (ParseTopiaryNode c : children) { c.getNodeTexts(map, includeNamedNodes); } }
6
@Override public void run() { if (isConnected && ossl != null) { bdl = new BroadcastDiscoveryListener(); bdl.start(); onServerStart(); } else { System.err.println("Could not launch onStartServerListener... null or not connected"); } while (isConnected) { if (Math.random() > 0.9999) { // update some times //dataHandler.updateBots(); } broadcastPositions(); try { Thread.sleep(NetworkManager.POSISTION_MESSAGE_WAIT_TIME); } catch (InterruptedException ex) { Logger.getLogger(GameServer.class.getName()).log(Level.SEVERE, null, ex); } } System.out.println("Server stopped sending pos..."); }
5
private synchronized static void startBackgroundThread () { if (backgroundThread == null) { backgroundThreadMayRun = true; backgroundThread = new Thread(asyncThreadGroup, "AnalyticsBackgroundThread") { @Override public void run () { Logger.logInfo("AnalyticsBackgroundThread started"); while (backgroundThreadMayRun) { try { String url = null; synchronized (fifo) { if (fifo.isEmpty()) { fifo.wait(); } if (!fifo.isEmpty()) { // Get a reference to the oldest element in the FIFO, but leave it in the FIFO until it is processed. url = fifo.getFirst(); } } if (url != null) { try { dispatchRequest(url); } finally { // Now that we have completed the HTTP request to GA, remove the element from the FIFO. synchronized (fifo) { fifo.removeFirst(); } } } } catch (Exception e) { Logger.logError("Got exception from dispatch thread", e); } } } }; backgroundThread.setDaemon(true); backgroundThread.start(); } }
6
public boolean isChoking() { return this.choking; }
0
private void processWalksFromSource(int source, ArrayList<Walk> walksFromSource) { // Now sort by target Collections.sort(walksFromSource, new Comparator<Walk>() { @Override public int compare(Walk walk1, Walk walk2) { int dest1 = walk1.getDestination(); int dest2 = walk2.getDestination(); return (dest1 == dest2 ? 0 : (dest1 < dest2 ? -1 : 1)) ; } }); // Group by target int curDest = -1; ArrayList<Walk> curSet = new ArrayList<Walk>(); for(Walk w : walksFromSource) { if (w.getDestination() != curDest) { if (curDest != -1) handleSourcePathSet(source, curDest, curSet); curDest = w.getDestination(); curSet = new ArrayList<Walk>(); } curSet.add(w); } }
5
public void update() { if (hasGameStarted()) { if (keyListener.isUp()) { sessionImpl.update(-1); } else if (keyListener.isDown()) { sessionImpl.update(1); } else { sessionImpl.update(0); } } else if (!hasGameStarted() && hasGameStopped()) { //game was started but interrupted (so hasGameStarted() is false) gameloop.interrupt(); button1.setLabel("Find game!"); } }
5
public AutomatonEnvironment(Automaton automaton) { super(automaton); Listener listener = new Listener(); automaton.addStateListener(listener); automaton.addTransitionListener(listener); automaton.addNoteListener(listener); initUndoKeeper(); }
0
final void paintBranchCircular( final PhylogenyNode p, final PhylogenyNode c, final Graphics2D g, final boolean radial_labels, final boolean to_pdf, final boolean to_graphics_file ) { final double angle = _urt_nodeid_angle_map.get( c.getNodeId() ); final double root_x = _root.getXcoord(); final double root_y = _root.getYcoord(); final double dx = root_x - p.getXcoord(); final double dy = root_y - p.getYcoord(); final double parent_radius = Math.sqrt( dx * dx + dy * dy ); final double arc = ( _urt_nodeid_angle_map.get( p.getNodeId() ) ) - angle; assignGraphicsForBranchWithColorForParentBranch( c, false, g, to_pdf, to_graphics_file ); if ( ( c.isFirstChildNode() || c.isLastChildNode() ) && ( ( Math.abs( parent_radius * arc ) > 1.5 ) || to_pdf || to_graphics_file ) ) { final double r2 = 2.0 * parent_radius; drawArc( root_x - parent_radius, root_y - parent_radius, r2, r2, ( -angle - arc ), arc, g ); } drawLine( c.getXcoord(), c.getYcoord(), root_x + ( Math.cos( angle ) * parent_radius ), root_y + ( Math.sin( angle ) * parent_radius ), g ); paintNodeBox( c.getXcoord(), c.getYcoord(), c, g, to_pdf, to_graphics_file, isInFoundNodes( c ) ); if ( c.isExternal() ) { final boolean is_in_found_nodes = isInFoundNodes( c ); if ( ( _dynamic_hiding_factor > 1 ) && !is_in_found_nodes && ( _urt_nodeid_index_map.get( c.getNodeId() ) % _dynamic_hiding_factor != 1 ) ) { return; } paintNodeDataUnrootedCirc( g, c, to_pdf, to_graphics_file, radial_labels, 0, is_in_found_nodes ); } }
9
public int getLEShort() { // method437 offset += 2; int v = ((payload[offset - 1] & 0xff) << 8) + (payload[offset - 2] & 0xff); if (v > 32767) { v -= 0x10000; } return v; }
1
private boolean interestedInBitfield(byte[] bfield) { if (amountLeft == 0) { return false; } for (int byteIndex = 0; byteIndex < bitfield.length; byteIndex++) { for (int bitIndex = 0; bitIndex < 8; bitIndex++) { try { if (!Util.isBitSet(this.bitfield[byteIndex], bitIndex) && Util.isBitSet(bfield[byteIndex], bitIndex)) { return true; } } catch (ArrayIndexOutOfBoundsException e) { System.out.println("byte index: " + byteIndex); System.out.println("bit index: " + bitIndex); } } } return false; }
6
public int getTableId(Block block) { Set<Integer> tilesKeys = tilesLocations.keySet(); for(Integer key : tilesKeys) { SerializableLocation blockLocation = new SerializableLocation(block.getLocation()); if(tilesLocations.get(key).contains(blockLocation)) return key; } Set<Integer> spinnersKeys = spinnersLocations.keySet(); for(Integer key : spinnersKeys) { SerializableLocation blockLocation = new SerializableLocation(block.getLocation()); if(spinnersLocations.get(key).equals(blockLocation)) return key;; } return -1; }
4
@Override public void mouseDragged(MouseEvent e) { if (this.grabbing) { Rectangle r = this.getRegionBounds(); int flags = 0; double pre = this.position; int left = e.getX() + this.grabOffset; this.position = left / (double) (r.width - this.grabSize) * (this.valueRange[1] - this.valueRange[0]); if (this.position < this.valueRange[0]) this.position = this.valueRange[0]; else if (this.position > this.valueRange[1]) this.position = this.valueRange[1]; if (e.isShiftDown() && this.position > this.valueRange[0] && this.position < this.valueRange[1]) { this.position = Math.round(this.position / this.snap) * this.snap; } if (this.position != pre) { flags |= ChangeEvent.CHANGED; this.dragFlags |= flags; } this.signalChange(ChangeEvent.DRAGGING | flags); this.repaint(); } }
7
public SFormat newSFormat(JType t, String colName) //public SFormat newSFormat(JType t, boolean editable) { // Try by name if (colName != null) { Object o = makerMap.get(colName); if (o != null) return getSFormatObj(o, t); } // Index on general class of the JType, // or on its underlying Java Class (for JavaJType) Class klass = t.getClass(); if (klass == JavaJType.class) klass = ((JavaJType) t).getObjClass(); System.err.println("newSFormat: " + klass); for (;;) { System.err.println(" trying: " + klass); Object o = makerMap.get(klass); if (o != null) return getSFormatObj(o, t); // Increment the loop... klass = klass.getSuperclass(); if (klass == null || klass == Object.class) break; } // No SFormat found, punt... System.err.println("Failed to find a SFormat"); return null; }
7
protected Object initialInput(Component component, String title) { if(title.equals("")) title = "Input"; if(getObject() instanceof TuringMachine){ // Do the multitape stuff. TuringMachine tm = (TuringMachine) getObject(); int tapes = tm.tapes(); if(title.equals("Expected Result? (Accept or Reject)")){ title = "Result"; tapes = 1; } if(title.equals("Expected Output?")){ title = "Output"; } return openInputGUI(component, title, tapes); } else{ if (title.equals("")){ return openInputGUI(component, "Input?", 0); //return JOptionPane.showInputDialog(component, "Input?"); } else { return openInputGUI(component, title, 0); //return JOptionPane.showInputDialog(component, title+ "?!!!!"); } } }
5
public void check(int x, int y, int [] loc, float startmag) { int r = 10; float [][] SSD = new float[size][size]; int N = size/4; for (int l = -size/2; l <= size/2; l++) for (int k = -size/2; k <= size/2; k++) SSD[l+size/2][k+size/2] = w[l+size/2][k+size/2]; IJ.write("Check minima at "+x+","+y+" max (peak)="+loc[0]+","+loc[1]); for (int i=0;i<r;i++) { float min_value = Float.MAX_VALUE; float SSDmag = startmag; // 0 or MAX_VALUE; int u_min = 0; int v_min = 0; for (int u=(-N);u<=N;u++) for (int v=(-N);v<=N;v++) { int u_index = u+N; int v_index = v+N; if ((Math.abs(SSD[u_index][v_index] - min_value) <= 0.1 && (u*u+v*v) < SSDmag) || (min_value - SSD[u_index][v_index] > 0.1)) { min_value = SSD[u_index][v_index]; v_min = v; u_min = u; SSDmag = u*u+v*v; // Euclidean distance from center. } } SSD[u_min+N][v_min+N] = Float.MAX_VALUE; if (startmag < 1) IJ.write(""+i+"th minimum: "+min_value+" at "+u_min+","+v_min +" SSDmag: "+(u_min*u_min+v_min*v_min)); else IJ.write(""+i+"th minimum: "+min_value+" at "+u_min+","+v_min); } }
9
public static void main(String[] args) { // TODO Auto-generated method stub int mat[][]={{1,2,3},{4,5,6},{7,8,0}}; boolean row[]=new boolean[mat.length]; boolean col[]=new boolean[mat[0].length]; for(int i=0;i<mat.length;i++) { for(int j=0;j<mat[0].length;j++) { if(mat[i][j]==0) { row[i]=true; col[j]=true; } } } for(int i=0;i<mat.length;i++) { for(int j=0;j<mat[0].length;j++) { if(row[i]==true || col[j]==true) mat[i][j]=0; } } for(int i=0;i<mat.length;i++) { for(int j=0;j<mat.length;j++) { System.out.print(mat[i][j]); } System.out.println(); } }
9
@Test public void testEquals() { try { System.out.println("equals"); Port port = new Port(); Ship instance = new Ship(port, "Test", 12, 23); Ship newInstance = new Ship(port, "Test", 12, 23); boolean expResult = true; boolean result = instance.equals(newInstance); assertEquals(expResult, result); } catch (ShipException ex) { Logger.getLogger(ShipTest.class.getName()).log(Level.SEVERE, null, ex); } }
1
private FieldIdentifier findField(String name, String typeSig) { for (Iterator i = fieldIdents.iterator(); i.hasNext();) { FieldIdentifier ident = (FieldIdentifier) i.next(); if (ident.getName().equals(name) && ident.getType().equals(typeSig)) return ident; } return null; }
3
public static void insert (int [ ] values, int pos, int newInt) { if (pos<0 || pos>=values.length) { return; } // your code goes here }
2
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Palette other = (Palette) obj; if (!Arrays.equals(data, other.data)) return false; return true; }
4
static public ReciboCertificado instancia() { if (UnicaInstancia == null) { UnicaInstancia = new ReciboCertificado(); } return UnicaInstancia; }
1
public int maxProfit(int[] prices) { if (prices == null || prices.length <= 1) return 0; int max = 0; for (int i = 0; i < prices.length - 1; ++i) { if (prices[i + 1] > prices[i]) { max += prices[i + 1] - prices[i]; } } return max; }
4
private static void loopCallBack() { Iterator<Entry<Long,UserNotificationBuffer>> it = monitors.entrySet().iterator(); while(it.hasNext()) { Entry<Long,UserNotificationBuffer> pair = it.next(); UserNotificationBuffer notification = pair.getValue(); notification.performSchedule(); } }
1
private static String normalize(String wiki) { pattern = Pattern.compile("(\\[\\[[^\\|]*\\|)([^\\]]*)(\\]\\])", Pattern.UNICODE_CASE); matcher = pattern.matcher(wiki); while (matcher.find()) { wiki = wiki.replaceFirst("(\\[\\[[^\\|]*\\|)([^\\]]*)(\\]\\])", matcher.group(2)); } wiki = wiki.replaceAll("<[^>]*>", ""); wiki = wiki.replaceAll("[\\[\\]\\{\\}]", ""); wiki = wiki.replaceAll("'''|''", ""); return wiki.trim(); }
1
private static boolean stack_boolean(CallFrame frame, int i) { Object x = frame.stack[i]; if (x == Boolean.TRUE) { return true; } else if (x == Boolean.FALSE) { return false; } else if (x == UniqueTag.DOUBLE_MARK) { double d = frame.sDbl[i]; return d == d && d != 0.0; } else if (x == null || x == Undefined.instance) { return false; } else if (x instanceof Number) { double d = ((Number)x).doubleValue(); return (d == d && d != 0.0); } else if (x instanceof Boolean) { return ((Boolean)x).booleanValue(); } else { return ScriptRuntime.toBoolean(x); } }
9
private static Class getAttributeTypeClass(int attributeType, String typeStr) { Class type = RadiusAttribute.class; if (typeStr.equalsIgnoreCase("string")) type = StringAttribute.class; else if (typeStr.equalsIgnoreCase("octets")) type = RadiusAttribute.class; // DAVI allow integer8 and integer16 //else if (typeStr.equalsIgnoreCase("integer") || typeStr.equalsIgnoreCase("date")) else if (typeStr.equalsIgnoreCase("integer") || typeStr.equalsIgnoreCase("integer8") || typeStr.equalsIgnoreCase("integer16") || typeStr.equalsIgnoreCase("date")) type = IntegerAttribute.class; else if (typeStr.equalsIgnoreCase("ipaddr")) type = IpAttribute.class; return type; }
7
public ArgumentReader resolveReader(Class<?> type) { ArgumentReader reader = getReader(type); if (reader == null) { for (Class<?> next : readers.keys()) { if (type.isAssignableFrom(next)) { reader = readers.get(next); if (reader != null) { register(reader, type); break; } } } } return reader; }
6
final Class318_Sub4 method2386(int i, AbstractToolkit var_ha) { anInt10159++; AnimatableToolkit class64 = ((Class318_Sub1_Sub5_Sub2) this).aClass235_10155 .method1668(false, true, -127, 2048, var_ha); if (class64 == null) return null; Class101 class101 = var_ha.method3705(); class101.method894((((Class318_Sub1) this).xHash + ((Class318_Sub1_Sub5) this).aShort8781), ((Class318_Sub1) this).anInt6382, (((Class318_Sub1) this).anInt6388 + ((Class318_Sub1_Sub5) this).aShort8769)); Class318_Sub4 class318_sub4 = DummyOutputstream.method136(i, aBoolean10153, false); int i_3_ = ((Class318_Sub1) this).xHash >> 1712008233; int i_4_ = ((Class318_Sub1) this).anInt6388 >> 321153897; ((Class318_Sub1_Sub5_Sub2) this).aClass235_10155.method1670 (i_3_, class101, i_4_, var_ha, i_3_, class64, true, (byte) -73, i_4_); if (!Class305.aBoolean3870) class64.method615(class101, (((Class318_Sub4) class318_sub4) .aClass318_Sub3Array6414[0]), 0); else class64.method608(class101, (((Class318_Sub4) class318_sub4) .aClass318_Sub3Array6414[0]), Class132.anInt1906, 0); if ((((Class235) ((Class318_Sub1_Sub5_Sub2) this).aClass235_10155) .aClass318_Sub10_3081) != null) { Class98 class98 = ((Class235) ((Class318_Sub1_Sub5_Sub2) this).aClass235_10155) .aClass318_Sub10_3081.method2525(); if (!Class305.aBoolean3870) var_ha.method3684(class98); else var_ha.method3685(class98, Class132.anInt1906); } aBoolean10148 = class64.F() || (((Class235) (((Class318_Sub1_Sub5_Sub2) this) .aClass235_10155)) .aClass318_Sub10_3081) != null; if (aClass30_10150 == null) aClass30_10150 = (Class348_Sub23_Sub1.method2967 (((Class318_Sub1) this).xHash, class64, ((Class318_Sub1) this).anInt6388, ((Class318_Sub1) this).anInt6382, 2)); else ItemLoader.method1935(((Class318_Sub1) this).anInt6388, ((Class318_Sub1) this).anInt6382, aClass30_10150, class64, false, ((Class318_Sub1) this).xHash); return class318_sub4; }
6
private HashSet<Integer> getForbiddenColors(Value n) { HashSet<Value> edges = adjacencyList.get(n); HashSet<Integer> rval = new HashSet<Integer>(); for(Value v : edges) { Integer c = v.getColor(); if(c != null && c != -1) { rval.add(c); } } return rval; }
3
protected boolean inBounds(int i, int j, BufferedImage completePic) { return (i > 0 && j > 0 && i < completePic.getWidth() && j < completePic .getHeight()); }
3
public static void changeUserLastLogDate (User user) { try { Connection conn = DriverManager.getConnection(Utils.DB_URL); PreparedStatement prS = conn.prepareStatement("update user set date_lastlog = ? where name = '" + user.getName() + "'"); prS.setString(1, Utils.getTodaysDate()); prS.execute(); System.out.println("Date edited!"); } catch (SQLException e) { e.printStackTrace(); } }
1
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(Rezervacija.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Rezervacija.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Rezervacija.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Rezervacija.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 Rezervacija().setVisible(true); } }); }
6
public void setjButtonPrevious(JButton jButtonPrevious) { this.jButtonPrevious = jButtonPrevious; }
0
private final void insertOnline(Entry<K,V> e) { if (onl[e.getH()].size()<this.w) { onl[e.getH()].add(e); onlsize++; } else { cam.put(e.getK(), e); } }
1
public Texture loadTexture(String paramFileName, boolean paramFlipped, boolean paramUseRes) { String fileLoc; try { if (paramUseRes) { fileLoc = "resources/" + paramFileName; } else { fileLoc = paramFileName; } return TextureLoader.getTexture("PNG", new FileInputStream(new File(fileLoc)), paramFlipped); } catch (IOException ex) { String usedResources = paramUseRes ? " using resources directory." : " not using resources directory."; Game.log(EnumLogWeight.MEDIUM, "CTextureLoader: Unable to load texture \"" + paramFileName + "\", was" + usedResources); Logger.getLogger(TexturesEntity.class.getName()).log(Level.SEVERE, null, ex); } return null; }
3
public int getStatusDuration(TileStatus.Type type) { if (!this.hasStatus(type)) { // Check if the tile even has the status at all. return 0; // If not, then that status has 0 effectively 0 duration. } else { // Loop through all the status the tile does have. for (TileStatus status : this.statuses) { // Check if it is the status we are looking for. if (status.getType() == type) { // If so, return that status' remaining duration. return status.getRemainingDuration(); } } // This return value is a fallback, // but theoretically the function should never reach this point. // Because we already made sure that the status existed, before we looped. return 0; } }
3
public static Map<String, List<Integer>> readCSV(String fileName) { Map<String, List<Integer>> disp = new HashMap<String, List<Integer>>(); File file = null; FileReader fr = null; BufferedReader br = null; try { file = new File(fileName); fr = new FileReader(file); br = new BufferedReader(fr); // File Read String linea; while ((linea = br.readLine()) != null) { String[] fields = linea.split(split); List<Integer> identifiers = new ArrayList<Integer>(); for (int i = 1; i < fields.length; i++) { identifiers.add(Integer.parseInt(fields[i])); } disp.put(fields[0], identifiers); } } catch (Exception e) { e.printStackTrace(); disp = null; } finally { try { if (null != fr) { fr.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return disp; }
5