text
stringlengths
14
410k
label
int32
0
9
public static boolean validate(int index, String listAdd, char addChar) { int isParenthesis = 0; if(listAdd.length() > 0) isParenthesis = listAdd.charAt(0) == '(' ? 1 : 0; if(isOperator(addChar) && listAdd.length() > 0 + isParenthesis) if(addChar != '/') return false; if(!listAdd.contains("_") && addChar == '/' && listAdd.length() > 0) return false; if(listAdd.contains("/")) return false; return true; }
9
public void buildFromBEDFile(File bedFile) throws IOException { intervals = new HashMap<String, List<Interval>>(); BufferedReader reader = new BufferedReader(new FileReader(bedFile)); String line = reader.readLine(); while(line != null && line.startsWith("#")) { line = reader.readLine(); } while(line != null) { if (line.trim().length() > 1) { String[] toks = line.split("\t"); if (toks.length > 2) { String contig = toks[0]; try { int first = Integer.parseInt(toks[1]); int last = Integer.parseInt(toks[2]); Interval inter = new Interval(first, last+1); addInterval(contig, inter); } catch (NumberFormatException nfe) { System.err.println("Warning: Could not parse position for BED file line: " + line ); } } else { System.err.println("Warning: Incorrect number of tokens on BED file line: " + line ); } } line = reader.readLine(); } sortAllIntervals(); reader.close(); }
6
private void scrapeFootball() { QBsPlaying = new ArrayList<BasketballPlayer>(); WRsPlaying = new ArrayList<BasketballPlayer>(); RBsPlaying = new ArrayList<BasketballPlayer>(); TEsPlaying = new ArrayList<BasketballPlayer>(); DSTPlaying = new ArrayList<BasketballPlayer>(); KickersPlaying = new ArrayList<BasketballPlayer>(); Elements script = doc.select("script"); Element playerScript = script.get(1); String playerInfo = playerScript.data(); String[] semiColon = playerInfo.split("\\{"); String players = semiColon[14]; String [] playerStrings = players.split("\\["); //For every player in the HTML Document, divide into commas to get the Name and Salary attributes; //Add that player to the ArrayList based upon their type. int lastInteger = (playerStrings.length - 1); for(int i = 0;i < playerStrings.length;i++){ //Need to not include the first or last if(i != 0 && i != lastInteger){ String[] playerData = playerStrings[i].split(","); String position = playerData[0].replaceAll("^\"|\"$", ""); //Remove the quotes from the position String playerName = playerData[1].replaceAll("^\"|\"$", ""); //Remove the quotes from the name int salary = Integer.parseInt(playerData[5].replaceAll("^\"|\"$","")); switch(position.toUpperCase()){ case "WR": FantasyApp.log.debug("Adding WR"); WRsPlaying.add(new BasketballPlayer(playerName, salary)); break; case "RB": FantasyApp.log.debug("Adding RB"); RBsPlaying.add(new BasketballPlayer(playerName, salary)); break; case "TE": FantasyApp.log.debug("Adding TE"); TEsPlaying.add(new BasketballPlayer(playerName, salary)); break; case "QB": FantasyApp.log.debug("Adding QB"); QBsPlaying.add(new BasketballPlayer(playerName, salary)); break; case "K": FantasyApp.log.debug("Adding Kicker"); KickersPlaying.add(new BasketballPlayer(playerName, salary)); break; case "D": FantasyApp.log.debug("Adding Defense/ST"); DSTPlaying.add(new BasketballPlayer(playerName, salary)); break; } FantasyApp.log.debug("Position: "+position+" Name: "+playerName+" Salary: "+salary); } } FantasyApp.log.info("The website FanDuel was scraped sucessfully"); }
9
@Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(cmd.getName().equalsIgnoreCase("Suffix")) { if(sender instanceof Player) { Player p = (Player) sender; PlayerUtil pu = new PlayerUtil(p); if(pu.hasPermission("Nostalgia.Command.suffix", PermissionType.NORMAL)) { if(args.length == 0) { String buildsuffix = StringUtil.arrangeString(args, " ", 0); String suffix = StringUtil.colorize(buildsuffix); pu.setSuffix(suffix); pu.updateName(); p.sendMessage(LangUtil.suffixChanged(p.getDisplayName())); } else if (args.length >= 1) { if(StringUtil.startsWithIgnoreCase(args[0], "p:")) { if(pu.hasPermission("Nostalgia.Command.suffix.others", PermissionType.NORMAL)){ String playerName = StringUtil.removePrefix(args[0], 2); Player t = Nostalgia.getPlayer(playerName); if(t != null) { PlayerUtil tu = new PlayerUtil(t); String buildsuffix = StringUtil.arrangeString(args, " ", 1); String suffix = StringUtil.colorize(buildsuffix, p, "suffix", PermissionType.NORMAL); tu.setSuffix(suffix); tu.updateName(); t.sendMessage(LangUtil.suffixChanged(t.getDisplayName())); } else { p.sendMessage(LangUtil.mustBeOnline(playerName)); } } else { MessageUtil.noPermission(p, "Nostalgia.Command.suffix.others"); } } else { String buildsuffix = StringUtil.arrangeString(args, " ", 0); String suffix = StringUtil.colorize(buildsuffix, p, "suffix", PermissionType.NORMAL); pu.setSuffix(suffix); pu.updateName(); p.sendMessage(LangUtil.suffixChanged(p.getDisplayName())); } } else { p.sendMessage(LangUtil.fourthWall()); } } else { MessageUtil.noPermission(p, "Nostalgia.Command.suffix"); } } else { sender.sendMessage(LangUtil.mustBePlayer()); } } return false; }
8
public void run() { try { enc.SetEndMarkerMode(true); if (LzmaOutputStream.LZMA_HEADER) { enc.WriteCoderProperties(out); // 5d 00 00 10 00 final long fileSize = -1; for (int i = 0; i < 8; i++) { out.write((int) (fileSize >>> 8 * i) & 0xFF); } } if (DEBUG) { dbg.printf("%s begins%n", this); } enc.Code(in, out, -1, -1, null); if (DEBUG) { dbg.printf("%s ends%n", this); } out.close(); } catch (final IOException _exn) { exn = _exn; if (DEBUG) { dbg.printf("%s exception: %s%n", exn.getMessage()); } } }
6
private Class<?>[] findMeasureClasses() { AutoExpandVector<Class<?>> finalClasses = new AutoExpandVector<Class<?>>(); Class<?>[] classesFound = AutoClassDiscovery.findClassesOfType("moa.evaluation", MeasureCollection.class); for (Class<?> foundClass : classesFound) { finalClasses.add(foundClass); } return finalClasses.toArray(new Class<?>[finalClasses.size()]); }
7
public synchronized void gameFinished(Player winnerPlayer, List<Player> players) { if (firstPhaseElectionTask != null) { firstPhaseElectionTask.cancel(); firstPhaseElectionTask = null; } if (secondPhaseElectionTask != null) { secondPhaseElectionTask.cancel(); secondPhaseElectionTask = null; } if (lastWordTask != null) { lastWordTask.cancel(); lastWordTask = null; } if (lastElectionTask != null) { lastElectionTask.cancel(); lastElectionTask = null; } System.out.println("##################################################"); System.out.println("Partita terminata, vincitore: " + winnerPlayer); System.out.println("##################################################"); }
4
private boolean hasPermission(Player player, String node) { if ( this.permissionHandler != null ) { return this.permissionHandler.has(player, node); } else { return player.hasPermission(node); } }
1
public void loadConfig() { config = new YamlConfiguration(); createConfig(); File file = new File(getDataFolder(), "config.yml"); try { config.load(file); } catch (FileNotFoundException e) { e.printStackTrace(); Logger.warning("Could not load config, using default settings!"); } catch (IOException e) { e.printStackTrace(); Logger.warning("Could not load config, using default settings!"); } catch (InvalidConfigurationException e) { e.printStackTrace(); Logger.warning("Could not load config, using default settings!"); } permissions = config.getBoolean("permissions", true); displayName = config.getBoolean("display-name", false); hideKick = config.getBoolean("silentkick", true); joinMessage = config.getString("join-message"); quitMessage = config.getString("quit-message"); }
3
@Override public void paintComponents(Graphics g) { Graphics2D graphics = (Graphics2D) g; graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); graphics.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); graphics.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); graphics.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE); graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); graphics.setFont(new Font(getFont().getName(), Font.ITALIC, 50)); graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f)); graphics.setPaint(PleaseWait.gradient); for (int i = 0; i < 11; i++) { graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, i * 0.1f)); graphics.fill(tickerOuter[i]); graphics.fill(tickerInner[i]); } Toolkit.getDefaultToolkit().sync(); g.dispose(); }
1
public static Sens getSens(String s){ switch(s){ case "A": return Sens.AVANCER; case "R": return Sens.RECULER; case "G": return Sens.GAUCHE; case "D": return Sens.DROITE; default: return null; } }
4
public boolean registerEventListener(final EventListener listener) { logger.debug("EventBus", "Registering "+listener.getClass().getName(), 0); try { for(Method method : listener.getClass().getMethods()) { EventMethod ema = method.getAnnotation(EventMethod.class); if(ema == null) continue; Class<?>[] parameters = method.getParameterTypes(); if(parameters.length != 1) { logger.printException(new IllegalArgumentException( "Method "+method.getName()+" (EventListener "+listener.getClass().getCanonicalName()+ ") has the wrong amount of arguments ("+parameters.length+")! EventMethods require "+ "one (1) argument. Please contact the dev to have this issue fixed.")); return false; } Class<?> eventType = parameters[0]; if(!IEvent.class.isAssignableFrom(eventType)) { logger.printException(new IllegalArgumentException( "Method "+method.getName()+"'s (EventListener "+listener.getClass().getCanonicalName()+ ") arguement does not implement the IEvent interface or extend a class that does so!")); return false; } return true; } } catch(Exception e) { logger.printException(e); return false; } return false; }
7
private String attack(Pawn enemy) { String message=this.letter + " attacks!\n"; if (this.board.isBonusSquare(x, y)) message+=enemy.suffer(2); else message+=enemy.suffer(1); if (enemy.isDead()) gold++; return message; }
2
public static void validate(Review review) throws ValidationMovieCatalogException { LinkedList<String> errorList = new LinkedList<>(); if (review == null) { errorList.add("Null pointer review"); } else { if(review.getUser() == null){ errorList.add("Null pointer user"); } if(review.getMovie() == null){ errorList.add("Null pointer movie"); } Pattern pattern = Pattern.compile(COMMENT_PATTERN); Matcher matcher = pattern.matcher(review.getComment()); if (!matcher.matches()) { errorList.add("Comment is not valid. It must match the pattern " + COMMENT_PATTERN); } if((review.getRating() < 0) || (review.getRating() > 100)){ errorList.add("Rating is not valid. Expected range: 0-100"); } } if(!errorList.isEmpty()){ String message = "Review validation failed: \n"; for(String err : errorList){ message += err + "\n"; } log.error(message); throw new ValidationMovieCatalogException(message); } }
8
private static JSONObject toJSONObject(String paramName, Object o, boolean required) throws BadConfig { if (o == null) { if (required) throw new BadConfig("Parameter \"" + paramName + "\" is required"); return null; } if (!(o instanceof JSONObject)) throw new BadConfig("In parameter \"" + paramName + "\", value \"" + o + "\" should be an object"); return (JSONObject) o; }
3
private boolean isNeedsEscape(String character) { if (character.matches("\\(")) { return true; } else if (character.matches("\\)")) { return true; } else if (character.matches("\\$")) { return true; } else if (character.matches("\\^")) { return true; } else if (character.matches("\\!")) { return true; } else { return false; } }
5
private String peekToken() { if (token == null) try { while (st == null || !st.hasMoreTokens()) { line = r.readLine(); if (line == null) return null; st = new StringTokenizer(line); } token = st.nextToken(); } catch (IOException e) { } return token; }
5
public static String permillage(double p1, double p2) { String str; double p3 = p1 / p2; if (p1 == 0.0) { return "0.00"; } if (p2 == 0.0 && p1 != 0.0) { return "-"; } DecimalFormat df1 = new DecimalFormat("0.00"); str = df1.format(p3 * 1000); return str; }
3
public static String[][] read_data_file(String file_name) { String[][] matrix = null; try { BufferedReader br = new BufferedReader(new FileReader(file_name)); String line, cell = ""; String[] tokens; boolean first_line = true; int row = 0, col = 0; while ((line = br.readLine()) != null) { // Use "whitespace" to tokenize each line // java.sun.com/docs/books/tutorial/extra/ // regex/pre_char_classes.html tokens = line.split("\\s"); int i = 0; if (first_line) { matrix = new String[Integer.parseInt(tokens[0]) ][Integer.parseInt(tokens[1])]; i = 2; first_line = false; } for (; i < tokens.length; ++i) { if (tokens[i].equals("")) { matrix[col][row++] = cell; cell = ""; col = 0; } else if (tokens[i].equals("")) { matrix[col++][row] = cell; cell = ""; } else { cell += " " + tokens[i]; } } } matrix[col][row] = cell; br.close(); } catch (Exception ex) { ex.printStackTrace(); } return matrix; }
6
public String getTopTexture(BlockType type){ // TODO: Make these use official Minecraft texture file names switch (type){ case STONE: return "stone.png"; case GRASS_BLOCK: // TODO: Make grass properly use different colors return "grass_top.png"; case DIRT: return "dirt.png"; case COBBLESTONE: return "cobblestone.png"; case BEDROCK: return "bedrock.png"; case SAND: // sand return "sand.png"; case WOOD: // wood return "wood_top.png"; case LEAVES: // leaves return "leaves.png"; default: if (!BlockType.unimplemented[type.blockType]){ System.out.printf("Unimplemented block: %d (%s)\n", type.blockType, type.toString()); BlockType.unimplemented[type.blockType] = true; } return "stone.png"; } }
9
public int getEast(){ return this.east; }
0
private static Color setGridChargeColor(float q, float qmin, float qmax) { if (Math.round(q) == 0) return Color.black; // pos. blue, neg. green, neu. black float scale = 1.0f; int ncolor; int isign = Math.round(qmax * qmin); if (isign > 0) { scale = 255.0f / (qmax - qmin); // all pos. or neg. ncolor = Math.round(scale * (q - qmin)); } else if (isign < 0) { scale = q > 0 ? 255.0f / qmax : 255.0f / qmin; // some pos., some neg. ncolor = Math.round(scale * q); } else { if (Math.round(qmax) > 0) { scale = 255.0f / qmax; // some pos., some neu., no neg. } else if (Math.round(qmin) < 0) { scale = 255.0f / qmin; // some neg., some neu., no pos. } ncolor = Math.round(scale * q); } ncolor = ncolor > 255 ? 255 : ncolor; ncolor = ncolor < 0 ? 0 : ncolor; return q > 0 ? new Color(0, 0, ncolor) : new Color(0, ncolor, 0); }
9
public HighscorePanel(Map<String, String> levelNameMap, Map<String, Integer> levelScoreMap) { this.levelNameMap = levelNameMap; this.levelScoreMap = levelScoreMap; header = new String[]{"Level Name", "Score"}; data = new String[this.levelNameMap.size()][2]; int count = 0; ValueComparator comparator = new ValueComparator(levelNameMap); TreeMap<String, String> sortedLevelNameMap = new TreeMap<>(comparator); sortedLevelNameMap.putAll(levelNameMap); for (Entry<String, String> entry : sortedLevelNameMap.entrySet()) { Integer score = this.levelScoreMap.get(entry.getKey()); data[count][1] = score == null ? "no score" : score.toString(); data[count][0] = entry.getValue(); count++; } table = new JTable(data, header); table.setEnabled(false); scrollPane = new JScrollPane(table); table.setFillsViewportHeight(true); add(scrollPane); int width = new Integer(CoreConstants.getProperty("game.highscore.width")); int height = new Integer(CoreConstants.getProperty("game.highscore.height")); setPreferredSize(new Dimension(width, height)); }
2
public boolean isEmpty() { return messageBuffer.isEmpty() && writePointer == 0; }
1
public boolean editRecord(String badgeId, String lastName, String recordID, String newStatus) { // check if the user is allowed to create this operation if (!isOfficerAuthorized(badgeId)) { log.error(badgeId + " is not a authorized user to perform editRecord"); System.out.println(badgeId + " is not a authorized user to perform editRecord"); return false; } // if no status is given try { if (newStatus == null && "".equals(newStatus)) { log.error("Invalid status:" + newStatus); return false; } } catch (IllegalArgumentException ex) { ex.printStackTrace(); return false; } // if last name is given if (hasLastName(lastName)) { // if valid record ID if (isInValidRecordId(recordID)) { log.error("Invalid recordID:" + recordID); return false; } log.debug("Editing record " + recordID); final List<Record> list = this.records.get(Character .toUpperCase(lastName.charAt(0))); if (list == null) { // if no entry exists for this last name log.error("No entry exists for this recordID:" + recordID + " with the given lastName:" + lastName); System.out.println("No entry exists for this recordID:" + recordID + " with the given lastName:" + lastName); return false; } // get the lock over entire list; because if not done there's a // chance that transfer record might delete a record from this list // and we get the concurrent modification exception synchronized (list) { for (Record record : list) { if (record.getRecordID().equals(recordID)) { // get the lock over the record that need's to be edited synchronized (record) { // change its status record.setStatus(newStatus); log.debug(this.stationType.getStationCode() + ":Successfully edited Record:" + recordID); System.out .println(this.stationType.getStationCode() + ":Successfully edited Record:" + recordID); } return true; } } } } else { log.error("LastName is required"); } log.debug("Edit failed"); return false; }
9
private Chromasome genChild(Chromasome parent1, Chromasome parent2) { int[] par1 = parent1.returnChrom(); int[] par2 = parent2.returnChrom(); Chromasome child = new Chromasome(par1.length); if (Constants.secondCrossover) { int index = 0; while (index < par1.length / 2) { child.chromasome[index] = par1[index]; index++; } while (index < par1.length) { child.chromasome[index] = par2[index]; index++; } } else{ for(int i = 0; i < child.chromasome.length; i++){ if(rand.nextBoolean()){ child.chromasome[i] = par1[i]; } else child.chromasome[i] = par2[i]; } } if (rand.nextDouble() < Constants.mutationChance) { child.mutate(); Constants.mutations++; } return child; }
6
private static void swap(int[] array, int index1, int index2) { int tmp = array[index2]; array[index2] = array[index1]; array[index1] = tmp; qSwaps++; }
0
public void stop() { synchronized (MP3Player.this) { isPaused = false; isStopped = true; MP3Player.this.notifyAll(); } if (playingThread != null) { try { playingThread.join(); } catch (InterruptedException e) { LOGGER.log(Level.SEVERE, "join() failed", e); } } }
2
public static void main(String[] args) { System.out.println(new Object().equals(new Object())); int m = 3, n = 4; Object[][] a1 = new Object[m][n], a2 = new Object[m][n]; for(int i = 0; i < m; ++i) { for(int j = 0; j < n; ++j) { a1[i][j] = new Object(); a2[i][j] = new Object(); } } System.out.println("Object[][]: " + Arrays.deepEquals(a1, a2)); System.out.println(new IntClass(3).equals(new IntClass(3))); IntClass[][] b1 = new IntClass[m][n], b2 = new IntClass[m][n]; for(int i = 0; i < m; ++i) { for(int j = 0; j < n; ++j) { b1[i][j] = new IntClass(i); b2[i][j] = new IntClass(i); } } System.out.println("IntClass[][]: " + Arrays.deepEquals(b1, b2)); }
4
protected int contest(int b, int g, int r) { /* finds closest neuron (min dist) and updates freq */ /* finds best neuron (min dist-bias) and returns position */ /* for frequently chosen neurons, freq[i] is high and bias[i] is negative */ /* bias[i] = gamma*((1/netsize)-freq[i]) */ int i, dist, a, biasdist, betafreq; int bestpos, bestbiaspos, bestd, bestbiasd; int[] n; bestd = ~(((int) 1) << 31); bestbiasd = bestd; bestpos = -1; bestbiaspos = bestpos; for (i = 0; i < netsize; i++) { n = network[i]; dist = n[0] - b; if (dist < 0) dist = -dist; a = n[1] - g; if (a < 0) a = -a; dist += a; a = n[2] - r; if (a < 0) a = -a; dist += a; if (dist < bestd) { bestd = dist; bestpos = i; } biasdist = dist - ((bias[i]) >> (intbiasshift - netbiasshift)); if (biasdist < bestbiasd) { bestbiasd = biasdist; bestbiaspos = i; } betafreq = (freq[i] >> betashift); freq[i] -= betafreq; bias[i] += (betafreq << gammashift); } freq[bestpos] += beta; bias[bestpos] -= betagamma; return (bestbiaspos); }
6
public static boolean downloadFile(String libName, File libPath, String libURL) { try { URL url = new URL(libURL); URLConnection connection = url.openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); InputSupplier<InputStream> urlSupplier = new URLISSupplier(connection); Files.copy(urlSupplier, libPath); return true; } catch (Exception e) { return false; } }
1
public static void main(String args[]) { Scanner in = new Scanner(System.in); Map<String, String> types = new HashMap<String, String>(); int N = in.nextInt(); // Number of elements which make up the association table. in.nextLine(); int Q = in.nextInt(); // Number Q of file names to be analyzed. in.nextLine(); for (int i = 0; i < N; i++) { String EXT = in.next(); // file extension String MT = in.next(); // MIME type. types.put(EXT.toLowerCase(), MT); in.nextLine(); } for (int i = 0; i < Q; i++) { String FNAME = in.nextLine(); // One file name per line. if(!FNAME.contains(".") || FNAME.split("\\.").length < 2 || FNAME.charAt(FNAME.length()-1) == '.') { System.out.println("UNKNOWN"); } else { String[] parsed = FNAME.split("\\."); if(!types.containsKey(parsed[parsed.length-1].toLowerCase())) { System.out.println("UNKNOWN"); } else { System.out.println(types.get(parsed[parsed.length-1].toLowerCase())); } } } }
6
public static boolean hasCut(Pokemon[] pokemon) { for (Pokemon aPokemon : pokemon) { if (aPokemon != null) { for (int j = 0; j < 4; j++) { if (aPokemon.move[j] == Pokemon.Move.CUT) return true; } } } return false; }
4
public @Override void setDNA(String dna) throws IllegalArgumentException { if (dna == null || dna.length() == 0) throw new IllegalArgumentException("argument null or empty"); if (dna.contains("TGC")) throw new IllegalArgumentException("argument contains TGC"); for (int i= 0; i < dna.length(); i= i+1) { char c= dna.charAt(i); if ("CTGA".indexOf(c) < 0) { throw new IllegalArgumentException("argument contains illegal character '" + c + "'"); } } this.dna= dna; }
5
public void loadIdent(String id) { Ident ident = Yaka.tabident.chercheIdent(id); if (ident != null) {// l'ident existe var_param_const if (ident.isVar()) {// ident est une variable int offset =((IdVar) ident).getOffset(); int index=-1*offset/2 - 1;// index de la variable dans la pile des variables if (Yaka.tabident.var.get(index)!=-1) {// la variable a été définie Yaka.yvm.iload(offset); } else {// variable non définie Erreur.message("La variable '" + id + "' n'est pas encore définie"); } } else if (ident.isParam()){//ident_param int offset =((IdParam) ident).getOffset(); Yaka.yvm.iload(offset); } else {// ident est une constante Yaka.yvm.iconst(((IdConst) ident).getValeur()); } } else { ident = Yaka.tabident.chercheIdentG(id); if(ident!=null){// ident existe fonc } else {// l'ident n'existe pas Erreur.message("La variable ou la constante '" + id + "' n'existe pas"); this.type.push(YakaConstants.ERREUR); } } }
5
@Override public void putAll(final Map<? extends K, ? extends V> m) { for (final java.util.Map.Entry<? extends K, ? extends V> entry : m .entrySet()) { final K key = entry.getKey(); final Entry newEntry = new Entry(key, entry.getValue()); final Entry old = this.lookUpMap.put(key, newEntry); if (old == null) { this.tail.next = newEntry; this.tail = this.tail.next; } } }
6
public static void ConvertToLibSVM(String directory, String outputDirectory) throws FileNotFoundException,IOException{ FileReader fr = new FileReader (directory); BufferedReader br = new BufferedReader(fr); FileWriter stream = new FileWriter(outputDirectory,false); BufferedWriter bo = new BufferedWriter(stream) ; int count=0; String line; int cc=0; while((line=br.readLine())!=null) { ++cc; boolean flag=true; String [] array = line.split(","); String output=""; String male="m"; if(array[0].compareTo(male)==0) { output="+1"; //System.out.println("----"+array[0]+"-----"); } else { output="-1"; //System.out.println("-1"); //System.out.println("----"+array[0]+"-----"); } for(int i=1;i<array.length;i++) { if(array[i].compareToIgnoreCase("Nan")==0) { flag=false; } if(array[i].compareToIgnoreCase("null")==0) { array[i]="0"; } if(array[i].compareToIgnoreCase("0")!=0) { output+=" "+i+":"+array[i]; } } if(flag==true) { bo.write(output); bo.newLine(); } else{ //bo.write("-1 "); //bo.newLine(); //System.out.println(++count+" "+output); } } br.close(); fr.close(); bo.close(); stream.close(); }
7
public Message(User u, String m) { this.user = u; this.content = m; }
0
public List<Instance> readData() { ArrayList<Instance> instances = new ArrayList<Instance>(); while (this._scanner.hasNextLine()) { String line = this._scanner.nextLine(); if (line.trim().length() == 0) continue; FeatureVector feature_vector = new FeatureVector(); // Divide the line into features and label. String[] split_line = line.split(" "); String label_string = split_line[0]; Label label = null; if (this._classification) { int int_label = Integer.parseInt(label_string); if (int_label != -1) { label = new ClassificationLabel(int_label); } } else { try { double double_label = Double.parseDouble(label_string); label = new RegressionLabel(double_label); } catch (Exception e) { } } for (int ii = 1; ii < split_line.length; ii++) { String item = split_line[ii]; String name = item.split(":")[0]; int index = Integer.parseInt(name); double value = Double.parseDouble(item.split(":")[1]); if (value != 0) feature_vector.add(index, value); } Instance instance = new Instance(feature_vector, label); instances.add(instance); } return instances; }
7
public void deleteAll(Collection<T> entities) { if (entities != null) for (T entity : entities) { session().delete(entity); } }
2
private void sortDACSpartitions(OneMutation mutArray[], int initDepth, int majorSplitPos[], int numPartitions[], PrunedRotamers<Boolean> prunedRotAtRes, Index3 indexMap[][], int numMutable, int strandMut[][], double pruningE, double initEw, RotamerSearch rsP) { RotamerSearch rs = rsP; //no changes should be made to the original RotamerSearch object rsP = null; System.out.print("Computing a lower bound on the conformational energy for each partition.."); for (int m=0; m<mutArray.length; m++){ //for each partition if(m%100 == 0) System.out.println("Starting Partition.. "+m+" out of "+mutArray.length+" "); PrunedRotamers<Boolean> prunedForPartition = new PrunedRotamers<Boolean>(prunedRotAtRes,false); //no changes should be made to prunedRotAtRes[] Iterator<RotInfo<Boolean>> iter1 = prunedRotAtRes.iterator(); while(iter1.hasNext()){ RotInfo<Boolean> ri = iter1.next(); prunedForPartition.set(ri, new Boolean(ri.state)); } //System.arraycopy(prunedRotAtRes, 0, prunedForPartition, 0, prunedRotAtRes.length); mutArray[m].setSortScores(true); //sort by lower bounds //artificially set to pruned all rotamers at the splitting position, other than the current partitioning rotamer for the given partitioning position for (int i=0; i<initDepth; i++){ //first, set all other rotamers for the partitioning positions to pruned Index3 curPart = mutArray[m].index[i]; for (int j=0; j<numPartitions[i]; j++){ Index3 curInd = indexMap[i][j]; if (curInd!=curPart) { //not the rotamer for the current partition if (!prunedForPartition.get(curInd)) //rotamer not already pruned prunedForPartition.set(curInd, true); } } } //compute a lower bound on the conformational energies for this partition rs.DoMinBounds(numMutable,strandMut,pruningE,prunedForPartition,initEw, false, false, true); mutArray[m].score = new BigDecimal(rs.getBoundForPartition()); } System.out.println("done"); //sort the partitions System.out.print("Sorting partitions by their lower energy bounds.."); //RyanQuickSort rqs = new RyanQuickSort(); //rqs.Sort(mutArray); //rqs = null; Arrays.sort(mutArray); System.out.println("done"); System.out.println("MinBoundOfMinPartition: "+mutArray[0].score); }
7
public List<TestResultData> process() { List<TestResultData> testResults = new ArrayList<TestResultData>(); try { BufferedReader bufferReader = new BufferedReader(new FileReader( resultFile)); String line = null; while((line = bufferReader.readLine()) != null) { if (line.startsWith("RESULT:") && line.endsWith(".xml")) { String[] fieldsData = line.split(" "); TestResultData resultData = new TestResultData(); String testNameField = fieldsData[2]; String methodName = testNameField.substring(testNameField.lastIndexOf(".") + 1); String datasetId = (testNameField.indexOf("-") >= 0 ? testNameField.substring( testNameField.indexOf("-") + 1, testNameField.lastIndexOf(methodName) - 1) : null); int testClassendIndex = (datasetId == null ? testNameField.lastIndexOf(".") : testNameField.indexOf("-")); String testClassName = testNameField.substring(0, testClassendIndex); resultData.setTestName(testClassName + (!"test".equals(methodName) ? "-" + methodName : "")); //append method name if TestGroup. resultData.setTestConfigId(datasetId); resultData.setTestStatus(toTestStatus(fieldsData[3])); String suiteNameField = fieldsData[4]; if (QcConstants.QC_TESTSET_NAME != null) { resultData.setTestSetName(QcConstants.QC_TESTSET_NAME); } else { resultData.setTestSetName(suiteNameField.substring(0, suiteNameField.lastIndexOf("."))); } testResults.add(resultData); } } } catch(FileNotFoundException fnfe) { log.error("File is not found :" + resultFile); } catch(IOException ioe) { log.error("Got an exception while reading file :", ioe); } return testResults; }
9
public List<Regional> getRegionals(URL url) { Document doc; Tidy tidy = new Tidy(); List<Regional> retVal = new ArrayList<Regional>(); Regional temp; String link = ""; String name = ""; int teamCounter = 0; try { doc = tidy.parseDOM(url.openStream(), null); XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr = xpath.compile("//tr[@bgcolor = '#FFFFFF']/td/a/@href|//tr[@bgcolor = '#FFFFFF']/td/text()"); NodeList nodes = (NodeList)expr.evaluate(doc, XPathConstants.NODESET); for(int i = 0; i < nodes.getLength();) { temp = new Regional(); temp.setType(nodes.item(i++).getNodeValue()); link = nodes.item(i++).getNodeValue(); link = link.replace("event_details", "event_teamlist"); temp.setUrl(FRCURL + link); temp.setVenue(nodes.item(i++).getNodeValue()); temp.setLocation(nodes.item(i++).getNodeValue()); temp.setDate(nodes.item(i++).getNodeValue()); retVal.add(temp); link = ""; } expr = xpath.compile("//tr[@bgcolor = '#FFFFFF']/td/a/text()|//tr[@bgcolor = '#FFFFFF']/td/a/em/text()"); nodes = (NodeList)expr.evaluate(doc, XPathConstants.NODESET); for(int i = 0; i < nodes.getLength();) { name = nodes.item(i++).getNodeValue(); while(i < nodes.getLength() && (nodes.item(i).getNodeValue().equals("FIRST") || nodes.item(i).getNodeValue().equals(" Robotics District Competition") || nodes.item(i).getNodeValue().equals(" Championship"))) { name += nodes.item(i++).getNodeValue(); } retVal.get(teamCounter++).setName(name); } } catch (IOException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } return retVal; }
8
@SuppressWarnings(value="unchecked") public void put(int field$, java.lang.Object value$) { switch (field$) { case 0: to = (java.lang.CharSequence)value$; break; case 1: from = (java.lang.CharSequence)value$; break; case 2: body = (java.lang.CharSequence)value$; break; default: throw new org.apache.avro.AvroRuntimeException("Bad index"); } }
3
public int GetBus() { return bus; }
0
public Solmu lisaa(Punamustapuu puu, int avain) { Solmu uusi = puu.binaariLisays(puu, avain); uusi.setVari("puna"); Solmu apu; while (uusi.getParent() != null && uusi.getParent().getVari().equals("puna")) { if (uusi.getParent() == uusi.getParent().getParent().getVasen()) { apu = uusi.getParent().getParent().getOikea(); if (apu != null && apu.getVari().equals("puna")) { uusi.getParent().setVari("musta"); apu.setVari("musta"); uusi.getParent().getParent().setVari("puna"); uusi = uusi.getParent().getParent(); } else { if (uusi == uusi.getParent().getOikea()) { uusi = uusi.getParent(); pyoritaVasemmalle(uusi); } uusi.getParent().setVari("musta"); uusi.getParent().getParent().setVari("puna"); pyoritaOikealle(uusi.getParent().getParent()); } } else { apu = uusi.getParent().getParent().getVasen(); if (apu != null && apu.getVari().equals("puna")) { uusi.getParent().setVari("musta"); apu.setVari("musta"); uusi.getParent().getParent().setVari("puna"); uusi = uusi.getParent().getParent(); } else { if (uusi == uusi.getParent().getVasen()) { uusi = uusi.getParent(); pyoritaOikealle(uusi); } uusi.getParent().setVari("musta"); uusi.getParent().getParent().setVari("puna"); pyoritaVasemmalle(uusi.getParent().getParent()); } } } puu.getJuuri().setVari("musta"); return uusi; }
9
public static List nMRSeperate(String arg){ List fileList = new ArrayList(); List fileList1 = new ArrayList(); List pdbList=new ArrayList(); List NMRresult=new ArrayList(); String line= ""; String nextline=""; int modelCount=0, linecount=0; String currDirectory = System.getProperty("user.dir"); fileList1 = FileOperation.getEntriesAsList(arg); // a list of PDBIDs for (int j = 0; j< fileList1.size(); j++){ // iteratively process PDB files String PDBID = ((String)fileList1.get(j)).substring(0,4); String fileName = currDirectory+"/inputdata/"+ PDBID +".pdb"; fileList = FileOperation.getEntriesAsList(fileName); for(int i = 0; i < fileList.size(); i++){ pdbList.clear(); if (i+1<fileList.size()){ linecount=0; line = (String)fileList.get(i); nextline=(String)fileList.get(i+1); if (line.startsWith("MODEL")&& (nextline.startsWith("ATOM")||nextline.startsWith("HETATM"))) { pdbList.add(line); modelCount++; while (nextline.startsWith("ENDMDL")==false){ linecount++; nextline=(String)fileList.get(i+linecount); pdbList.add(nextline); } String modelName=modelCount+""; if (modelName.length()==1){ modelName="MO0"+modelCount; } if (modelName.length()==2){ modelName="MO"+modelCount; } NMRresult.add(modelName); FileOperation.saveResults(pdbList, currDirectory+ "/inputdata/"+ modelName+ ".pdb", "w"); FileOperation.saveResults(modelName, currDirectory+ "/inputdata/"+ PDBID+"list.txt", "a"); i=i+linecount; } } } int bb=1; }// end for return NMRresult; }
9
public void saveStatus(){ myKeeper.saveStatus(); }
0
public static void initCommandLineParameters(String[] args, LinkedList<Option> specified_options, String[] manditory_args) { Options options = new Options(); if (specified_options != null) for (Option option : specified_options) options.addOption(option); Option option = null; OptionBuilder.withArgName("file"); OptionBuilder.hasArg(); OptionBuilder .withDescription("A file containing command line parameters as a Java properties file."); option = OptionBuilder.create("parameter_file"); options.addOption(option); CommandLineParser command_line_parser = new GnuParser(); CommandLineUtilities._properties = new Properties(); try { CommandLineUtilities._command_line = command_line_parser.parse( options, args); } catch (ParseException e) { System.out.println("***ERROR: " + e.getClass() + ": " + e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("parameters:", options); System.exit(0); } if (CommandLineUtilities.hasArg("parameter_file")) { String parameter_file = CommandLineUtilities.getOptionValue("parameter_file"); // Read the property file. try { _properties.load(new FileInputStream(parameter_file)); } catch (IOException e) { System.err.println("Problem reading parameter file: " + parameter_file); } } boolean failed = false; if (manditory_args != null) { for (String arg : manditory_args) { if (!CommandLineUtilities.hasArg(arg)) { failed = true; System.out.println("Missing argument: " + arg); } } if (failed) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("parameters:", options); System.exit(0); } } }
9
public boolean isActive() { if (context == 0) { context = -1; try { if (getAppletContext() != null) { context = 1; } } catch (final Exception localException) { } } if (context == -1) { return active; } return super.isActive(); }
4
@Override public String toString() { return "[com.cube.geojson.LngLatAlt lng: " + longitude + " lat: " + latitude + " alt: " + altitude + "]"; }
0
public String getOtherWolve(int current) { String result = ""; boolean first = true; for (int i = 0; i < wolves.size(); i++) { if (wolves.get(i) == current) { continue; } if (!first) { if (i == wolves.size() - 2) { result += " and "; } else { result += ", "; } } first = false; result += wolves.get(i); } return result; }
4
public void create(ConfigDecripcionLogin configDecripcionLogin) { if (configDecripcionLogin.getCmProfesionalesList() == null) { configDecripcionLogin.setCmProfesionalesList(new ArrayList<CmProfesionales>()); } EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); ConfigLogin idLogin = configDecripcionLogin.getIdLogin(); if (idLogin != null) { idLogin = em.getReference(idLogin.getClass(), idLogin.getId()); configDecripcionLogin.setIdLogin(idLogin); } List<CmProfesionales> attachedCmProfesionalesList = new ArrayList<CmProfesionales>(); for (CmProfesionales cmProfesionalesListCmProfesionalesToAttach : configDecripcionLogin.getCmProfesionalesList()) { cmProfesionalesListCmProfesionalesToAttach = em.getReference(cmProfesionalesListCmProfesionalesToAttach.getClass(), cmProfesionalesListCmProfesionalesToAttach.getId()); attachedCmProfesionalesList.add(cmProfesionalesListCmProfesionalesToAttach); } configDecripcionLogin.setCmProfesionalesList(attachedCmProfesionalesList); em.persist(configDecripcionLogin); if (idLogin != null) { idLogin.getConfigDecripcionLoginList().add(configDecripcionLogin); idLogin = em.merge(idLogin); } for (CmProfesionales cmProfesionalesListCmProfesionales : configDecripcionLogin.getCmProfesionalesList()) { ConfigDecripcionLogin oldIdDescripcionLoginOfCmProfesionalesListCmProfesionales = cmProfesionalesListCmProfesionales.getIdDescripcionLogin(); cmProfesionalesListCmProfesionales.setIdDescripcionLogin(configDecripcionLogin); cmProfesionalesListCmProfesionales = em.merge(cmProfesionalesListCmProfesionales); if (oldIdDescripcionLoginOfCmProfesionalesListCmProfesionales != null) { oldIdDescripcionLoginOfCmProfesionalesListCmProfesionales.getCmProfesionalesList().remove(cmProfesionalesListCmProfesionales); oldIdDescripcionLoginOfCmProfesionalesListCmProfesionales = em.merge(oldIdDescripcionLoginOfCmProfesionalesListCmProfesionales); } } em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } }
7
private JFreeChart getChart(){ /*Create data for building all graphs */ XYSeriesCollection data = new XYSeriesCollection(); /*Mark line*/ int index = 0; for(Coordinates[] kit: listCoordinates ){ /*Add data to kit of one line*/ XYSeries series = new XYSeries("Line #"+ ++index); for(int i = 0; i<kit.length; i++){ series.add(kit[i].x, kit[i].y); } data.addSeries(series); } /* //створюємо 1 ряд даних XYSeries series = new XYSeries("a"); //додаємо точки на графіку series.add(1, 11); series.add(2, 12); series.add(3, 13); series.add(4, 14); series.add(5, 15); series.add(6, 16); series.add(7, 17); series.add(8, 14); series.add(9, 13.5); series.add(10, 11); XYSeries series2 = new XYSeries("b"); //додаємо точки на графіку series2.add(0, 21); series2.add(4, 22); series2.add(5, 23); series2.add(6, 24); series2.add(7, 25); series2.add(8, 26); series2.add(9, 27); series2.add(10, 24); series2.add(11, 23.5); series2.add(12, 21); // зразу ж додаємо ряд в набір даних data.addSeries(series); data.addSeries(series2); */ //створюємо діаграму final JFreeChart chart = ChartFactory.createXYLineChart( titleGraph, //Заголовок діаграми "Number of elements", //назва осі X "Time", //назва осі Y data, //дані PlotOrientation.VERTICAL, //орієнтація true, // включити легенду true, //підказки false // urls ); return chart; }
2
public static List<String> buscaSiglas(String texto) { List<String> siglas = new ArrayList<String>(); List<String> siglasFim = new ArrayList<String>(); int countUppers = 0; String[] palavras = texto.split(" "); for (String palavra : palavras) { if (isAllUpper(palavra) && palavra.length() > 2) { countUppers++; siglas.add(palavra); } } if (countUppers < palavras.length) { for (String sigla : siglas) { if (sigla.matches(".*\\d.*")) { if (!sigla.startsWith("20") && !sigla.startsWith("19") && sigla.length() > 4) { siglasFim.add(sigla); } siglasFim.add(sigla); } } return siglasFim; } else { return new ArrayList<String>(); } }
9
public final void startTile(final Attributes attributes) { tmpTile = new TileType(); if (attributes.getValue("name") != null) { tmpTile.setName(attributes.getValue("name")); } else { tmpTile.setName(""); } tmpTile.setCount(Integer.parseInt(attributes.getValue("count"))); String img = attributes.getValue("img"); // name is img value without '.png' final String tname = img.substring(0, img.lastIndexOf('.')); tmpTile.setFileName(tname); new Thread(new Runnable() { @Override public void run() { TileGraphic.loadImage(tname); } }).start(); if (attributes.getValue("zombies") != null) { tmpTile.setZombieCount(Integer.parseInt(attributes .getValue("zombies"))); } if (attributes.getValue("life") != null) { tmpTile.setLifeCount(Integer.parseInt(attributes.getValue("life"))); } if (attributes.getValue("ammo") != null) { tmpTile.setAmmoCount(Integer.parseInt(attributes.getValue("ammo"))); } }
4
public void buildClassifier(Instances data) throws Exception { super.buildClassifier(data); // can classifier handle the data? getCapabilities().testWithFail(data); // remove instances with missing class Instances newData = new Instances(data); newData.deleteWithMissingClass(); double sum = 0; double temp_sum = 0; // Add the model for the mean first m_zeroR = new ZeroR(); m_zeroR.buildClassifier(newData); // only class? -> use only ZeroR model if (newData.numAttributes() == 1) { System.err.println( "Cannot build model (only class attribute present in data!), " + "using ZeroR model instead!"); m_SuitableData = false; return; } else { m_SuitableData = true; } newData = residualReplace(newData, m_zeroR, false); for (int i = 0; i < newData.numInstances(); i++) { sum += newData.instance(i).weight() * newData.instance(i).classValue() * newData.instance(i).classValue(); } if (m_Debug) { System.err.println("Sum of squared residuals " +"(predicting the mean) : " + sum); } m_NumIterationsPerformed = 0; do { temp_sum = sum; // Build the classifier m_Classifiers[m_NumIterationsPerformed].buildClassifier(newData); newData = residualReplace(newData, m_Classifiers[m_NumIterationsPerformed], true); sum = 0; for (int i = 0; i < newData.numInstances(); i++) { sum += newData.instance(i).weight() * newData.instance(i).classValue() * newData.instance(i).classValue(); } if (m_Debug) { System.err.println("Sum of squared residuals : "+sum); } m_NumIterationsPerformed++; } while (((temp_sum - sum) > Utils.SMALL) && (m_NumIterationsPerformed < m_Classifiers.length)); }
7
public void service( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { PrintWriter out = response.getWriter(); moduli.setRequestResponse(request, response); //passaggio di request e response a moduli per il corretto funzionamento moduli.stampaIntestazione(); moduli.stampaMenu(); boolean errore = false; String nomeArticolo = request.getParameter("nomeArticolo"); //recupero articolo dal post if (nomeArticolo != null) { out.print("<h1 align=center>" + nomeArticolo + "</h1>"); } else { out.print("<h1>Articolo non trovato</h1><p>Possibile errore di rete</p>"); errore = true; } if (!errore) { Statement s; try { s = c.createStatement(); //recupero info del prodotto dal db ResultSet r = s.executeQuery("SELECT * FROM articolo WHERE nome=\"" + nomeArticolo + "\";"); //output info profotto if (r.next()) { out.print("" + "<p align=center><img src=\"prodotti/" + moduli.getNomeImage((r.getString("nome"))) + ".jpg\"></p>" + "<p align=center><br><br><br>" + "Nome: <strong>" + r.getString("nome") + "</strong><br><br><br>" + "Ambiente: <strong>" + r.getString("ambiente") + "</strong><br><br><br>" + "Ombra: <strong>" + r.getString("ombra") + "</strong><br><br><br>" + "Umidita: <strong>" + r.getString("umidita") + "</strong><br><br><br>" + "Cura: <strong>" + r.getString("cura") + "</strong><br><br><br>" + "Prezzo: <strong>" + r.getString("prezzo") + " euro</strong><br><br>" + "</p>" + ""); } else { out.print("" + "<p align=center>Prodotto non nel database</p>" + ""); } s.close(); // Controllo quanti prodotti sono disponibili nel database s = c.createStatement(); r = s.executeQuery("SELECT sum(quantita) AS somma FROM disponibilita WHERE nome_articolo=\"" + nomeArticolo + "\";"); if (r.next()) { if ((r.getString("somma") != null) && (Integer.parseInt(r.getString("somma")) != 0) ) { out.print("" + "<p align=center>Sono disponibili " + r.getString("somma") + " prodotti</p>" + "<table width=\"100%\"><tr><td align=center><form name=\"vendita\" action=\"MioCarrello\" method=\"post\">" + "<input type=\"hidden\" name=\"nome_articolo\" value=\"" + nomeArticolo + "\">" + "Quantita' di articoli desiderata:&nbsp;<select name=\"quantita\">" + ""); //mette nel select la disponibilita' del prodotto for (int k=1 ; k <= r.getInt("somma") ; k++) { out.print("<option value=\"" + k + "\">" + k + "</option>"); } out.print("" + "</select>" + "&nbsp;<input type=\"submit\" name=\"aggiungi\" value=\"Aggiungi al carrello\">" + "</form></td></tr></table>" + ""); } else { out.print("" + "<p align=center>Prodotto non disponibile al momento</p>" + ""); } } else { out.print("" + "<p align=center>Prodotto non disponibile al momento</p>" + ""); } s.close(); } catch (SQLException ex) { out.println("Errore nella comunicazione con il database"); ex.printStackTrace(); } moduli.stampaFooter(); out.close(); } }
8
public void subgridPressed(final String face) { int[] nulled = {-1, -1}; boolean correct = false; if(face.equals("L") || face.equals("R")) { dir = "Hor"; sub_grids.setColor(face, color_correct); repaint(); } else if(face.equals("U") || face.equals("D")) { dir = "Ver"; sub_grids.setColor(face, color_correct); repaint(); } else { correct = true; sub_grids.setColor(face, color_incorrect); repaint(); } grid[0] = nulled; grid[1] = nulled; grid[2] = nulled; user_move = true; final Cluster Correct = new Cluster(correct); CTimer timer = new CTimer(200, Correct, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(!Correct.getBoolean()) {shiftRubiks(face);} sub_grids.setColor(color_bg); repaint(); } }); timer.setRepeats(false); timer.start(); }
5
public void run(){ if (time!=0){time=time-1;} GosLink2.dw.append("HeartBeat Started."); while (true){ try { OLH.put(1,0); OLH.put(2,0); OLH.put(3,0); CTH.put(1,0); CTH.put(2,0); CTH.put(3,0); Thread.sleep(60000); for (int v:GosLink2.TNH.keySet()){ checkserver(v); } gosbot.enterchk(); } catch (Exception e) {e.printStackTrace();} } }
4
public static String getProperty(String key) { //return rb.getString(key); //TODO make a normal config file! switch(key) { case "path.page.index": return "/index.jsp"; case "path.page.login": return "/jsp/login.jsp"; case "path.page.admin": return "/jsp/admin.jsp"; case "path.page.main": return "/jsp/main.jsp"; case "path.page.rent": return "/jsp/rent.jsp"; case "path.page.pay": return "/jsp/pay.jsp"; case "path.page.error": return "/jsp/error/error.jsp"; default : return null; } }
7
public static float taxesDue(Actor actor) { final int bracket = actor.vocation().standing ; if (bracket == Background.SLAVE_CLASS) return 0 ; if (bracket == Background.RULER_CLASS) return 0 ; final BaseProfiles BP = actor.base().profiles ; int taxLevel = 0 ; if (bracket == Background.LOWER_CLASS) { taxLevel = BP.querySetting(AuditOffice.KEY_LOWER_TAX) ; } if (bracket == Background.MIDDLE_CLASS) { taxLevel = BP.querySetting(AuditOffice.KEY_MIDDLE_TAX) ; } if (bracket == Background.LOWER_CLASS) { taxLevel = BP.querySetting(AuditOffice.KEY_UPPER_TAX) ; } final int percent = AuditOffice.TAX_PERCENTS[taxLevel], savings = AuditOffice.TAX_EXEMPTED[taxLevel] ; float afterSaving = actor.gear.credits() - savings ; if (afterSaving < 0) return 0 ; afterSaving = Math.min(afterSaving, actor.gear.unTaxed()) ; return afterSaving * percent / 100f ; }
6
public boolean equals( Object other ) { if ( _set.equals( other ) ) { return true; // comparing two trove sets } else if ( other instanceof Set ) { Set that = ( Set ) other; if ( that.size() != _set.size() ) { return false; // different sizes, no need to compare } else { // now we have to do it the hard way Iterator it = that.iterator(); for ( int i = that.size(); i-- > 0; ) { Object val = it.next(); if ( val instanceof Integer ) { int v = ( ( Integer ) val ).intValue(); if ( _set.contains( v ) ) { // match, ok to continue } else { return false; // no match: we're done } } else { return false; // different type in other set } } return true; // all entries match } } else { return false; } }
6
public static String readData(String filename){ File file = new File(filename); FileReader fr; BufferedReader br; String line; int index = -1; int indexstart = 38; String lineresult; StringBuffer sb = new StringBuffer(); try { fr = new FileReader(file); br = new BufferedReader(fr); while(br.ready()) { line = br.readLine(); index = line.indexOf("|"); lineresult = line.substring(0, index); lineresult += line.substring(line.length()-indexstart, line.length()); lineresult = lineresult.replaceAll("\\|", " "); sb.append(lineresult+"\n"); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sb.toString(); }
3
public void itemSent(Auction auction, String time, String trackingId){ auction.itemSent(time, trackingId); }
0
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { }
0
public void recursivePrint(LeftistTreeNode root, int parentPosition, Node innerNode, Node p) { Node innerParent; int position; if (root != null) { int height = tree.heightRootToNode(root); int nextTop = getRectNextTop(height); if (innerNode != null) innerParent = innerNode; else innerParent = p; if (root.parent.left != null && root.parent.left.equals(root)) { position = getRectNextLeft(parentPosition, height); innerNode = makeNode(root.value + "<br/>npl: " + tree.npl(root, -1), new Point(position, nextTop), Node.COLOR_LEFT); } else { position = getRectNextRight(parentPosition, height); innerNode = makeNode(root.value + "<br/>npl: " + tree.npl(root, -1), new Point(position, nextTop), Node.COLOR_RIGHT); } innerNode.setParent(innerParent); parentPosition = position; // -- recursivePrint(root.left, parentPosition, innerNode, p); recursivePrint(root.right, parentPosition, innerNode, p); } }
4
public void setBombs(){ boolean duplicateBomb=true; // checks for bombs with the same x,y coordinates Random numGenerator = new Random(); int xcoord,ycoord; for(int numBombs=0;numBombs<10;numBombs++){ xcoord = numGenerator.nextInt(10); ycoord = numGenerator.nextInt(10); duplicateBomb=true; while(duplicateBomb){//keep generating random numbers until a unique coordinate is found for(int j=0;j<numBombs;j++){ if(xcoord==bombs[j][0] && ycoord==bombs[j][1]){//if a bomb exists at this set of coords, generate new coords and break out duplicateBomb=true; xcoord = numGenerator.nextInt(10); ycoord = numGenerator.nextInt(10); break; } duplicateBomb=false;//no bomb? fahgettabotit - http://www.youtube.com/watch?v=z-CL9qVG9iI } if(!duplicateBomb || numBombs==0){//unique coordinates are stored in bombs[][]; loop is ended bombs[numBombs][0]=xcoord; bombs[numBombs][1]=ycoord; break; } } grid[xcoord][ycoord].isBomb=true;// set boolean to show this tile is a bomb } }
7
public GenericObject load(final String filename) { final long startTime = System.nanoTime(); if (!openInStream(filename)) return null; //notify about loading if (settings.isPrintTimingInfo()) System.out.println("Loading " + filename + "."); GenericObject root = null; try { root = new GenericObject(); GenericObject curr = readObject(root); //reading loop (per line mainly) while (tokenType != TokenType.EOF) { curr = readObject(curr); } } catch (ParserException ex) { System.err.println(ex.getMessage()); if (!settings.isTryToRecover()) root = null; } finally { closeInStream(); } //Tell some things about the current state: if (m_errors > 0) System.out.println("There were " + m_errors + " errors during loading."); // System.out.println("Read " + tokenizer.getCharsRead() + " bytes."); if (settings.isPrintTimingInfo()) System.out.println("Loading took " + (System.nanoTime()-startTime) + " ns.\n"); return root; }
7
private double pareseMulOrDiv() throws Exception { char op; //运算符 double result; //结果 double partialResult; //子表达式结果 //用指数运算计算当前子表达式的值 result = this.parseExponent(); //如果当前标记的第一个字母是乘、除或者取模运算,则继续进行乘除法运算 while ((op = this.token.charAt(0)) == '*' || op == '/' || op == '%') { this.getToken(); //取下一标记 //用指数运算计算当前子表达式的值 partialResult = this.parseExponent(); switch (op) { case '*': //如果是乘法,则用已处理子表达式的值乘以当前子表达式的值 result = result * partialResult; break; case '/': //如果是除法,判断当前字表达式的值是否为0,如果为0,则抛出被0除异常 if (partialResult == 0.0) { this.handleError(DIVBYZERO_ERROR); } //除数不为0,则进行除法运算 result = result / partialResult; break; case '%': //如果是取模运算,也要判断当前子表达式的值是否为0 if (partialResult == 0.0) { this.handleError(DIVBYZERO_ERROR); } result = result % partialResult; break; } } return result; }
8
public static final Define makeMethod(String proxyPackage, final Class clazz, final String methodName, Class... parameters) { parameters = parameters == null ? new Class[0] : parameters; final Method method = Utilities.getMethod(clazz, methodName, parameters); if (method == null) { throw new RuntimeException("Method[" + methodName + "] was not exist!"); } if (proxyPackage == null || proxyPackage.trim().length() == 0) { proxyPackage = Utilities.getProxyPackage(); } final int modifier = method.getModifiers(); // 拒绝非public方法 if (!Modifier.isPublic(modifier)) { throw new RuntimeException("Method[" + methodName + "] was not a public method!"); } // 被代理类名 final String className = clazz.getName().replace('.', '/'); // 代理类名 final String proxyClassName = Utilities.toProxyClassName(proxyPackage, className); // 创建ClassWriter final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); // 创建类 cw.visit(Utilities.VERSION, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER, proxyClassName, null, Utilities.SUPER, null); // 创建默认构造方法 Utilities.doDefaultConstructor(cw); // 创建方法 final MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_VARARGS, "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;", null, new String[]{"java/lang/Exception"} ); // 非静态方法使用1号位参数作为实例;静态方法使用类名,不占用参数位 if (!Modifier.isStatic(modifier)) { // 调出第一个参数(第一个临时变量),实例 mv.visitVarInsn(Opcodes.ALOAD, 1); Utilities.doClassCast(mv, Type.getType(clazz)); } // 生成参数列表, 实例方法参数列表因1号位被实例占用需增加偏移量1 final Class[] parameterTypes = method.getParameterTypes(); final StringBuffer buffer = new StringBuffer(128); // 循环构建参数列表,调出第一个临时变量遍历并强制转换 buffer.append('('); for (int i = 0, n = parameterTypes.length; i < n; i++) { // 调出第二个参数(第二个临时变量) mv.visitVarInsn(Opcodes.ALOAD, 2); // 序号压栈 mv.visitIntInsn(Opcodes.BIPUSH, i); // 组合取值 mv.visitInsn(Opcodes.AALOAD); Type paramType = Type.getType(parameterTypes[i]); Utilities.doClassCast(mv, paramType); // 加入参数描述 buffer.append(paramType.getDescriptor()); } buffer.append(')'); // 加入返回值描述 buffer.append(Type.getDescriptor(method.getReturnType())); if (Modifier.isStatic(modifier)) { // 调用类方法,使用类调用 mv.visitMethodInsn(Opcodes.INVOKESTATIC, className, methodName, buffer.toString()); Utilities.doPackPrimitive(method.getReturnType(), mv); } else { // 调用实例方法 mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, className, methodName, buffer.toString()); Utilities.doPackPrimitive(method.getReturnType(), mv); } // 返回结果 mv.visitInsn(Opcodes.ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); cw.visitEnd(); final Define define = new Define(); define.setClassName(className); define.setProxyClassName(proxyClassName); define.setTargetName(methodName); define.setMethod(true); define.setRedirect(null); define.setReturnType(method.getReturnType()); define.setBytes(cw.toByteArray()); return define; }
8
public final void visitEnd() { addEnd("class"); if (!singleDocument) { addDocumentEnd(); } }
1
public void setLineEnding(String lineEnding) { this.lineEnding = lineEnding; }
0
public void run() { Message message; MessageObject messageObject; Socket socket; try { while (true) { socket = socketServeur.accept(); System.out.println("Connection de " + socket); synchronized (outputStreams) { outputStreams.put(socket, new DataOutputStream(socket.getOutputStream())); BufferedReader inStream = new BufferedReader(new InputStreamReader(socket.getInputStream())); String messageData = inStream.readLine(); if(messageData.contains("SetBet")){ messageObject = new MessageObject(this, socket, messageData); pool.addTask(messageObject); } else{ message = new Message(this, socket, messageData); pool.addTask(message); } } } } catch (SocketTimeoutException s) { System.out.println("Timeout waiting for client..."); } catch (IOException e) { e.printStackTrace(); // break; } }
4
public static IMod loadMod(File jar) { try { URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] {jar.toURI().toURL()}); @SuppressWarnings("resource") JarFile jarFile = new JarFile(jar); Enumeration<JarEntry> entries = jarFile.entries(); IMod mainClass = null; while (entries.hasMoreElements()) { JarEntry element = entries.nextElement(); if (element.getName().endsWith(".class")) { @SuppressWarnings("rawtypes") Class clazz = classLoader.loadClass(element.getName().replaceAll(".class", "").replaceAll("/", ".")); try { Object obj = clazz.newInstance(); if (obj instanceof IMod) { mainClass = (IMod) obj; } } catch (InstantiationException e) { } } } return mainClass; } catch(MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; }
8
public boolean _setLevel(int level) { if(level > 0) { this.level = level; return true; } else { return false; // Invalid level given. } }
1
static void test(Runnable r) throws InterruptedException { Future<?> f = exec.submit(r); TimeUnit.MILLISECONDS.sleep(100); System.out.println("Interrupting " + r.getClass().getName()); f.cancel(true); // Interrupts if running System.out.println("Interrupt sent to " + r.getClass().getName()); }
1
@EventHandler(priority=EventPriority.HIGH ) public void onBlockRedstone(BlockRedstoneEvent event) { Block block = event.getBlock(); int iBlockID = block.getTypeId(); if (iBlockID==69 || iBlockID==77 || iBlockID==143) { return; } if(event.getOldCurrent() >=1 && event.getNewCurrent() == 0 ) { return; } if(event.getNewCurrent()>=1) { router.umschauenNachSchild(block, event); } return; }
6
final public void Integral_type() throws ParseException { /*@bgen(jjtree) Integral_type */ SimpleNode jjtn000 = new SimpleNode(JJTINTEGRAL_TYPE); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); jjtn000.jjtSetFirstToken(getToken(1)); try { jj_consume_token(INTEGER); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); jjtn000.jjtSetLastToken(getToken(0)); } } }
1
public WebServices() { // TODO Auto-generated constructor stub }
0
public static boolean writeEdges(int numNodes, int idTopology) { try { PrintStream ps = new PrintStream("./Topology/Edges/"+idTopology+"_edge_"+numNodes+".txt"); ps.println("Number of nodes: " + numNodes); Configuration.printConfiguration(ps); ps.println(separator); Iterator<Node> it = Tools.getNodeList().iterator(); Iterator<Edge> eIt; Edge e; Node n; while(it.hasNext()){ n = it.next(); eIt = n.outgoingConnections.iterator(); while(eIt.hasNext()){ e = eIt.next(); ps.println(((GenericWeightedEdge) e).printEdgeInformation()); } } /*for(Node n : Tools.getNodeList()) { Position p = n.getPosition(); ps.println(p.xCoord + ", " + p.yCoord + ", " + p.zCoord); }*/ ps.close(); return true; } catch (FileNotFoundException e) { // TODO Auto-generated catch block Tools.minorError(e.getMessage()); } System.out.println("------------------------------------------------------"); System.out.println("End ConfigTest"); System.out.println("------------------------------------------------------"); return false; }
3
@Override public IautosSellerInfo getIncompletedSeller(String seqID) { EntityManager em = this.getEntityManager(); return em.find(IautosSellerInfo.class, seqID); }
0
public void map(LongWritable key, Text inputValue, Context context) throws IOException, InterruptedException { String htmlLine = inputValue.toString(); String toLowerCaseHtml = htmlLine.toLowerCase(Locale.US); // Get the source URL for this page if (null == _contributingPageUrl && true == toLowerCaseHtml.contains("source page url")) { int urlStartIndex = toLowerCaseHtml.indexOf(':') + 1; _contributingPageUrl = toLowerCaseHtml.substring(urlStartIndex); } // End of a page else if (true == toLowerCaseHtml.contains("</table>")) { _contributingPageUrl = null; } // Get contributors' name and write to map output else if ((null != _contributingPageUrl) && (true == toLowerCaseHtml.contains("td")) && (true == toLowerCaseHtml.contains("user"))) { Document htmlFormattedLine = Jsoup.parse(htmlLine); org.jsoup.select.Elements contributorInfoLine = htmlFormattedLine .select("a[href]"); String contributor = null; if (contributorInfoLine.size() == 1) { contributor = contributorInfoLine.get(0).text(); } else { System.err.println("Failed to extract contributor name"); } context.write(new Text(contributor), new Text(_contributingPageUrl)); } }
7
private int executeViewer(int posX, int posY, boolean stop) { if (stop) return 1; if (posY < 0 || posY == matrix[0].length) return 1; if (posX < 0 || posX == matrix.length) return 1; stop = matrix[posX][posY].showValue(); executeViewer(posX, (posY + 1), stop); executeViewer(posX, (posY - 1), stop); executeViewer((posX + 1), posY, stop); executeViewer((posX - 1), posY, stop); return 0; }
5
private boolean validarDatos(){ boolean error= false; if(txtNombre.getText().isEmpty()){ txtNombre.setBorder(javax.swing.BorderFactory.createEtchedBorder(Color.lightGray, Color.red)); txtNombre.setToolTipText("Por favor digite el nombre del producto."); error= true; } if(txtDescripcion.getText().isEmpty()){ txtDescripcion.setBorder(javax.swing.BorderFactory.createEtchedBorder(Color.lightGray, Color.red)); txtDescripcion.setToolTipText("Por favor digite el nombre del producto."); error= true; } if(txtGrado.getText().isEmpty()){ txtGrado.setBorder(javax.swing.BorderFactory.createEtchedBorder(Color.lightGray, Color.red)); txtGrado.setToolTipText("Por favor digite los grados de alcohol del producto"); error= true; } else{ try{ float gradoAlcohol = Float.parseFloat(this.txtGrado.getText().trim()); }catch(NumberFormatException ex){ txtGrado.setText(""); txtGrado.setBorder(javax.swing.BorderFactory.createEtchedBorder(Color.lightGray, Color.red)); txtGrado.setToolTipText("Por favor digite cantidades numericas unicamente."); error= true; } } if(txtContenido.getText().isEmpty()){ txtContenido.setBorder(javax.swing.BorderFactory.createEtchedBorder(Color.lightGray, Color.red)); txtContenido.setToolTipText("Por favor digite el contenido o capacidad del producto"); error= true; } else{ try{ float contenido = Float.parseFloat(this.txtGrado.getText().trim()); }catch(NumberFormatException ex){ txtGrado.setText(""); txtGrado.setBorder(javax.swing.BorderFactory.createEtchedBorder(Color.lightGray, Color.red)); txtGrado.setToolTipText("Por favor digite cantidades numericas unicamente."); error= true; } } if(cmbFabricacion.getSelectedItem().toString().isEmpty()){ cmbFabricacion.setBackground(Color.red); cmbFabricacion.setToolTipText("Por favor seleccione el tipo de fabricación"); error=true; } return error; }
7
public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int count=0; for(int i=0;i<n;i++){ int temp = in.nextInt(); if(5-temp >= k) count++; } System.out.println(count/3); }
2
public void write(int address, int data) { int sets = Cache.MAX_SIZE / this.assoc / this.blockSize; int blockNo = address / this.blockSize; int pos = blockNo % sets; byte tag = (byte) (address / sets); //MRU Way Prediction if (this.mru[pos] >= 0 && tag == this.tags[pos+this.mru[pos]]) { this.hit++; this.lruBits[pos+this.mru[pos]] = clock++; this.data[this.blockSize * (pos + this.mru[pos]) + (address % this.blockSize)] = data; if ((this.hit + this.miss) % 500 == 0) { this.missRates.put(this.hit + this.miss, (double) this.miss / (this.hit + this.miss)); } return; } // for (int i = 0; i < this.assoc; i++) { if (tag == this.tags[pos+i]) { this.hit++; this.lruBits[pos+i] = clock++; this.data[this.blockSize * (pos + i) + (address % this.blockSize)] = data; this.validBits[pos+i] = false; if ((this.hit + this.miss) % 500 == 0) { this.missRates.put(this.hit + this.miss, (double) this.miss / (this.hit + this.miss)); } return; } } this.miss++; getFromMemory(address); for (int i = 0; i < this.assoc; i++) { if (tag == this.tags[pos+i]) { this.lruBits[pos+i] = clock++; this.data[this.blockSize * (pos + i) + (address % this.blockSize)] = data; this.validBits[pos+i] = false; } } if ((this.hit + this.miss) % 500 == 0) { this.missRates.put(this.hit + this.miss, (double) this.miss / (this.hit + this.miss)); } return; }
9
public User findByID(String userID) { User foundUser = null; try { // Erforderlicher SQL-Befehl String sqlStatement = "SELECT * FROM bookworm_database.users WHERE id LIKE " + userID + ";"; // SQL-Befehl wird ausgeführt myResultSet = mySQLDatabase.executeSQLQuery(sqlStatement); // da das Select-Statement immer nur genau einen oder keinen // Datensatz liefern kann, genügt hier diese Abfrage if (myResultSet.next()) { foundUser = new User(myResultSet.getString(1), myResultSet.getString(2), myResultSet.getString(3), myResultSet.getString(4)); } } catch (Exception e) { System.out.println(e.toString()); // Ein Dialogfenster mit entsprechender Meldung soll erzeugt werden String errorText = "Datenbankabfrage konnte nicht durchgeführt werden."; errorMessage.showMessage(errorText); } finally { // offene Verbindungen werden geschlossen mySQLDatabase.closeConnections(); } return foundUser; }
2
public static Command parseCommand(Game game, String desc) throws NoFactoryFoundException{ ArrayList<String> commandDesc = new ArrayList<String>(); String allDescArray[] = desc.split(" "); for (int i = 0; i < allDescArray.length; i++) { commandDesc.add(allDescArray[i]); } String commandName = commandDesc.remove(0).toUpperCase().trim(); T2<? extends Class<? extends Game>, String> key = Tuple.makeTuple(game.getClass(), commandName); if(commandFactories.containsKey(key)) { return commandFactories.get(key).buildCommand(game, commandDesc); } throw new NoFactoryFoundException("Command Factory for '" + commandName + "' not found!"); }
4
private void addVM() { final SlaveVM slave = new SlaveVM(openNebula); slave.createVM(); slave.setState(VMState.INIT); allVms.put(slave.getId(), slave); Thread creator = new Thread() { public void run() { while (!slave.getVm().lcmStateStr().equals("RUNNING")) { slave.getVm().info(); } System.out.println("VM " + slave.getId() + " " + slave.getVm().stateStr()); while (!slave.testConnection()) { try { Thread.sleep(1000); } catch (InterruptedException e) { } } System.out.println("VM " + slave.getId() + " SSH connection established"); if (slave.initialize()) { synchronized (vmsAvailable) { vmsAvailable.add(slave); slave.setState(VMState.WAITING); slave.setBootEndtime(System.currentTimeMillis()); } System.out.println("VM " + slave.getId() + " now available. " + vmsAvailable.size() + " VMs in total"); } } }; creator.start(); }
4
public double getDiag(){ return lengh_diag = this.getHig()*Math.sqrt(3); }
0
public void worldInput(int mouseX, int mouseY){ int button = -1; if (Mouse.isButtonDown(0)){ button = 0; } if (mouseX < 800){ int newX = -1; int newY = -1; int cx = Boot.getPlayer().getX(); int cy = Boot.getPlayer().getY(); newX = cx + (mouseX / Standards.TILE_SIZE) - 12; newY = cy + ((Standards.W_HEIGHT - mouseY) / Standards.TILE_SIZE) - 12; AbstractMob mob = Boot.getNPCList().NPCAtLocation(newX, newY); if (mob != null){ Boot.getPlayer().mobInteract(mob); } else { Tile active = Boot.getWorldObj().getTileAtCoords(newX, newY); if (active != null){ active.getMouseEvent(button); } } } }
4
public void insert(T newVal) { if (newVal == null) { throw new IllegalArgumentException(); } if (root == null) { root = new Node<>(newVal); return; } Node<T> tmp = root; int compRes = -1; while (tmp != null) { compRes = comparator.compare(newVal, tmp.value); if (compRes > 0) { if (tmp.right == null) { tmp.right = new Node<>(newVal); break; } tmp = tmp.right; } else if (compRes < 0) { if (tmp.left == null) { tmp.left = new Node<>(newVal); break; } tmp = tmp.left; } else { tmp.count++; break; } } }
7
private ArrayList<String> parseRow(String row) { ArrayList<String> data = new ArrayList<>(); String s = ""; char expect = STRING_CONTAINER; for (int i = 0; i < row.length(); i++) { char c = row.charAt(i); switch (expect) { case STRING_CONTAINER: if (c != STRING_CONTAINER) { System.out.println(data); throw new RuntimeException("Illegal character (" + c + ")"); } s = ""; expect = (char) -1; break; case COLUMN_SEPERATOR: data.add(s); expect = STRING_CONTAINER; break; default: if (c != STRING_CONTAINER) { if (c == ESCAPE_CARACTER) s += row.charAt(++i); else s += c; } else expect = COLUMN_SEPERATOR; break; } } data.add(s); return data; }
6
public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) { AnnotationVisitor av = super.visitAnnotation(desc, visible); if (fv != null) { ((TraceAnnotationVisitor) av).av = fv .visitAnnotation(desc, visible); } return av; }
1
public int[] getBoundaryPositions(ByteBuffer b, byte[] boundary) { int matchcount = 0; int matchbyte = -1; List<Integer> matchbytes = new ArrayList<Integer>(); for (int i=0; i<b.limit(); i++) { if (b.get(i) == boundary[matchcount]) { if (matchcount == 0) matchbyte = i; matchcount++; if (matchcount == boundary.length) { matchbytes.add(matchbyte); matchcount = 0; matchbyte = -1; } } else { i -= matchcount; matchcount = 0; matchbyte = -1; } } int[] ret = new int[matchbytes.size()]; for (int i = 0; i < ret.length; i++) { ret[i] = matchbytes.get(i); } return ret; }
5
static boolean isOnBoard(int x, int y){ return(x >= 0 && x <= 7 && y >= 0 && y <= 7); }
3
protected boolean decodeFrame() throws JavaLayerException { try { AudioDevice out = audio; if (out == null) return false; Header h = bitstream.readFrame(); if (h == null) return false; // sample buffer set when decoder constructed SampleBuffer output = (SampleBuffer) decoder.decodeFrame(h, bitstream); synchronized (this) { out = audio; if(out != null) { out.write(output.getBuffer(), 0, output.getBufferLength()); } } bitstream.closeFrame(); } catch (RuntimeException ex) { throw new JavaLayerException("Exception decoding audio frame", ex); } return true; }
4
public boolean stateRight() throws Exception { int[] temp = new int[numbers.length + 1]; int spaces=0; for (int i = 0; i < temp.length; ++i) temp[i] = 0; for (int i = 0; i < numbers.length; ++i) { int x = 0; if (!numbers[i].toString().equals(" ")) { x = new Integer(numbers[i].toString()); if (x >= numbers.length || x < 1) return false; temp[x]++; if (temp[x] > 1) return false; } else { ++spaces; temp[0]++; if (temp[0] > 1) return false; } } if(spaces>1) return false; return true; }
8
public AStarGraphics(List<CellDescription> cd, List<Cell> ol, List<Cell> cl, List<CellDescription> rp ) { returnPath = rp; knownCells = cd; openList = ol; closedList = cl; int floorXdimension = 1; floorYdimension = 1; for ( int i = 0; i < cd.size(); i ++ ) { if ( cd.get(i).locX > floorXdimension ){ floorXdimension = cd.get(i).locX; } if ( cd.get(i).locY > floorYdimension ){ floorYdimension = cd.get(i).locY; } } cSJP = new FloorJPanel(); floorBI = new BufferedImage(floorXdimension * 50, floorYdimension * 50, BufferedImage.TYPE_BYTE_BINARY); cSJP.paintComponent(floorBI.createGraphics()); floorFrame = new JFrame("A* tracking"); floorFrame.isAlwaysOnTop(); floorFrame.setMinimumSize(new Dimension(floorXdimension * 62 + 100, floorYdimension * 62 + 100)); floorFrame.add(cSJP); floorFrame.pack(); floorFrame.setVisible(true); try { Thread.sleep(1000); } catch (Exception e) { LOGGER.log(Level.WARNING, "Just to shutup Sonar", e); } }
4