text
stringlengths
14
410k
label
int32
0
9
private SimpleJsonState readJsonObject(SimpleJsonTokenizer x) { Map<String, SimpleJsonState> elements = new LinkedHashMap<String, SimpleJsonState>(); SimpleJsonState res = new SimpleJsonState(elements); char c; String key; if ( x.nextClean() != '{' ) { throw x.syntaxError("A JSONObject text must begin with '{'"); } L: for (;;) { c = x.nextClean(); switch (c) { case 0: throw x.syntaxError("A JSONObject text must end with '}'"); case '}': break L; default: x.back(); key = x.nextValue(); } c = x.nextClean(); if ( c != ':' ) { throw x.syntaxError("Expected a ':' after a key"); } elements.put(key, read(x)); switch (x.nextClean()) { case ';': case ',': if ( x.nextClean() == '}' ) { break L; } x.back(); break; case '}': break L; default: throw x.syntaxError("Expected a ',' or '}'"); } } return res; }
9
public void saveScoreStats() { File file = new File("Scores.txt"); boolean flag = false; FileWriter writer; ArrayList<String> scoreData = new ArrayList<String>(); ListIterator<String> iterator; try { Scanner s = new Scanner(file); while(s.hasNextLine()) { scoreData.add(s.nextLine()); } s.close(); iterator = scoreData.listIterator(); while(iterator.hasNext()) { if(iterator.next().equals(user.getUsername())) { iterator.next(); iterator.set(String.valueOf(user.getScore().getHighScore())+ " " + String.valueOf(user.getScore().getBestTime()) + " " + user.getScore().getBestDifficulty() + " " + user.getScore().getBestSize()+ " " + user.getScore().getCurrentScore() + " " + String.valueOf(user.getScore().getCurrentTime()) + " " + user.getScore().getLastDifficulty() + " " + user.getScore().getLastSize()); flag = true; break; } } if(flag == false) { scoreData.add(user.getUsername()); scoreData.add(String.valueOf(user.getScore().getHighScore())+ " " + String.valueOf(user.getScore().getBestTime()) + " " + user.getScore().getBestDifficulty() + " " + user.getScore().getBestSize()); } writer = new FileWriter("Scores.txt"); iterator = scoreData.listIterator(); while(iterator.hasNext()) { writer.write(iterator.next()); writer.write("\n"); } writer.close(); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null, "Could not find Scores. Contact system administrator.", "Error", JOptionPane.ERROR_MESSAGE); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Could not update Scores. Contact system administrator.", "Error", JOptionPane.ERROR_MESSAGE); } }
7
public void visitPhiStmt(final PhiStmt stmt) { if (stmt instanceof PhiCatchStmt) { visitPhiCatchStmt((PhiCatchStmt) stmt); } else if (stmt instanceof PhiJoinStmt) { visitPhiJoinStmt((PhiJoinStmt) stmt); /* * else if (stmt instanceof PhiReturnStmt) * visitPhiReturnStmt((PhiReturnStmt) stmt); */ } }
2
public boolean exactlySameAs(PhoneNumber other) { if (other == null) { return false; } if (this == other) { return true; } return (countryCode_ == other.countryCode_ && nationalNumber_ == other.nationalNumber_ && extension_.equals(other.extension_) && italianLeadingZero_ == other.italianLeadingZero_ && rawInput_.equals(other.rawInput_) && countryCodeSource_ == other.countryCodeSource_ && preferredDomesticCarrierCode_.equals(other.preferredDomesticCarrierCode_) && hasPreferredDomesticCarrierCode() == other.hasPreferredDomesticCarrierCode()); }
9
public static void main(String[] args) throws Exception { if(args.length < 2) { System.out.print("Usage : bdecoder -f <file> \n" + " : bdecoder -s <string1> [string2] ...\n"); return; } String argument; if(args[0].equals("-f")) { argument = args[1]; File file = new File(argument); if(!file.exists()) { System.out.println("File \""+ file +"\" does not exsits !"); } else { List<String> brands = FileUtils.readLines(file); int i=1; for(String brand : brands) { brand = brand.toLowerCase(); try { System.out.println(""+decode(brand.trim())); } catch (Exception e) { System.out.println(""+(brand.trim())); } i++; } } } else if(args[0].equals("-s")){ for(int i=1; i<args.length; i++) { argument = args[i].toLowerCase(); try { System.out.println(""+decode(argument.trim())); } catch (Exception e) { System.out.println(""+(argument.trim())); } } } }
8
@Override protected void paintContentBorder(Graphics g, int tabPlacement, int selectedIndex ) { int width = tabPane.getWidth(); int height = tabPane.getHeight(); Insets insets = tabPane.getInsets(); int x = insets.left; int y = insets.top; int w = width - insets.right - insets.left; int h = height - insets.top - insets.bottom; switch(tabPlacement) { case LEFT: x += calculateTabAreaWidth(tabPlacement, runCount, maxTabWidth); x -= tabAreaInsets.right; w -= (x - insets.left); break; case RIGHT: w -= calculateTabAreaWidth(tabPlacement, runCount, maxTabWidth); w += tabAreaInsets.left; break; case BOTTOM: h -= calculateTabAreaHeight(tabPlacement, runCount, maxTabHeight); h += tabAreaInsets.top; break; case TOP: default: y += calculateTabAreaHeight(tabPlacement, runCount, maxTabHeight); y -= tabAreaInsets.bottom; h -= (y - insets.top); } if ( tabPane.getTabCount() > 0 ) { Color color = UIManager.getColor("TabbedPane.contentAreaColor"); if (color != null) { g.setColor(color); } else if ( colorContentBorder == null || selectedIndex == -1 ) { g.setColor(tabPane.getBackground()); } else { g.setColor(colorContentBorder); } g.fillRect(x,y,w,h); } }
8
@Before public void setUp()throws Exception{ //first courier firstCourier.put("slug","india-post-int"); firstCourier.put("name","India Post International"); firstCourier.put("phone","+91 1800 11 2011"); firstCourier.put("other_name","भारतीय डाक, Speed Post & eMO, EMS, IPS Web"); firstCourier.put("web_url","http://www.indiapost.gov.in/"); //first courier in your account firstCourierAccount.put("slug","usps"); firstCourierAccount.put("name","USPS"); firstCourierAccount.put("phone","+1 800-275-8777"); firstCourierAccount.put("other_name","United States Postal Service"); firstCourierAccount.put("web_url","https://www.usps.com"); if(firstTime) { firstTime=false; //delete the tracking we are going to post (in case it exist) Tracking tracking = new Tracking("05167019264110"); tracking.setSlug("dpd"); try {connection.deleteTracking(tracking); } catch (Exception e) { System.out.println("**1"+e.getMessage());} Tracking tracking1 = new Tracking(trackingNumberToDetect); tracking1.setSlug("dpd"); try{connection.deleteTracking(tracking1);} catch (Exception e) { System.out.println("**2"+e.getMessage());} try{ Tracking newTracking = new Tracking(trackingNumberDelete); newTracking.setSlug(slugDelete); connection.postTracking(newTracking);}catch (Exception e) { System.out.println("**3"+e.getMessage()); } } }
4
public boolean isBlocking() { if ( channel instanceof SocketChannel ) return ( (SocketChannel) channel ).isBlocking(); else if ( channel instanceof WrappedByteChannel ) return ( (WrappedByteChannel) channel ).isBlocking(); return false; }
2
public Env(EnvParams ep) throws Exception{ super(); int PAGE_SIZE=10; int cur_page_offset=0; instances=new ArrayList<CompositeInstance>(); logger= Logger.getLogger("driver"); locator(ep); if(locator==null) throw new Exception(this.error); CompositeInstanceFilter filter=make_filter(ep); try{ List<CompositeInstance> tmp; filter.setPageSize(PAGE_SIZE); do{ filter.setPageStart(cur_page_offset); tmp=locator.getCompositeInstances(filter); instances.addAll(tmp); cur_page_offset+=PAGE_SIZE; }while(tmp.size()>0); logger.info(" Number of instances after filtering: " + instances.size()); } catch(Exception e){ this.error="Error in getting composite instances"; logger.error(this.error,e); e.printStackTrace(); } }
3
public TinyELStatement parseFor() { accept(TinyELToken.FOR); accept(TinyELToken.LPAREN); String type = exprParser.type(); String varName = exprParser.name().toString(); if (lexer.token() == TinyELToken.COLON) { lexer.nextToken(); TinyELForEachStatement stmt = new TinyELForEachStatement(); stmt.setType(type); stmt.setVariant(varName); stmt.setTargetExpr(exprParser.expr()); accept(TinyELToken.RPAREN); statementListBody(stmt.getStatementList()); return stmt; } TinyELForStatement stmt = new TinyELForStatement(); stmt.setType(type); accept(TinyELToken.EQ); { TinyELVariantDeclareItem var = new TinyELVariantDeclareItem(varName); var.setInitValue(exprParser.expr()); stmt.getVariants().add(var); } while (lexer.token() == TinyELToken.COMMA) { lexer.nextToken(); if (lexer.token() != TinyELToken.IDENTIFIER) { throw new ELException("parse error : " + lexer.token()); } varName = lexer.stringVal(); lexer.nextToken(); TinyELVariantDeclareItem var = new TinyELVariantDeclareItem(varName); stmt.getVariants().add(var); if (lexer.token() == TinyELToken.EQ) { lexer.nextToken(); var.setInitValue(exprParser.expr()); } } accept(TinyELToken.SEMI); if (lexer.token() != TinyELToken.SEMI) { stmt.setCondition(exprParser.expr()); } accept(TinyELToken.SEMI); if (lexer.token() != TinyELToken.RPAREN) { stmt.setPostExpr(exprParser.expr()); } accept(TinyELToken.RPAREN); statementListBody(stmt.getStatementList()); return stmt; }
6
public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException { Octopart.setApiKey("566cc7d2"); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); FileDialog filepicker = new FileDialog((java.awt.Frame) null); try { PartCache.getInstance().loadCache(new File("./mpncache.json")); } catch (Exception e) { System.out.println("no cache found, creating one"); } Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { PropertyManager.getInstance().clear(); HashMap<String,Object> props = PropertyManager.getInstance().getProperties(); List<Object> inventories = (List<Object>) props.get("inventories"); List<Object> projects = (List<Object>) props.get("projects"); for (Frame frame : JFrame.getFrames()) { if (!frame.isVisible()) continue; if (frame instanceof MicropartMonster) { inventories.add(((MicropartMonster)frame).getWindowState()); } else if (frame instanceof Project) { projects.add(((Project)frame).getWindowState()); } } PropertyManager.getInstance().save(); } }); HashMap<String,Object> data = PropertyManager.getInstance().getProperties(); List<Object> inventories = (List<Object>) data.get("inventories"); boolean inventoryWindow = false; for (Object inv : inventories) { MicropartMonster mm = new MicropartMonster(); try { mm.restoreWindowState(inv); inventoryWindow = true; } catch (FileNotFoundException e) { mm.dispose(); } } if (!inventoryWindow) { System.out.println("none found, creating new.."); new MicropartMonster(); } List<Object> projects = (List<Object>) data.get("projects"); for (Object proj : projects) { new Project().restoreWindowState(proj); } }
9
public static String format(String line){ String formattedLine = line; if (line.subSequence(0, 1).equals("/")){ String[] words = line.split("\\s+"); words[0] = words[0].substring(1,words[0].length()).toUpperCase(); formattedLine = new String(); for (String word: words){ formattedLine += word + " "; } } System.out.println(formattedLine); return formattedLine; }
2
public int run(String [] args) throws Exception { Job job = new Job(getConf()); job.setJarByClass(MapReduce.class); job.setJobName("LogAnalyser"); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); job.setMapperClass(Map.class); job.setCombinerClass(Reduce.class); job.setReducerClass(Reduce.class); job.setInputFormatClass(Log4netInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.setInputPaths(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); boolean success = job.waitForCompletion(true); return success ? 0 : 1; }
1
public void deletePollingScheme(String objectName) { String objectPath; Folder schemeFolder; objectPath = "/PollingSchemes/" + objectName; try { schemeFolder = (Folder) session.getObjectByPath(objectPath); ItemIterable<CmisObject> children = schemeFolder.getChildren(); for (CmisObject o : children) { FileableCmisObject child = (FileableCmisObject) o; child.removeFromFolder(schemeFolder); } schemeFolder.delete(true); } catch (CmisObjectNotFoundException e) { System.out.println("Object not found: " + objectPath); } catch (CmisConstraintException e) { System.out.println("Could not delete '" + objectPath + "': " + e.getMessage()); } }
3
public void eventListner(String message) { Message messageObj = GameApiJsonHelper.getMessageObject(message); if (messageObj instanceof UpdateUI) { game.sendUpdateUI((UpdateUI) messageObj); } else if (messageObj instanceof VerifyMove) { game.sendVerifyMove((VerifyMove) messageObj); } }
2
public ArrayList<String> traerListaCargos(){ conn = Conector.conectorBd(); String sql = "select descripcion from usuario"; try { pst = conn.prepareStatement(sql); ArrayList<String> ls = new ArrayList<String>(); rs = pst.executeQuery(); while(rs.next()){ ls.add(rs.getString("descripcion")); } return ls; } catch (Exception e) { return null; } }
2
public String processInput(String input) { stringParts = input.split(" "); try { cmdPart = stringParts[0]; } catch (NullPointerException e) { System.out.println("Error: found no Command"); } if (cmdPart.equals("!login")) { return logginUser(); } if (cmdPart.equals("!logout")) { return loggoutUser(); } if (cmdPart.equals("!list")) { return listAuctions(); } if (cmdPart.equals("!create")) { return createAuction(); } if (cmdPart.equals("!bid")) { return bidForAuction(); } return "Error: Unknown command: " + input; }
6
public static void main(String[] args) throws IOException { int port = 4444; String localhost = "localhost"; // create a new serversocketchannel. The channel is unbound. ServerSocketChannel channel = ServerSocketChannel.open(); // bind the channel to an address. The channel starts listening to // incoming connections. channel.bind(new InetSocketAddress(localhost, port)); // mark the serversocketchannel as non blocking channel.configureBlocking(false); // create a selector that will by used for multiplexing. The selector // registers the socketserverchannel as // well as all socketchannels that are created Selector selector = Selector.open(); // register the serversocketchannel with the selector. The OP_ACCEPT option marks // a selection key as ready when the channel accepts a new connection. // When the socket server accepts a connection this key is added to the list of // selected keys of the selector. // when asked for the selected keys, this key is returned and hence we // know that a new connection has been accepted. SelectionKey socketServerSelectionKey = channel.register(selector, SelectionKey.OP_ACCEPT); //Set property in the key that identifies the channel Map<String, String> properties = new HashMap<String, String>(); properties.put(channelType, serverChannel); socketServerSelectionKey.attach(properties); // wait for the selected keys for (;;) { // the select method is a blocking method which returns when at least one of the registered // channel is selected. In this example, when the socket accepts a // new connection, this method // will return. Once a socketclient is added to the list of // registered channels, then this method // would also return when one of the clients has data to be read or // written. It is also possible to perform a nonblocking select // using the selectNow() function. // We can also specify the maximum time for which a select function // can be blocked using the select(long timeout) function. if (selector.select() == 0) continue; // the select method returns with a list of selected keys Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> iterator = selectedKeys.iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); // the selection key could either by the socketserver informing // that a new connection has been made, or // a socket client that is ready for read/write // we use the properties object attached to the channel to find // out the type of channel. if (((Map) key.attachment()).get(channelType).equals(serverChannel)) { // a new connection has been obtained. This channel is // therefore a socket server. ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); // accept the new connection on the server socket. Since the // server socket channel is marked as non blocking // this channel will return null if no client is connected. SocketChannel clientSocketChannel = serverSocketChannel.accept(); connect++; if (clientSocketChannel != null) { // set the client connection to be non blocking clientSocketChannel.configureBlocking(false); SelectionKey clientKey = clientSocketChannel.register(selector, SelectionKey.OP_READ, SelectionKey.OP_WRITE); Map<String, String> clientproperties = new HashMap<String, String>(); clientproperties.put(channelType, clientChannel); clientKey.attach(clientproperties); System.out.println("Socket connected! " + clientSocketChannel.getRemoteAddress() + " #: " + connect + "\n"); // write something to the new created client CharBuffer buffer = CharBuffer.wrap("Server> Hello Client"); while (buffer.hasRemaining()) { clientSocketChannel.write(Charset.defaultCharset().encode(buffer)); } buffer.clear(); } //if the key attachment isn't of type serverChannel } else { // data is available for read // buffer for reading ByteBuffer buffer = ByteBuffer.allocate(20); SocketChannel clientChannel = (SocketChannel) key.channel(); int bytesRead = 0; if (key.isReadable()) { // the channel is non blocking so keep it open till the // count is >=0 if ((bytesRead = clientChannel.read(buffer)) > 0) { buffer.flip(); System.out.println(connect + " " + Charset.defaultCharset().decode(buffer) + "\n"); buffer.clear(); } if (bytesRead < 0) { // the key is automatically invalidated once the // channel is closed clientChannel.close(); } } } // once a key is handled, it needs to be removed iterator.remove(); } } }
9
@Override public void run() { Scanner keyboard = new Scanner(System.in); System.out.println("Welcome to the Smart Parking Lot " + "administrative control panel. (type h for help)"); while (true) { String input = keyboard.nextLine(); if (input.equalsIgnoreCase("h")) { System.out.println("'D': Show destination info"); System.out.println("'S': Show parking space info"); System.out.println("'Q': Exit administrative control"); } // if - help menu else if (input.equalsIgnoreCase("D")) { for (Destination dest : CCU.destinations) { System.out.println("Destination: " + dest.getId()); System.out.println("\tX: " + dest.getX() + "\tY: " + dest.getY()); } // for each - destinations } // else if - Destination info else if (input.equalsIgnoreCase("S")) { for (ParkingSpace space : CCU.spaces) { System.out.println("Space: " + space.getId()); String available = (space.isAvailable() ? "Available" : "Occupied"); System.out.println("\tX: " + space.getX() + "\tY: " + space.getY() + "\tController ID: " + space.getController().getId() + "\t" + available); } // for each - spaces } // else if - Space info else if (input.equals("Q")) break; } // while - true keyboard.close(); }
8
public void save() { StringBuilder data = new StringBuilder(); data.append("-" + nameText.getText() + "-" + System.getProperty("line.separator")); if(meleeButton.isSelected()) { data.append("<THRUST>" + System.getProperty("line.separator")); data.append(thrustPanel.save()); data.append("<CRUSH>" + System.getProperty("line.separator")); data.append(crushPanel.save()); data.append("<SLASH>" + System.getProperty("line.separator")); data.append(slashPanel.save()); data.append("<PARRY>" + System.getProperty("line.separator")); data.append("0.55" + System.getProperty("line.separator")); data.append("<BREAK>" + System.getProperty("line.separator")); data.append("<DEFEND>" + System.getProperty("line.separator")); data.append("-1.0" + System.getProperty("line.separator")); data.append("<BREAK>" + System.getProperty("line.separator")); data.append("<END>" + System.getProperty("line.separator")); } else if(magicButton.isSelected()) { data.append("<SPELL1>" + System.getProperty("line.separator")); data.append("-1.0" + System.getProperty("line.separator")); data.append("<BREAK>" + System.getProperty("line.separator")); data.append("<SPELL2>" + System.getProperty("line.separator")); data.append("-1.0" + System.getProperty("line.separator")); data.append("<BREAK>" + System.getProperty("line.separator")); data.append("<SPELL3>" + System.getProperty("line.separator")); data.append("-1.0" + System.getProperty("line.separator")); data.append("<BREAK>" + System.getProperty("line.separator")); data.append("<ATTACK>" + System.getProperty("line.separator")); data.append(attackPanel.save()); data.append("<DEFEND>" + System.getProperty("line.separator")); data.append("-1.0" + System.getProperty("line.separator")); data.append("<BREAK>" + System.getProperty("line.separator")); data.append("<END>" + System.getProperty("line.separator")); } else if(rangedButton.isSelected()) { data.append("<HEADSHOT>" + System.getProperty("line.separator")); data.append("-1.0" + System.getProperty("line.separator")); data.append("<BREAK>" + System.getProperty("line.separator")); data.append("<BODYSHOT>" + System.getProperty("line.separator")); data.append("-1.0" + System.getProperty("line.separator")); data.append("<BREAK>" + System.getProperty("line.separator")); data.append("<CRIPPLE>" + System.getProperty("line.separator")); data.append("-1.0" + System.getProperty("line.separator")); data.append("<BREAK>" + System.getProperty("line.separator")); data.append("<ATTACK>" + System.getProperty("line.separator")); data.append(attackPanel.save()); data.append("<DEFEND>" + System.getProperty("line.separator")); data.append("-1.0" + System.getProperty("line.separator")); data.append("<BREAK>" + System.getProperty("line.separator")); data.append("<END>" + System.getProperty("line.separator")); } else { data.append("<THRUST>" + System.getProperty("line.separator")); data.append("0.45" + System.getProperty("line.separator")); data.append("<BREAK>" + System.getProperty("line.separator")); data.append("<END>" + System.getProperty("line.separator")); } BufferedReader reader; try { reader = new BufferedReader(new FileReader(System.getProperty("resources") + "/database/weapons")); String line; StringBuilder fileContent = new StringBuilder(); boolean makeNew = true; while((line = reader.readLine()) != null) { if(line.matches("-" + nameText.getText() + "-")) { fileContent.append(data); makeNew = false; while(!(line = reader.readLine()).matches("<END>")) { } } else { fileContent.append(line); fileContent.append(System.getProperty("line.separator")); } } if(makeNew) { fileContent.append(System.getProperty("line.separator")); fileContent.append(data); } BufferedWriter out = new BufferedWriter(new FileWriter(System.getProperty("resources") + "/database/weapons")); out.write(fileContent.toString()); out.close(); reader.close(); } catch (FileNotFoundException e) { System.out.println("The weapon database has been misplaced!"); e.printStackTrace(); } catch (IOException e) { System.out.println("Weapon database failed to load!"); e.printStackTrace(); } }
9
@Transactional public void deleteById(Integer id) { tasksDao.setDeletedById(id, true); }
0
public void setUserinfo(String p_userinfo) throws MalformedURIException { if (p_userinfo == null) { m_userinfo = null; } else { if (m_host == null) { throw new MalformedURIException( Messages.getString("URI.userinfoCannotBeSetWhenHostIsNull")); //$NON-NLS-1$ } // userinfo can contain alphanumerics, mark characters, escaped // and ';',':','&','=','+','$',',' int index = 0; int end = p_userinfo.length(); char testChar = '\0'; while (index < end) { testChar = p_userinfo.charAt(index); if (testChar == '%') { if (index + 2 >= end || !isHex(p_userinfo.charAt(index + 1)) || !isHex(p_userinfo.charAt(index + 2))) { throw new MalformedURIException( Messages.getString("URI.userinfoContainsInvalidEscapeSequence")); //$NON-NLS-1$ } } else if (!isUnreservedCharacter(testChar) && USERINFO_CHARACTERS.indexOf(testChar) == -1) { throw new MalformedURIException( MessageFormat.format(Messages.getString("URI.userinfoContainsInvalidCharacter"), new Object[] { String.valueOf(testChar) } ) ); //$NON-NLS-1$ } index++; } } m_userinfo = p_userinfo; }
9
public void readPublisher(){ while(true){ Publisher publisher = new Publisher(); publisher.setName(read("Name")); publisher.setCountryCode(read("Country code")); publisher.setPostCode(read("Post code")); publishers.add(publisher); String yes = read("Create another author? (y/n)"); if(yes != null && !yes.equals("y")) break; } sendPublisher(); }
3
public boolean sqlEjecutar(String sql){ try { int resultado = stmt.executeUpdate(sql); if (resultado == 0) return false; return true; } catch (SQLException ex) { //Log.rutea("Error Ejecutar " +ex.getMessage() + "\n" + sql); return false; } }
2
public int slideChar() { AlignWin win = curAli.randWin(2); AlignCol col1 = win.first, col2 = win.last; int[] inds1 = col1.inds, inds2 = col2.inds; int s = 0; // slidables for(int i = 0; i < inds1.length; i++) if(inds1[i] >= 0 ^ inds2[i] >= 0) rows[s++] = i; if(s > 0) { // choose a random slidable s = rows[Utils.generator.nextInt(s)]; if((inds1[s] >= 0 ? col1.singOrd : col2.singOrd) < 0) { // disallow sliding character from singular column // evaluate swap int ch1 = inds1[s], ch2 = inds2[s]; // characters to swap int newDist = curDist; newDist -= distCalc.distSingle(inds1, s, ch1)+distCalc.distSingle(inds2, s, ch2); newDist += distCalc.distSingle(inds1, s, ch2)+distCalc.distSingle(inds2, s, ch1); if(Utils.DEBUG) { inds1[s] = ch2; inds2[s] = ch1; int testDist = distCalc.dist(curAli); inds1[s] = ch1; inds2[s] = ch2; if(testDist != newDist) throw new Error("Inconsistency in distance calculation in slideChar"); } double newPi = logPi(newDist); // double mh = newPi/curPi; double logMh = newPi-curPi; if(logMh >= 0 || Utils.generator.nextDouble() < Math.exp(logMh)) { scAccept.inc(); inds1[s] = ch2; inds2[s] = ch1; curAli.updateSing(col1); curAli.updateSing(col2); curDist = newDist; curPi = newPi; return 1; } else { scReject.inc(); } } else { scSing.inc(); // shift from singular column was selected } } else { scNoMoves.inc(); // no rows with possible shift (i.e. gap - nongap pair) } return 0; }
9
public void setFont(Font font) { if (days != null) { for (int i = 0; i < 49; i++) { days[i].setFont(font); } } if (weeks != null) { for (int i = 0; i < 7; i++) { weeks[i].setFont(font); } } }
4
private String createColumnListString() { ClassInspect inspector = getClassInspector(); List<Field> annotatedFields = inspector.findAllAnnotatedFields(Column.class); int columnCount = 0; StringBuilder columnBuilder = new StringBuilder(); StringBuilder valueBuilder = new StringBuilder(); columnBuilder.append("("); valueBuilder.append("("); for(Field field : annotatedFields) { if(hasIgnoredAnnotation(field)) { continue; } if(columnCount >= 1) { columnBuilder.append(", "); valueBuilder.append(", "); } Column annotation = field.getAnnotation(Column.class); if(annotation == null) continue; columnCount++; String columnName = annotation.name(); columnBuilder.append(columnName); valueBuilder.append("?"); } columnBuilder.append(")"); valueBuilder.append(")"); return columnBuilder.toString() + " VALUES " + valueBuilder.toString(); }
4
public Set<Coordinate> findThreatenedSquares(Color color) { Set<Coordinate> threatenedSquaresSet = new LinkedHashSet<Coordinate>(); for (int col = 0; col < NUMBER_OF_COLS; col++) { for (int row = 0; row < NUMBER_OF_ROWS; row++) { Piece currPiece = pieces[col][row]; if (currPiece.isNone()) continue; else if (currPiece.getColor() != color) { Set<Coordinate> currThreatenedSquares = currPiece.threatens(new Coordinate(col, row), this); threatenedSquaresSet.addAll(currThreatenedSquares); } } } return threatenedSquaresSet; }
4
public void runScene() throws InterruptedException { while (!this.finished) { Display.update(); if (Display.isCloseRequested()) { this.finished = true; } else if (Display.isActive()) { Display.sync(FRAMERATE); this.traitementsLogiques(); this.dessinerLaScene(); } } }
3
public JLabel getjLabel4() { return jLabel4; }
0
public List<BeerResponse> getBeers() { return beers; }
0
private void moveRandomDirection() { while (true) { int move = (int) (Math.random() * 4); switch (move) { case 0: if (up()) { return; } break; case 1: if (down()) { return; } break; case 2: if (left()) { return; } break; case 3: if (right()) { return; } break; } } }
9
public String getLineStyle() { switch(magnitude) { case HIGH: return HIGH_SIZE; case MEDIUM: return MEDIUM_SIZE; case LOW: return LOW_SIZE; default: return ""; } }
3
public CheckSum(File file) throws Exception{ super(file); }
0
@Override public Exception getException() { return exception; }
0
public void show() { StringBuffer report = new StringBuffer(); for(Slot<String> s : theDraft.copy()) { report.append(s.pickId); report.append(" "); if (Slot.BasicStates.USED.equals(s.state)) { report.append(s.player); } else { report.append(s.state); } report.append('\n'); } System.out.println(report.toString()); }
2
private void onFullnessChanged(double oldVolume) { for(IFullnessChangedObserver fo: fullnessObservers) { fo.fullnessChangedHandler(this, oldVolume); } }
1
private static final double getResolution(final int port) { return (double) port < 4 ? 1023 : 63; }
1
public synchronized Exception getException() { Exception e = exception; for (ConnectionProcessor pipe : pipes) { if (e == null) { e = pipe.getException(); } if (e != null) return e; } return e; }
3
Item newLong(final long value) { key.set(value); Item result = get(key); if (result == null) { pool.putByte(LONG).putLong(value); result = new Item(index, key); put(result); index += 2; } return result; }
1
@Override public double[] getAmountVariableValues() { double[] amountVariables = new double[periods.length]; for (int i = 0; i < amountVariables.length; i++){ amountVariables[i] = periods[i].amount; } return amountVariables; }
1
public void close () { Connection[] connections = this.connections; if (INFO && connections.length > 0) info("kryonet", "Closing server connections..."); for (int i = 0, n = connections.length; i < n; i++) connections[i].close(); connections = new Connection[0]; ServerSocketChannel serverChannel = this.serverChannel; if (serverChannel != null) { try { serverChannel.close(); if (INFO) info("kryonet", "Server closed."); } catch (IOException ex) { if (DEBUG) debug("kryonet", "Unable to close server.", ex); } this.serverChannel = null; } UdpConnection udp = this.udp; if (udp != null) { udp.close(); this.udp = null; } // Select one last time to complete closing the socket. synchronized (updateLock) { selector.wakeup(); try { selector.selectNow(); } catch (IOException ignored) { } } }
9
private void createVirtualNodesAndEdges() { int idCounter = 1; for(LayoutNode v : graph.getAllVertices()) { if(v.getId() >= idCounter) { idCounter = v.getId() + 1; } } LayoutNodeFactory vertexFactory = new LayoutNodeFactory(idCounter); Set<LayoutEdge> edges = graph.getAllEdges(); for (LayoutEdge e : edges) { int labelRank = -1; if(!e.getLabel().isEmpty()) { labelRank = (e.getSourceVertex().getRank() + e.getTargetVertex().getRank()) / 2; } LayoutNode previousNode = e.getTargetVertex(); for(int rank = e.getTargetVertex().getRank() + 1; rank <= e.getSourceVertex().getRank(); rank++) { LayoutNode virtualNode = null; if(rank < e.getSourceVertex().getRank()) { if(rank == labelRank) { /* * Create a label node. */ virtualNode = vertexFactory.createVertex(); virtualNode.setLeftWidth(GraphLayoutParameters.NODE_SEPARATION); //FIXME: Set right width and height based on edge label dimensions. virtualNode.setRightWidth(graph.getRenderingContext().getTextWidth(e.getLabel())); virtualNode.setHeight(graph.getRenderingContext().getTextHeight(e.getLabel())); virtualNode.setRank(rank); virtualNode.setVirtual(true); virtualNode.setLabel(true); virtualNode.setLabel("l_" + e.getLabel()); graph.addVertex(virtualNode); if(!this.edgeVirtualVerticesMap.containsKey(e)) { this.edgeVirtualVerticesMap.put(e, new HashSet<LayoutNode>()); } this.edgeVirtualVerticesMap.get(e).add(virtualNode); } else { /* * Create a plain virtual node. */ virtualNode = vertexFactory.createVertex(); virtualNode.setLeftWidth(GraphLayoutParameters.NODE_SEPARATION/2 + 1); virtualNode.setRightWidth(GraphLayoutParameters.NODE_SEPARATION/2 + 1); virtualNode.setHeight(1); virtualNode.setRank(rank); virtualNode.setVirtual(true); virtualNode.setLabel("v_" + e.getLabel() + "_" + rank); graph.addVertex(virtualNode); if(!this.edgeVirtualVerticesMap.containsKey(e)) { this.edgeVirtualVerticesMap.put(e, new HashSet<LayoutNode>()); } this.edgeVirtualVerticesMap.get(e).add(virtualNode); } } else { virtualNode = e.getSourceVertex(); } LayoutEdge virtualEdge = graph.getEdgeFactory().createEdge(virtualNode, previousNode); virtualEdge.setVirtual(true); virtualEdge.setLabel(""); virtualEdge.setMinLength(e.getMinLength()); virtualEdge.setEdgeWeight(e.getEdgeWeight()); graph.addEdge(virtualEdge); previousNode = virtualNode; } } graph.removeAllEdges(edges); }
9
private void addSnapshotImage(Component parent, ImageIcon image, String filename, boolean inputDescription, String pageAddress) { if (editor == null) editor = new SnapshotEditor(this); String s = Modeler.getInternationalText("TakeSnapshot"); if (editor.showInputDialog(JOptionPane.getFrameForComponent(parent), image, s != null ? s : "Add Snapshot", inputDescription, false, pageAddress)) { if (flashComponents != null && !flashComponents.isEmpty()) { for (JComponent a : flashComponents) { if (a.isShowing() && (a.getClientProperty("flashing") == null || a.getClientProperty("flashing") == Boolean.FALSE)) Blinker.getDefault().createTimer(a, null, "Click me!").start(); } } } }
9
public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException { // Folder containing the Zargo UML files File f = new File("models/"); File[] fileArray = f.listFiles(); // File for saving the statistics for the processed models File summary = new File("result/zargo-xmi.txt"); summary.delete(); summary.createNewFile(); FileWriter writer = new FileWriter(summary, true); for (int i = 0; i < fileArray.length; i++) { File file = fileArray[i]; System.out.println("******************"); System.out.println(file.getName()); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(file); doc.getDocumentElement().normalize(); // Get all elements contained in the XML file NodeList nodeLst = doc.getElementsByTagName("*"); // Store for all element types and their instance cardinality HashMap<String, Integer> result = new HashMap<String, Integer>(); for (int s = 0; s < nodeLst.getLength(); s++) { Node fstNode = nodeLst.item(s); if (fstNode.getNodeType() == Node.ELEMENT_NODE) { if (!fstNode.getNodeName().startsWith("UML:")) continue; Element fstElmnt = (Element) fstNode; if (!(fstElmnt.hasAttribute("xmi.idref") || fstElmnt.getNodeName().contains("."))) { if (result.containsKey(fstElmnt.getNodeName())) { result.put(fstElmnt.getNodeName(), result.get(fstElmnt.getNodeName()) + 1); } else { result.put(fstElmnt.getNodeName(), 1); } } } } // Store information in result file Set<Entry<String, Integer>> set = result.entrySet(); for (Entry<String, Integer> e : set) { String fileName = file.getName().substring(0, file.getName().indexOf(".")); String elementName = e.getKey().substring( e.getKey().indexOf(":") + 1, e.getKey().length()); writer.write("zargo/" + fileName + ";" + elementName + ";" + e.getValue() + "\n"); } System.out.println(result); } writer.flush(); writer.close(); }
8
@After public void tearDown() throws Exception { pool.shutdown(); pool.awaitTermination(100, TimeUnit.SECONDS); final Xpp3Dom results = xmlRunListener.getResults(); assertAllTestCasesHaveRequiredElements(results); assertEquals(700, results.getChildCount()); assertEquals(500, countTestsWithExternalIdfinal(results)); assertEquals(200, countIgnoredTests(results)); final PrintStream stream = new PrintStream(new File("target/parallel-testlink.xml")); try { stream.print(results.toString()); } finally { stream.close(); } }
0
public static void removeReservation(int productID, int memberID){ try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try{ conn.setAutoCommit(false); PreparedStatement stmnt = conn.prepareStatement("DELETE FROM Reservations WHERE product_id = ? AND member_id = ?"); stmnt.setInt(1, productID); stmnt.setInt(2, memberID); stmnt.execute(); conn.commit(); conn.setAutoCommit(true); } catch(SQLException e){ System.out.println("Remove fail: " + e); } }
4
public void populate(String games) { //TODO System.out.println("lobby: games = " + games); if(!games.equals(input)){ System.out.println("repopulating"); System.out.println(games); System.out.println(input); input = games; int pos = 0; int i; gameNumID.clear(); ArrayList<String> listData = new ArrayList<String>(); for(numberOfGames = 0; pos < games.length(); ++numberOfGames){ String gameID; String gameName; String cardsLeft; String playerName; for(i = pos; games.charAt(i) != ';'; ++i){ } gameID = games.substring(pos, i); for(pos = ++i; games.charAt(i) != ';'; ++i){ } gameName = games.substring(pos, i); gameNumID.put(gameName, gameID); for(pos = ++i; games.charAt(i) != ';'; ++i){ } cardsLeft = games.substring(pos, i); for(pos = ++i; games.charAt(i) != ';' || games.charAt(i+1) != ';' || (i+2 < games.length() && games.charAt(i+2) != ';'); ++i){ } playerName = games.substring(pos, i); pos = i + 3; listData.add(gameName + "\t " + cardsLeft + " cards left " + " " + parseName(playerName)); } String [] myData = new String[listData.size()]; listData.toArray(myData); list.setListData(myData); } }
9
protected void fetchLegendItems() { this.items.clear(); RectangleEdge p = getPosition(); if (RectangleEdge.isTopOrBottom(p)) { this.items.setArrangement(this.hLayout); } else { this.items.setArrangement(this.vLayout); } if (this.sortOrder.equals(SortOrder.ASCENDING)) { for (LegendItemSource source : this.sources) { LegendItemCollection legendItems = source.getLegendItems(); if (legendItems != null) { for (int i = 0; i < legendItems.getItemCount(); i++) { addItemBlock(legendItems.get(i)); } } } } else { for (int s = this.sources.length - 1; s >= 0; s--) { LegendItemCollection legendItems = this.sources[s].getLegendItems(); if (legendItems != null) { for (int i = legendItems.getItemCount()-1; i >= 0; i--) { addItemBlock(legendItems.get(i)); } } } } }
8
private int find_K(int A[], int startA, int B[], int startB, int k) { if(A.length ==0 || A.length <= startA) return B[startB+k-1]; if(B.length ==0 || B.length <= startB) return A[startA+k-1]; if(k==1) { if(A[startA]<B[startB]) return A[startA]; else return B[startB]; } int checkAIndex = k/2; if(startA+checkAIndex > A.length) checkAIndex = A.length -startA; int checkBIndex = k-checkAIndex; checkAIndex--; checkBIndex--; if(A[startA+checkAIndex] == B[startB+checkBIndex]) return A[startA+checkAIndex]; if(A[startA+checkAIndex] < B[startB+checkBIndex]) { startA += checkAIndex+1; k = k-checkAIndex-1; return find_K(A, startA, B, startB, k); }else { startB += checkBIndex+1; k = k-checkBIndex-1; return find_K(A, startA, B, startB, k); } }
9
* @param superclass * @return boolean */ public static boolean subclassOfP(Stella_Class subclass, Stella_Class superclass) { if (subclass == superclass) { return (true); } { TaxonomyNode subnode = subclass.classTaxonomyNode; TaxonomyNode supernode = superclass.classTaxonomyNode; int sublabel = Stella.NULL_INTEGER; if ((subnode == null) || ((supernode == null) || ((sublabel = subnode.label) == Stella.NULL_INTEGER))) { return (subclass.classAllSuperClasses.membP(superclass)); } { Interval interval = null; Cons iter000 = supernode.intervals; for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { interval = ((Interval)(iter000.value)); if ((sublabel >= interval.lowerBound) && (sublabel <= interval.upperBound)) { return (true); } } } return (false); } }
7
public void adjustListPosition(int val){ //Checks for positive or negative value if(val == 1) { //Checking if at end of list if(listPosition == listImages.size()-1){ listPosition = 0; } else { listPosition += val; } // Checking if on far right of screen if(positionOnScreen == 4){ shiftRight(false); positionOnScreen = 0; } else { positionOnScreen += val; } } else { //Checking if at beginning of list if(listPosition == 0){ listPosition = files.size()-1; } else { listPosition += val; } //Checking if on far left of screen if(positionOnScreen == 0){ shiftLeft(false); positionOnScreen = 4; } else { positionOnScreen += val; } } //Debug statements for all position indicators System.out.println("PositionOnScreen:: " + positionOnScreen + " reDrawIndex:: " + reDrawIndex + " listPosition:: " + listPosition); }
5
@Override public void rotateZPlus() { if(orientation == Z) return; orientation = (orientation == X ? Y : X); for(int i = 0; i < others.length; i++) { IntPoint p = others[i]; others[i] = new IntPoint(-p.getY(), p.getX(), p.getZ()); } }
3
@After public void tearDown() { }
0
public static HashMap<String, Double> getOneWayAnovaPValues(ENode root) throws Exception { HashMap<String, Double> returnMap = new HashMap<String, Double>(); HashMap<Float, List<ENode>> map = ReadCluster.getMapByLevel(root); System.out.println(map.size()); for( Float f : map.keySet()) { File outFile = new File(ConfigReader.getETreeTestDir() + File.separator + "Mel74ColumnsAsTaxaFor" + f + ".txt"); System.out.println(outFile.getAbsolutePath()); PivotOut.pivotOut(map.get(f), outFile.getAbsolutePath()) ; OtuWrapper wrapper = new OtuWrapper(outFile); List<List<Double>> list = wrapper.getDataPointsNormalizedThenLogged(); for( int x=0; x < wrapper.getOtuNames().size(); x++ ) { double pValue = 1; if( ! wrapper.getOtuNames().get(x).equals(ETree.ROOT_NAME)) { List<Number> data = new ArrayList<Number>(); List<String> factors = new ArrayList<String>(); for( int y=0; y < wrapper.getSampleNames().size(); y++) { if( ! wrapper.getSampleNames().get(y).equals(ETree.ROOT_NAME)) { data.add(list.get(y).get(x)); factors.add("" + stripSuffix(wrapper.getSampleNames().get(y))); } } OneWayAnova owa =new OneWayAnova(data, factors); if(map.containsKey(wrapper.getOtuNames().get(x))) throw new Exception("Duplicate"); pValue = owa.getPValue(); } returnMap.put(wrapper.getOtuNames().get(x), pValue); } } return returnMap; }
6
private void tuplaaKoko(){ Siirto[] uusi = new Siirto[keko.length*2]; for (int i = 0; i < keko.length; i++){ uusi[i] = keko[i]; } this.keko = uusi; }
1
public void setDateModified(String dateModified) {this.dateModified = dateModified;}
0
public double weightedStandardError_of_ComplexModuli() { boolean hold = Stat.nFactorOptionS; if (nFactorReset) { if (nFactorOptionI) { Stat.nFactorOptionS = true; } else { Stat.nFactorOptionS = false; } } boolean hold2 = Stat.nEffOptionS; if (nEffReset) { if (nEffOptionI) { Stat.nEffOptionS = true; } else { Stat.nEffOptionS = false; } } boolean holdW = Stat.weightingOptionS; if (weightingReset) { if (weightingOptionI) { Stat.weightingOptionS = true; } else { Stat.weightingOptionS = false; } } double varr = Double.NaN; if (!weightsSupplied) { System.out.println("weightedStandardError_as_Complex: no weights supplied - unweighted value returned"); varr = this.standardError_of_ComplexModuli(); } else { double[] cc = this.array_as_modulus_of_Complex(); double[] wc = amWeights.array_as_modulus_of_Complex(); varr = Stat.standardError(cc, wc); } Stat.nFactorOptionS = hold; Stat.nEffOptionS = hold2; Stat.weightingOptionS = holdW; return varr; }
7
@Override public void send(String n, String m) { try { m_server.pushMessage(new Send(n, m)); } catch (RemoteException e) { e.printStackTrace(); } catch(InterruptedException e){ e.printStackTrace(); } }
2
public void setValueB(Value value) { if(!opcode.isBasic()) throw new IllegalArgumentException("Can not setValueB on non-basic opcode"); this.valueB = value; }
1
private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) { int tamaño = this.jTextField1.getText().length(); if (tamaño >= 12) { evt.consume(); } }
1
public void chessPieceRedirection(int originLetter, int originNum, int newLetter, int newNum) { System.out.println(); String chessPiece = b.checkBoard(originNum, originLetter); if(chessPiece.equalsIgnoreCase("r")) { RookMovement rook = new RookMovement(chessPiece, b); rook.checkMove(originLetter, originNum, newLetter, newNum); } else if(chessPiece.equalsIgnoreCase("k")) { KingMovement king = new KingMovement(chessPiece, b); king.checkMove(originLetter, originNum, newLetter, newNum); } else if(chessPiece.equalsIgnoreCase("b")) { BishopMovement bishop = new BishopMovement(chessPiece, b); bishop.checkMove(originLetter, originNum, newLetter, newNum); } else if(chessPiece.equalsIgnoreCase("q")) { QueenMovement queen = new QueenMovement(chessPiece, b); queen.checkMove(originLetter, originNum, newLetter, newNum); } else if(chessPiece.equalsIgnoreCase("n")) { KnightMovement knight = new KnightMovement(chessPiece, b); knight.checkMove(originLetter, originNum, newLetter, newNum); } }
5
public LinkedList<Integer> stackDFS(Digraph G, int source) { if (G.bag.length < source) { // If length of bag is lesser than source, source can't exist return null; } boolean[] visited = new boolean[G.V()]; // Create boolean array to flag visited vertices Stack<Integer> stack = new Stack<Integer>(); // Create new stack stack.push(source); // Push initial vertex while(!stack.isEmpty()) { int v = stack.pop(); if (!visited[v]) { // If the popped value isn't visited.. visited[v] = true; // Flag it as visited for (int i : G.bag[v]) { // Then push every adjacent vertex stack.push(i); } } } LinkedList<Integer> results = new LinkedList<Integer>(); // Create LinkedList to summarize results visited[source] = false; // Every vertex can visit itself, redundant for (int i = 0; i < visited.length; i++) { if (visited[i]) { // For every visited vertex results.add(i); // Add that index (vertex) to the list } } return results; }
6
public Configuration[] getConfigurations() { return (Configuration[]) configurationToButtonMap.keySet().toArray( new Configuration[0]); }
0
private List<Symbol> removeEpsilon(List<Symbol> alphabet) { List<Symbol> results = alphabet; for(Symbol result : results){ if(result.mathValue("epsilon")){ results.remove(result); break; } } return results; }
2
private void calculateAnchors(){ //get rack and print it int[] tmpRack = rack.getCards(); //analyze the rack to find the anchor points //if the card in slot "i" fits roughly the flat, maximal spread distribution, it is an anchor int slotLow = 1, slotHigh; for (int i = 1; i <= rack_size; i++){ slotHigh = i * (card_count / rack_size); if (tmpRack[i-1] >= slotLow && tmpRack[i-1] <= slotHigh) anchorPoints.add(new Integer(i)); slotLow = slotHigh + 1; } //add index to anchor points if one of the other anchors is a consecutive of it /* THIS CODE DOESNT WORK FOR SOME REASON; SEE BELOW FOR REVISED VERSION for (int i = 0; i < anchorPoints.size(); i++) { if ((tmpRack[i+1] == tmpRack[i] + 1) && !anchorPoints.contains(new Integer(i+1))) anchorPoints.add(new Integer(i+1)); } */ //I had to modify this section quite a bit to get it to not throw errors; //... not sure if this is what Kyle meant by his above comment for (int i=0; i<anchorPoints.size(); i++){ int anchor = anchorPoints.get(i), consec_anchor = new Integer(anchor+1); if (anchor != rack_size && tmpRack[anchor-1] + 1 == tmpRack[anchor] && !anchorPoints.contains(consec_anchor)) anchorPoints.add(consec_anchor); } Collections.sort(anchorPoints); //sort the collection if any ranges were added }
7
private AcctsRecTransRec parseDeleteTransaction() { String mastID; AcctsRecTransRec result; if (tokens.length > 1) { mastID = tokens[1]; if (tokens.length == 2) { result = new AcctsRecDeleteTransRec(mastID); } else { result = new AcctsRecIllFormedTransRec(mastID, line.getBytes()); } } else { result = new AcctsRecIllFormedTransRec("", line.getBytes()); } return result; }
2
private static ArrayList<Line> readLineInfo(Scanner input, HashMap<String, BusStop> busStops) throws Exception { String temp, lineNo; int period; Time start, last; lines = new ArrayList<Line>(); input.useDelimiter("[:=<>,\\s]+"); while (input.hasNext()) { temp = input.next(); if (temp.compareTo("line") != 0) throw new Exception(temp + " when keyword line is expected"); lineNo = input.next(); temp = input.next(); if (temp.compareTo("route") != 0) throw new Exception(temp + " when keyword route is expected"); ArrayList<BusStop> route = new ArrayList<BusStop>(); ArrayList<Integer> timepoints = new ArrayList<Integer>(); while (!input.hasNext("start")) { temp = input.next(); if (busStops.containsKey(temp)) route.add(busStops.get(temp)); else throw new Exception("Busstop " + temp + " not defined!"); timepoints.add(input.nextInt()); } temp = input.next(); if (temp.compareTo("start") != 0) throw new Exception(temp + " when keyword start is expected"); start = new Time(input.nextInt(), input.nextInt()); temp = input.next(); if (temp.compareTo("last") != 0) throw new Exception(temp + " when keyword last is expected"); last = new Time(input.nextInt(), input.nextInt()); temp = input.next(); if (temp.compareTo("period") != 0) throw new Exception(temp + " when keyword period is expected"); period = input.nextInt(); Line line = new Line(lineNo,route.get(0), route.get(route.size() - 1), start, last, period); for(int i=0; i < route.size(); i++) line.addNextBusStop(route.get(i), timepoints.get(i)); lines.add(line); } return lines; }
9
public void event() { System.out.println("DELETE 버튼 이벤트 발생!"); Iterator<Information> it = list.iterator(); Information i; int count = 0; try { while (it.hasNext()) { i = it.next(); if (i.getName().equals(name_tf.getText()) // 이름으로 삭제 && id_tf.getText().equals("")) { list.remove(count); } else if (i.getId().equals(id_tf.getText()) // 아이디로 삭제 && name_tf.getText().equals("")) { list.remove(count); } else if (i.getName().equals(name_tf.getText()) // 이름과 아이디로 삭제 && i.getId().equals(id_tf.getText())) { list.remove(count); } count++; } } catch (Exception e) { } refreshTable(); }
8
public void addButton(Container c, String title, ActionListener listener) { JButton button = new JButton(title); c.add(button); button.addActionListener(listener); }
0
public void end(Integer statusCode){ this.setStatus(Call.CALL_ENDED); if (getPastStatus()==Call.CALL_INITIALIZED){ try { initialRequest.createResponse(statusCode).send(); } catch (IOException ex) { ex.printStackTrace(); } } else if (getPastStatus() == Call.CALL_STARTED || getPastStatus() == Call.CALL_KILLED || getPastStatus() >= Call.MEDIA_CALL_INITIALIZED){ Iterator i = initialRequest.getApplicationSession().getSessions(); while (i.hasNext()){ Object o = i.next(); if (o instanceof SipSession){ SipSession ss = (SipSession)o; SipServletRequest bye = ss.createRequest("BYE"); try { ss.setHandler("EndSessionServlet"); bye.send(); } catch (IOException ex) { ex.printStackTrace(); } catch (ServletException e){ e.printStackTrace(); } } } } CacheHandler.getCacheHandler().getCallsMap().remove(id); }
9
int alloc(int len) { if (hp+len+1 > size) { // Check for space in the heap. garbageCollect(); // Invoke garbage collector. if (hp+len+1 > size) { // And then retest for space in heap. fatal("Out of memory!"); } } int result = hp-size; for (heap[hp++]=len; len>0; len--) { heap[hp++] = 0; } return result; }
3
private double _value(final Interval<Double> region, final Function<Double, Double> function, final double firstGuess, final int iteration, final DoubleAbsolute criterion) { if (this.getMaximumIterations() < iteration) throw new MaximumIterationsException(iteration); HashMap<Interval<Double>, Double> values = new HashMap<Interval<Double>, Double>(); Evaluator<Function<Double, Double>, Interval<Double>, Double> evaluator = this.getEvaluator(); for (Interval<Double> interval : this._SplitInterval(region, iteration)) values.put(interval, evaluator.value(function, interval)); double v = 0.0; for (Interval<Double> value : values.keySet()) v += values.get(value); if (!criterion.value(firstGuess, v)) { for (Interval<Double> value : values.keySet()) values.put(value, this._value(value, function, values.get(value), iteration+1, new DoubleAbsolute(criterion.getPrecision()/2.0))); v = 0.0; for (Interval<Double> value : values.keySet()) v += values.get(value); } return v; }
6
public void addNeighbor(Region ar) { this.neighbors.add(ar); }
0
public void startUpload() throws InterruptedException { Random random = new Random(); uploadWindow.statusLabel.setText("Loading image..."); System.out.println(filePath); BufferedImage image = getBufferedImage(filePath); if (image == null) { uploadWindow.statusLabel.setText("An error occured!"); uploadWindow.statusLabel.setForeground(Color.RED); uploadWindow.progressBar.setIndeterminate(false); return; } Thread.sleep(1500); uploadWindow.statusLabel.setText("Encoding image data..."); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write(image, "png", baos); URL url = new URL(IMGUR_POST_URI); String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(Base64.encode(baos.toByteArray()), "UTF-8"); data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(IMGUR_API_KEY, "UTF-8"); Thread.sleep(300 + random.nextInt(200)); uploadWindow.statusLabel.setText("Connecting to Imgur..."); URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.addRequestProperty("Authorization", "Client-ID " + IMGUR_API_KEY); Thread.sleep(300 + random.nextInt(500)); uploadWindow.statusLabel.setText("Uploading image..."); OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream()); wr.write(data); wr.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String response; String responseURL = ""; while ((response = in.readLine()) != null) { String[] bits = response.split("\""); for (int i = 0; i < bits.length; i++) { if (bits[i].equals("link")) { responseURL = bits[i + 2]; } } } System.out.println(responseURL); in.close(); Thread.sleep(250); uploadWindow.statusLabel.setText("Upload complete!"); uploadWindow.progressBar.setVisible(false); uploadWindow.label1.setVisible(true); uploadWindow.urlField.setVisible(true); uploadWindow.urlField.setText(responseURL.replace("\\", "")); uploadWindow.copyButton.setVisible(true); if (Desktop.isDesktopSupported()) { uploadWindow.browserButton.setVisible(true); } } catch (Exception e) { e.printStackTrace(); uploadWindow.statusLabel.setText("An error occured!"); uploadWindow.statusLabel.setForeground(Color.RED); uploadWindow.progressBar.setIndeterminate(false); } }
6
public Operator<Boolean> getOperator() { return operator; }
0
void NewickPrintBinaryTree( PrintStream out ) throws Exception { NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits( DOUBLE_PRECISION ); edge e, f; node rootchild; e = root.leftEdge; rootchild = e.head; out.write('('); f = rootchild.leftEdge; if ( null != f ) { NewickPrintSubtree( f, out ); out.write(','); } f = rootchild.rightEdge; if ( null != f ) { NewickPrintSubtree( f, out ); out.write(','); } out.write( root.label.getBytes() ); out.write( ':'); out.write( nf.format(e.distance).getBytes() ); out.write(')'); if ( null != rootchild.label ) out.write( rootchild.label.getBytes() ); out.write(';'); out.write('\n'); }
3
public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println( "usage: java PKCS12Import {pkcs12file} [newjksfile]"); System.exit(1); } File fileIn = new File(args[0]); File fileOut; if (args.length > 1) { fileOut = new File(args[1]); } else { fileOut = new File("newstore.jks"); } if (!fileIn.canRead()) { System.err.println( "Unable to access input keystore: " + fileIn.getPath()); System.exit(2); } if (fileOut.exists() && !fileOut.canWrite()) { System.err.println( "Output file is not writable: " + fileOut.getPath()); System.exit(2); } KeyStore kspkcs12 = KeyStore.getInstance("pkcs12"); KeyStore ksjks = KeyStore.getInstance("jks"); LineNumberReader in = new LineNumberReader(new InputStreamReader(System.in)); System.out.print("Enter input keystore passphrase: "); char[] inphrase = in.readLine().toCharArray(); System.out.print("Enter output keystore passphrase: "); char[] outphrase = in.readLine().toCharArray(); kspkcs12.load(new FileInputStream(fileIn), inphrase); ksjks.load( (fileOut.exists()) ? new FileInputStream(fileOut) : null, outphrase); Enumeration eAliases = kspkcs12.aliases(); int n = 0; while (eAliases.hasMoreElements()) { String strAlias = (String)eAliases.nextElement(); System.err.println("Alias " + n++ + ": " + strAlias); if (kspkcs12.isKeyEntry(strAlias)) { System.err.println("Adding key for alias " + strAlias); Key key = kspkcs12.getKey(strAlias, inphrase); Certificate[] chain = kspkcs12.getCertificateChain(strAlias); ksjks.setKeyEntry(strAlias, key, outphrase, chain); } } OutputStream out = new FileOutputStream(fileOut); ksjks.store(out, outphrase); out.close(); }
8
@Override public synchronized void mouseMoved(MouseEvent e) { Point mousePoint = e.getPoint(); // Test all objects to see if the mouse position is within the bounds of // the eventable object. If it is, add their event to the // waitingEventsMouseOver list. We must also add it to the list of // currentMouseOver, so that we can fire the mouse out events when the // mouse is outside of the dimensions of the eventable object synchronized (registeredListeningObjects) { for (IMouseEventable eventable : registeredListeningObjects) { // If the mouse is within the dimensions of the object, and if // the // object hasn't already received its mouse over event before. // And isEventsDisabled is called to make sure that it actually // wants to recieve the events still if (eventable.getDimensions().contains(mousePoint) && !currentMouseOver.contains(eventable) && !eventable.isEventsDisabled()) { synchronized (waitingEventLists) { waitingEventLists.get(MouseEventType.MOUSE_OVER).add(eventable); } synchronized (currentMouseOver) { currentMouseOver.add(eventable); } } } } synchronized (currentMouseOver) { for (IMouseEventable eventable : currentMouseOver) { if (!eventable.getDimensions().contains(mousePoint)) { synchronized (waitingEventLists) { waitingEventLists.get(MouseEventType.MOUSE_OUT).add(eventable); } synchronized (currentMouseOver) { currentMouseOver.remove(eventable); } } } } // Update the latest position of the mouse moved x,y mousePosX = e.getX(); mousePosY = e.getY(); }
6
public synchronized Entity operateEntityList(int op, int index, Entity e){ switch(op){ case 0 : playerList.add(e); return null; case 1 : return playerList.get(index); case 2 : playerList.remove(index); return null; default : return null; } }
3
public List<TravelDataBean> getarticleList(int start, int end, int area) throws Exception{ Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; List<TravelDataBean> articleList = null; String sql = ""; try{ conn = getConnection(); /*추천지수 불러오는sql*/ sql = "update travel set recommand_count = recommand - non_recommand "; pstmt = conn.prepareStatement(sql); pstmt.executeUpdate(); sql = "select a.* from (select ROWNUM as RNUM, b.* from (select * from travel" + " where area=? order by idx desc) b order by ref desc, step asc) a where a.RNUM >=? and a.RNUM <=?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, area); pstmt.setInt(2, start); pstmt.setInt(3, end); rs = pstmt.executeQuery(); if(rs.next()){ articleList = new ArrayList<TravelDataBean>(end); do{ TravelDataBean article = new TravelDataBean(); article.setIdx(rs.getInt("idx")); article.setArea_idx(rs.getInt("area_idx")); article.setTitle(rs.getString("title")); article.setContent(rs.getString("content")); article.setNickname(rs.getString("nickname")); article.setId(rs.getString("id")); article.setWdate(rs.getTimestamp("wdate")); article.setRead_count(rs.getInt("read_count")); article.setRecommand_count(rs.getInt("recommand_count")); article.setRecommand(rs.getInt("recommand")); article.setNon_recommand(rs.getInt("non_recommand")); article.setCategory(rs.getString("category")); article.setDepth(rs.getInt("depth")); articleList.add(article); } while(rs.next()); } }catch(Exception ex){ ex.printStackTrace(); }finally{ if(rs != null){ try{rs.close();} catch(SQLException e){e.printStackTrace();} } if(pstmt != null){ try{pstmt.close();} catch(SQLException e){e.printStackTrace();} } if(conn != null){ try{conn.close();} catch(SQLException e){e.printStackTrace();} } } return articleList; }
9
@Override public final boolean equals(Object o) { if ((o != null) && (o instanceof IPNetwork)) { IPNetwork net = (IPNetwork)o; return (net != null) && address.equals(net.address) && mask.equals(net.mask) && (BITS == net.BITS); } return false; }
5
public void mergeBreakedStack(VariableStack stack) { if (breakedStack != null) breakedStack.merge(stack); else breakedStack = stack; }
1
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.content == null) ? 0 : this.content.hashCode()); result = prime * result + ((this.mime == null) ? 0 : this.mime.hashCode()); result = prime * result + ((this.reference == null) ? 0 : this.reference.hashCode()); result = prime * result + ((this.url == null) ? 0 : this.url.hashCode()); result = prime * result + ((this.caption == null) ? 0 : this.caption.hashCode()); return result; }
5
public void histogramme(ShortPixmap img) { short[] histogramme = new short[256]; for (int i=0; i<=img.width; i++) { for (int j=0; j<=img.height; i++ ) { //int k = img. //histogramme[k]++; } } }
2
public static Database getInstance() throws Exception { if(Database.db == null) throw new Exception("No database initialized."); else return Database.db; }
1
@Override public void execute() { for(int i = 0; i<rockArray.length; i++){ EfficientMiner.operation = "Looking for ores"; rockArray[i] = SceneEntities.getAt(ORES_TILES[i]); if(rockArray[i].getId() == ORES[i]) if(rockArray[i].isOnScreen()){ rockArray[i].interact("Mine"); EfficientMiner.operation = "Mining ore"; sleep(1000); while(rockArray[i].validate()){ sleep(10); } }else Camera.turnTo(rockArray[i]); } }//end execute
4
private void getNumMappedFlagstat(String flagstatPattern, String dirName) throws IOException{ numMapped = new HashMap<String, Integer>(); TextFile flagstat; File dir = new File(dirName); for (File ch : dir.listFiles()) { if (ch.isDirectory()){ for (File child : ch.listFiles()){ if ( (child.getName().equals(flagstatPattern))){ flagstat = new TextFile(child.getPath(), false); flagstat.readLine(); flagstat.readLine(); int num = Integer.parseInt(flagstat.readLineElems(TextFile.space)[0]); String sampleId = ch.getName(); numMapped.put(sampleId, num); flagstat.close(); } } } } }
4
public boolean[][] fillIn(int[] order, boolean[][] bAdjacencyMatrix) { int nNodes = bAdjacencyMatrix.length; int[] inverseOrder = new int[nNodes]; for (int iNode = 0; iNode < nNodes; iNode++) { inverseOrder[order[iNode]] = iNode; } // consult nodes in reverse order for (int i = nNodes - 1; i >= 0; i--) { int iNode = order[i]; // find pairs of neighbors with lower order for (int j = 0; j < i; j++) { int iNode2 = order[j]; if (bAdjacencyMatrix[iNode][iNode2]) { for (int k = j+1; k < i; k++) { int iNode3 = order[k]; if (bAdjacencyMatrix[iNode][iNode3]) { // fill in if (m_debug && (!bAdjacencyMatrix[iNode2][iNode3] || !bAdjacencyMatrix[iNode3][iNode2]) ) System.out.println("Fill in " + iNode2 + "--" + iNode3); bAdjacencyMatrix[iNode2][iNode3] = true; bAdjacencyMatrix[iNode3][iNode2] = true; } } } } } return bAdjacencyMatrix; } // fillIn
9
private void updateTypeMenu() { if(specificType != null) { panel.remove(specificType); } if(playerType.equals(AI)) { specificType = new JComboBox<String>(AIList.getNames()); } else { specificType = new JComboBox<String>(GUIList.getNames()); } panel.add(specificType); Thread t = new Thread() { public void run () { try { SwingUtilities.invokeAndWait(new Runnable() { public void run () { frame.revalidate(); frame.pack(); } }); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }; t.start(); }
4
public Photograph(String[] photograph) { if (photograph == null) { photograph = new String[]{}; } this.pic = photograph; }
1
public static ArrayList<BasicNode> GetPath(LevelEntity[][] level, BasicNode start,BasicNode goal){ int[][] temp = {{ 1,-1}, { 1,-2}, { 2,-2}, { 2,-3}, { 3,-3}, { 3,-4}, { 4,-4}, { 5,-3}, { 6,-3}, { 7,-3}, { 8,-2}, { 8,-1}}; int[][] temp2 = {{ 1,-1}, { 1,-2}, { 1,-3}, {1,-4}, { 2,-4}}; longJumpLocations = temp; shortJumpLocations = temp; HashSet<BasicNode> closedSet = new HashSet<BasicNode>(); Hashtable<BasicNode,BasicNode> cameFrom = new Hashtable<BasicNode,BasicNode>(); Hashtable<BasicNode,Double> gScore =new Hashtable<BasicNode,Double>(); Hashtable<BasicNode,Double> fScore =new Hashtable<BasicNode,Double>(); BasicNode[][] nodeGrid = new BasicNode[level.length][level[0].length]; PriorityQueue<BasicNode> openSet = new PriorityQueue<BasicNode>(500,new BasicComparator(fScore)); nodeGrid[start.xx][start.yy] = start; nodeGrid[goal.xx][goal.yy] = goal; gScore.put(start, 0.0); fScore.put(start, (double) (goal.xx - start.xx)); openSet.add(start); while (openSet.size() > 0){ BasicNode current = openSet.poll(); if (current == goal){ ArrayList<BasicNode> path = new ArrayList<BasicNode>(); while (current != start){ path.add(current); current = cameFrom.get(current); } return path;//reconstructPath(cameFrom,goal); } closedSet.add(current); for (BasicNode neighbor : getNeighbors(current,level,nodeGrid)){ if (!closedSet.contains(neighbor)){ double tentativeGScore = gScore.get(current) + getDistance(current,neighbor); if (!openSet.contains(neighbor) || tentativeGScore < gScore.get(neighbor)){ cameFrom.put(neighbor, current); gScore.put(neighbor, tentativeGScore); fScore.put(neighbor, tentativeGScore + goal.xx-neighbor.xx); if (openSet.contains(neighbor)){ openSet.remove(neighbor); } openSet.add(neighbor); } } } } return null; }
8
public static void main(String[] args) { System.out.println("Starting failure example 1..."); try { if (args.length < 1) { System.out.println("Usage: java ResFailureEx01 network_ex01.txt"); return; } ////////////////////////////////////////// // First step: Initialize the GridSim package. It should be called // before creating any entities. We can't run this example without // initializing GridSim first. We will get a run-time exception // error. // a flag that denotes whether to trace GridSim events or not. boolean trace_flag = false; // dont use SimJava trace int num_user = 1; // number of grid users Calendar calendar = Calendar.getInstance(); // Initialize the GridSim package System.out.println("Initializing GridSim package"); GridSim.init(num_user, calendar, trace_flag); trace_flag = true; ////////////////////////////////////////// // Second step: Builds the network topology among Routers. String filename = args[0]; // get the network topology System.out.println("Reading network from " + filename); LinkedList routerList = NetworkReader.createFIFO(filename); ////////////////////////////////////////// // Third step: Creates one RegionalGISWithFailure entity, // linked to a router in the topology Router router = null; double baud_rate = 100000000; // 100Mbps, i.e. baud rate of links double propDelay = 10; // propagation delay in milliseconds int mtu = 1500; // max. transmission unit in byte int totalMachines = 10; // num of machines each resource has String NAME = "Ex01_"; // a common name String gisName = NAME + "Regional_GIS"; // GIS name // a network link attached to this regional GIS entity Link link = new SimpleLink(gisName + "_link", baud_rate, propDelay, mtu); // HyperExponential: mean, standard deviation, stream // how many resources will fail HyperExponential failureNumResPattern = new HyperExponential(totalMachines / 2, totalMachines, 4); // when they will fail HyperExponential failureTimePattern = new HyperExponential(25, 100, 4); // how long the failure will be HyperExponential failureLengthPattern = new HyperExponential(20, 25, 4); // big test: (20, 100, 4); // creates a new Regional GIS entity that generates a resource // failure message according to these patterns. RegionalGISWithFailure gis = new RegionalGISWithFailure(gisName, link, failureNumResPattern, failureTimePattern, failureLengthPattern); gis.setTrace(trace_flag); // record this GIS activity // link these GIS to a router router = NetworkReader.getRouter("Router0", routerList); linkNetwork(router, gis); // print some info messages System.out.println("Created a REGIONAL GIS with name " + gisName + " and id = " + gis.get_id() + ", connected to " + router.get_name() ); ////////////////////////////////////////// // Fourth step: Creates one or more GridResourceWithFailure // entities, linked to a router in the topology String sched_alg = "SPACE"; // use space-shared policy int totalResource = 3; // number of resources ArrayList resList = new ArrayList(totalResource); // Each resource may have different baud rate, // totalMachine, rating, allocation policy and the router to // which it will be connected. However, in this example, we assume // all have the same properties for simplicity. int totalPE = 4; // num of PEs each machine has int rating = 49000; // rating (MIPS) of PEs int GB = 1000000000; // 1 GB in bits baud_rate = 2.5 * GB; for (int i = 0; i < totalResource; i++) { // gets the router object from the list router = NetworkReader.getRouter("Router0", routerList); // creates a new grid resource String resName = NAME + "Res_" + i; GridResourceWithFailure res = createGridResource(resName, baud_rate, propDelay, mtu, totalPE, totalMachines, rating, sched_alg); // add a resource into a list resList.add(res); res.setRegionalGIS(gis); // set the regional GIS entity res.setTrace(trace_flag); // record this resource activity // link a resource to this router object linkNetwork(router, res); System.out.println("Created a RESOURCE (" + totalMachines + " machines, each with " + totalPE + " PEs) with name = " + resName + " and id = " + res.get_id() + ", connected to router " + router.get_name() + " and registered to " + gis.get_name() ); } ////////////////////////////////////////// // Fifth step: Creates one GridUserFailure entity, // linked to a router of the topology int totalGridlet = 5; // total jobs double pollTime = 100; // time between polls int glSize = 100000; // the size of gridlets (input/output) int glLength = 42000000; // the length (MI) of gridlets String userName = NAME + "User0"; // gets the router object from the list router = NetworkReader.getRouter("Router0", routerList); // a network link attached to this entity Link link2 = new SimpleLink(userName + "_link", baud_rate, propDelay, mtu); GridUserFailureEx01 user = new GridUserFailureEx01(userName, link2, pollTime, glLength, glSize, glSize, trace_flag); user.setRegionalGIS(gis); // set the regional GIS entity user.setGridletNumber(totalGridlet); // link a resource to this router object linkNetwork(router, user); System.out.println("Created a USER with name " + userName + " and id = " + user.get_id() + ", connected to " + router.get_name() + ", and with " + totalGridlet + " gridlets. Registered to " + gis.get_name() ); System.out.println(); ////////////////////////////////////////// // Sixth step: Starts the simulation GridSim.startGridSimulation(); System.out.println("\nFinish failure example 1... \n"); } catch (Exception e) { e.printStackTrace(); System.out.println("Unwanted errors happen"); } }
3
private TreeModel generateLoggerTreeModel() { myLogger.fine("Erzeuge Tree-Model mit allen Loggern"); // Das Tree-Model mitsamt Root-Knoten anlegen TreeNodeObject tno = new TreeNodeObject("Alle Logger"); DefaultMutableTreeNode root = new DefaultMutableTreeNode(tno); DefaultTreeModel tree = new DefaultTreeModel(root); // Alle Logger in den Tree schreiben Enumeration loggerNames = LogManager.getLogManager().getLoggerNames(); while(loggerNames.hasMoreElements()) { String name = (String)loggerNames.nextElement(); myLogger.fine("Neuer Logger: " + name); if (name.length() == 0) continue; // Den Baum "Teil"-weise durchlaufen und ggf. // neue Knoten anlegen. String[] parts = name.split("\\."); DefaultMutableTreeNode currentNode = root; DefaultMutableTreeNode childNode; for (int i=0; i<parts.length; i++) { int childCount = currentNode.getChildCount(); // Testen, ob es diesen Knoten bereits gibt. boolean setFlag = false; for (int j=0; j<childCount; j++) { childNode = (DefaultMutableTreeNode)currentNode.getChildAt(j); TreeNodeObject content = (TreeNodeObject)childNode.getUserObject(); // Der getestet Knoten liegt alphabetisch hinter dem // neuen Knoten. Daher wird er jetzt an diesem Index // angelegt. if (content.getName().compareTo(parts[i]) > 0) { myLogger.fine("Logger wird in Liste eingefügt"); childNode = createNode(parts, i); currentNode.insert(childNode, j); currentNode = childNode; setFlag = true; break; } else if (content.getName().equals(parts[i])) { myLogger.fine("Pfad für Logger existiert bereits"); checkNode(parts, i, childNode); currentNode = childNode; setFlag = true; break; } } // Noch hier? Dann muss der Knoten angelegt werden if (!setFlag) { myLogger.fine("Logger wird an Liste angehängt"); childNode = createNode(parts, i); currentNode.add(childNode); currentNode = childNode; } } } return tree; }
7
@Override public void updatePlayersList(Players players) { playersInGame.removeAllElements(); for (Player player : players.getPlayers()) { playersInGame.addElement(player.getName() + " " + "(" + player.getRole() + ")"); } }
1
public void update(final Observable model, Object ignored) { if (_disposed) throw new IllegalStateException(); // Redraw the window SwingUtilities.invokeLater(new Runnable() { public void run() { // _content.repaint() causes a call to _content.paint(g) // where g is an appropriate graphics argument. _content.repaint(); }}); // Delay the main thread try { Thread.currentThread().sleep(_delay); } catch (InterruptedException e) {} }
2
@Override public void buildDough() { pizza.setDough("cross"); }
0
@Override public void mouseExited(MouseEvent e) { unprocessedEvents.add(e); mouse = new Point2D.Double(-1, -1); }
0
@Test public void EnsureNothingIsRemovedWhenNoLeadingTrailingSlashes() { String path = "x/y"; String newpath = Path.trimSlashes(path); assertEquals("x/y", newpath); }
0
public static Tile CONCRETE() { if (random.nextInt(100) == 0) { return WASTELAND_GROUND1; } else if (random.nextInt(100) == 0) { return WASTELAND_GROUND2; } else if (random.nextInt(100) == 0) { return WASTELAND_GROUND3; } else if (random.nextInt(100) == 0) { return WASTELAND_GROUND4; } else if (random.nextInt(100) == 0) { return WASTELAND_GROUND7; } else if (random.nextInt(100) == 0) { return WASTELAND_GROUND6; } else { return WASTELAND_GROUND5; } }
6