text
stringlengths
14
410k
label
int32
0
9
private Map<Integer, Double> calcUptime(File experiment) throws Exception{ //takes in a file, creates the average of each 1m distance bucket in terms of connected or not Map<Integer, List<Integer>> values = new HashMap<Integer, List<Integer>>(); BufferedReader reader = new BufferedReader(new FileReader(experiment)); int loc= 0; String line; boolean service = true; int connected = 0; while((line = reader.readLine()) != null) { //may need line assignment switch(line) { case "#Location:": String l = reader.readLine(); loc = (int)Math.round(Double.parseDouble(l.substring(l.indexOf("(")+1, l.indexOf(",")))); break; case "#HasService:": service = Boolean.parseBoolean(reader.readLine()); break; case "#ShouldBeConnected:": switch (reader.readLine()) { case "true": connected = 1; break; default: connected = 0; break; } if(!service) { if (values.containsKey(loc)) { values.get(loc).add(connected); } else { List<Integer> nl = new ArrayList<Integer>(); nl.add(connected); values.put(loc, nl); } } break; default: //do nothing break; } } reader.close(); Map<Integer, Double> average = new HashMap<Integer, Double>(); for (int location: values.keySet()) { double sum = 0; for (int conn: values.get(location)) { sum = sum + conn; } double av = (sum/values.get(location).size()); average.put(location, av); } return average; }
9
public static boolean matchesTypeName(Class<?> clazz, String typeName) { return (typeName != null && (typeName.equals(clazz.getName()) || typeName.equals(clazz.getSimpleName()) || (clazz.isArray() && typeName .equals(getQualifiedNameForArray(clazz))))); }
5
@Test public void canGetShoppingCart() { Map<Integer, Integer> sc = new LinkedHashMap<>(); try { insertShoppingCart(user1.getEmail(), prod_id1, 20); insertShoppingCart(user1.getEmail(), prod_id2, 10); sc = shoppingCart.getShoppingCart(user1); deleteShoppingCartUser(user1); } catch (WebshopAppException e) { e.printStackTrace(); } assertTrue((sc.size() == 2) && (sc.get(prod_id1) == 20) && (sc.get(prod_id2) == 10)); }
3
public int getType() { return type; }
0
public String getBoardSurface() { String ret = ""; for(int y = 0; y < 9; y++) { ret += "P" + (y+1); for(int x = 0; x < 9; x++) { Player player; if (attacker.getPieceTypeOnBoardAt(new Point(x, y)) > 0) player = attacker; else player = defender; Boolean existPiece = player.getPieceTypeOnBoardAt(new Point(x,y)) != Piece.NONE; if (player instanceof AheadPlayer && existPiece) ret += "+"; else if (player instanceof BehindPlayer && existPiece) ret += "-"; if (!existPiece) ret += " * "; else ret += player.getPieceOnBoardAt(new Point(x,y)).getName(true); } if (y != 8) ret += "\n"; } return ret; }
9
public void setTile(int x, int y, int num) { if(isTile(x,y)) sea[x][y] = num; }
1
public AutoCompletion(final JComboBox comboBox) { this.comboBox = comboBox; model = comboBox.getModel(); comboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!selecting) highlightCompletedText(0); } }); comboBox.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { if (e.getPropertyName().equals("editor")) configureEditor((ComboBoxEditor) e.getNewValue()); if (e.getPropertyName().equals("model")) model = (ComboBoxModel) e.getNewValue(); } }); editorKeyListener = new KeyAdapter() { public void keyPressed(KeyEvent e) { if (comboBox.isDisplayable()) comboBox.setPopupVisible(true); hitBackspace=false; switch (e.getKeyCode()) { // determine if the pressed key is backspace (needed by the remove method) case KeyEvent.VK_BACK_SPACE : hitBackspace=true; hitBackspaceOnSelection=editor.getSelectionStart()!=editor.getSelectionEnd(); break; // ignore delete key case KeyEvent.VK_DELETE : e.consume(); comboBox.getToolkit().beep(); break; } } }; // Bug 5100422 on Java 1.5: Editable JComboBox won't hide popup when tabbing out hidePopupOnFocusLoss=System.getProperty("java.version").startsWith("1.5"); // Highlight whole text when gaining focus editorFocusListener = new FocusAdapter() { public void focusGained(FocusEvent e) { highlightCompletedText(0); } public void focusLost(FocusEvent e) { // Workaround for Bug 5100422 - Hide Popup on focus loss if (hidePopupOnFocusLoss) comboBox.setPopupVisible(false); } }; configureEditor(comboBox.getEditor()); // Handle initially selected object Object selected = comboBox.getSelectedItem(); if (selected!=null) setText(selected.toString()); highlightCompletedText(0); }
8
private static boolean check(HashMap<String, Boolean> wordMap, String word, boolean isSub) { if (isSub && wordMap.containsKey(word)) { // don't check for the // original // word, only for sub-words System.out.println(word); return wordMap.get(word); } for (int len = 1; len < word.length(); ++len) { String sub = word.substring(0, len); if (wordMap.containsKey(sub) && wordMap.get(sub) && check(wordMap, word.substring(len), true)) { wordMap.put(word, true); return true; } } if (isSub) { wordMap.put(word, false); } return false; }
7
public static void main( String[] args ) throws InterruptedException, IOException { ExecutorService executeService = ThreadPool.getInstance().getExecutorService(); List<Future<Integer>> resultList = new ArrayList<Future<Integer>>(); //约车日期 String date = DateUtil.getFetureDay(7); String dateModel = NetSystemConfigurations.getSystemStringProperty("system.yueche.date.model", "auto"); if(dateModel.equals("config")){ date = NetSystemConfigurations.getSystemStringProperty("system.yueche.date", DateUtil.getFetureDay(7)); } //初始化代理信息 // Host host = ConfigHttpProxy.getInstance().getRandomHost(); System.out.println("抢车日期为:"+ date); YueCheHelper.waitForService(); if (YueCheHelper.isEnterCreakerModel()){ // 进入破解模式 // 速度肯定是最快的了 // 利用海驾的验证码漏洞,事先输入验证码,之后约车 System.out.println("Open Creak Model"); log.info("Open Creak Model"); CookieImgCodeHelper.getImageCodeCookie(); } for (String accoutId: AccountMap.getInstance().getXueYuanAccountMap().keySet()){ YueCheItem xy =AccountMap.getInstance().getXueYuanAccountMap().get(accoutId); if ( xy!=null){ if (YueCheHelper.isUseProxy()){ for ( int num = 0 ; num < YueCheHelper.getProxyNumPreUser(); num++){ YueCheTask yueCheTask = new YueCheTask(xy,date,ConfigHttpProxy.getInstance().getRandomHost()); resultList.add(executeService.submit(yueCheTask) ); } }else{ YueCheTask yueCheTask = new YueCheTask(xy,date,null); resultList.add(executeService.submit(yueCheTask) ); } } } executeService.shutdown(); for (Future<Integer> fs : resultList) { try { System.out.println(fs.get()); // 打印各个线程(任务)执行的结果 } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { executeService.shutdownNow(); e.printStackTrace(); return; } } System.out.println("请按任意键退出程序!"); System.in.read(); }
9
public void updateTab(int alg, int alg_){ if(permutation_.get(alg).size() == 0){ for(int i = 0 ; i < tab.size(); i++){ if(tab.get(i) == alg){ tab.remove(i); } } } boolean isOnTab = false; for(int i = 0 ; i < tab.size(); i++){ if(tab.get(i) == alg_){ isOnTab = true; } } if(!isOnTab){ tab.add(alg_); } }
6
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; } synchronized (updateLock) { // Blocks to avoid a select while the selector is used to bind the server connection. } // Select one last time to complete closing the socket. selector.wakeup(); try { selector.selectNow(); } catch (IOException ignored) { } }
9
public boolean pickAndExecuteAnAction(){ /* * if cashier has just started, go to position */ if (mOrders.size() > 0){ synchronized(mOrders) { for (MarketOrder iOrder : mOrders){ //notify customer if an order has been placed if ((iOrder.mStatus == EnumOrderStatus.PLACED) && (iOrder.mEvent == EnumOrderEvent.ORDER_PLACED)){ iOrder.mStatus = EnumOrderStatus.PAYING; processOrderAndNotifyPerson(iOrder); return true; } } } synchronized(mOrders) { for (MarketOrder iOrder : mOrders){ if ((iOrder.mStatus == EnumOrderStatus.PAID) && (iOrder.mEvent == EnumOrderEvent.ORDER_PAID)){ iOrder.mStatus = EnumOrderStatus.SENT; fulfillOrder(iOrder); return true; } } } } /* * if time for role change * DoLeaveMarket(); */ return false; }
7
@Override public Converter put(String key, Converter value) { Converter v = super.put(key, value); if (v != null) { throw new IllegalArgumentException("Duplicate Converter for " + key); } return v; }
2
public void dumpInstruction(TabbedPrintWriter writer) throws java.io.IOException { /* * Only print the comment if jump null, since otherwise the block isn't * completely empty ;-) */ if (jump == null) writer.println("/* empty */"); }
1
public void onKeyReleased(KeyEvent e) { switch (e.getKeyCode()) { case VK_UP: case VK_W: directions.remove(Direction.UP); break; case VK_DOWN: case VK_S: directions.remove(Direction.DOWN); break; case VK_RIGHT: case VK_D: directions.remove(Direction.RIGHT); break; case VK_LEFT: case VK_A: directions.remove(Direction.LEFT); break; } }
8
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(TampilanGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TampilanGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TampilanGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TampilanGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TampilanGUI().setVisible(true); } }); }
6
public int DoSet(Pos setPos, Stone myColor, boolean provisionalFlg) { int reverseCnt = 0; // 設置可能な方向をすべて取得 ArrayList<Pos> doSetDirection = canSetDirection(setPos, myColor); // 設置可能な方向があるか判断 if (doSetDirection.size() > 0) { // 設置開始位置に一石置くため、反転カウントに1加算 reverseCnt++; if (provisionalFlg) { setColor(setPos, myColor); } for (Pos direction : doSetDirection) { // 設置の開始位置をセット Pos nawPos = new Pos(setPos.getX(), setPos.getY()); // 移動できなくなるか、石が置ける場合は処理を終了 while (true) { nawPos.doMove(direction); // 探索先の石を取得 Stone nawStone = getColor(nawPos); if (nawStone == Stone.NONE || nawStone == myColor) { // 自分の石の場合 break; } else if (nawStone != myColor) { // 敵の石の場合 if (provisionalFlg) { setColor(nawPos, myColor); } reverseCnt++; } } } } return reverseCnt; }
8
@Override public void startSetup(Attributes atts) { String min = atts.getValue(A_MIN); String max = atts.getValue(A_MAX); String def = atts.getValue(A_DEFAULT); try { this.lowerBound = Integer.parseInt(min); this.upperBound = Integer.parseInt(max); this.defaultValue = Integer.parseInt(def); } catch (NumberFormatException e) { e.printStackTrace(); } super.startSetup(atts); }
1
@Test public void testTransform() { System.out.println("transform"); byte[] rawdata = {1,2,3,15,16}; boolean[] expResult = { false,false,false,false,false,false,false,true, false,false,false,false,false,false,true,false, false,false,false,false,false,false,true,true, false,false,false,false,true,true,true,true, false,false,false,true,false,false,false,false }; boolean[] result = TransformRawData.transform(rawdata); Assert.assertEquals(expResult.length, result.length); for(int i=0;i<result.length;i++){ System.out.println(result[i]+" "); } for(int i=0;i<expResult.length;i++){ System.out.println(String.format("Test %d Expected %s was %s",i,expResult[i],result[i])); Assert.assertEquals(expResult[i], result[i]); } }
2
private static void readData(String path) throws XMLStreamException { XMLInputFactory factory = XMLInputFactory.newInstance(); File file = new File(path); try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) { XMLStreamReader reader = factory.createXMLStreamReader(bufferedReader); FileWriter writer = new FileWriter(path); XMLParser parser = new XMLParser(reader); parser.parseXml(); List<Entry> entryList = parser.getEntries(); writer.writeToFile(entryList); System.out.println("Total entries: " + entryList.size()); System.out.println("Path to converted file: " + writer.getPath()); } catch (FileNotFoundException e) { System.err.printf("No such file"); } catch (IOException e) { System.err.println("Unexpected error: " + e.getMessage()); } }
2
private int checkFourOfAKind(int player) { int[] hand = new int[players[player].cards.size()]; int i = 0; for (int card : players[player].cards) { hand[i++] = card % 13; } int matchCount = 0; for (int j = 0; j < hand.length; j++) { for (int k = 0; k < hand.length; k++) { if (j != k) { if (hand[j] == hand[k]) { matchCount++; if (matchCount == 3) return hand[j]; } } } matchCount = 0; } return -1; }
6
public static void main(String args[]) throws RemoteException, MalformedURLException { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ClientView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ClientView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ClientView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ClientView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> ServerInterface server = new Server("rmi://localhost:1099/enshare_server", "."); AbstractClientController controller = new CentralizedClientController("rmi://localhost:1099/enshare_client", server); ClientView editor = new ClientView(controller); }
6
@EventHandler(priority = EventPriority.MONITOR) public void onSellTransaction(TransactionEvent event) { if (event.getTransactionType() != SELL) { return; } String firstLine = SELL_TRANSACTION_FIRST_LINE .replace("%client", event.getClient().getName()) .replace("%stock", parseItemInformation(event.getStock())); String secondLine = SELL_TRANSACTION_SECOND_LINE .replace("%owner", event.getOwner().getName()) .replace("%price", Economy.formatBalance(event.getPrice())); Notification notification = new Notification("ChestShop", firstLine, secondLine); notifications.showNotification(notification); }
1
@Override /** * This method will be used by the table component to get * value of a given cell at [row, column] */ public Object getValueAt(int rowIndex, int columnIndex) { Object value = null; Contestant contestant = contestants.get(rowIndex); switch (columnIndex) { case COLUMN_CONTESTANT: value = contestant.getUsername(); break; case COLUMN_PROBLEMS_SOLVED: value = contestant.getProblemsSolved(); break; case COLUMN_PENALTY: value = contestant.getPenalty(); break; } return value; }
3
@Override protected void fixAfterInsertion(N x) { x.setColour(RED); while (x != null && x != getRoot() && x.getParent().getColour() == RED) { if (parentOf(x) == leftOf(parentOf(parentOf(x)))) { N y = rightOf(parentOf(parentOf(x))); if (colorOf(y) == RED) { setColor(parentOf(x), BLACK); setColor(y, BLACK); setColor(parentOf(parentOf(x)), RED); x = parentOf(parentOf(x)); } else { if (x == rightOf(parentOf(x))) { x = parentOf(x); rotateLeft(x); } setColor(parentOf(x), BLACK); setColor(parentOf(parentOf(x)), RED); rotateRight(parentOf(parentOf(x))); } } else { N y = leftOf(parentOf(parentOf(x))); if (colorOf(y) == RED) { setColor(parentOf(x), BLACK); setColor(y, BLACK); setColor(parentOf(parentOf(x)), RED); x = parentOf(parentOf(x)); } else { if (x == leftOf(parentOf(x))) { x = parentOf(x); rotateRight(x); } setColor(parentOf(x), BLACK); setColor(parentOf(parentOf(x)), RED); rotateLeft(parentOf(parentOf(x))); } } } getRoot().setColour(BLACK); }
8
@SuppressWarnings("static-access") @EventHandler(priority = EventPriority.HIGH) public void onMobDeath (EntityDeathEvent event) { Entity entity = event.getEntity(); World world = event.getEntity().getWorld(); if (entity instanceof Skeleton) { Skeleton lich = (Skeleton) entity; Location lichLoc = lich.getLocation(); if (MMLich.isLich(lich)) { try { world.playSound(lichLoc, Sound.GHAST_DEATH, 1.0F, - 1.0F); event.getDrops().clear(); if (entity.getLastDamageCause().getCause().equals(DamageCause.ENTITY_ATTACK)) { event.setDroppedExp(15); } } catch (Exception ex) { return; } } } }
4
private void verifyEntry(Entry entry) { for (Object key : entry.getExtensionAttributes().keySet()) { QName qname = (QName) key; // Foundation 1.9 assertEquals(NAMESPACE, qname.getNamespaceURI()); } // Atom 2.2 assertTrue(entry.getId().toString().contains("urn:uuid:")); String uuid = entry.getId().toString().replace("urn:uuid:", ""); // Atom 2.3.1 assertTrue(entry.getCategories().size() > 0); Category typeCategory = findCategory(SrampAtomConstants.X_S_RAMP_TYPE, entry); assertNotNull(typeCategory); if (typeCategory.getTerm().equals("query") || typeCategory.getTerm().equals("classification")) { // Do nothing: stored query or classification. } else { // Else, assume it's an artifact. ArtifactType artifactType = SrampAtomUtils.getArtifactTypeFromEntry(entry); if (artifactType.isDocument()) { // Atom 2.3.5.3 -- verify /media returns the content. verifyMedia(uuid, artifactType); } // TODO: Not sure if this is correct. In Overlord, the term is the name of the extended type, // not "ExtendedArtifactType" if (! artifactType.isExtendedType()) { assertEquals(artifactType.getArtifactType().getType(), typeCategory.getTerm()); } // verify :kind Category kindCategory = findCategory(SrampAtomConstants.X_S_RAMP_KIND, entry); assertNotNull(kindCategory); if (artifactType.isDerived()) { assertEquals("derived", kindCategory.getTerm()); } else { assertEquals("modeled", kindCategory.getTerm()); } } }
6
public void setAction(final Action action) { if (this.action != null) { removeActionListener(this.action); action.removePropertyChangeListener(this); } this.action = action; String imgName = LARGE_ICONS.equals(iconDisplay) ? (String) action.getValue(Action.IMAGE_PATH) : ( SMALL_ICONS.equals(iconDisplay) ? (String) action.getValue(Action.SMALL_IMAGE_PATH) : null); Image img = null; if (imgName != null) { img = UIUtil.loadImage(action.getClass(), imgName); if (img != null) { setImage(UIUtil.waitFor(img, this)); } } Boolean hide = (Boolean) action.getValue(Action.HIDE_TOOLBAR_TEXT); setToolTipText((String)action.getValue(Action.LONG_DESCRIPTION)); setText( (String) action.getValue(Action.NAME)); // Also show text if icons were requested but this one is not available - prevents empty buttons setTextVisible( img == null || SHOW_TEXT.equals(textDisplay) || ( SELECTIVE_TEXT.equals(textDisplay) && ( hide == null || !hide.booleanValue() ) )); addActionListener(action); setEnabled(action.isEnabled()); action.addPropertyChangeListener(this); }
9
private static HashMap<String, HashMap<String, Double>> getMap() throws Exception { BufferedReader reader = new BufferedReader(new FileReader(ConfigReader.getMbqcDir() + File.separator + "dropbox" + File.separator + "raw_design_matrix.txt")); HashMap<String, HashMap<String, Double>> map =new LinkedHashMap<String, HashMap<String,Double>>(); List<String> taxa = new ArrayList<String>(); String[] headerSplits = reader.readLine().split("\t"); int x=4; while(headerSplits[x].startsWith("k__")) { taxa.add(getPhyla(headerSplits[x])); x++; } x+=2; for(String s = reader.readLine(); s!= null; s= reader.readLine()) { //System.out.println(s); String[] splits = s.split("\t"); HashMap<String, Double> innerMap = map.get(splits[0]); if( innerMap == null) { innerMap = new HashMap<String, Double>(); map.put(splits[0], innerMap); } for(int y=0; y < taxa.size(); y++) { String thisTaxa = taxa.get(y); if( innerMap.containsKey(thisTaxa) ) throw new Exception("Unexpected duplicate " + s); if( ! splits[y+4].equals("NA")) innerMap.put(thisTaxa, Double.parseDouble(splits[y+4])); } } reader.close(); return map; }
6
public Obstacle(){ super((Math.random()*Board.getWIDTH()-Board.robots.get(0).getWidth()), (Math.random()*Board.getHEIGHT()-Board.robots.get(0).getHeight()), 0.0f); switch(Board.getTheme()){ case "Desert": ii = new ImageIcon(this.getClass().getResource("/resources/images/scenarios/desertObject.png")); break; case "Forest": ii = new ImageIcon(this.getClass().getResource("/resources/images/scenarios/forestObject.png")); break; case "Spacial": ii = new ImageIcon(this.getClass().getResource("/resources/images/scenarios/specialObject.png")); break; case "Sea": ii = new ImageIcon(this.getClass().getResource("/resources/images/scenarios/seaObject.png")); break; default: ii = new ImageIcon(this.getClass().getResource("/resources/images/scenarios/desertObject.png")); break; } this.image = ii.getImage(); this.width = ii.getIconWidth(); this.height = ii.getIconHeight(); this.value = 2; // this.degrees = Math.random()*360 + 1; this.degrees = 0; }
4
protected void handleTaskSubmittedRequest(Runnable runnable, Address source, long requestId, long threadId) { // We store in our map so that when that task is // finished so that we can send back to the owner // with the results _running.put(runnable, new Owner(source, requestId)); // We give the task to the thread that is now waiting for it to be returned // If we can't offer then we have to respond back to // caller that we can't handle it. They must have // gotten our address when we had a consumer, but // they went away between then and now. boolean received; try { _tasks.put(threadId, runnable); CyclicBarrier barrier = _taskBarriers.remove(threadId); if (received = (barrier != null)) { // Only wait 10 milliseconds, in case if the consumer was // stopped between when we were told it was available and now barrier.await(10, TimeUnit.MILLISECONDS); } } catch (InterruptedException e) { if (log.isDebugEnabled()) log.debug("Interrupted while handing off task"); Thread.currentThread().interrupt(); received = false; } catch (BrokenBarrierException e) { if (log.isDebugEnabled()) log.debug("Consumer " + threadId + " has been interrupted, " + "must retry to submit elsewhere"); received = false; } catch (TimeoutException e) { if (log.isDebugEnabled()) log.debug("Timeout waiting to hand off to barrier, consumer " + threadId + " must be slow"); // This should only happen if the consumer put the latch then got // interrupted but hadn't yet removed the latch, should almost never // happen received = false; } if (!received) { // Clean up the tasks request _tasks.remove(threadId); if (log.isDebugEnabled()) log.debug("Run rejected not able to pass off to consumer"); // If we couldn't hand off the task we have to tell the client // and also reupdate the coordinator that our consumer is ready sendRequest(source, Type.RUN_REJECTED, requestId, null); _running.remove(runnable); } }
9
public void listShowTimes() { int index = 0; _showTimes = new ArrayList<ShowTime>(); // To be used for update and remove showTime System.out.println("ShowTimes"); System.out.println("========="); for(Cineplex cineplex: cineplexBL.getCineplexes()) { List<Movie> movies = cineplex.getMovies(); if(movies.size() == 0) { continue; } System.out.println(cineplex.getCineplexName()); System.out.println("-----------------------------------"); for(Movie movie: movies) { List<ShowTime> showTimes = showTimeBL.getShowTimes(movie, cineplex); if(showTimes.size() == 0) { continue; } System.out.println(movie.getTitle()); System.out.println("********************************"); Hashtable<String, List<ShowTime>> showTimeHashTable = new Hashtable<String, List<ShowTime>>(); //Preprocessing for showTime to follow the cathay format for(ShowTime st: showTimes) { String d = new SimpleDateFormat("d MMM, E").format(st.getTime()); if(showTimeHashTable.get(d) == null) { showTimeHashTable.put(d, new ArrayList<ShowTime>()); } showTimeHashTable.get(d).add(st); } for(Enumeration<String> e = showTimeHashTable.keys();e.hasMoreElements();) { String dateString = e.nextElement(); System.out.print(dateString); for(ShowTime showTime: showTimeHashTable.get(dateString)) { // showTime can be accessed using the index. It is in the sequence it is printed. // index starts at zero even though the index printed out start at 1. -1 before accessing. _showTimes.add(showTime); String time = new SimpleDateFormat("HH:mm").format(showTime.getTime()); System.out.print("\t[" + (index+1) + "] " + time); index++; } System.out.println(); } System.out.println(); } } }
8
public void actionPerformed(ActionEvent event) { Universe.frameForEnvironment(environment).save(true); }
0
@Override public String saveNewAlbum(Album album) throws RemoteException { try { List<Album> albums = getAlbums(); album.setUuid(UUID.randomUUID().toString()); List<Artist> artists = getArtists(); Artist artist = null; for (Artist artist1 : artists){ if (artist1.getName().equals(album.getArtist().getName())){ artist = artist1; } } if (artist == null){ artist = saveNewArtist(album.getArtist()); } album.setArtist(artist); albums.add(album); FileOutputStream fileOutputStream = new FileOutputStream(path.concat(albumsSERFile)); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); objectOutputStream.writeObject(albums); objectOutputStream.close(); fileOutputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return path.concat(albumsSERFile).concat(" nicht gefunden!"); } catch (IOException e) { e.printStackTrace(); } return album.toString().concat(" erfolgreich in ").concat(albumsSERFile).concat(" geschrieben!"); }
5
private void doUrls(Document oDoc) throws ForceErrorException, SQLException { // TODO StringIndexOutOfBoundsException Elements oLinks = oDoc.select("a[href]"); HashMap<String, Link> links = new HashMap<String, Link>(); int counter = 0; for (Element oLink : oLinks) { counter++; if (counter > Bot.maxDoLinks) { break; } Link tmpLink; try { tmpLink = new Link(oLink.attr("href"), this.url); if (!tmpLink.isValid()) { continue; } } catch (MalformedURLException e) { /* * błąd tworzenia urla, więc go pomiń */ continue; } if (!(links.containsKey(tmpLink.getUrl()))) { links.put(tmpLink.getUrl(), tmpLink); } } ArrayList<Link> linkMap = new ArrayList<Link>(links.values()); /* * Dobierz się do mapy w koleności losowej */ Collections.shuffle(linkMap); /** * Zapisz linki przychodzące jako mapę */ this.saveInboudMap(linkMap); this.saveLinks(linkMap); }
5
public static final HashMap<String, Course> loadCourseCatalog() throws IOException { LOGGER.log(Level.INFO, "Loading course catalog.."); HashMap<String, Course> courses = new HashMap<String, Course>(); JSONParser parser = new JSONParser(); File[] files = new File(COURSE_ROOT).listFiles(); for (File file : files) { if (file.isDirectory()) { Course course = readCourse(new File(file + "/course.json")); for (File definitionFile : file.listFiles()){ try { // Course definition if (!definitionFile.getCanonicalPath().contains("course.json")) { LOGGER.log(Level.INFO, "Adding hole to course '" + course.getName() + "'"); course.addHole(readHole(definitionFile)); } else { // Hole definition } } catch (IOException e) {e.printStackTrace();} } courses.put(course.getName(), course); LOGGER.log(Level.INFO, "Loaded course '" + course.getName() + "'"); } else {/* Do nothing */} } LOGGER.log(Level.INFO, "Loaded course catalog"); return courses; }
5
public String getTime() { return time; }
0
private void closeStatement(Statement statement) { try (Connection connection = statement.getConnection();) { connection.commit(); statement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } }
1
public int[][] makeReflection(int img[][], int kernel) { for (int i = 0; i < img.length; i++) { for (int j = 0; j < img[i].length; j++) { //---- Top ----// if (i == 0) { int a = i+2; //if(a>9) a=9; if(a>img.length) a=img.length; img[i][j] = img[a][j]; } //---- Left ----// else if ((i != 0) && (j == 0)) { int a = j+2; img[i][j] = img[i][a]; } //---- Bottom -----// else if (i == img.length - 1) { int a = i-2; img[i][j] = img[a][j]; } //---- Right ----// else if ((i > 0) && (j == img.length-1)) { int a = j-2; img[i][j] = img[i][a]; } //----- inside ----// else { //System.out.format("%3s ", "x"); //System.out.format("%3d ", img[i][j]); } } } //--- LeftTop Corner ---// img[0][0] = img[kernel-1][kernel-1]; //---- LeftBottom Corner ---// img[img.length-1][0] = img[img.length-1][kernel-1]; //--- RightTop Corner ---// img[0][img.length-1] = img[kernel-1][img.length-1]; //--- RightBottom Corner ---// img[img.length-1][img.length-1] = img[img.length-3][img.length-3]; return img; }
9
@Override public void run() { try { bw = new BufferedReader(new InputStreamReader( client.getInputStream())); try { while (true) { String line = bw.readLine(); server.handleMessage(clientNR, line); } } catch (IOException e) { e.printStackTrace(); } } catch (IOException e1) { e1.printStackTrace(); } }
3
private void linkSrgDataToCsvData() { for (Entry<String, MethodSrgData> methodData : srgFileData.srgMethodName2MethodData.entrySet()) { if (!srgMethodData2CsvData.containsKey(methodData.getValue()) && csvMethodData.hasCsvDataForKey(methodData.getKey())) { srgMethodData2CsvData.put(methodData.getValue(), csvMethodData.getCsvDataForKey(methodData.getKey())); } else if (srgMethodData2CsvData.containsKey(methodData.getValue())) System.out.println("SRG method " + methodData.getKey() + " has multiple entries in CSV file!"); } for (Entry<String, FieldSrgData> fieldData : srgFileData.srgFieldName2FieldData.entrySet()) { if (!srgFieldData2CsvData.containsKey(fieldData.getValue()) && csvFieldData.hasCsvDataForKey(fieldData.getKey())) { srgFieldData2CsvData.put(fieldData.getValue(), csvFieldData.getCsvDataForKey(fieldData.getKey())); } else if (srgFieldData2CsvData.containsKey(fieldData.getValue())) System.out.println("SRG field " + fieldData.getKey() + " has multiple entries in CSV file!"); } }
8
private void validate() { if ( ( getPresentCount() != COUNT_DEFAULT ) && ( getPresentCharacters().size() > 0 ) && ( getPresentCount() != getPresentCharacters().size() ) ) { throw new IllegalStateException( "present characters size and count are unequal" ); } if ( ( getGainedCount() != COUNT_DEFAULT ) && ( getGainedCharacters().size() > 0 ) && ( getGainedCount() != getGainedCharacters().size() ) ) { throw new IllegalStateException( "gained characters size and count are unequal" ); } if ( ( getLostCount() != COUNT_DEFAULT ) && ( getLostCharacters().size() > 0 ) && ( getLostCount() != getLostCharacters().size() ) ) { throw new IllegalStateException( "lost characters size and count are unequal" ); } }
9
public SqlParameter(int type, Object value) { this.type = type; this.value = value; }
0
public void tickDownStatuses(int currentPlayerIndex) { // Tick down all of the tile's status effects. for (TileStatus status : statuses) { status.tickDown(currentPlayerIndex); if (status.getRemainingDuration() <= 0) { statuses.remove(status); //TODO: If we had multiple statuses, then this would cause visual problems. this.setBackground(PropertiesLoader.getColour("normal_tile")); } } }
2
public boolean Apagar(Endereco obj){ try{ PreparedStatement comando = banco.getConexao() .prepareStatement("UPDATE enderecos SET ativo = 0 WHERE id= ?"); comando.setInt(1, obj.getId()); comando.getConnection().commit(); return true; }catch(SQLException ex){ ex.printStackTrace(); return false; } }
1
public static void playerTurn(Scanner scan, Color player, Board board) { boolean cont = true; while (cont) { System.out.printf("Column to play %s on: ", player.getChar()); int num = 0; // Gets the players column choice and drops their token there try { num = scan.nextInt(); // Check that it's a valid column if (num > 6 || num < 0) { System.out.printf("%d is not a valid number!\n", num); } else if (board.dropColumn(num, player)) { cont = false; } else { System.out.println("That column is full. Please try another."); } } catch (java.util.InputMismatchException e) { System.out.printf("%s is not a valid number! Please try again!\n", scan.next()); } } }
5
public static void main(String[] args) { int p[] = { 0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30}; TDRodCutting topDown = new TDRodCutting(10, p); System.out.println("Read as, Length of Rod : Cuts : Maximal Revenue"); for ( int i = 1; i <= topDown.n; i++) System.out.println(i + " : " + topDown.cuts[i] + " : " + topDown.r[i]); }
1
@SuppressWarnings("nls") public void write(File file) { try (PrintWriter out = new PrintWriter(new BufferedOutputStream(new FileOutputStream(file)))) { mOut = out; mDepth = 0; mOut.println("<?xml version=\"1.0\" ?>"); mOut.println("<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">"); mOut.println("<plist version=\"1.0\">"); mDepth++; startDictionary(); emitKeyValue("CFBundleDevelopmentRegion", "English"); emitKeyValue("CFBundleExecutable", mExecutableName); emitKeyValue("CFBundleIconFile", "app.icns"); emitKeyValue("CFBundleIdentifier", mId); emitKeyValue("CFBundleName", mName); emitKeyValue("CFBundleInfoDictionaryVersion", "6.0"); emitKeyValue("CFBundlePackageType", "APPL"); emitKeyValue("CFBundleShortVersionString", Version.toString(mVersion, false)); emitKeyValue("CFBundleVersion", Version.toString(mVersion, true)); emitKeyValue("CFBundleSignature", mSignature); emitKeyValue("LSApplicationCategoryType", mCategory); emitKeyValues("LSArchitecturePriority", "x86_64", "i386"); emitKey("LSEnvironment"); startDictionary(); emitKeyValue("LC_CTYPE", "UTF-8"); endDictionary(); emitKeyValue("LSMinimumSystemVersion", "10.7.0"); emitKeyValue("NSHumanReadableCopyright", getCopyrightBanner()); emitKeyValue("NSHighResolutionCapable", true); emitKeyValue("NSSupportsAutomaticGraphicsSwitching", true); FileType[] openable = FileType.getOpenable(); if (openable.length > 0) { emitKey("CFBundleDocumentTypes"); startArray(); for (FileType type : openable) { startDictionary(); emitKeyValue("CFBundleTypeName", type.getDescription()); String extension = type.getExtension(); emitKeyValue("CFBundleTypeIconFile", extension + ".icns"); emitKeyValue("CFBundleTypeRole", "Editor"); emitKeyValue("LSHandlerRank", "Owner"); emitKeyValues("LSItemContentTypes", mId + "." + extension); endDictionary(); } endArray(); emitKey("UTExportedTypeDeclarations"); startArray(); for (FileType type : openable) { startDictionary(); String extension = type.getExtension(); emitKeyValue("UTTypeIdentifier", mId + "." + extension); emitKeyValue("UTTypeReferenceURL", type.getReferenceURL()); emitKeyValue("UTTypeDescription", type.getDescription()); emitKeyValue("UTTypeIconFile", extension + ".icns"); emitKeyValues("UTTypeConformsTo", "public.xml", "public.data"); emitKey("UTTypeTagSpecification"); startDictionary(); emitKeyValue("com.apple.ostype", "." + extension); emitKeyValues("public.filename-extension", extension); emitKeyValue("public.mime-type", "application/" + mExecutableName + "." + extension); endDictionary(); endDictionary(); } endArray(); } endDictionary(); mDepth--; mOut.println("</plist>"); mOut.flush(); } catch (Exception exception) { Log.error(exception); } }
4
public static void main(String[] args) { ArrayList<ArrayList<Integer>> lists = new ArrayList<ArrayList<Integer>>(); lists.add(new ArrayList<Integer>()); lists.add(new ArrayList<Integer>()); setReader(); int row = 1; ArrayList<Integer> newList = lists.get(row%2); ArrayList<Integer> oldList = lists.get((row+1)%2); //row 1 newList.add(reader.nextInt()); row++; while(reader.hasNext()) { newList = lists.get(row%2); oldList = lists.get((row+1)%2); newList.clear(); //first column newList.add( reader.nextInt() + oldList.get(0) ); //middle columns for(int i = 1; i < row-1; i++) newList.add( reader.nextInt() + Math.max(oldList.get(i-1), oldList.get(i)) ); //last column newList.add( reader.nextInt() + oldList.get(oldList.size()-1) ); row++; } int max = Integer.MIN_VALUE; for(int num : newList) if( num > max ) max = num; System.out.println(max); }
4
public LongDataType getCounter() { return counter; }
0
public void setVisible(boolean paramBoolean) { this.Visible = paramBoolean; PhysicalObject localPhysicalObject; int i; String str; if (paramBoolean) { Enumeration localEnumeration = this.Loopers.elements();////<Vector> while (localEnumeration.hasMoreElements()) { localPhysicalObject = (PhysicalObject)localEnumeration.nextElement(); if (!isInWindow(localPhysicalObject)) { continue; } this.CurrentlyLooping.addElement(localPhysicalObject); Vector localObject = localPhysicalObject.getLoopList();//// for (i = 0; i < ((Vector)localObject).size(); i++) { str = (String)((Vector)localObject).elementAt(i); GameApplet.audio.loop(str, localPhysicalObject); } } return; } Enumeration localEnumeration = this.Players.elements(); while (localEnumeration.hasMoreElements()) { localPhysicalObject = (PhysicalObject)localEnumeration.nextElement(); Vector localObject = localPhysicalObject.getPlayList(); for (i = 0; i < ((Vector)localObject).size(); i++) { GameApplet.audio.stop((String)((Vector)localObject).elementAt(i), localPhysicalObject); } ((Vector)localObject).removeAllElements(); } this.Players.removeAllElements(); Object localObject = this.CurrentlyLooping.elements(); while (((Enumeration)localObject).hasMoreElements()) { localPhysicalObject = (PhysicalObject)((Enumeration)localObject).nextElement(); Vector localVector = localPhysicalObject.getLoopList(); for (int j = 0; j < localVector.size(); j++) { str = (String)localVector.elementAt(j); GameApplet.audio.stop(str, localPhysicalObject); } } this.CurrentlyLooping.removeAllElements(); }
8
public void InsertaFinal(int ElemInser) { if ( VaciaLista()) { PrimerNodo = new NodosProcesos (ElemInser); PrimerNodo.siguiente = PrimerNodo; } else { NodosProcesos Aux = PrimerNodo; while (Aux.siguiente != PrimerNodo) Aux = Aux.siguiente; NodosProcesos Nuevo=new NodosProcesos (ElemInser); Aux.siguiente = Nuevo; Nuevo.siguiente = PrimerNodo; //Referencia hacia primer Nodo } }
2
@SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { lbNome = new javax.swing.JLabel(); tfNome = new javax.swing.JTextField(); tfEndereco = new javax.swing.JTextField(); lbBairro = new javax.swing.JLabel(); comboCidade = new javax.swing.JComboBox(); comboBairro = new javax.swing.JComboBox(); lbEndereco = new javax.swing.JLabel(); lbNuemro = new javax.swing.JLabel(); tfNumero = new javax.swing.JTextField(); lbTelefone = new javax.swing.JLabel(); tfTelefone = new javax.swing.JFormattedTextField(); lbCelular = new javax.swing.JLabel(); tfCelular = new javax.swing.JFormattedTextField(); btCancelar = new javax.swing.JButton(); btSalvar = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); tfCep = new javax.swing.JFormattedTextField(); jLabel10 = new javax.swing.JLabel(); tfEstado = new javax.swing.JTextField(); jLabel11 = new javax.swing.JLabel(); tfEmail = new javax.swing.JTextField(); tfCpf = new javax.swing.JFormattedTextField(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jLabel12 = new javax.swing.JLabel(); tfWhats = new javax.swing.JFormattedTextField(); lbCelular1 = new javax.swing.JLabel(); cWhats = new javax.swing.JCheckBox(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); setResizable(false); lbNome.setText("NOME"); lbBairro.setText("BAIRRO"); comboCidade.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecionar...." })); comboCidade.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseExited(java.awt.event.MouseEvent evt) { comboCidadeMouseExited(evt); } }); comboCidade.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { comboCidadeActionPerformed(evt); } }); comboBairro.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecionar..." })); comboBairro.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { comboBairroMouseClicked(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { comboBairroMouseEntered(evt); } }); comboBairro.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { comboBairroActionPerformed(evt); } }); lbEndereco.setText("ENDEREÇO"); lbEndereco.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); lbNuemro.setText("NÚMERO"); lbNuemro.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); lbTelefone.setText("TELEFONE"); lbTelefone.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); try { tfTelefone.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##) ####-####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } tfTelefone.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tfTelefoneActionPerformed(evt); } }); lbCelular.setText("CELULAR"); lbCelular.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); try { tfCelular.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##) ####-####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } tfCelular.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { tfCelularKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { tfCelularKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { tfCelularKeyTyped(evt); } }); btCancelar.setText("CANCELAR"); btCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btCancelarActionPerformed(evt); } }); btSalvar.setText("SALVAR"); btSalvar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btSalvarActionPerformed(evt); } }); jLabel5.setText("CPF"); jLabel9.setText("CEP"); try { tfCep.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("#####-###"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } tfCep.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tfCepActionPerformed(evt); } }); jLabel10.setText("ESTADO"); jLabel11.setText("E-MAIL"); try { tfCpf.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } jButton1.setText("+"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("+"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jLabel12.setText("CIDADE"); try { tfWhats.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##) ####-####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } lbCelular1.setText("WhatsApp"); lbCelular1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); cWhats.setSelected(true); cWhats.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cWhatsActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(23, 23, 23) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(71, 71, 71) .addComponent(btCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 196, Short.MAX_VALUE) .addComponent(btSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(80, 80, 80)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(375, 375, 375) .addComponent(jLabel10)) .addGroup(layout.createSequentialGroup() .addGap(375, 375, 375) .addComponent(tfEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(comboCidade, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tfTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbTelefone)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lbCelular) .addGroup(layout.createSequentialGroup() .addComponent(tfCelular, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(cWhats))))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(6, 6, 6) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(lbBairro) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(comboBairro, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(119, 119, 119)))) .addGroup(layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tfWhats, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbCelular1)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel11) .addComponent(tfEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE)))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tfNome, javax.swing.GroupLayout.PREFERRED_SIZE, 310, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tfEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, 348, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbNome) .addComponent(jLabel12) .addComponent(lbEndereco)) .addGap(29, 29, 29) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(lbNuemro) .addGap(85, 85, 85) .addComponent(jLabel9) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(tfNumero, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(tfCep, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(73, 73, 73)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addComponent(tfCpf, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(35, 35, 35) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lbNome) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tfNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tfCpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(lbEndereco)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lbNuemro) .addComponent(jLabel9))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tfEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tfNumero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tfCep, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jLabel12) .addGap(15, 15, 15)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lbBairro, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel10)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(comboCidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1) .addComponent(comboBairro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton2) .addComponent(tfEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(38, 38, 38) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lbTelefone) .addComponent(lbCelular) .addComponent(lbCelular1) .addComponent(jLabel11)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tfTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tfCelular, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tfWhats, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tfEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(cWhats, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(69, 69, 69) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE) .addComponent(btSalvar, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)) .addContainerGap()) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents
5
public static ArrayList<MeetingRoom> searchRoomByID(String ID) { try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ArrayList<MeetingRoom> rooms = new ArrayList<MeetingRoom>(); try { PreparedStatement stmnt = conn.prepareStatement("SELECT * FROM MeetingRooms WHERE room_id LIKE ? "); stmnt.setString(1, ID + "%"); ResultSet res; res = stmnt.executeQuery(); while(res.next()){ meetingroom = new MeetingRoom(res.getInt("room_id"), res.getInt("floor"),res.getInt("seats_amount"), res.getString("name")); rooms.add(meetingroom); } } catch(SQLException e){ e.printStackTrace(); } return rooms; }
5
@Override public void parse(CommandInvocation invocation, List<ParsedParameter> params, List<Parameter> suggestions) { ParsedParameter pParam = this.parseValue(invocation); if (!params.isEmpty() && params.get(params.size() - 1).getParameter().equals(pParam.getParameter())) { ParsedParameter last = params.remove(params.size() - 1); String joined = last.getParsedValue() + " " + pParam.getParsedValue(); pParam = ParsedParameter.of(pParam.getParameter(), joined, joined); } params.add(pParam); }
2
@Override public void keyReleased(KeyEvent e) { if ((e.getKeyCode() == KeyEvent.VK_W) || (e.getKeyCode() == KeyEvent.VK_UP)) { jumpKeyPressed = false; } if ((e.getKeyCode() == KeyEvent.VK_D) || (e.getKeyCode() == KeyEvent.VK_RIGHT)) { rightKeyPressed = false; } if ((e.getKeyCode() == KeyEvent.VK_A) || (e.getKeyCode() == KeyEvent.VK_LEFT)) { leftKeyPressed = false; } }
6
public static void writeElementEnd( StringBuffer buf, int depth, String line_ending, String name ) throws IllegalArgumentException { if (isValidXMLElementName(name)) { indent(buf, depth); buf.append("</").append(name).append(">"); if (line_ending != null) { buf.append(line_ending); } } else { throw new IllegalArgumentException("Invalid element name: " + name); } }
2
private boolean nextPerm(int[] inPerm){ // returns true if this was successful in finding the next permutation int[] outPerm = new int[inPerm.length]; for(int i = 0; i < outPerm.length; i++){ outPerm[i] = inPerm[i]; } // have function (incrementWolf) which returns the next wolf ID, or zero if none // run increment wolf on last wolf // if zero, run on previous until not zero. // then run on wolves skipped over to end. int p = 0; int i = inPerm.length; do { i--; p = incrementID(i, inPerm); if(p == -1) break; outPerm[i] = p; } while((p == 0) && (i != -1)); if(i == -1) return false; // This was the final permutation, inPerm remains unchanged. for(i = 0; i < inPerm.length; i++){ if(outPerm[i] == 0){ outPerm[i] = incrementID(i, outPerm); } } // outPerm now contains the next permutation for(int n = 0; n < inPerm.length; n++){ inPerm[n] = outPerm[n]; } // inPerm is updated to next permutation return true; }
8
@Override public int compareTo(HelperPoint o) { if (o.relX == relX && o.relY == relY) return 0; int f = this.relativeCross(o); boolean isLess = f > 0 || f == 0 && relativeMDist() > o.relativeMDist(); return isLess ? -1 : 1; }
5
@Override public boolean fits(HasPosition p) { /* * Check if fits inside the container (i.e parent) */ if (! ( (getLeftUpperCornerX() <= p.getLeftUpperCornerX()) && (getLeftUpperCornerX() + getWidth() >= p.getLeftUpperCornerX() + p.getWidth()) && (getLeftUpperCornerY() <= p.getLeftUpperCornerY()) && (getLeftUpperCornerY() + getHeight() >= p.getLeftUpperCornerY() + p.getHeight()))) return false; /** * Checks overlapping with children */ for (HasPosition child : getChildren()) { if (child == p){ continue; } if (! child.clears(p)) return false; } /** * No overlapping with the children or the block itself */ return true; }
7
public static void main(String[] args) { for (Seasons season : Seasons.values()) { System.out.println(season.name() + " -> " + season); System.out.println("getName(): " + season.getName() + " getId():" + season.getId()); } }
1
public static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double)o).isInfinite() || ((Double)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float)o).isInfinite() || ((Float)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } }
7
private boolean evaluateMvdClause(String clause) { if (model instanceof MesoModel) return false; if (clause == null || clause.equals("")) return false; String[] sub = clause.split(REGEX_AND); Mvd.Parameter[] par = new Mvd.Parameter[sub.length]; boolean scalar = false; byte id; float vmax; String direction; for (int n = 0; n < sub.length; n++) { int i = sub[n].indexOf("within"); String str = i == -1 ? sub[n] : sub[n].substring(0, i).trim(); try { String[] s = str.split(REGEX_SEPARATOR + "+"); scalar = Boolean.valueOf(s[0].trim()).booleanValue(); direction = s[1].trim(); vmax = Float.valueOf(s[2].trim()).floatValue(); id = Float.valueOf(s[3].trim()).byteValue(); } catch (Exception e) { out(ScriptEvent.FAILED, "Script error at: " + str + "\n" + e); return false; } if (i >= 0) { str = sub[n].substring(i).trim(); Matcher matcher = WITHIN_RECTANGLE.matcher(str); if (matcher.find()) { Rectangle2D area = getWithinArea(str); if (area == null) return false; par[n] = new Mvd.Parameter(scalar, direction, vmax, id, area); } } else { par[n] = new Mvd.Parameter(scalar, direction, vmax, id, model.boundary); } } ((AtomicModel) model).showMVD(par); return true; }
9
public boolean deleteGroup(int groupId) { Connection connection = ConnectionManager.getConnection(); if (connection == null) { logger.log(Level.SEVERE, "Couln't establish a connection to database"); return false; } TopicManager topicManager = new TopicManager(); List<TopicManager.Topic> topicList = topicManager.getAllChildrenTopics(groupId); List<Group> groupList = getAllChildrenGroup(groupId); for (TopicManager.Topic topic : topicList) { topicManager.deleteTopic(topic.getId()); } for (Group group : groupList) { deleteGroup(group.getId()); } try { PreparedStatement ps = connection.prepareStatement(DELETE_GROUP_BY_ID_QUERY); ps.setInt(1, groupId); return ps.execute(); } catch (SQLException ex) { logger.log(Level.SEVERE, null, ex); return false; } }
4
public void createTweetStruct() throws ParseException,IOException { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy"); simpleDateFormat.setLenient(true); String line = null; BufferedReader intermediateDumpReader = new BufferedReader(new FileReader(intermediateFile)); int count = 0; while((line = intermediateDumpReader.readLine()) != null) { Tweet t = new Tweet(); t.setTweetId(new Long(line.substring(1))); line = intermediateDumpReader.readLine(); t.setTweetTimestamp(simpleDateFormat.parse(line.substring(1))); line = intermediateDumpReader.readLine(); t.setTweetText(line.trim().substring(1)); line = intermediateDumpReader.readLine(); t.setTweetUserId(new Long(line.substring(1))); line = intermediateDumpReader.readLine(); if( line.equals("$null")) line = "$0"; t.setTweetInReplyToStatusId(new Long(line.substring(1))); line = intermediateDumpReader.readLine(); tweeStruct.insert(t); count++; } System.out.println("insertion count : " + count); intermediateDumpReader.close(); postProcess(); }
2
public void sortConfectionByCost() { Collections.sort(confections, new Comparator() { public int compare(Object ob1, Object ob2) { Confections co1 = (Confections) ob1; Confections co2 = (Confections) ob2; if (co1.getCost() > co2.getCost()) { return 1; } if (co2.getCost() > co1.getCost()) { return -1; } return 0; } }); }
2
public void start(List<TickerQuotes> _quotes){ try{ System.out.println("Running Quote Thread"); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); DateFormat idateFormat = new SimpleDateFormat("HH:mm:ss"); System.out.println("STILL ALIVE"); for(TickerQuotes quote : _quotes) { if (quote.symbol.equals("GBPUSD")) { quote.Price = BS.getFX(); } if (quote.symbol.equals("sap")) { quote.Price = BS.getFuture("sap"); } if (quote.symbol.equals("nasdaq")) { quote.Price = BS.getFuture("nasdaq"); } GS.getLast(quote.symbol,_quotes); System.out.println(quote.symbol); try { String _vol = GS.getVolume(quote.symbol); String[] __vol = _vol.split("/"); if (__vol[0].contains("M")) { __vol[0] = String.valueOf(Double.valueOf(__vol[0].substring(0,__vol[0].length()-1))*1000000); } if (__vol[0].contains(",")) { __vol[0] = __vol[0].replace(",","" ); } if (_env.equals("PROD")) { ExecuteQuery("insert into volume (Ticker,ivol,adv,date,time) values ('"+quote.symbol+"','"+__vol[0]+"','"+__vol[1]+"','"+dateFormat.format(date)+"','"+idateFormat.format(date)+"')"); } } catch (Exception e) { } } } catch (Exception e) { System.out.println("ERROR : "+e.toString()); Server S = new Server(); S.WriteLog("ERROR : "+e.toString()); } }
9
public Integer getId() { return id; }
0
@Override public void exec(String channel, String sender, String commandName, String[] args, String login, String hostname, String message) { try { SourceServer tf4 = new SourceServer("tf4.joe.to"); tf4.initialize(); System.out.println(tf4.getServerInfo()); this.bot.sendMessage(channel, "[TF4] Map: " + tf4.getServerInfo().get("mapName") + " Players: " + tf4.getServerInfo().get("numberOfPlayers") + " / " + tf4.getServerInfo().get("maxPlayers")); } catch (TimeoutException e) { this.bot.sendMessage(channel, "[TF4] Error: Timed out."); e.printStackTrace(); } catch (SteamCondenserException e) { this.bot.sendMessage(channel, "[TF4] Error: I don't even know what went wrong."); e.printStackTrace(); } try { SourceServer tf5 = new SourceServer("tf5.joe.to"); tf5.initialize(); System.out.println(tf5.getServerInfo()); this.bot.sendMessage(channel, "[TF5] Map: " + tf5.getServerInfo().get("mapName") + " Players: " + tf5.getServerInfo().get("numberOfPlayers") + " / " + tf5.getServerInfo().get("maxPlayers")); } catch (TimeoutException e) { this.bot.sendMessage(channel, "[TF5] Error: Timed out."); e.printStackTrace(); } catch (SteamCondenserException e) { this.bot.sendMessage(channel, "[TF5] Error: I don't even know what went wrong."); e.printStackTrace(); } }
4
public void addLocation(DataPoint loc) { this.locations.add(loc); }
0
protected SolexaFastqParser(String id) { Matcher m = Pattern.compile(REGEX).matcher(id); // Last guard block if (!m.matches()) return; setAttribute(IdAttributes.FASTQ_TYPE, NAME); for (IdAttributes a : regexAttributeMap.keySet()) { String value = m.group(regexAttributeMap.get(a)); if (value != null) setAttribute(a, m.group(regexAttributeMap.get(a))); } }
3
public void modify() throws IOException{ /*Allows user to modify Questions on a given Test. Questions are modified in the Question classes themselves. This overloaded method of Test also includes modifying of Question answers.*/ boolean repeat = true; String s; int val = 0; while(repeat){ display(); Out.getDisp().renderLine("Enter the number of the question to modify."); val = Input.inputNum(1,questions.size()); //Input a number within an acceptable range Out.getDisp().renderLine("Question " + val + " selected."); questions.get(val-1).modify(); Out.getDisp().renderLine("Modify the answer? (Y/N)"); // answers.get(val-1).render(); s = Input.inputString(); if (s.equals("Y")||s.equals("y")){ answers.set(val-1, questions.get(val-1).modifyAns()); //Modify answer, save in the same location. }else Out.getDisp().renderLine("Answer left unchanged."); Out.getDisp().renderLine("Edit another question? (Y/N)"); s = Input.inputString(); if (s.equals("N")||s.equals("n")) repeat = false; }//while(repeat) }
5
public Object nextValue() throws JSONException { char c = this.nextClean(); String string; switch (c) { case '"': case '\'': return this.nextString(c); case '{': this.back(); return new JSONObject(this); case '[': this.back(); return new JSONArray(this); } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuffer sb = new StringBuffer(); while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = this.next(); } this.back(); string = sb.toString().trim(); if ("".equals(string)) { throw this.syntaxError("Missing value"); } return JSONObject.stringToValue(string); }
7
@Override public int hashCode() { return (int) this.appt.getId(); }
0
@Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (UUID != null ? UUID.hashCode() : 0); result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (links != null ? links.hashCode() : 0); return result; }
4
public boolean conflictWith(Word other) { int tdx, tdy, odx, ody; tdx = tdy = odx = ody = 0; switch ( this.getOrient() ) { case RIGHT: tdx = 1; break; case DOWN: tdy = 1; break; } switch ( other.getOrient() ) { case RIGHT: odx = 1; break; case DOWN: ody = 1; break; } int tx = this.getX(), ty = this.getY(); for ( int i=0; i<this.getLength(); ++i ) { int ox = other.getX(), oy = other.getY(); for ( int j=0; j<other.getLength(); ++j ) { if ( tx == ox && ty == oy ) { return true; } ox += odx; oy += ody; } tx += tdx; ty += tdy; } return false; }
8
public static void main(String[] args){ MasterFind masterfind = new MasterFind(); ArrayList<String> Master = masterfind.find_baseNumOfCowork(); FileWriter fw; try { fw = new FileWriter("parserResult/master.csv"); PrintWriter pw = new PrintWriter(fw); for(int i = 0; i < Master.size(); i++){ pw.println(Master.get(i)); } pw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
2
public static void multiThreadUpload(String projectName, File loc, String rmPath){ Travel t=new Travel(); t.directoryTravel(loc); HashMap<String, ArrayList<File>> tl=t.returnTravelList(); ArrayList<File> dl=tl.get("directories"); ArrayList<File> fl=tl.get("files"); SFTP sftp=new SFTP(); StringBuffer sb=new StringBuffer(); for (int i = 0; i < dl.size(); i++) { sb.append("mkdir -p " + rmPath + "/" + dl.get(i).getAbsolutePath().substring(loc.getAbsolutePath().lastIndexOf(projectName)).replace(File.separator, "/") + "\n"); sb.append("chmod 777 "+rmPath+"/"+dl.get(i).getAbsolutePath().substring(loc.getAbsolutePath().lastIndexOf(projectName)).replace(File.separator, "/")+"\n"); } sftp.doShell(sb.toString()); MyCountDownLatch mcd=new MyCountDownLatch(0); // Log.Print(fl.size()); int cnt=0; while(cnt<fl.size()){ if(mcd.getCount()<3){ // Log.Print(projectName+" - "+mcd.getCount()); // Log.Print(rmPath+"/"+fl.get(cnt).getAbsolutePath().substring(fl.get(cnt).toString().indexOf(projectName), fl.get(cnt).toString().lastIndexOf(File.separator)).replace(File.separator, "/")); if(fl.get(cnt).getName().equalsIgnoreCase("sftp-config.json")){ cnt++; continue; } SFTPMultiThread smt=new SFTPMultiThread(fl.get(cnt),rmPath+"/"+fl.get(cnt).getAbsolutePath().substring(loc.getAbsolutePath().lastIndexOf(projectName)).replace(File.separator, "/"),mcd); smt.start(); mcd.countUp(); cnt++; } if(cnt==fl.size()) break; } }
5
private static RealMatrix csvToMatrix(final String sourceFilePath) throws IOException { BufferedReader in = new BufferedReader(new FileReader(sourceFilePath)); double[][] matrixArray = null; while (in.ready()) { String currentLine = in.readLine(); if (currentLine.startsWith("#") || currentLine.trim().isEmpty()) { continue; } String[] tokens = currentLine.split(","); if (matrixArray == null) { matrixArray = new double[0][tokens.length]; } double[][] tmpArray = new double[1][tokens.length]; for (int i = 0; i < tokens.length; ++i) { if (!tokens[i].trim().isEmpty()) { tmpArray[0][i] = Double.parseDouble(tokens[i]); } } matrixArray = concat(matrixArray, tmpArray); } return MatrixUtils.createRealMatrix(matrixArray); }
6
private void loadDatabaseWithData(String root) { time = System.currentTimeMillis(); // try to load from obj else { root += File.separator + "sm" + File.separator; System.out.println("---*****************************--->>>>>>>" + root); files_q = new File(root + "q").list(); Arrays.sort(files_q); files_y = new File(root + "y").list(); Arrays.sort(files_y); System.out.println("loading database: " + files_q.length + " files to load"); // for each file store last price for each ticker for (int i = 0; i < files_q.length; i++) { System.out.println("loading files " + files_q[i] + " " + files_y[i]); convertFileDataToArray(i, root); } addMapToDividendDataForEachTicker(); DataUtil.loadStringData(EarningsTest.REPORTS_ROOT + "NASDAQ_PROFILES_I.txt", DESCRIPTIONS); DataUtil.loadStringData(EarningsTest.REPORTS_ROOT + "NYSE_PROFILES_I.txt", DESCRIPTIONS); calculateWordStatistics(DESCRIPTIONS, WORD_STATS); }
1
public static List<Integer> sieveOfEratosthenes(final int max) { final SieveWithBitset sieve = new SieveWithBitset(max + 1); // +1 to include max itself for (int i = 3; (i * i) <= max; i += 2) { if (sieve.isComposite(i)) continue; // We increment by 2*i to skip even multiples of i for (int multiplei = i * i; multiplei <= max; multiplei += 2 * i) sieve.setComposite(multiplei); } final List<Integer> primes = new ArrayList<Integer>(); primes.add(2); for (int i = 3; i <= max; i += 2) if (!sieve.isComposite(i)) primes.add(i); return primes; }
5
private static void printAll() { String value; Iterator iter = queue.iterator(); while(iter.hasNext()) { value = (String)iter.next(); System.out.print(value+", "); } System.out.println(); }
1
private boolean onCommandQuery(CommandSender sender, Command command, String label, String cmd, String[] args) { if (sender.hasPermission(ReplicatedPermissionsPlugin.ADMIN_PERMISSION_NODE)) { String queryPlayerName = getQueryPlayerName(sender, args, 1); if (!queryPlayerName.equals("CONSOLE")) { Hashtable<String, ReplicatedPermissionsContainer> playerMods = null; for (Entry<String, Hashtable<String, ReplicatedPermissionsContainer>> player : this.parent.getMonitor().getPlayerModInfo().entrySet()) { if (player.getKey().equalsIgnoreCase(queryPlayerName)) { playerMods = player.getValue(); queryPlayerName = player.getKey(); break; } } String reply = ""; if (playerMods != null) { boolean first = true; for (Entry<String, ReplicatedPermissionsContainer> modInfo : playerMods.entrySet()) { if (!modInfo.getKey().equals("all")) { String modName = String.format("%S%s %.2f", modInfo.getKey().substring(0, 1), modInfo.getKey().substring(1), modInfo.getValue().modVersion); if (!first) reply += ", "; first = false; reply += ChatColor.AQUA + modName + ChatColor.RESET; } } } else { reply = ChatColor.YELLOW + "not registered"; } sender.sendMessage(ChatColor.GREEN + "Player: " + ChatColor.AQUA + queryPlayerName); sender.sendMessage(ChatColor.GREEN + "Mods: " + reply); } else { sender.sendMessage(String.format(ChatColor.GREEN + "/%s %s " + ChatColor.AQUA + "<player>", label, cmd)); } } else { sender.sendMessage(ChatColor.RED + "No permission"); } return true; }
8
@Override protected void paintComponent(Graphics g) { if(!isShowing()) return; super.paintComponent(g); if(!loadingDone && faderTimer == null) return; Insets insets = getInsets(); int x = insets.left; int y = insets.top; int width = getWidth() - insets.left - insets.right; int height = getHeight() - insets.top - insets.bottom - 100; //offset from centre of screen Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Composite oldComposite = g2.getComposite(); if(damaged) { drawableAvatars = sortAvatarsByDepth(x, y, width, height); damaged = false; } drawAvatars(g2, drawableAvatars); if(drawableAvatars.length > 0) { drawAvatarName(g2); } g2.setComposite(oldComposite); }
5
public static void editAdress(Adress a){ 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("UPDATE Addresses set street = ?, number = ?, bus = ?, postal_code = ?, city = ? WHERE address_id = ?"); stmnt.setString(1, a.getStreet()); stmnt.setString(2, a.getHouseNr()); stmnt.setString(3, a.getBus()); stmnt.setInt(4, a.getZipcode()); stmnt.setString(5, a.getCity()); stmnt.setInt(6, a.getAdressID()); stmnt.execute(); conn.commit(); conn.setAutoCommit(true); }catch(SQLException e){ System.out.println("update fail!! - " + e); } }
4
public static void readCollection(BusinessCollection businessCollection, File parentFolder){ String businessCollectionName = businessCollection.getName(); File xmlFile = new File(parentFolder, businessCollectionName+".xml"); try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); // documentBuilderFactory.setValidating(true); DocumentBuilder dBuilder = documentBuilderFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlFile.getAbsolutePath()); doc.getDocumentElement().normalize(); String collectionName = businessCollection.getBusinessObjectType(); // get Root Element e.g. <Accountings> Element rootElement = (Element) doc.getElementsByTagName(collectionName).item(0); readChildren(rootElement, businessCollection); } catch (IOException io) { io.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } for(Object businessObject : businessCollection.getBusinessObjects()) { if(businessObject instanceof BusinessCollection){ BusinessCollection<BusinessObject> subCollection = ((BusinessCollection<BusinessObject>)businessObject); String type = subCollection.getBusinessObjectType(); String name = subCollection.getName(); if(type.equals(name) || (subCollection instanceof MustBeRead)){ File childFolder = new File(parentFolder, businessCollectionName); readCollection(subCollection, childFolder); } } } }
6
public static <T extends Comparable<? super T>> void sort(List<T> input) { if (input.size() <= 1) { return; } // Going only till input.size() - 1 because as result of swapping the biggest element would be at last index // naturally for (int i = 0; i < input.size() - 1; i++) { int smallIndex = i; for (int j = i + 1; j < input.size(); j++) { if (input.get(j).compareTo(input.get(smallIndex)) < 0) { smallIndex = j; } } if (smallIndex != i) { Collections.swap(input, i, smallIndex); } } }
6
@EventHandler public void equipmentClick(PlayerInteractEvent e) { Player player = e.getPlayer(); if (e.getAction() == Action.RIGHT_CLICK_BLOCK || e.getAction() == Action.RIGHT_CLICK_AIR){ ItemStack stack = player.getItemInHand(); if (stack.getTypeId()==397 || stack.getTypeId() == 384 ){ e.setCancelled(true); stack.setAmount(1); player.getInventory().setItemInHand(stack); return; } } }
4
private JPanel getPanCode() { if (panCode == null) { panCode = new JPanel(); panCode.setBorder(BorderFactory.createTitledBorder("Code :")); panCode.setLayout(new BoxLayout(this.panCode,BoxLayout.Y_AXIS)); ButtonGroup group=new ButtonGroup(); for(int i=0;i<=Interface.CODES.values().length;i++) { final int l=i; if(i!=Interface.CODES.values().length) { if(Interface.CODES.values()[i].estCryptanalysable()) { JRadioButton temp=new JRadioButton(Interface.CODES.values()[i].getNom()); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectionne=Interface.CODES.values()[l]; } }); group.add(temp); panCode.add(temp); } } else { JRadioButton temp=new JRadioButton("Tous"); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selectionne=null; } }); group.add(temp); panCode.add(temp); } } } return panCode; }
4
public static void deleteUnusedFiles(File residentDir, Set<String> fileNames) { int count = 0; if (residentDir.isDirectory()) { File[] children = residentDir.listFiles(); if (children != null) { for (File child : children) { try { String filename = child.getName(); if (child.isFile()) { if (filename.contains(".txt")) filename = filename.split("\\.txt")[0]; // Delete the file if there is no matching resident. if (!fileNames.contains(filename.toLowerCase())) { deleteFile(child); count ++; } } } catch (Exception e) { // Ignore file } } if (count > 0) { System.out.println(String.format("[ccSpawners] Deleted %d old files.", count)); } } } }
8
void history(int pt) throws ScriptException { if (statementLength == 1) { // show it showString(viewer.getSetHistory(Integer.MAX_VALUE)); return; } if (pt == 2) { // set history n; n' = -2 - n; if n=0, then set history OFF checkLength3(); int n = intParameter(2); if (n < 0) invalidArgument(); viewer.getSetHistory(n == 0 ? 0 : -2 - n); return; } switch (statement[1].tok) { // pt = 1 history ON/OFF/CLEAR case Token.on: case Token.clear: viewer.getSetHistory(Integer.MIN_VALUE); return; case Token.off: viewer.getSetHistory(0); break; default: keywordExpected(); } }
7
public List<Connection.KeyVal> formData() { ArrayList<Connection.KeyVal> data = new ArrayList<Connection.KeyVal>(); // iterate the form control elements and accumulate their values for (Element el: elements) { if (!el.tag().isFormSubmittable()) continue; // contents are form listable, superset of submitable String name = el.attr("name"); if (name.length() == 0) continue; if ("select".equals(el.tagName())) { Elements options = el.select("option[selected]"); for (Element option: options) { data.add(HttpConnection.KeyVal.create(name, option.val())); } } else { data.add(HttpConnection.KeyVal.create(name, el.val())); } } return data; }
5
public List<Float> getFloatList(String path) { List<?> list = getList(path); if (list == null) { return new ArrayList<Float>(0); } List<Float> result = new ArrayList<Float>(); for (Object object : list) { if (object instanceof Float) { result.add((Float) object); } else if (object instanceof String) { try { result.add(Float.valueOf((String) object)); } catch (Exception ex) { } } else if (object instanceof Character) { result.add((float) ((Character) object).charValue()); } else if (object instanceof Number) { result.add(((Number) object).floatValue()); } } return result; }
8
public final LogoParser.expression_return expression() throws RecognitionException { LogoParser.expression_return retval = new LogoParser.expression_return(); retval.start = input.LT(1); Object root_0 = null; LogoParser.logical_return logical33 =null; try { // /home/carlos/Proyectos/logojava/Logo.g:87:2: ( logical ) // /home/carlos/Proyectos/logojava/Logo.g:87:4: logical { root_0 = (Object)adaptor.nil(); pushFollow(FOLLOW_logical_in_expression422); logical33=logical(); state._fsp--; adaptor.addChild(root_0, logical33.getTree()); retval.value = (logical33!=null?logical33.value:null); } retval.stop = input.LT(-1); retval.tree = (Object)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { // do for sure before leaving } return retval; }
2
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; if (age != student.age) return false; if (group != null ? !group.equals(student.group) : student.group != null) return false; if (name != null ? !name.equals(student.name) : student.name != null) return false; return true; }
8
public void update() { for (int i = 0; i < population.size(); ++i) { population.get(i).update(); } for (int i = 0; i < buildings.length; ++i) { for (int j = 0; j < buildings[i].length; ++j) { if (buildings[i][j] != null) { buildings[i][j].update(); } } } }
4
public void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(CustomerAccount_Rent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(CustomerAccount_Rent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(CustomerAccount_Rent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(CustomerAccount_Rent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new CustomerAccount_Rent(db, currentUser, movieID).setVisible(true); } }); }
6
public static Inventory fromString(String s) { YamlConfiguration configuration = new YamlConfiguration(); try { configuration.loadFromString(Base64Coder.decodeString(s)); Inventory i = Bukkit.createInventory(null, configuration.getInt("Size"), configuration.getString("Title")); ConfigurationSection contents = configuration.getConfigurationSection("Contents"); for (String index : contents.getKeys(false)) i.setItem(Integer.parseInt(index), contents.getItemStack(index)); return i; } catch (InvalidConfigurationException e) { return null; } }
2
public static void setupAmbient(){ File dir = new File(Params.testFolder); if(dir.exists()){ Ambient.clearAmbient(); } dir.mkdir(); }
1
public void eliminar(String nombre){ NodoPersonas q = this.inicio; NodoPersonas t = null; boolean band = true; while(q.getInfo().getNombre() != nombre && band){ if(q.getLiga() != null){ t = q; q = q.getLiga(); }else{ band = false; } } if(!band){ System.out.println("No se encontro a la persona"); }else{ if(this.inicio == q){ this.inicio = q.getLiga(); }else{ t.setLiga(q.getLiga()); } } //System.out.println(this.inicio.getInfo()); }
5