text
stringlengths
14
410k
label
int32
0
9
public void mouseClicked(int button, int x, int y, int clickCount) { switch (GameplayState.currentState) { case PAUSED: case PLACE: case NORMAL: this.gui.mouseClicked(button, x, y, clickCount); break; case WIN: case LOSE: this.gameOverUI.mouseClicked(button, x, y, clickCount); break; } }
5
public Object next() { int pos = rand.nextInt(pool.size()); Iterator i = pool.iterator(); while (pos > 0) i.next(); return (String) i.next(); }
1
public DialogCase open() { Shell dialog = createContent(); UI.centerShell(shell, dialog); dialog.open(); while (!dialog.isDisposed()) { if (!dialog.getDisplay().readAndDispatch()) dialog.getDisplay().sleep(); } if (!dialog.isDisposed()) { dialog.close(); } return dialogOutput[0]; }
3
public KorpaBean PotrosackaKorpa(KorisnikBean kb) throws Exception{ KorpaBean korpa = null; try{ stmt=con.createStatement(); String query1 = "select * from potrosackakorpa where korisnikID=(select KorisnikId from korisnik where korisnickoIme = '"+kb.getKorisnickoIme()+"' ) AND status="+1; RS=stmt.executeQuery(query1); //int br=0; if(RS.next()){ // br++; KorpaBean k = new KorpaBean(); k.setKorisnikId(RS.getInt("KorisnikID")); k.setPKID(RS.getInt("PKID")); k.setDatumNarucivanja(RS.getString("DatumNarucivanja")); k.setDatumKreiranja(RS.getString("DatumKreiranja")); k.setStatus(RS.getInt("Status")); k.setAdresaIsporuke(RS.getString("AdresaIsporuke")); k.setStatus(RS.getInt("Status")); korpa=k; }else{ Statement st=con.createStatement(); String queryMax="Select MAX(PKID) as MPK from potrosackakorpa where korisnikID=(select KorisnikId from korisnik where korisnickoIme = '"+kb.getKorisnickoIme()+"' )"; ResultSet rs=st.executeQuery(queryMax); int mpk=1; if(rs.next()){ mpk=rs.getInt("MPK")+1; } String query="Insert Into potrosackakorpa (KorisnikID, PKID, DatumKreiranja, AdresaIsporuke, Status) values ((select KorisnikId from korisnik where korisnickoIme = '"+kb.getKorisnickoIme()+"'), "+mpk+", '"+DateFormat.getDateInstance(DateFormat.MEDIUM,new Locale("SR")).format(new Date())+"', (select adresa from korisnik where korisnickoIme = '"+kb.getKorisnickoIme()+"'),"+1+")"; Statement st1=con.createStatement(); st1.executeUpdate(query); stmt=con.createStatement(); String query111 = "select * from potrosackakorpa where korisnikID=(select KorisnikId from korisnik where korisnickoIme = '"+kb.getKorisnickoIme()+"' ) AND status="+1; RS=stmt.executeQuery(query111); //int br=0; if(RS.next()){ // br++; KorpaBean k = new KorpaBean(); k.setKorisnikId(RS.getInt("KorisnikID")); k.setPKID(RS.getInt("PKID")); k.setDatumNarucivanja(RS.getString("DatumNarucivanja")); k.setDatumKreiranja(RS.getString("DatumKreiranja")); k.setStatus(RS.getInt("Status")); k.setAdresaIsporuke(RS.getString("AdresaIsporuke")); k.setStatus(RS.getInt("Status")); korpa=k; } } Statement stmt1=con.createStatement(); String query2 = "select * from stavkapk where KorisnikID="+korpa.getKorisnikId()+" AND PKID="+korpa.getPKID(); ResultSet RS=stmt1.executeQuery(query2); while(RS.next()){ StavkaPKBean spk=new StavkaPKBean(); spk.setKorisnikId(korpa.getKorisnikId()); spk.setPKID(korpa.getPKID()); spk.setRB(RS.getInt("RB")); spk.setProizvod(getProizvodByID(RS.getInt("proizvodID"))); spk.setKolicina(RS.getInt("kolicina")); korpa.getStavke().add(spk); } //if(br==0) { // throw new Exception("Nema unetih proizvoda!"); //} }catch(Exception e){ throw new Exception("Greska pri pregledu potrosacke korpe! "+e); } return korpa; }
5
public void testWithStartInstant_RI2() { Interval test = new Interval(TEST_TIME1, TEST_TIME2); try { test.withStart(new Instant(TEST_TIME2 + 1)); fail(); } catch (IllegalArgumentException ex) {} }
1
public static int maxProfit(int[] prices) { int profit=0; if(prices.length <= 0) return profit; for(int i=0;i<prices.length-1;i++){ if(prices[i+1]-prices[i] >0) profit+=prices[i+1]-prices[i]; } return profit; }
3
@Override public void union(Vector vector, VectorVectorMapper callback) { int size = Math.max(size(), vector.size()); for(int i=0; i<size; i++) { float v1 = get(i); float v2 = vector.get(i); if (v1 != 0 || v2!= 0) { if (!callback.map(i, v1, v2)) { return; } } } }
4
public void addCalendar(boolean weekView, Date date) { JPanel container = new JPanel(); FlowLayout panelLayout = new FlowLayout(); panelLayout.setHgap(0); panelLayout.setVgap(0); container.setLayout(panelLayout); scrollPane = new JScrollPane(container); if (weekView == true) { int width = 100; int height = 1000; Date d = date; Calendar cal = Calendar.getInstance(); cal.setTime(d); // cal.add(Calendar.DATE, -1); // d = cal.getTime(); for (int i = 0; i < 7; i++) { CalendarPanel p; if (i == 0) { p = new CalendarPanel(d, true, true, width, height); } else if (i == 6) { p = new CalendarPanel(d, false, false, width, height); } else { p = new CalendarPanel(d, false, true, width, height); } cal.add(Calendar.DATE, 1); d = cal.getTime(); cpanels.add(p); container.add(p); } } else { int width = 700; int height = 1000; CalendarPanel p = new CalendarPanel(date, true, false, width, height); cpanels.add(p); container.add(p); } scrollPane.setPreferredSize(new Dimension(730, 490)); if (lastScrollPosition != null) { scrollPane.getViewport().setViewPosition(lastScrollPosition); } calendarContainer.add(scrollPane, BorderLayout.SOUTH); }
5
public static boolean insertlistcheck (Connection conTst ) throws SQLException { boolean chk = true; boolean doCreate = false; try { Statement s = conTst.createStatement(); s.execute("update SYSTEMINSERT set ENTRY_DATE = CURRENT_TIMESTAMP, INSERT_ITEM = 'TEST ENTRY' where 1=3"); } catch (SQLException sqle) { String theError = (sqle).getSQLState(); // System.out.println(" Utils GOT: " + theError); /** If table exists will get - WARNING 02000: No row was found **/ if (theError.equals("42X05")) // Table does not exist { return false; } else if (theError.equals("42X14") || theError.equals("42821")) { System.out.println("WwdChk4Table: Incorrect table definition. Drop table INSERT_LIST and rerun this program"); throw sqle; } else { System.out.println("WwdChk4Table: Unhandled SQLException" ); throw sqle; } } // System.out.println("Just got the warning - table exists OK "); return true; } /*** END wwdInitTable **/
4
public Disparo doDisparar(TipoDisparo tipo, Posicion posicion){ Disparo disparo = null; switch(tipo){ case CONVENCIONAL: disparo = new Convencional(this, posicion); disparo.setCosto(200); this.disparar((Convencional) disparo); break; case MINA_SIMPLE: disparo = new MinaRetardada(this, posicion); disparo.setCosto(50); ((MinaRetardada) disparo).setRetardo(3); this.disparar((Mina) disparo); break; case MINA_DOBLE: disparo = new MinaRetardada(this, posicion); disparo.setCosto(100); ((MinaRetardada) disparo).setRetardo(3); ((MinaRetardada) disparo).setRadio(1); this.disparar((MinaRetardada) disparo); break; case MINA_TRIPLE: disparo = new MinaRetardada(this, posicion); disparo.setCosto(125); ((MinaRetardada) disparo).setRetardo(3); ((MinaRetardada) disparo).setRadio(2); this.disparar((MinaRetardada) disparo); break; case MINA_CONTACTO: disparo = new MinaContacto(this, posicion); disparo.setCosto(150); this.disparar((MinaContacto) disparo); break; } return disparo; }
5
private void updateState(boolean sevenedOut) { if (isNumberEstablished()) { if (dice.getTotal() == 7 || dice.getTotal() == number) number = 0; } else { if ((dice.getTotal() >= 4 && dice.getTotal() <= 6) || (dice.getTotal() >= 8 && dice.getTotal() <= 10)) number = dice.getTotal(); } RollCompleteEvent event = null; if (sevenedOut) { event = new SevenOutEvent("Seven Out! All bets paid.\n"); } else { String message = isNumberEstablished() ? "The point is "+number+"!" : "Coming out roll!"; event = new RollCompleteEvent("All bets paid. "+message+"\n"); } setChanged(); notifyObservers(event); }
9
protected boolean isSubTypeOf(final Value value, final Value expected) { Type expectedType = ((BasicValue) expected).getType(); Type type = ((BasicValue) value).getType(); switch (expectedType.getSort()) { case Type.INT: case Type.FLOAT: case Type.LONG: case Type.DOUBLE: return type.equals(expectedType); case Type.ARRAY: case Type.OBJECT: if ("Lnull;".equals(type.getDescriptor())) { return true; } else if (type.getSort() == Type.OBJECT || type.getSort() == Type.ARRAY) { return isAssignableFrom(expectedType, type); } else { return false; } default: throw new Error("Internal error"); } }
9
@Override public String toString() { StringBuilder string = new StringBuilder(game.name) .append(" - (") .append(game.getTick()) .append(":") .append(String.format("%.3f", (double) game.getFrames() / game.getTick())) .append("): "); Alliance no1 = null; for (Alliance alliance : this) { if (no1 == null || no1.getScore() < alliance.getScore()) { no1 = alliance; } string.append(alliance.name).append(": ").append(alliance.getScore()).append(", "); } return no1 == null ? string.toString() : string.append(no1.name).append(no1.name.endsWith("s") ? " are" : " is").append(" winning").toString(); }
5
public void print(){ for(int k=1;k<=cols;k++){ System.out.print(vnames[k]+"\t"); } System.out.print("\n"); for(int k=1;k<=cols;k++){ System.out.print(vunits[k]+"\t"); } System.out.print("\n"); for(int i=0;i<rows;i++){ for(int j=0;j<cols;j++){ System.out.print(vls[i][j]+"\t"); } System.out.print("\n"); } }
4
public void writeCONTROL_REG(int /* reg8 */control) { waveform = (control >> 4) & 0x0f; ring_mod = control & 0x04; sync = control & 0x02; int /* reg8 */test_next = control & 0x08; if (ANTTI_LANKILA_PATCH) { /* * SounDemoN found out that test bit can be used to control the * noise register. Hear the result in Bojojoing.sid. */ // testbit set. invert bit 19 and write it to bit 1 if (test_next != 0 && test == 0) { accumulator = 0; int /* reg24 */bit19 = (shift_register >> 19) & 1; shift_register = (shift_register & 0x7ffffd) | ((bit19 ^ 1) << 1); } // Test bit cleared. // The accumulator starts counting, and the shift register is reset // to // the value 0x7ffff8. // NB! The shift register will not actually be set to this exact // value // if the // shift register bits have not had time to fade to zero. // This is not modeled. else if (test_next == 0 && test > 0) { int /* reg24 */bit0 = ((shift_register >> 22) ^ (shift_register >> 17)) & 0x1; shift_register <<= 1; shift_register &= 0x7fffff; shift_register |= bit0; } // clear output bits of shift register if noise and other waveforms // are selected simultaneously if (waveform > 8) { shift_register &= 0x7fffff ^ (1 << 22) ^ (1 << 20) ^ (1 << 16) ^ (1 << 13) ^ (1 << 11) ^ (1 << 7) ^ (1 << 4) ^ (1 << 2); } } else { // Test bit set. // The accumulator and the shift register are both cleared. // NB! The shift register is not really cleared immediately. It // seems // like the individual bits in the shift register start to fade down // towards zero when test is set. All bits reach zero within // approximately $2000 - $4000 cycles. // This is not modeled. There should fortunately be little audible // output from this peculiar behavior. if (test_next != 0) { accumulator = 0; shift_register = 0; } // Test bit cleared. // The accumulator starts counting, and the shift register is reset // to // the value 0x7ffff8. // NB! The shift register will not actually be set to this exact // value // if the // shift register bits have not had time to fade to zero. // This is not modeled. else if (test != 0) { shift_register = 0x7ffff8; } } test = test_next; // The gate bit is handled by the EnvelopeGenerator. }
8
public void setGoalGradMerged() { // set high values for (int row = 0; row < Board.getNbRows(); row++) { // for each col for (int col = 0; col < Board.getNbCols(); col++) { goalGradMerged[row][col] = -1; } } int value; // for each row for (int row = 0; row < Board.getNbRows(); row++) { // for each col for (int col = 0; col < Board.getNbCols(); col++) { // for every goal value = Integer.MAX_VALUE; for (int i = 0; i < Board.getNbOfGoals(); i++) { if (goalsOccupied[i]){ //do nothing } else if(value > Board.getGoalGrad(i, row, col) && Board.getGoalGrad(i, row, col) != -1) { goalGradMerged[row][col] = Board.getGoalGrad(i, row, col); value = goalGradMerged[row][col]; } } } } }
8
public static void main(String args[]) { int x; for (x = 0; x < 6; x++) { if(x == 1) System.out.println("x is one"); else if (x == 2) System.out.println(" x is two"); else if (x == 3) System.out.println(" x is three"); else if (x == 4) System.out.println(" x is four"); else System.out.println("x is not between 1 and 4"); } }
5
protected static void search(ProcessSearchRentacars processSearchRentalcars) { StringBuffer stringBuffer = new StringBuffer(TravelSDK.INSTANCE.getSettingsResult().getWsUrl()); stringBuffer.append("?prgm=rentacar.search"); TravelSDK.appendStandartServiceParameters(stringBuffer); stringBuffer.append("&limit=").append(TravelSDK.INSTANCE.getPageLimit()); RentacarSearchParameters searchParameters = processSearchRentalcars.getSearchParameters(); if(searchParameters.getFromAirportId() != null) { // Search by airport code stringBuffer.append("&rac-from=").append(searchParameters.getFromAirportId()); stringBuffer.append("&rac-to=").append(searchParameters.getToAirportId()); } else { // Search by geolocation stringBuffer.append("&lat=").append(searchParameters.getLat()); stringBuffer.append("&lon=").append(searchParameters.getLon()); stringBuffer.append("&lat-dropoff=").append(searchParameters.getLatDropOf()); stringBuffer.append("&lon-dropoff=").append(searchParameters.getLonDropOff()); stringBuffer.append("&rad=").append(searchParameters.getRadius()); } stringBuffer.append("&rac-dep-date=").append( StringUtil.toDateSting_YYYY_MM_DD(searchParameters.getDepartureDate())); stringBuffer.append("&rac-dep-time=1200");//.append(StringUtil.toTimeString(searchParameters.getDepartureTime())); stringBuffer.append("&rac-rt-date=") .append(StringUtil.toDateSting_YYYY_MM_DD(searchParameters.getReturnDate())); stringBuffer.append("&rac-rt-time=1300");//.append(StringUtil.toTimeString(searchParameters.getReturnTime())); stringBuffer.append("&rac-size=").append(searchParameters.getCategory()); if (searchParameters.isAirConditioned()) { stringBuffer.append("&rac-ac=1"); } if (searchParameters.isAutomaticTransmission()) { stringBuffer.append("&rac-aut=1"); } if (searchParameters.isStationWagon()) { stringBuffer.append("&rac-stw=1"); } if (TravelSDK.INSTANCE.getCurrencyCode() != null) { stringBuffer.append("&currency=").append(TravelSDK.INSTANCE.getCurrencyCode()); } // Result filters appendFilters(stringBuffer, processSearchRentalcars.getFilterParameters()); new RequestThread(stringBuffer.toString(), processSearchRentalcars, true).start(); }
5
private void initA() { A = new HashSet<Edge>(); vertex = new HashSet<Integer>(); // copy edges: ArrayList<Edge> ce = new ArrayList<Edge>(edges); int cost = ce.get(0).getweight(); Edge anedge = ce.get(0); // 1. find a least cost edge and insert to A as first Edge for (Edge E : ce) { if (E.getweight() < cost) { cost = E.getweight(); anedge = E; } } if (isEdgesafe(anedge)) { A.add(anedge); vertex.add(anedge.getvA()); vertex.add(anedge.getvB()); ce.remove(anedge); } boolean stop = false; while (!stop) { Edge least = null; int lc = 9999; Iterator<Integer> ite = vertex.iterator(); while (ite.hasNext()) { int v = ite.next(); Edge lv = findleastcost(v); if (lv != null && lv.getweight() < lc) { lc = lv.getweight(); least = lv; } } if (least != null) { A.add(least); vertex.add(least.getvA()); vertex.add(least.getvB()); } if (A.size() == forest.size() - 1) { stop = true; } } }
9
public void setMasterVolume(float masterVolume) { this.masterVolume = masterVolume; adjustVolume = true; if(background != null) background.adjustVolume(masterVolume); }
1
protected void moveCar(int[] nextCoordinates) throws GameEndException{ if(countMoves > 10000/waitingDuration){ throw new GameEndException("Car " + name + " has " + getPoints() + " points"); } if(nextCoordinates[0] != -1){ this.x = nextCoordinates[0]; this.y = nextCoordinates[1]; Field newField = map.getField(x, y); try{ newField.checkHit(this); }catch(GameEndException ex){ throw ex; } newField.parkCar(this); try { Thread.sleep(waitingDuration); } catch (InterruptedException e) { throw new GameEndException("Car " + name + " has " + getPoints() + " points"); } newField.unParkCar(this); }else{ //nexCoordinates[0] == -1 -> the next field would be illegal try { Thread.sleep(waitingDuration); } catch (InterruptedException e) { throw new GameEndException("Car " + name + " has " + getPoints() + " points"); } //unless algorithm is random, the car is stuck forever } countMoves++; }
5
void deviceAdded (Device dev, DefaultTreeModel model) throws IOException { HubNode h = getHubOf ("add", dev); if (h == null) { System.err.println ("what hub has " + dev); return; } else if (h != this) { h.deviceAdded (dev, model); return; } synchronized (children) { for (int i = 0; i < last; i++) { if (children [i].dev == dev) return; } children [last] = createTreeNode (dev); if (trace) System.err.println ("HubNode " + addr + " add child " + last + ", addr " + dev.getAddress () ); if (model != null) model.nodesWereInserted (this, new int [] { last }); last++; } }
6
public static JButton getAttackButton() { if (attackButton == null) { attackButton = new JButton("Attack"); attackButton.setEnabled(false); attackButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (GameData.COLLECT_ROUND == true) { gameLabel.setText("You have already collected!"); } else { attackResultLabel1.setText(""); attackResultLabel2.setText(""); attackResultLabel3.setText(""); defenceResultLabel1.setText(""); defenceResultLabel2.setText(""); String result = (String) destinationBox .getSelectedItem(); GameData.setTargetProvince(result); if (RiskGame.unplacedArmies() == true) { gameLabel .setText("There are still armies to be placed!!"); } else { if (GameData.CURRENT_PLAYER .isPlayerProvince(GameData.TARGET_PROVINCE) == true) { gameLabel .setText("You cannot attack your own province!!"); } else if (GameData.SELECTED_PROVINCE.getArmy() == 1) { gameLabel .setText("You will need more than one army to attack!"); } else { // returns 0 in case of a 'Yes' answer, 1 in // case of // a // 'No' int ATTACK_ANSWER = JOptionPane .showConfirmDialog( game, "Do you want to attack from " + GameData.SELECTED_PROVINCE .getName() + " to " + GameData.TARGET_PROVINCE .getName() + "?", "Confirm Attack", JOptionPane.YES_NO_OPTION); if (ATTACK_ANSWER == 0) { RiskGame.setAttack(true); attackResultLabel1.setIcon(null); attackResultLabel2.setIcon(null); attackResultLabel3.setIcon(null); defenceResultLabel1.setIcon(null); defenceResultLabel2.setIcon(null); gameLabel .setText("You may now select the amount of armies!"); attackSpinner.setEnabled(true); defenceSpinner.setEnabled(true); attackThrowButton.setEnabled(true); defenceThrowButton.setEnabled(true); } } } } } }); attackButton.setBounds(SCREEN_WIDTH - 300, 310, 95, 50); } return attackButton; }
6
public int compareToNumbers(double n1, double n2, String name1, String name2, boolean descending) { int order = (descending ? -1 : 1); // Both are NaN => compare strings (always in alphabetical order) if (Double.isNaN(n1) && Double.isNaN(n2)) { return name1.compareTo(name2); } // One of them is NaN? (when sorted, push them to the end of the list) if (Double.isNaN(n1)) return +1; if (Double.isNaN(n2)) return -1; // Both are 'normal' numbers, just compare them if (n1 < n2) return -1 * order; if (n1 > n2) return +1 + order; // If both numbers are equal, sort by 'name' return name1.compareTo(name2); }
7
public void push(String stack, E element) { synchronized(lock) { if(STACK1.equals(stack)) { array[tail1++] = element; if(tail1 >= array.length/3-1) { resize(); } } else if (STACK2.equals(stack)) { array[tail2--] = element; if(tail2 <= tail3+1) { resize(); } } else if (STACK3.equals(stack)) { array[tail3++] = element; if(tail3 >= tail2-1) { resize(); } } } }
6
private Scene createPreloaderScene() { loading = new Loading(); try { loading.buildComponents(); } catch (IOException ex) { } return loading.getScene(); }
1
public void visitFieldInsn(final int opcode, final String owner, final String name, final String desc) { mv.visitFieldInsn(opcode, owner, name, desc); if (constructor) { char c = desc.charAt(0); boolean longOrDouble = c == 'J' || c == 'D'; switch (opcode) { case GETSTATIC: pushValue(OTHER); if (longOrDouble) { pushValue(OTHER); } break; case PUTSTATIC: popValue(); if (longOrDouble) { popValue(); } break; case PUTFIELD: popValue(); if (longOrDouble) { popValue(); popValue(); } break; // case GETFIELD: default: if (longOrDouble) { pushValue(OTHER); } } } }
9
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
private void cppPrintMethodSignature(Method m, boolean isImplementation, boolean isStatic) throws ClassNotFoundException { out.print("\t" + (isStatic && !isImplementation ? "static " : "")); cppPrintType(m.getReturnType(), false); if (isImplementation) out.print(classNameWithUnderscores + "::"); out.printf("%s%s(", m.getName(), (cppReserved.contains(m.getName()) ? "1" : "")); Class<?>[] pType = m.getParameterTypes(); if (isStatic) out.printf("cppToJavaRpc::Connection * conn%s", (pType.length == 0 ? "" : ", ")); for (int i = 0; i < pType.length; i++) { cppPrintType(pType[i], true); out.printf("var%d%s", i, (i == pType.length - 1 ? "" : ", ")); } out.print(")"); }
9
private static int fastSq(int base, int power) { if (power == 1) { return base; } else if (power == 0) { return 1; } else if (power % 2 == 0) { return (int) Math.pow(fastSq(base, power / 2), 2); } else { return (int) (Math.pow(fastSq(base, power / 2), 2) * base); } }
3
public String getStringWithDefault(String entry, String defaultEntry) { String result = getString(entry); if (result == null) { result = getString(defaultEntry); } return result; }
1
public GameOptions() { setResizable(false); setBounds(100, 100, 267, 221); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(null); final JToggleButton tglbtnDefaultMaze = new JToggleButton("Default maze"); tglbtnDefaultMaze.setSelected(true); tglbtnDefaultMaze.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent arg0) { if(tglbtnDefaultMaze.getModel().isSelected()) { mazeslider.setEnabled(false); dragonslider.setEnabled(false); } else { mazeslider.setEnabled(true); dragonslider.setEnabled(true); } } }); tglbtnDefaultMaze.setBounds(10, 11, 95, 23); contentPanel.add(tglbtnDefaultMaze); String []options={"Stopped","Asleep","Random & Asleep"}; comboBox = new JComboBox<String>(options); comboBox.setSelectedIndex(1); comboBox.setBounds(115, 12, 95, 23); contentPanel.add(comboBox); dragonslider = new JSlider(); dragonslider.setEnabled(false); dragonslider.setValue(1); dragonslider.setMinimum(1); dragonslider.setMaximum(3); dragonslider.setBounds(10, 65, 200, 26); contentPanel.add(dragonslider); mazeslider = new JSlider(); mazeslider.setEnabled(false); mazeslider.setValue(10); mazeslider.setMaximum(20); mazeslider.setMinimum(8); mazeslider.setBounds(10, 122, 200, 26); contentPanel.add(mazeslider); JLabel lblNumberOfDragons = new JLabel("Number of Dragons"); lblNumberOfDragons.setBounds(10, 48, 142, 14); contentPanel.add(lblNumberOfDragons); JLabel lblMazeSize = new JLabel("Maze size"); lblMazeSize.setBounds(10, 102, 83, 14); contentPanel.add(lblMazeSize); { JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { JButton okButton = new JButton("OK"); okButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { if(tglbtnDefaultMaze.getModel().isSelected()) { gameoptions[0]=-1; gameoptions[1]=1; switch(comboBox.getSelectedIndex()) { case 0: gameoptions[2]=2; break; case 1: gameoptions[2]=1; break; case 2: gameoptions[2]=3; break; } } else { gameoptions[0]=mazeslider.getValue(); switch(comboBox.getSelectedIndex()) { case 0: gameoptions[2]=2; break; case 1: gameoptions[2]=1; break; case 2: gameoptions[2]=3; break; } gameoptions[1]=dragonslider.getValue(); } setVisible(false); } }); okButton.setActionCommand("OK"); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } { JButton cancelButton = new JButton("Cancel"); cancelButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { setVisible(false); } }); cancelButton.setActionCommand("Cancel"); buttonPane.add(cancelButton); } } }
8
public static void ReadFromFile(String fileName){ BufferedReader br = null; try{ br = new BufferedReader(new FileReader(fileName)); String line = null; while((line = br.readLine()) != null){ HashMap<Integer, ArrayList<Double>> geneEntry = new HashMap<Integer, ArrayList<Double>>(); ArrayList<Double> gene = new ArrayList<Double>(); String[] values = line.split("\t"); if(Integer.parseInt(values[1]) > -1){ externalIndex.put(Integer.parseInt(values[0]), Integer.parseInt(values[1])); for(int i = 2; i < values.length; i++){ gene.add(Double.parseDouble(values[i])); } geneEntry.put(Integer.parseInt(values[0]), gene); geneList.add(geneEntry); } // reference.put(Integer.parseInt(values[0]), gene); } br.close(); }catch(FileNotFoundException e1){ // TODO Auto-generated catch block e1.printStackTrace(); }catch (IOException e){ // TODO Auto-generated catch block e.printStackTrace(); } }
5
private void getOldMods(){ Patch_Controller.delete(new File(Strings.TEMPORARY_DATA_LOCATION_B)); UnZip.unZipIt(Strings.MODDEDZIP_LOCATION, Strings.TEMPORARY_DATA_LOCATION_B); ArrayList<Integer> rows = new ArrayList<Integer>(); ArrayList<Integer> rows1 = new ArrayList<Integer>(); try { ArrayList<String[]> data = new ArrayList<String[]>(); BufferedReader in = new BufferedReader(new FileReader(Strings.TEMPORARY_DATA_LOCATION_B+ File.separator +Strings.MODTABLE_EXPORT)); String readline = in.readLine(); while (readline != null) { //add file info String[] text = new String[2]; text[0] = readline.split(Strings.COMMA)[0]; text[1] = readline.split(Strings.COMMA)[1]; data.add(text); readline = in.readLine(); } in.close(); //compare dates for(int j=0; j<data.size();j++){ SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyy"); Date oldDate = formatter.parse(data.get(j)[1]); for(int i=0; i<Soartex_Patcher.tableData.length;i++){ try { Date modDate = formatter.parse((String)Soartex_Patcher.tableData[i][5] ); if(((String)Soartex_Patcher.tableData[i][1]).equals(data.get(j)[0])){ if(modDate.after(oldDate)){ rows.add(i); System.out.println("Outdated: "+data.get(j)[0]); } else{ rows1.add(i); } } } catch (ParseException e1) { System.out.println("Program could NOT get list of installed mods!"); } } } } catch(Exception e1){ System.out.println("Program could NOT get list of installed mods!"); } HighlightCell tableRender = new HighlightCell(rows, rows1, Color.RED, Color.ORANGE); Soartex_Patcher.table.getColumnModel().getColumn(1).setCellRenderer(tableRender); Soartex_Patcher.table.updateUI(); Patch_Controller.delete(new File(Strings.TEMPORARY_DATA_LOCATION_B)); }
7
public String toString() { String s; s = "Vertices:\n"; for (int i=0; i < current; i++) { s += " " + i + ": " + locations[i].getName() + "\n"; } s+="\n"; s += "Edges:\n"; for (int i=0; i < current; i++) { for (int j=0; j < i; j++) { if (adjacent[i][j]) { s+=" "+i+"->"+j+": "+weight[i][j]+"\n"; } } } return s; }
4
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(KittyMiningBuddyManagementConsol.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(KittyMiningBuddyManagementConsol.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(KittyMiningBuddyManagementConsol.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(KittyMiningBuddyManagementConsol.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new KittyMiningBuddyManagementConsol().setVisible(true); } }); }
6
public static int getBillTotalCost(int billId) { int total = 0; String query = "SELECT ifNull(sum(`cost` * `quantity`),0) + `consultationCost` as `total` " + "FROM `bill` " + "LEFT JOIN `billItem` on `bill`.`billId` = `billItem`.`billId` " + "LEFT JOIN `medicine` on `billItem`.`medicineid` = `medicine`.`id` " + "WHERE `bill`.`billId` = '%d' " + "group by `bill`.`billid`;"; DBA dba = Helper.getDBA(); try { ResultSet rs = dba.executeQuery(String.format(query, billId)); if (rs != null) { while (rs.next()) { total = rs.getInt("total"); } rs.close(); } dba.closeConnections(); } catch (SQLException sqlEx) { dba.closeConnections(); Helper.logException(sqlEx); } return total; }
3
public void move(boolean isLeft) { if (this.getLeft() <= 0 && moveInt == 1) { this.setMoveInt(0); x = 1; } else if (this.getRight() >= 500 && moveInt == 2) { this.setMoveInt(0); x = 499 - width; } if (isLeft) { x -= 5; } else { x += 5; } }
5
public void testPropertyAddNoWrapHour() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.hourOfDay().addNoWrapToCopy(9); check(test, 10, 20, 30, 40); check(copy, 19, 20, 30, 40); copy = test.hourOfDay().addNoWrapToCopy(0); check(copy, 10, 20, 30, 40); copy = test.hourOfDay().addNoWrapToCopy(13); check(copy, 23, 20, 30, 40); try { test.hourOfDay().addNoWrapToCopy(14); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); copy = test.hourOfDay().addNoWrapToCopy(-10); check(copy, 0, 20, 30, 40); try { test.hourOfDay().addNoWrapToCopy(-11); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); }
2
public ArrayList<Patch> getTargetsInRange(int r){ ArrayList <Patch> ans = new ArrayList(); ArrayList <Patch> temp = new ArrayList(); ans.addAll(getPatch().getNeighbors4()); while (r > 0){ for (int i = 0; i<ans.size();i++){ if (ans.get(i).getTurtle()==null||(ans.get(i).getTurtle().getFriendly()==_friendly)) temp.addAll(ans.get(i).getNeighbors4()); } HashSet hs = new HashSet(); hs.addAll(temp); hs.addAll(ans); ans.clear(); temp.clear(); ans.addAll(hs); r--; System.out.println(r); } return ans; }
4
public FenPrincipale() { initComponents(); this.nomAnimal = "Aucun animal"; this.positions = new ArrayList(); this.positionsAff = new ArrayList(); nbrPointsAff = sliderNbrPoints.getValue()+1; nbrPointsAffiche = Integer.toString(nbrPointsAff); choixNbPtsLabel2.setText(nbrPointsAffiche); initParam(); initBoutons(); initFolder(); lireDonnees( false ); }
0
public int getDegree(final City city) { int index = getIndex(city); if (index < 0) { return -1; } int degree = 0; for (int[] edge : edges) { for (int x = 0; x < edge.length; x++) { if (x == index && edge[x] != 0) { degree++; /*if (i == index) { ++degree; } */ } } } return degree; }
5
public void writeVariable(CycVariable cycVariable) throws IOException { if (trace == API_TRACE_DETAILED) { Log.current.println("writeVariable = " + cycVariable.toString()); } final String name = cycVariable.toString(); if (cycVariable.isHLVariable()) { write(CFASL_COMPLETE_VARIABLE); writeInt(cycVariable.hlVariableId.intValue()); writeString(name); } else { write(CFASL_SYMBOL); writeString(cycVariable.toCanonicalString()); } }
2
public Hospital getHospitalidHospital() { return hospitalidHospital; }
0
@Override public void setMemoryAllocation(int[] memory) { DefaultTableModel mdlMemory = new DefaultTableModel(); if (memory != null && memory.length > 0) { for(int i = 0; i < memory.length; i++) { if (memory[i] > -1) { //If value is -1 then leave it blank mdlMemory.addColumn(i, new Object[]{memory[i]}); } else { mdlMemory.addColumn(i, new Object[]{""}); } } } else { for (int i = 0; i < 1024; i++) { mdlMemory.addColumn(i, new Object[]{""}); } } tblMemory.setModel(mdlMemory); }
5
private ReflectUtils() { }
0
public static void MWF() throws IOException{ int timeblock = 5; BufferedReader r = new BufferedReader (new InputStreamReader(System.in)); while (timeblock > 0){ System.out.println("What would you like to do right now?"); if (timeblock >= 3) { System.out.println("1. Go to class (not likely)"); System.out.println("2. Go workout at the Gym"); System.out.println("3. Play games at home"); System.out.println("4. Sleep (what you always do anyways)"); System.out.println("Damon would like to choose option: "); int choice = DamonTools.validInput(Integer.parseInt(r.readLine()), 4, 1); if (choice == 1){ DamonStats.Knowledge ++; DamonActions.CLASS(); } else if (choice == 2) DamonActions.Gym(); else if (choice == 3) { DamonActions.GAMING(); } else { System.out.println("Damon slept through the day. He did not get to do anything."); timeblock = 0; } timeblock -= 1; } else { System.out.println("1. Go workout at the Gym"); System.out.println("2. Play games at home"); System.out.println("3. Sleep (what you always do anyways)"); int choice = DamonTools.validInput(Integer.parseInt(r.readLine()), 3, 1); if (choice == 1) { DamonActions.Gym(); } else if (choice == 2) { DamonActions.GAMING(); } else { System.out.println("Damon slept through the day. He did not get to do anything."); timeblock = 0; } timeblock -= 1; } } }
7
public void loadFromObject() { try { if (cls==null) return; for (int i=0; i<fields.size(); i++) { String fieldname = (String)fields.get(i); String fieldtype = (String)fieldtypes.get(fieldname); //System.out.println("<field "+fieldname+" "+fieldvalue); if (fieldtype.equals("key") || fieldtype.equals("int") || fieldtype.equals("double") || fieldtype.equals("boolean") || fieldtype.equals("String") ) { Field field = cls.getField(fieldname); // if obj==null we get a static field fieldvalues.put(fieldname, field.get(obj)); } else { System.out.println("not implemented!"); } } } catch (NoSuchFieldException e) { throw new JGameError("Field not found."); } catch (IllegalAccessException e) { throw new JGameError("Field cannot be accessed."); } }
9
private void txtPasswordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPasswordActionPerformed String username,stringPass=""; char[] pass; String passHash=""; username=this.txtUsername.getText(); pass=this.txtPassword.getPassword(); for(int i=0;i<pass.length;i++){ stringPass+=pass[i]; } try{ MessageDigest md = MessageDigest.getInstance("MD5"); md.update(stringPass.getBytes()); byte byteData[] = md.digest(); //convert the byte to hex format StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } passHash=sb.toString(); } catch(Exception ex){ ex.printStackTrace(); } String tempUserId,tempUserType,tempPassword; try{ String query="SELECT userid,password,usertype FROM users WHERE username='"+username+"'"; Statement st=con.createStatement(); ResultSet rs=st.executeQuery(query); if(rs.next()==false){ JOptionPane.showMessageDialog(null, "Username not found!", "Login failed!", JOptionPane.ERROR_MESSAGE); } else{ tempUserId=Integer.toString(rs.getInt(1)); tempPassword=rs.getString(2); tempUserType=rs.getString(3); if(tempPassword.equals(passHash)){ this.lblSignedIn.setVisible(true); this.lblName.setText(this.txtUsername.getText()); this.btnEmployees.setEnabled(true); this.lblEmployees.setEnabled(true); this.lblProjects.setEnabled(true); this.btnProjects.setEnabled(true); if(tempUserType.equals("administrator")){ this.lblDepartments.setEnabled(true); this.btnDepartments.setEnabled(true); this.lblDepartments.setText("Add/Remove/Change department details"); this.lblRegisterUser.setVisible(true); } else{ this.lblDepartments.setEnabled(false); this.btnDepartments.setEnabled(false); this.lblRegisterUser.setVisible(false); this.lblDepartments.setText("This Option is only for Database administrators"); } this.btnLogout.setEnabled(true); this.txtPassword.setEnabled(false); this.txtUsername.setEnabled(false); this.btnLogin.setEnabled(false); } else{ JOptionPane.showMessageDialog(null, "Password not valid!", "Login failed!", JOptionPane.ERROR_MESSAGE); } } } catch(Exception ex){ ex.printStackTrace(); } }//GEN-LAST:event_txtPasswordActionPerformed
7
int insertKeyRehash(char val, int index, int hash, byte state) { // compute the double hash final int length = _set.length; int probe = 1 + (hash % (length - 2)); final int loopIndex = index; int firstRemoved = -1; /** * Look until FREE slot or we start to loop */ do { // Identify first removed slot if (state == REMOVED && firstRemoved == -1) firstRemoved = index; index -= probe; if (index < 0) { index += length; } state = _states[index]; // A FREE slot stops the search if (state == FREE) { if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } else { consumeFreeSlot = true; insertKeyAt(index, val); return index; } } if (state == FULL && _set[index] == val) { return -index - 1; } // Detect loop } while (index != loopIndex); // We inspected all reachable slots and did not find a FREE one // If we found a REMOVED slot we return the first one found if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } // Can a resizing strategy be found that resizes the set? throw new IllegalStateException("No free or removed slots available. Key set full?!!"); }
9
private void jButton0MouseMouseClicked(MouseEvent event) { this.dispose(); }
0
public void choixDuGeneral(Set<Joueur> hjoueur, Set<General> hgeneral){ Scanner sc = new Scanner(System.in); String nomgeneral = new String(); for(Joueur j : hjoueur){ boolean isCorrect = false; // On vérifie que le choix du général est bien possible (pas déjà pris, existant) // Et on affecte ce général au joueur do{ System.out.println("\n" + j.getPseudo() + ", quel général désirez-vous être ? "); // Affichage des généraux for(General g : hgeneral){ System.out.println(g.toString()); } nomgeneral = sc.nextLine(); // On ajoute le général au joueur s'il existe for(General g : hgeneral){ if(nomgeneral.equalsIgnoreCase(g.getNom())){ j.setGeneral(g); hgeneral.remove(g); isCorrect = true; break; } } if(!isCorrect){System.err.println("Le général que vous avez choisi n'existe pas !");} }while(!isCorrect); } }
6
private void splitImage() { int vertical = ytrans[0].length / 8; int horizontal = ytrans.length / 8; for(int y = 0; y < vertical; y++) { for(int x = 0; x < horizontal; x++) { int xoff = (x * 8); int yoff = (y * 8); double[][] Y = new double[8][8]; double[][] Cb = new double[8][8]; double[][] Cr = new double[8][8]; for(int z = 0; z < 8;z++) { for(int w = 0; w < 8; w++) { Y[w][z] = ytrans[xoff + w][yoff + z]; Cb[w][z] = cbtrans[xoff + w][yoff + z]; Cr[w][z] = crtrans[xoff + w][yoff + z]; } } yblocks.add(Y); cbblocks.add(Cb); crblocks.add(Cr); } } int cbcrV = cbtranssub[0].length / 8; int cbcrH = cbtranssub.length / 8; for(int y = 0; y < cbcrV; y++) { for(int x = 0; x < cbcrH; x++) { int xoff = (x * 8); int yoff = (y * 8); double[][] Cb = new double[8][8]; double[][] Cr = new double[8][8]; for(int z = 0; z < 8;z++) { for(int w = 0; w < 8; w++) { Cb[w][z] = cbtranssub[xoff + w][yoff + z]; Cr[w][z] = crtranssub[xoff + w][yoff + z]; } } cbsubblocks.add(Cb); crsubblocks.add(Cr); } } }
8
public static short parse_serial_parameter(final String cur_serial_data, boolean highlight, byte show_device_flags) { if (show_device_flags == SHOW_DEVICE_NONE) return ANALYZER_SUCCESS; String title = null; String content = null; String date = null; String time = null; String number = null; String severity = null; // String severity_color = null; String tmp_serial_data = cur_serial_data; // printf("%s [%d]\n", serial_data, serial_data_size); short ret = ANALYZER_SUCCESS; int pos = tmp_serial_data.indexOf(": "); if (pos < 0) { WriteWarnFormatSyslog("Ignore incorrect data format(1): %s", tmp_serial_data); ret = ANALYZER_FAILURE_IGNORE_DATA; } else { if (pos < MIN_SERAIL_DATA_TITLE_LENGTH) { WriteWarnFormatSyslog("Ignore incorrect data format(2): %s", tmp_serial_data); ret = ANALYZER_FAILURE_IGNORE_DATA; } else { // Copy the title title = tmp_serial_data.substring(0, pos); // Parse the title Pattern datePattern = Pattern.compile("([\\d/]{5}) ([\\d:]{8}) ([\\d]{3,5}) ([\\w]{4,5})"); Matcher dateMatcher = datePattern.matcher(title); if (dateMatcher.find()) { date = dateMatcher.group(1); time = dateMatcher.group(2); number = dateMatcher.group(3); severity = dateMatcher.group(4); // WriteDebugFormatSyslog("Date: %s, Time: %s, Number: %s, Severity: %s", date, time, number, severity); // Copy the content content = tmp_serial_data.substring(pos + 2); // WriteDebugFormatSyslog("Content: %s", content); // severity_color = get_severity_color(severity); // if (severity_color == null) // ret = ANALYZER_FAILURE_INCORRECT_SERIAL_DATA; } else { WriteWarnFormatSyslog("Ignore incorrect data format(3): %s", title); ret = ANALYZER_FAILURE_IGNORE_DATA; } } } if (CheckSuccess(ret)) { String res = String.format("Date: %s, Time: %s, Number: %s, Severity: %s, Content: %s", date, time, number, severity, content); if (checkShowDeviceEnable(show_device_flags, SHOW_DEVICE_CONSOLE)) { if (highlight) // Exploit the red color in console to highlight the interesting string... System.err.println(res); else System.out.println(res); // System.out.printf("%s%s\n",(highlight ? DUMP_CYN : severity_color), res); } if (checkShowDeviceEnable(show_device_flags, SHOW_DEVICE_SYSLOG)) WriteDebugSyslog(res); } return ret; }
8
public boolean doLogin(String username, String password){ PreparedStatement preparedStatement; ResultSet resultSet; String dbPassword = null; PasswordService passwordService = new DefaultPasswordService(); Connection connection = DatabaseConnection.connectDB(); // be conservative: make this the default boolean loginSuccess = false; try { preparedStatement = connection.prepareStatement("select * from user_auth where username = ?"); preparedStatement.setString(1, username); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { dbPassword = resultSet.getString("password"); } } catch (SQLException e) { e.printStackTrace(); } finally { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } if (passwordService.passwordsMatch(password, dbPassword)) { loginSuccess = true; } return loginSuccess; }
4
public boolean stem() { int v_1; int v_2; int v_3; int v_4; // (, line 64 // do, line 66 v_1 = cursor; lab0: do { // call mark_regions, line 66 if (!r_mark_regions()) { break lab0; } } while (false); cursor = v_1; // backwards, line 67 limit_backward = cursor; cursor = limit; // (, line 67 // do, line 68 v_2 = limit - cursor; lab1: do { // call main_suffix, line 68 if (!r_main_suffix()) { break lab1; } } while (false); cursor = limit - v_2; // do, line 69 v_3 = limit - cursor; lab2: do { // call consonant_pair, line 69 if (!r_consonant_pair()) { break lab2; } } while (false); cursor = limit - v_3; // do, line 70 v_4 = limit - cursor; lab3: do { // call other_suffix, line 70 if (!r_other_suffix()) { break lab3; } } while (false); cursor = limit - v_4; cursor = limit_backward; return true; }
8
private static TypedObject parseObject(LinkedList<Character> json) { TypedObject ret = new TypedObject(null); char c = json.removeFirst(); if (c == '}') // Check for empty object return ret; json.addFirst(c); do { json.removeFirst(); // Read quote String key = parseString(json); json.removeFirst(); // Read colon Object val = parse(json); ret.put(key, val); c = json.removeFirst(); } while (c != '}'); return ret; }
2
public void convertPointsToShape(){ if(allData.size()!=0) return; try{ for(int i=0; i<allPoints.size(); i++){ SeShape shape = new SeShape(); ArrayList<SDEPoint> points = allPoints.get(i); //convert to array of SDEPoint SDEPoint pts[] = new SDEPoint[points.size()]; for(int j=0; j<pts.length; j++){ pts[j] = points.get(j); } ArrayList<Object>data = new ArrayList<Object>(); // Add null for the first column, which is dataset_id data.add(null); data.add(allIds.get(i)); data.add(pts); allData.add(data); } } catch (SeException se){ System.out.println(se.getMessage()); } }
4
public static Object fromByteArray(byte[] array){ try{ ByteArrayInputStream bis = new ByteArrayInputStream(array); ObjectInput in = null; in = new ObjectInputStream(bis); Object o = in.readObject(); try{ bis.close(); in.close(); }catch(Exception e){System.out.println("A Memory Leak Has Happened!");e.printStackTrace();} return (Object)o; }catch(Exception e){} return null; }
2
public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if(l1 == null) return l2; else if(l2 == null){ return l1; } ListNode head = new ListNode(-1); ListNode index = head; while(l1 != null && l2 != null){ if(l1.val > l2.val){ index.next = l2; l2 = l2.next; }else{ index.next = l1; l1 = l1.next; } index = index.next; } if(l1 == null) index.next = l2; else index.next = l1; return head.next; }
6
private void getEndElement(String name) throws MiniXMLException { MiniXMLToken oMiniXMLToken; boolean bEnd = false; // String attrName, attrValue; MiniXMLEndElement element = new MiniXMLEndElement( automaton.getStateInt(), name); automaton.endElement(name); // System.out.print("</" + name); do { oMiniXMLToken = oTokenParser.getToken(); switch (oMiniXMLToken.getType()) { case MiniXMLTokenParser.tError: throw new MiniXMLException( MiniXMLException._MXMLE_TGE_END_ELEMENT); case MiniXMLTokenParser.tTagEnd: handler.endElement(element); // System.out.print(">" + oMiniXMLToken.getValue()); bEnd = true; break; default: throw new MiniXMLException( MiniXMLException._MXMLE_TGE_UKNOWN_END_TOKEN); } } while (!bEnd); }
3
public Final fingFinalByValues(List<String> values){ for(String value : values){ Final finalElement = findFinalByValue(value); if(finalElement != null) return finalElement; } return null; }
2
private void timerActie(){ if(baanTeller < baanPad.size()){ volgendeStapAfgelegdeBaan(); if(baanTeller == baanPad.size()){ try{ onCompleteFunc.call(); //moet gecalld worden op de voorlaatste stap van de animatie } catch(Exception e){ e.printStackTrace(); } timer.stop(); } repaint(); } }
3
public void testBuildInitialization() { String[][][] results; Instances inst; int i; int n; int m; results = new String[2][m_Instances.numInstances()][m_NumNeighbors]; // two runs of determining neighbors for (i = 0; i < 2; i++) { try { m_NearestNeighbourSearch.setInstances(m_Instances); for (n = 0; n < m_Instances.numInstances(); n++) { for (m = 1; m <= m_NumNeighbors; m++) { inst = m_NearestNeighbourSearch.kNearestNeighbours( m_Instances.instance(n), m); results[i][n][m - 1] = inst.toString(); } } } catch (Exception e) { fail("Build " + (i + 1) + " failed: " + e); } } // compare the results for (n = 0; n < m_Instances.numInstances(); n++) { for (m = 1; m <= m_NumNeighbors; m++) { if (!results[0][n][m - 1].equals(results[1][n][m - 1])) fail("Results differ: instance #" + (n+1) + " with " + m + " neighbors"); } } }
7
private void doQueryRound(int n, int range) { Future<RPCMessage> futureReply; int i=0; int rangeCounter=1; Iterator<Contact> it = shortList.iterator(); Contact c; while (it.hasNext() && rangeCounter <= range && i < n) { c = it.next(); //if c is unprobed and it is not the local node then query it if (!markedList.contains(c) && !(node.getNodeId().equals(c.getNodeId()))) { try { futureReply = node.findValue(c, key, type, owner, recent, true); replies.add(new Couple<Contact,Future<RPCMessage>>(c,futureReply)); i++; } catch (Exception e) { //If something went wrong, discard the node from the list shortList.remove(c); } } rangeCounter++; } FindValueResponse reply; Contact contact; for (Couple<Contact,Future<RPCMessage>> replyCouple : replies) { contact = replyCouple.first(); futureReply = replyCouple.second(); try { //waits the FIND_NODE responses for a short time reply = (FindValueResponse)(futureReply.get(TIME_OUT, Settings.DEFAULT_TIME_UNIT).getRPC()); if (reply.getCounters() != null) { result.add(reply.getCounters()); } markedList.add(contact); } catch (Exception e) { //contacts that fail to respond quickly are removed from consideration shortList.remove(contact); System.err.println("IterativeFindVaue" + contact + " failed to respond. Removedfrom shortlist."); } } replies.clear(); }
9
public void layout(Graph g, Set notMoving) { graph = g; ArrayList vertices = getMovableVertices(graph, notMoving); if (graph==null || vertices.size() == 0) return; /* After checking to see if the graph has movable vertices, sort the vertices * degree in the graph, and then insert them in a VertexChain to minimize * edge intersections. */ VertexChain chain = new VertexChain(graph); Collections.sort(vertices, new Comparator() { public int compare(Object o1, Object o2) { if (graph.degree(o1) == graph.degree(o2)) return 0; else if (graph.degree(o1) > graph.degree(o2)) return -1; else return 1; }}); for (int i=0; i<vertices.size(); i++) chain.addVertex(vertices.get(i)); /* * Now, calculate the polar coordinate positions of each element in the vertex, ordering them * by their order in the chain. "posShift" is the distance between vertices next to each other * in the chain. */ double r, theta, posShift; r = 0; theta = 0; posShift = (Math.sqrt(Math.pow(vertexDim.getHeight(), 2) + Math.pow(vertexDim.getWidth(), 2))) + vertexBuffer; for (int i=0; i<vertices.size(); i++) { r = Math.sqrt(Math.pow(r, 2) + Math.pow(posShift, 2)); theta = theta + Math.asin(posShift / r); graph.moveVertex(chain.get(i), new Point2D.Double(r, theta)); } // Finally, convert the points to Cartesian points, and make sure they all fit onto the screen polarToCartesian(graph, vertices); shiftOntoScreen(graph, size, vertexDim, true); }
6
* @param id 選択レコードのID */ private void setTblData(boolean selectedQuery, String selectedId) { // ソート解除 for (int i=0; i<recTable.getColumnCount(); i++) { recSorter.setSortingStatus(i, TableSorter.NOT_SORTED); } DefaultTableModel dataModel = (DefaultTableModel)recSorter.getTableModel(); dataModel.setRowCount(0); if (recNum == 0) { return; } PackageRecData recData = null; Object[] recordData; int number = recNum; for (int i=0; i<recNum; i++) { recData = specData.getRecInfo(i); // レコード情報生成 recordData = new Object[dataModel.getColumnCount()]; recordData[0] = String.valueOf(number--); if (recData.isQueryRecord()) { recordData[1] = QUERY_RECORD; } else if (recData.isResultRecord()) { recordData[1] = RESULT_RECORD; } if (recData.isIntegRecord()) { recordData[1] = recordData[1] + INTEGRATE_RECORD; } recordData[2] = recData.getName(); recordData[3] = recData.getMatchPeakNum(); recordData[4] = recData.getId(); recordData[5] = Boolean.valueOf(recData.isDisable()); // if (!recData.getSite().equals("")) { // recordData[6] = SearchPage.siteNameList[Integer.parseInt(recData.getSite())]; // } // else { // recordData[6] = ""; // } recordData[6] = SiteUtil.getSiteNameByRecordIdPrefix(recData.getSite()); recordData[7] = recData.getScore(); recordData[8] = recData.getHitPeakNum(); recordData[9] = String.valueOf(recData.getPeakNum()); recordData[10] = recData.getPrecursor(); // テーブルへのレコード追加 dataModel.addRow(recordData); if (selectedQuery == recData.isQueryRecord() && selectedId.equals(recData.getId())) { // クエリーDBタブ、DB Hitタブでの選択レコードを初期選択 recTable.setRowSelectionInterval(i, i); } } }
8
public static Path findDoorToDoorPath(Door start, Door end) { double[][] adjacency; if (start.equals(end)) { Path result = new Path(start.getCentralPoint(), end.getCentralPoint()); result.add(start.getCentralPoint()); return result; } try { adjacency = SimulationEngine.getInstance().getWorld() .getDoorGraph(); if (adjacency[start.getIntIdentifier()][end.getIntIdentifier()] > 0) { Path test = SimulationEngine.getInstance().getWorld() .getDoorPath(start, end); if (test != null) { // Path was calculated yet return test; } // doors are adjacent but there is no calculated path: Set<Door> doorSet = new HashSet<Door>(); doorSet.add(start); doorSet.add(end); // two doors can belong to multiple rooms (in most cases they do // not): Room fittingRoom = WorldFactory.getRoomWithPoints(start.getCentralPoint(), end.getCentralPoint()); if (fittingRoom == null) { log.severe("No room was found. This shouldn't happen!"); return null; } // Take the first room and calculate a path: InRoomPathSolver solver = new InRoomPathSolver(fittingRoom, end.getCentralPoint()); List<Point2D> tempPath = solver .compute(start.getCentralPoint()); Path finalPath = new Path(start.getCentralPoint(), end.getCentralPoint()); finalPath.addAll(tempPath); return finalPath; } } catch (IllegalAccessException e) { log.severe("This shouldn't happen. Don't call this method at this time! " + e.fillInStackTrace()); } // start and end are adjacent: // Last case: doors arn't adjacent: return findDoorToDoorPathOfNonAdjacentDoors(start, end); }
5
public void setVue(VueAbstraite vue) { this.vue = vue; }
0
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(TimeKeeper.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TimeKeeper.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TimeKeeper.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TimeKeeper.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 TimeKeeper().setVisible(true); } }); }
6
public void executeCommand(final String... inputs) throws IOException { final ArrayList<String> commands = new ArrayList<String>(); commands.add("c:/windows/system32/cmd.exe"); commands.add("/c"); for (String x : inputs) { commands.add(x); } BufferedReader br = null; BufferedReader br2 = null; try { final ProcessBuilder p = new ProcessBuilder(commands); final Process process = p.start(); final InputStream is = process.getInputStream(); final InputStream es = process.getErrorStream(); final InputStreamReader isr = new InputStreamReader(is); final InputStreamReader isr2 = new InputStreamReader(es); br = new BufferedReader(isr); br2 = new BufferedReader(isr2); String line; while ((line = br.readLine()) != null) { System.out.println("Retorno do comando = [" + line + "]"); } while ((line = br2.readLine()) != null) { System.out.println("Retorno do comando = [" + line + "]"); } } catch (IOException ioe) { log.severe("Erro ao executar comando shell" + ioe.getMessage()); throw ioe; } finally { secureClose(br); secureClose(br2); } }
4
private static boolean allSameFormat(List<String> input, ArrayList<SECTION_ALIGN> order) { int n = 0; if (order == null) { order = getAlignOrder(input.get(0)); ++n; } // now check that remainder follow this order for (; n < input.size(); ++n) { String line = input.get(n); int formatNum = 0; for (int i = 0; i < line.length(); ++i) { for (int j = 0; j < tagStrings.length; ++j) { if (strStart(line, i, tagStrings[j])) { if (formatNum >= order.size() || tagAlignments[j] != order.get(formatNum)) { return false; } ++formatNum; i += tagStrings[j].length(); break; } // else if (i == 0) { ++formatNum; } } } if (formatNum < order.size()) { return false; } } return true; }
8
@Override protected void shutdownOutput () throws IOException { if ( !this.closed && this.fd.valid() ) { NativeUnixSocket.shutdown(this.fd, SHUT_WR); } }
2
public void generateNet (int length, int width) { ArrayList<Node> firstLayer = new ArrayList<Node>(); ArrayList<Node> secondLayer = new ArrayList<Node>(); // populate the first layer for (int i = 0; i < width; i++) { InputNode firstNode = new InputNode(getNextId()); firstLayer.add(firstNode); _inputs.add(firstNode); _nodes.add(firstNode); } for (int j = 0; j < length; j++) { for (int i = 0; i < width; i++) { NodeOps OpChoice = NodeOps.values()[NeuralNets.generator.nextInt(NodeOps.values().length)]; Node secondNode = new Node(getNextId(), OpChoice); secondLayer.add(secondNode); _nodes.add(secondNode); } for (Node firstNode : firstLayer) { for (Node secondNode : secondLayer) { Link newLink = new Link(firstNode, secondNode); _links.add(newLink); } } firstLayer = secondLayer; //move up one layer secondLayer = new ArrayList<Node>(); //reset the second layer } for (int i = 0; i < 1; i++) { //Node node : firstLayer) { OutputNode newOutput = new OutputNode(getNextId()); _outputs.add(newOutput); _nodes.add(newOutput); } for (Node node : firstLayer) { for (Node output : _outputs) { Link newLink = new Link(node, output); _links.add(newLink); } } }
8
public void actionPerformed(ActionEvent e){ if(e.getSource().equals(timer)){ model.updatePositions(); view.update(); timeCounter += (int)timer.getDelay(); if(record){ try { skrivfil(); } catch (IOException e1) {} } } if(e.getSource().equals(recordButton)){ if(!record){record=true; } else { record=false; try{ outputStream.close(); } catch (IOException e1) {} } } if(e.getSource().equals(simulationButton)){ if(!timer.isRunning()){timer.start();} else {timer.stop();} } if(e.getSource().equals(crystallizeButton)){ model.changeCrystallize(); } }
9
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); request.setCharacterEncoding("UTF-8"); User loggedIn = (User) session.getAttribute("loggedIn"); String name = request.getParameter("playername"); String gameidString = request.getParameter("gameid"); int gameid = Integer.parseInt(gameidString); if (!isLoggedIn(session)) { showJSP("index.jsp", request, response); } else { if (name == null || name.equals("")) { setError("You didn't give a name!", request); showJSP("CreatePlayer?id=" + gameid, request, response); } else { try { if (Player.isNameAvailable(name, gameid) == false) { setError("A player with that name already exists!", request); showJSP("CreatePlayer?id=" + gameid, request, response); } else { try { Player.createPlayer(name, gameid); } catch (SQLException ex) { Logger.getLogger(CreatePlayerServlet2.class.getName()).log(Level.SEVERE, null, ex); } request.setAttribute("user", loggedIn); response.sendRedirect("Game?id=" + gameid); } } catch (SQLException ex) { Logger.getLogger(CreatePlayerServlet2.class.getName()).log(Level.SEVERE, null, ex); } } } }
6
@Override public Date decodeFromString(String value) throws Exception { if (value.contains("y")) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.MONTH, Calendar.JANUARY); cal.set(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.YEAR, Integer.valueOf(value.replace("y", ""))); return cal.getTime(); } else if (value.contains("d")) { Calendar cal = Calendar.getInstance(); try { String[] years = value.replace("d", "").split("-"); cal.set(Calendar.MONTH, Integer.valueOf(years[1]) - 1); cal.set(Calendar.DAY_OF_MONTH, Integer.valueOf(years[2])); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.YEAR, Integer.valueOf(years[0])); } catch (Throwable t) { log.warning("Cannot parse day scoped date '" + value + "'!"); } return cal.getTime(); } else if (value.contains("m")) { Calendar cal = Calendar.getInstance(); try { String[] years = value.replace("m", "").split("-"); cal.set(Calendar.MONTH, Integer.valueOf(years[1]) - 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.YEAR, Integer.valueOf(years[0])); } catch (Throwable t) { log.warning("Cannot parse day scoped date '" + value + "'!"); } return cal.getTime(); } else { return new Date(Long.valueOf(value)); } }
5
static boolean seq_valid(int[] seq) { int j; boolean positive = false; boolean pred_not = false; boolean operand = false; for(j=0;j<SEQ_MAX;++j) { switch ((seq)[j]) { case CODE_NONE : break; case CODE_OR : if (!operand || !positive) return false; pred_not = false; positive = false; operand = false; break; case CODE_NOT : if (pred_not) return false; pred_not = !pred_not; operand = false; break; default: if (!pred_not) positive = true; pred_not = false; operand = true; break; } } return positive && operand; }
9
private static byte[] readPasswordFromHex(String hexPassword) { byte[] passwordBytes = new byte[hexPassword.length() / 2]; for (int i = 0; i < passwordBytes.length; i++) { passwordBytes[i] = (byte) Integer.parseInt(hexPassword.substring(2 * i, 2 * i + 2), 16); } return passwordBytes; }
1
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Roles)) { return false; } Roles other = (Roles) object; if ((this.rolidRol == null && other.rolidRol != null) || (this.rolidRol != null && !this.rolidRol.equals(other.rolidRol))) { return false; } return true; }
5
@Test public void testDuplicateAnalyzerMethods() throws IOException, TesseractException { // HACK: this will be impossible to maintain. Need a better way to identify and // test methods that should fail (possibly reflection) ImageAnalyzerFactory factory = TestContext.getImageAnaylzerFactory(); try { ImageAnalyzer analyzer = TestContext.getImageAnalyzer(factory, TestContext.poetryImageFile); LayoutIterator blockIterator = analyzer.analyzeLayout(); // try to create other iterators and manipulate factory while iterator is open LayoutIterator badIterator; try { badIterator = analyzer.analyzeLayout(); assertFalse("Was able to create duplicate iterator. Should have thrown an exception", true); badIterator.close(); } catch (Exception ex) { /* expected */ } try { badIterator = analyzer.analyzeLayout(new Rectangle(50, 50)); assertFalse("Was able to create duplicate iterator. Should have thrown an exception", true); badIterator.close(); } catch (Exception ex) { /* expected */ } try { badIterator = analyzer.recognize(); assertFalse("Was able to create duplicate iterator. Should have thrown an exception", true); badIterator.close(); } catch (Exception ex) { /* expected */ } try { badIterator = analyzer.recognize(new Rectangle(50, 50)); assertFalse("Was able to create duplicate iterator. Should have thrown an exception", true); badIterator.close(); } catch (Exception ex) { /* expected */ } blockIterator.close(); analyzer.close(); } finally { if (factory != null) factory.close(); } }
5
public boolean validargrado(String Grado) { boolean correcto = false; String[] rrecorregrado = Grado.split("-"); // for (int i = 0; i < rrecorregrado.length; i++) {} try { if (esnumero(rrecorregrado[0]) && esnumero(rrecorregrado[1]) && Integer.parseInt(rrecorregrado[0]) <= 12 && Integer.parseInt(rrecorregrado[1]) <= 5) { char[] x = rrecorregrado[0].toCharArray(); char[] y = rrecorregrado[1].toCharArray(); if (x.length <= 2 && y.length <= 2) { correcto = true; } else { correcto = false; } } else { correcto = false; } } catch (Exception ex) { correcto = false; } return correcto; }
7
@Override public boolean equals(Object r) { return r != null && r instanceof Reponse && getId() == ((Reponse)r).getId(); }
2
private void playSong(){ if(songStatus == SONG_STOPPED){ Song selectedSong = playerLibrary.getSongByIndex(titlesList.getSelectedIndex()); myPlayer = new MP3Player(selectedSong); new Thread(myPlayer).start(); songStatus = SONG_PLAYING; songInfoField.setText(selectedSong.getTitle() + " - " + selectedSong.getArtist()); } else if(songStatus == SONG_PAUSED){ myPlayer.resumePlay(); songStatus = SONG_PLAYING; } }
2
public String addRoute(List<String> stationsForNewRoute, String routeName) throws IOException { String message = ""; log.debug("Start method \"addRoute\""); if (stationsForNewRoute.size() <= 1) { message = "Маршрут должен содержать больше одной станции"; return message; } if ("".equals(routeName)) { message = "Введите название"; return message; } Route route = routeDAO.loadRoute(routeName); if (route != null) { message = "Маршрут с таким названием уже существует"; return message; } route = new Route(); route.setName(routeName); if (!routeDAO.saveRoute(route)) { log.debug("Send AddRouteRespondInfo to client with SERVER_ERROR_STATUS"); message = "Server error status"; return message; } List<Schedule> schedules = new ArrayList<Schedule>(); route = routeDAO.loadRoute(route.getName()); for (int i = 1; i < stationsForNewRoute.size(); i++) { Way way = wayDAO.loadWayByStations(stationsForNewRoute.get(i - 1), stationsForNewRoute.get(i)); Schedule schedule = new Schedule(); schedule.setRouteByIdRoute(route); schedule.setWayByIdWay(way); schedule.setSeqNumber(i); schedules.add(schedule); if (!scheduleDAO.saveSchedule(schedule)) { log.debug("Send AddRouteRespondInfo to client with SERVER_ERROR_STATUS"); message = "Server error status"; return message; } } log.debug("Send AddRouteRespondInfo to client with OK_STATUS"); message = "Маршрут успешно добавлен"; return message; }
6
public static void main(String[] args) { // TODO Auto-generated method stub String Driver = "sun.jdbc.odbc.JdbcOdbcDriver"; String connectStr = "jdbc:odbc:test"; try { Class.forName(Driver); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { Connection con = DriverManager.getConnection(connectStr, "java", "java"); // Statement stmt = con.createStatement(); PreparedStatement psql = con.prepareStatement("select stu_name,stu_age from stu_info where ID < ?"); psql.setInt(1, 10); // psql.setString(1, "ID"); ResultSet res = psql.executeQuery(); while(res.next()){ System.out.println(res.getString("stu_name") + "\t" + res.getInt("stu_age")); } psql.close(); con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
3
public boolean removeID(String ID) { boolean OK = false; OK = IDList.remove(ID); //If false, then ID not found! IDList.remove(ID); System.out.print(IDList); if( OK ) { int gradeHistIndex = Integer.parseInt( ID.substring(0,1) ); gradesHist.set(gradeHistIndex, new Integer(( (Integer)gradesHist.get(gradeHistIndex) ).intValue()-1) ); if( ID.charAt(1) == 'M' ) genderHist.set(0,new Integer(( (Integer)genderHist.get(0) ).intValue()-1) ); else genderHist.set(1,new Integer(( (Integer)genderHist.get(1) ).intValue()-1) ); } return OK; }
2
private void jButton9MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton9MouseReleased // TODO add your handling code here: //System.out.println(this.CommandBox.getSelectedIndex()); switch ( this.CommandBox.getSelectedIndex() ) { case 0: communicator.writeData('!'); communicator.writeData('1'); communicator.writeDataNewLine(); this.txtLog.append("\n"); break; case 1: communicator.writeData('!'); communicator.writeData('2'); communicator.writeDataNewLine(); communicator.writeData('4'); communicator.writeData('2'); communicator.writeDataNewLine(); this.txtLog.append("\n"); break; case 2: communicator.writeData('!'); communicator.writeData('3'); communicator.writeDataNewLine(); this.txtLog.append("\n"); break; case 3: communicator.writeData('!'); communicator.writeData('4'); communicator.writeDataNewLine(); this.txtLog.append("\n"); break; case 4: communicator.writeData('!'); communicator.writeData('5'); communicator.writeDataNewLine(); this.txtLog.append("\n"); break; case 5: communicator.writeData('!'); communicator.writeData('6'); communicator.writeDataNewLine(); this.txtLog.append("\n"); break; case 6: communicator.writeData('!'); communicator.writeData('7'); communicator.writeDataNewLine(); this.txtLog.append("\n"); break; case 7: communicator.writeData('!'); communicator.writeData('8'); communicator.writeDataNewLine(); this.txtLog.append("\n"); break; default: communicator.writeData('!'); communicator.writeData('8'); communicator.writeDataNewLine(); this.txtLog.append("\n"); } communicator.writeData('!'); }//GEN-LAST:event_jButton9MouseReleased
8
public static void evaluate_queue(String type) { System.out.println("Evaluating " + type + " queue +++++++++++++++++++"); int total_ops = 25000; int[] n_threads_arr = {2, 3, 4, 5, 6}; for (int t = 0; t < n_threads_arr.length; t++) { int n_threads = n_threads_arr[t]; System.out.println("For " + n_threads + " threads: ------------------------"); MyQueue<Integer> q = null; if (type.equals("lock-based")) { q = new LockBasedQueue<Integer>(); } else if (type.equals("lock-free")) { q = new LockFreeQueue<Integer>(); } else { System.err.println("ERROR: no such queue implemented"); System.exit(-1); } int n_enq = 0; int n_deq = 0; long enq_time = 0; long deq_time = 0; for (int i = 0; i < 100; i++) { q.enq(-i); } int r = total_ops % n_threads; QueueThread[] threads = new QueueThread[n_threads]; for (int i = 0; i < threads.length; i++) { int n_ops_per_thread = total_ops/n_threads; if (i < r) { n_ops_per_thread++; } threads[i] = new QueueThread(q, n_ops_per_thread); } for (int i = 0; i < threads.length; i++) { threads[i].start(); } for (int i = 0; i < threads.length; i++) { try { threads[i].join(); n_enq += threads[i].n_enq; n_deq += threads[i].n_deq; enq_time += threads[i].enq_time; deq_time += threads[i].deq_time; } catch (InterruptedException e) { e.printStackTrace(); } } long q_time = enq_time + deq_time; double throughput = (Math.pow(10, 9))*(n_deq+n_enq)/(q_time + 0.0); System.out.println("Overall time taken = " + q_time + " ns"); System.out.println("Overall throughput: " + throughput + " ops/s"); } }
9
public boolean validFile() throws NullPointerException { String regex = "(<notestore)(.*)(nextId=\")(\\d+)(\">)(.*)(<\\/notestore>)"; Pattern p = Pattern.compile(regex, Pattern.DOTALL); Matcher m = p.matcher(data); if(m.find()) { regex = "(<note>)(.*?)(<\\/note>)"; p = Pattern.compile(regex, Pattern.DOTALL); m = p.matcher(data); boolean validNote = false; while(m.find()) { String idRegex = "(<id>)(\\d+)(<\\/id>)"; Pattern idP = Pattern.compile(idRegex, Pattern.DOTALL); Matcher idM = idP.matcher(m.group()); if(idM.find()) { validNote = true; } else { return false; } String titleRegex = "(<title>)(.*?)(<\\/title>)"; Pattern titleP = Pattern.compile(titleRegex, Pattern.DOTALL); Matcher titleM = titleP.matcher(m.group()); if(titleM.find()) { validNote = true; } else { return false; } String contentRegex = "(<content>)(.*?)(<\\/content>)"; Pattern contentP = Pattern.compile(contentRegex, Pattern.DOTALL); Matcher contentM = contentP.matcher(m.group()); if(contentM.find()) { validNote = true; } else { return false; } if(validNote) { notesFound++; } } return validNote; } return false; }
6
private final void method740(AbstractToolkit var_ha, Class72 class72_60_) { Model class124 = Class300.createModel(0, Class260.aClass45_3309, anInt1224); if (class124 != null) { var_ha.getDimensions(anIntArray1226); var_ha.setDimensions(0, 0, anInt1220, anInt1220); var_ha.drawQuad(0, 0, anInt1220, anInt1220, 0, 0); int i = 0; int i_61_ = 0; int i_62_ = 256; if (class72_60_ != null) { if (class72_60_.aBoolean1223) { i = -class72_60_.anInt1225; i_61_ = -class72_60_.anInt1216; i_62_ = -class72_60_.anInt1229; } else { i = anInt1225 - class72_60_.anInt1225; i_61_ = anInt1216 - class72_60_.anInt1216; i_62_ = anInt1229 - class72_60_.anInt1229; } } if (anInt1231 != 0) { int i_63_ = -anInt1231 & 0x3fff; int i_64_ = Class70.sineTable[i_63_]; int i_65_ = Class70.cosineTable[i_63_]; int i_66_ = i_61_ * i_65_ - i_62_ * i_64_ >> 14; i_62_ = i_61_ * i_64_ + i_62_ * i_65_ >> 14; i_61_ = i_66_; } if (anInt1219 != 0) { int i_67_ = -anInt1219 & 0x3fff; int i_68_ = Class70.sineTable[i_67_]; int i_69_ = Class70.cosineTable[i_67_]; int i_70_ = i_62_ * i_68_ + i * i_69_ >> 14; i_62_ = i_62_ * i_69_ - i * i_68_ >> 14; i = i_70_; } var_ha.xa(1.0F); var_ha.ZA(16777215, 1.0F, 1.0F, (float) i, (float) i_61_, (float) i_62_); AnimatableToolkit class64 = var_ha.method3625(class124, 2048, 0, 64, 768); int i_71_ = class64.RA() - class64.V(); int i_72_ = class64.EA() - class64.fa(); int i_73_ = class64.V() + i_71_ / 2; int i_74_ = class64.fa() + i_72_ / 2; int i_75_ = i_71_ > i_72_ ? i_71_ : i_72_; var_ha.DA(i_73_, i_74_, i_75_, i_75_); var_ha.method3638(var_ha.method3654()); Class101 class101 = var_ha.method3705(); class101.method894(0, 0, var_ha.i() - class64.HA()); class64.method608(class101, null, var_ha.i(), 1); aClass105_1221 = var_ha.createRaster(0, 0, anInt1220, anInt1220, true); aClass105_1221.method968(0, 0, 3); var_ha.setDimensions(anIntArray1226[0], anIntArray1226[1], anIntArray1226[2], anIntArray1226[3]); } }
6
public void mouseDragged(MouseEvent e) { if(e.isControlDown()) { markerRect.draw(); markerRect.setWidth(-(mouseStartX-e.getX())); markerRect.setHeight(-(mouseStartY-e.getY())); repaint(); } /* else if(markerRect.isSelectedDrag()) { markerRect.setX(-(mouseStartX-e.getX())); markerRect.setY(-(mouseStartY-e.getY())); repaint(); }*/ /* else if((markerRect.isSelectedWidth())||(markerRect.isSelectedHeight())) { if(markerRect.isSelectedWidth()){ markerRect.changeWidth(-(mouseStartX-e.getX()));} if(markerRect.isSelectedHeight()) { markerRect.changeHeight(-(mouseStartY-e.getY())); } repaint(); }*/ // else if(markerArray.isSelecetedHeigh()) // { // markerArray.changeHeight(-(mouseStartY-e.getY())); // repaint(); // } else { mDragged=true; mouseX=e.getX(); mouseY=e.getY(); imageVX=mouseStartX-mouseX; imageVY=mouseStartY-mouseY; repaint(); System.out.println("ruch"); } repaint(); //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. }
1
private boolean jj_3_15() { if (jj_3R_33()) return true; return false; }
1
@Override public void draw() { glColor3d(255, 204, 0); Rectangle bounds = getAbsoluteRect(); glBegin(GL_QUADS); glVertex3i(bounds.x + width, bounds.y, 0); glVertex3i(bounds.x + width, bounds.y + height, 0); glVertex3i(bounds.x, bounds.y + height, 0); glVertex3i(bounds.x, bounds.y, 0); glEnd(); }
0
private Chunk generate(Point p) { Chunk c = new Chunk((new Random()).nextInt(Chunk.NUM_BIOMES-1), 0, p); if (p.x == 0 && p.y == 0) { ArrayList<Villager> population = new ArrayList<Villager>(); population.add(new Villager()); population.add(new Villager()); population.add(new Villager()); population.add(new Villager()); population.add(new Villager()); population.add(new Villager()); population.add(new Villager()); population.add(new Villager()); population.add(new Villager()); population.add(new Villager()); population.add(new Villager()); Village village = new Village(population, 0, 0); c.addVillage(village); } return c; }
2
@Override /** * Issues actions to units *@param gs the game state *@param time_limit how much time is given for this turn (msec) */ public void getAction(GameState gs, int time_limit) { turn_start = System.currentTimeMillis(); turn_limit = time_limit; state = gs; current_turn++; if (!init) { initialize(); } update_unit_list(); traffic_map.update(current_turn); production_manager.update(this); farm_manager.update(this); attack_manager.update(this); exploration_manager.update(this); town_manager.update(this); production_manager.manage_units(this); farm_manager.manage_units(this); town_manager.manage_units(this); attack_manager.manage_units(this); exploration_manager.manage_units(this); // execute unit orders boolean finished = true; boolean builders = false; for (int i = last_unit; i < units.size(); i++) { if (System.currentTimeMillis()-turn_start > turn_limit) { // System.out.println(player_id+" out of time on turn "+current_turn); last_unit = i; builders = false; finished = false; break; // out of time } units.get(i).act(this); if (units.get(i).stats.hasAction() && units.get(i).stats.getAction().getType() == UnitAction.BUILD) { builders = true; } } if (finished) { last_unit = 0; } if (!builders) { for (int i = 0; i < money.size(); i++) { money.set(i, state.getResources(i)); } } }
8
private void runTree(RBNode root) { if (root != nil) { if (root.getColor() == Color.BLACK) { treeStr.add(root.getKey() + " [style=filled,color=black,fontcolor=white];"); } else { treeStr.add(root.getKey() + " [style=filled,color=red];"); } runTree(root.getLeft()); if (root.getLeft() != nil) { treeStr.add(root.getKey() + " -> " + root.getLeft().getKey() + ";"); } else { treeStr.add("LNil" + root.getKey() + " [label=\"Nil\"];"); treeStr.add(root.getKey() + " -> " + "LNil" + root.getKey() + ";"); } if (root.getRight() != nil) { treeStr.add(root.getKey() + " -> " + root.getRight().getKey() + ";"); runTree(root.getRight()); } else { treeStr.add("RNil" + root.getKey() + " [label=\"Nil\"];"); treeStr.add(root.getKey() + " -> " + "RNil" + root.getKey() + ";"); } } else { return; } }
4
public static Visualization Fusion(Visualization visu1, Visualization visu2) throws IncompatibleIndexAxisException { Visualization visualization = new Visualization(); for(Resource resource : visu1.getResources()) visualization.addResource(resource); for(Resource resource : visu2.getResources()) visualization.addResource(resource); boolean sametype = true; Object[] array = visualization.getResources().toArray(); Resource first = (Resource)array[0]; DataType type = first.getKey().getType(); for(int i=1;i<array.length;i++) { Resource current = (Resource)array[i]; if (!current.getKey().getType().equals(type)) throw new IncompatibleIndexAxisException("You can't fusion visualization with different index types !"); } for(Concern concern : visu1.getConcerns()) visualization.addConcern(concern); for(Concern concern : visu2.getConcerns()) visualization.addConcern(concern); return visualization; }
6
public List<String> getWords(){ List<String> res = new ArrayList<String>(); for (int x = 0; x < points.length; x++) { for (int y = 0; y < points.length;y++) { Point[][] points = getPointArray(x, y); Point[] word = new Point[WORD_LENGTH]; Boolean b; for (int j = 0; j < (int) Math.pow(8, WORD_LENGTH); j++) { b = false; for (int i = 0; i < WORD_LENGTH; i++) { word[i] = points[i][j / (int) Math.pow(8, WORD_LENGTH - i - 1)]; if (word[i].getLetter() == '*') { b = true; } for (int k = 0; k < i; k++) { if (word[k].equals(word[i])) { b = true; } } } if (!b) { char[] charRes = new char[WORD_LENGTH]; for (int k = 0; k < WORD_LENGTH; k++) { charRes[k] = word[k].getLetter(); } res.add(new String(charRes)); } } } } return res; }
9
public void testDefaultSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); DateTimeZone.setDefault(PARIS); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } }
2