text
stringlengths
14
410k
label
int32
0
9
public void createBankAccount(CommandSender sender, String name, String player) { Bank bank = iConomy.getBank(name); if (!iConomy.hasAccount(player)) { Messaging.send(sender, this.Template.color("error.bank.account.none")); return; } Account account = iConomy.getAccount(player); if (bank == null) { Messaging.send(sender, this.Template.parse("error.bank.doesnt", new String[] { "+bank,+name,+b,+n" }, new String[] { name })); return; } int count = iConomy.Banks.count(player); if (((count > 1) && (!Constants.BankingMultiple)) || (!iConomy.hasPermissions(sender, "iConomy.bank.join.multiple"))) { Messaging.send(sender, this.Template.color("error.bank.account.maxed")); return; } if (bank != null) { double fee = bank.getFee(); if (fee > account.getHoldings().balance()) { Messaging.send(sender, this.Template.color("error.bank.account.funds")); return; } if (bank.createAccount(player)) { account.getHoldings().subtract(fee); Messaging.send(sender, this.Template.color("tag.bank") + this.Template.parse("accounts.bank.create", new String[] { "+bank,+b", "+name,+n" }, new String[] { name, player })); if (count == 0) { iConomy.getAccount(player).setMainBank(bank.getId()); } return; } Messaging.send(sender, this.Template.color("error.bank.account.failed")); } }
9
private void updateView() { /* Siuntėjo/gavėjo grupė */ int index = 0; if (textRadio.isSelected()) { index = 1; } else if (imageRadio.isSelected()) { index = 2; } /* Pakeičiamas siuntėjas/gavėjas */ currentSender = senders[index]; currentReceiver = receivers[index]; for (int i = 0; i < senders.length; i++) { if (i == index) { senders[i].setVisible(true); receivers[i].setVisible(true); } else { senders[i].setVisible(false); receivers[i].setVisible(false); } } /* Pakeičiamas vertimo į dvejetainį kodą patikrinimo objektas */ integrityPanel.setVisible(index != 0); if (index != 0) { integrityCheck = integrityChecks[index - 1]; for (int i = 1; i < senders.length; i++) { if (i == index) { integrityChecks[i - 1].setVisible(true); } else { integrityChecks[i - 1].setVisible(false); } } } else { integrityCheck = null; } /* Išvalomos kitų duomenų struktūrų paliktos šiukšlės */ resetData(); }
7
static final boolean method2354(LocationMode class364, int i) { anInt3954++; if (i != -1) method2355(-93, (byte) 115, true, null, -92, -67, 6); if (Class367_Sub8.aClass364_7361 != class364 && Class26.aClass364_382 != class364 && Class108.aClass364_1657 != class364 && class364 != Class342.aClass364_4246) return false; return true; }
5
public SingleTaskQueue(TaskExecutor<T> taskExecutor) { this.taskExecutor = taskExecutor; }
0
public int getHealthyPeople() { int persons = 0; for (int i = 0; i < items.size(); i++) { if (items.get(i) instanceof Person) { if(! items.get(i).dying() ) persons++; } } return persons; }
3
public boolean Step(int direction) { boolean result = super.Step(direction); // call Moveables Step if(result) // Check if we were able to move? { client.setEye(this); //Update eye. return true; } return false;// Otherwise return false }
1
public void demarrer(Client joueur) { int choiceInt = -1; boolean wrong = true; System.out.println("Bienvenue dans l'hôtel\nQue voulez-vous faire?"); System.out.println("Votre solde est de " + joueur.soldeDuCompte + "€"); System.out.println("Bienvenue à l'hotel du Casino" + "\nVeuillez choisir la chambre desiree" + "\n pour prendre une chambre de luxe (100€) tapez 1" + "\n pour prendre une chambre familiale (60€) tapez 2" + "\n pour une chambre standard (50€) tapez 3" + "\n pour partir tapez 4"); do { String choice = keyboard.nextLine(); try { choiceInt = Integer.parseInt(choice); if (choiceInt != 1 && choiceInt != 2 && choiceInt != 3 && choiceInt != 4) { throw new Exception("not 1, 2 or 3or 4"); } wrong = false; } catch (Exception e) { System.out.println("Mauvaise valeur inseree"); } } while (wrong); switch (choiceInt) { case 1: this.dette += 100; this.dette += ChambreLuxe.Action(joueur); break; case 2: this.dette += 60; this.dette += ChambreFamiliale.Action(joueur); break; case 3: this.dette += 50; this.dette += ChambreStandard.Action(joueur); break; default : break; } this.PrendreUneChambre(joueur); }
9
private static void getCmdsPlayer(Player player) { m.player(player, "&a____________[ &6DoOdy Commands &a]____________"); m.player(player, "&a____________[ &6Short: /dm, /duty &a]____________"); if (player.isOp() || player.hasPermission("doody.duty")) { m.player(player, "&6/doody &bon &fTurns on Duty Mode."); m.player(player, "&6/doody &boff &fTurns off Duty Mode."); } if (player.isOp() || player.hasPermission("doody.others")) { m.player(player, "&6/doody &b<player> <on/off> &fPut <player> <on/off> Duty Mode."); } m.player(player, "&6/doody &blist &fShows players on DoOdy Duty."); if (player.isOp() || player.hasPermission("doody.reload")) { m.player(player, "&6/doody &breload &fReload the config.yml changes ingame."); } if (player.isOp() || player.hasPermission("doody.debug")) { m.player(player, "&6/doody &bdebug on/off &fEnable/Disable debug mode."); } if (!dutyList.isEmpty()) { m.player(player, "&a____________[ &6Players on Duty &a]____________"); m.player(player, "&6" + dutyList); } }
9
public final boolean equals(Object par1Obj) { if (!(par1Obj instanceof LongHashMapEntry)) { return false; } else { LongHashMapEntry var2 = (LongHashMapEntry)par1Obj; Long var3 = Long.valueOf(this.getKey()); Long var4 = Long.valueOf(var2.getKey()); if (var3 == var4 || var3 != null && var3.equals(var4)) { Object var5 = this.getValue(); Object var6 = var2.getValue(); if (var5 == var6 || var5 != null && var5.equals(var6)) { return true; } } return false; } }
7
private void attack(){ if (attackTime >= attackSpeed && isHooked){ attackTime = 0; int k = ms.getDmg(); int levelP = hookedPlayer.getInfo().getLevel(); int levelM = ms.getLevel(); float pierce = (levelM - levelP) * Balance.PIERCE_REDUCT; if (pierce < 0){ pierce = 0; } float reduct = hookedPlayer.getInfo().getDmgReduct() - pierce; float dmg = k - (k * reduct); String s = df.format(dmg); dmg = Float.parseFloat(s); if (!hookedPlayer.isDead()){ log.writeToLog(ms.getName() + " hit " + hookedPlayer.getInfo().getName() + " for " + dmg, new Color(100,0,0)); hookedPlayer.takeDamage(dmg); } if (hookedPlayer.isDead()){ isHooked = false; isDespawned = true; } } }
5
protected boolean isFinished() { return _hasChanged && !Robot.tomahawk.isForward(); }
1
public boolean canSellerLogout() { String serviceName; Set<String> services = this.matchingUsers.keySet(); Iterator<String> serviceIt = services.iterator(); HashMap<String, String> userStatuses; while (serviceIt.hasNext()) { serviceName = serviceIt.next(); if (!this.matchingUsers.isEmpty()) { userStatuses = this.matchingUsers.get(serviceName); if (userStatuses.containsValue(StatusMessages.offerExceeded) || userStatuses.containsValue(StatusMessages.offerMade) || userStatuses.containsValue(StatusMessages.transferStarted) || userStatuses.containsValue(StatusMessages.transferInProgress)) return false; } } return true; }
6
private void populate() { Random rand = Randomizer.getRandom(); field.clear(); for(int row = 0; row < field.getDepth(); row++) { for(int col = 0; col < field.getWidth(); col++) { if(rand.nextDouble() <= FOX_CREATION_PROBABILITY) { Location location = new Location(row, col); Fox fox = new Fox(true, field, location); actors.add(fox); } else if(rand.nextDouble() <= RABBIT_CREATION_PROBABILITY) { Location location = new Location(row, col); Rabbit rabbit = new Rabbit(true, field, location); actors.add(rabbit); } else if(rand.nextDouble() <= BEAR_CREATION_PROBABILITY) { Location location = new Location(row, col); Bear bear = new Bear(true, field, location); actors.add(bear); } else if(rand.nextDouble() <= HUNTER_CREATION_PROBABILITY) { Location location = new Location(row, col); Hunter hunter = new Hunter(field, location); actors.add(hunter); } else if(rand.nextDouble() <= GRASS_CREATION_PROBABILITY) { Location location = new Location(row, col); Grass grass = new Grass(true, field, location); actors.add(grass); } // else leave the location empty. } } }
7
public static void main(String[] args) { try{ System.out.println("Start time ms:" +System.currentTimeMillis()); if(args.length>=1){ min_support = Integer.parseInt(args[0]); System.out.println("Using Min Support of "+min_support); } Vector<String> candidates = new Vector<String>(); MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("POS"); DBCollection itemColl = db.getCollection("SMALLPOSTX"); BasicDBList list = (BasicDBList)itemColl.distinct("LINEITEMS.EAN"); System.out.println(list.size()+" unique EANs, determining how many occur >"+min_support+" times"); for(int n=0; n<list.size(); n++){ if(itemColl.find(new BasicDBObject("LINEITEMS.EAN", list.get(n))).count()>min_support) candidates.add(""+list.get(n)); } System.out.println("Found "+candidates.size()+" candidates (EANs appear more that "+min_support+" times)"); //this needs to be multi-threaded! combination(itemColl,candidates); System.out.println("End time ms:" +System.currentTimeMillis()); } catch(Exception e){ e.printStackTrace(); System.exit(-1); } }
4
public static Mapper parseMapTask(String mapTaskDetailsJsp, boolean needMetrics) { Document mapDetails = HtmlFetcher.getHtml(mapTaskDetailsJsp); Element tr = null; for(Element elem : mapDetails.getElementsByTag("tbody").first().children()) { if(elem.child(2).text().equals("SUCCEEDED")) { tr = elem; break; } } Mapper mapper = new Mapper(); String taskId = tr.child(0).text(); mapper.setTaskId(taskId); // set TaskId String machine = tr.child(1).text(); machine = machine.substring(machine.lastIndexOf('/')+1); Element locTr = mapDetails.getElementsByTag("tbody").last(); String[] splitLocations = new String[locTr.children().size()]; int i = 0; for(Element elem : locTr.children()) { String location = elem.text(); splitLocations[i++] = location.substring(location.lastIndexOf('/') + 1); } mapper.getInput().setInputItems(machine, splitLocations); // set machine and splitLocations String counterLink = tr.child(8).child(0).absUrl("href"); parseMapTaskCounters(counterLink, mapper); //set task counters String logLink = tr.child(7).child(4).absUrl("href"); parseMapTaskLog(logLink, mapper); // set task log infos String metricsLink = tr.child(0).child(0).absUrl("href") + "&text=true"; if(needMetrics) parseMapTaskMetrics(metricsLink, mapper); // set task metrics return mapper; }
4
public static Object[][] getData(String csvFile) throws Exception { int numberOfLines = countLines(new File(csvFile)); if (numberOfLines == -1) { throw new Exception("File not found exception"); } BufferedReader br = null; String line = "", csvSplitBy = ","; String[] temp; Object[][] loginDetails = new Object[numberOfLines][]; ArrayList<String> csvDetails = new ArrayList<String>(); Map<String, String> passDetails = new HashMap<String, String>(); try { br = new BufferedReader(new FileReader(csvFile)); while ((line = br.readLine()) != null) { csvDetails.add(line); } int i = 0; for (String s : csvDetails) { passDetails.clear(); temp = s.split(csvSplitBy); passDetails.put("username", temp[0]); passDetails.put("password", temp[1]); loginDetails[i] = new Object[]{passDetails}; i++; } return loginDetails; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; }
7
public void advanceX(Direction direction) { if(limitToScreenBounds) { if(direction == Direction.LEFT) { if((this.x - speed) < 0) { // Prevent movement, object is at min screen bounds return; } } else if(direction == Direction.RIGHT) { if((this.x + speed) > (this.panelWidth - this.width)) { // Prevent movement, object is at max screen bounds return; } } } if(direction == Direction.LEFT) { this.x -= speed; } else if(direction == Direction.RIGHT) { this.x += speed; } else { System.out.println("Unsupported direction for x axis!"); } this.bounds.setElevation(this.x, this.y); }
7
private Class<?> compileSource0(String className, String sourceCode) throws Exception { List<MemorySourceJavaFileObject> compUnits = new ArrayList<MemorySourceJavaFileObject>(1); compUnits.add(new MemorySourceJavaFileObject(className + ".java", sourceCode)); DiagnosticCollector<JavaFileObject> diag = new DiagnosticCollector<JavaFileObject>(); log.debug("Running compiler with options: " + compilerOptions); Boolean result = compiler.getTask(null, fileManager, diag, compilerOptions, null, compUnits).call(); if (result.equals(Boolean.FALSE)) { throw new RuntimeException(diag.getDiagnostics().toString()); } try { String classDotName = className.replace('/', '.'); return Class.forName(classDotName, true, loader); } catch (ClassNotFoundException e) { throw e; } }
3
public static Map toMap(JSONObject json, String key) { if (null == json) { return null; } if (!StringUtils.isEmpty(key) && !json.has(key)) { return null; } Map jsonMap = new HashMap(); JSONObject convertible = StringUtils.isEmpty(key) ? json : (JSONObject) json.get(key); Iterator keysIterator = convertible.keys(); while (keysIterator.hasNext()) { String k = (String) keysIterator.next(); Object v = convertible.get(k); jsonMap.put(k, v); } return jsonMap; }
5
public static String getFileHeader(InputStream is) { byte[] b = new byte[28]; try { is.read(b); } catch (IOException e) { LOGGER.info("InputStream Reading Error!"); } finally { if (is != null) { try { is.close(); } catch (IOException e) { LOGGER.info("InputStream Closing Error!"); } } } return bytesToHexString(b).toUpperCase(); }
3
private String getJSONString() throws UBLFetchException { InputStream inputStream = null; try { inputStream = m_ublLocation.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder jsonStringBuilder = new StringBuilder(); String tempLine; while ((tempLine = reader.readLine()) != null) { jsonStringBuilder.append(tempLine); } return jsonStringBuilder.toString(); } catch (IOException ioe) { throw new UBLFetchException(); } finally { try { if(inputStream != null) { inputStream.close(); } } catch (IOException ignored) {} } }
4
@Override public void actionPerformed(ActionEvent event) { if ((event.getSource().equals(btnOk)) || (event.getSource().equals(btnCancel))) { modalResult = (event.getActionCommand().equals("ok")); setVisible(false); } }
2
private Fraction reduce() { Fraction result = new Fraction(); int common = 0; // get absolute values for numerator and denominator int num = Math.abs(numerator); int den = Math.abs(denominator); // figure out which is less, numerator or denominator if (num > den) common = gcd(num, den); else if (num < den) common = gcd(den, num); else // if both are the same, don't need to call gcd common = num; // set result based on common factor derived from gcd result.numerator = numerator / common; result.denominator = denominator / common; if (result.numerator < 0 && result.denominator < 0){ result.numerator = -result.numerator; result.denominator = -result.denominator; } else if ( result.numerator >= 0 && result.denominator < 0){ result.denominator =-result.denominator; result.numerator =-result.numerator; } return result; }
6
@Override public void flush() { // Only a streaming source can be flushed, because only streaming // sources have queued buffers: if( channelType != SoundSystemConfig.TYPE_STREAMING ) return; // determine how many buffers have been queued: int queued = AL10.alGetSourcei( ALSource.get( 0 ), AL10.AL_BUFFERS_QUEUED ); // Check for errors: if( checkALError() ) return; IntBuffer intBuffer = BufferUtils.createIntBuffer( 1 ); while( queued > 0 ) { try { AL10.alSourceUnqueueBuffers( ALSource.get( 0 ), intBuffer ); } catch( Exception e ) { return; } if( checkALError() ) return; queued--; } millisPreviouslyPlayed = 0; }
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 void addPropertyFilter(String key, PropertyFilter filter) { PropertyFilterChain filter_chain = getPropertyFilterChain(key); if (filter_chain == null) { filter_chain = new PropertyFilterChainImpl(); setPropertyFilterChain(key, filter_chain); } filter_chain.addFilter(filter); }
1
private void createContent() { content = new JEditorPane(); content.setContentType("text/html"); content.setEditable(false); setNicerFont(content); content.addHyperlinkListener( new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent e) { if( e.getEventType() == HyperlinkEvent.EventType.ACTIVATED && Desktop.isDesktopSupported() ) { try { Desktop.getDesktop().browse( e.getURL().toURI() ); } catch (URISyntaxException | IOException ex) { /* not supported */ } } } }); }
3
private void treatmentPage(){ TTP_remark.setText(null); TreatmentRec treatmentRec = new TreatmentRec(db,patient,doctorID); if (patient != null){ patient.addTreatmentRec(treatmentRec); TTP_remark.setText(patient.getTreatmentRec(patient.getTreatmentRecSize()-1).getCondition()); patient.getTreatmentRec(patient.getTreatmentRecSize()-1).setRemarks(TTP_remark.getText()); } treatmentPane = new JPanel(); treatmentPane.setBackground(SystemColor.activeCaption); treatmentPane.setLayout(null); JLabel lblTreatment = new JLabel("Treatment"); lblTreatment.setHorizontalAlignment(SwingConstants.CENTER); lblTreatment.setFont(new Font("Arial", Font.BOLD, 30)); lblTreatment.setBounds(349, 20, 286, 47); treatmentPane.add(lblTreatment); JLabel lbl_Tt = new JLabel("Enter treatment type"); lbl_Tt.setFont(new Font("Arial", Font.PLAIN, 20)); lbl_Tt.setBounds(10, 10, 193, 24); JP_treatmentType.add(lbl_Tt); TtCB_text.removeAllItems(); TreatmentMeta.addCombo(db, TtCB_text); TtL_model.removeAllElements(); TbL_model.removeAllElements(); TtL_list.getSelectionModel().addListSelectionListener(new ListSelectionListener(){ @Override public void valueChanged(ListSelectionEvent arg0) { if (TtL_list.getSelectedIndex()!=-1){ Tlbl_total.setText(Float.toString(patient.getTreatmentRec(patient.getTreatmentRecSize()-1).getTreatment(TtL_list.getSelectedIndex()).getPrice())); TbL_model.removeAllElements(); if (TtL_list.getSelectedIndex()!=-1) for (int i=0; i<patient.getTreatmentRec(patient.getTreatmentRecSize()-1).getTreatment(TtL_list.getSelectedIndex()).getPartsSize(); i++){ TbL_model.add(i, patient.getTreatmentRec(patient.getTreatmentRecSize()-1).getTreatment(TtL_list.getSelectedIndex()).getParts(i)); } } }}); if (patient!=null){ final float discount = patient.getTreatmentRec(patient.getTreatmentRecSize()-1).getDiscount(); JButton TtB_save = new JButton("Save"); TtB_save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { int cur_rec = patient.getTreatmentRecSize()-1; float tmp_price; float tmp_sub_price; //add treatment Treatment treatment = new Treatment(); treatment.setType(db.getClinic().getTreatmentMeta(TtCB_text.getSelectedIndex()).getType()); patient.getTreatmentRec(patient.getTreatmentRecSize()-1).addTreatment(treatment); //update list TtL_model.add(patient.getTreatmentRec(patient.getTreatmentRecSize()-1).getTreatmentSize()-1, patient.getTreatmentRec(patient.getTreatmentRecSize()-1).getTreatment(patient.getTreatmentRec(patient.getTreatmentRecSize()-1).getTreatmentSize()-1).getType()); if (!(db.getClinic().getTreatmentMeta(TtCB_text.getSelectedIndex()).isBodyPart())){ //calculate price tmp_sub_price = patient.getTreatmentRec(cur_rec).getTotalPrice() + db.getClinic().getTreatmentMeta(TtCB_text.getSelectedIndex()).getFpp()*discount; patient.getTreatmentRec(cur_rec).setTotalPrice(tmp_sub_price); tmp_price = db.getClinic().getTreatmentMeta(TtCB_text.getSelectedIndex()).getFpp()*discount; patient.getTreatmentRec(cur_rec).getTreatment(patient.getTreatmentRec(cur_rec).getTreatmentSize()-1).setPrice(tmp_price); //update price Tlbl_total.setText(Float.toString(tmp_price)); Tlbl_Sub_total.setText(Float.toString(tmp_sub_price)); } } }); TtB_save.setFont(new Font("Arial", Font.PLAIN, 20)); TtB_save.setBounds(39, 90, 79, 33); JP_treatmentType.add(TtB_save); JButton Ttb_clear = new JButton("Clear"); Ttb_clear.setFont(new Font("Arial", Font.PLAIN, 20)); Ttb_clear.setBounds(157, 90, 90, 33); JP_treatmentType.add(Ttb_clear); JLabel lbl_Tb = new JLabel("Enter Body part"); lbl_Tb.setFont(new Font("Arial", Font.PLAIN, 20)); lbl_Tb.setBounds(10, 10, 155, 24); JP_bodyPart.add(lbl_Tb); JButton TbB_save = new JButton("Save"); TbB_save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if ((db.getClinic().getTreatmentMeta(TtCB_text.getSelectedIndex()).isBodyPart())){ if (!TbT_text.getText().equals("")){ int cur_rec = patient.getTreatmentRecSize()-1; int cur_treat = TtL_list.getSelectedIndex(); float tmp_price; float tmp_sub_price; if (cur_treat!=-1){ //add parts patient.getTreatmentRec(cur_rec).getTreatment(cur_treat).addParts(TbT_text.getText()); //update list TbL_model.add(patient.getTreatmentRec(cur_rec).getTreatment(cur_treat).getPartsSize()-1, patient.getTreatmentRec(cur_rec).getTreatment(cur_treat).getParts(patient.getTreatmentRec(cur_rec).getTreatment(cur_treat).getPartsSize()-1)); //clear textField TbT_text.setText(null); //calculate price tmp_sub_price = patient.getTreatmentRec(cur_rec).getTotalPrice() + db.getClinic().getTreatmentMeta(db.getClinic().searchType(patient.getTreatmentRec(cur_rec).getTreatment(cur_treat).getType())).getFpp()*discount; patient.getTreatmentRec(cur_rec).setTotalPrice(tmp_sub_price); tmp_price = patient.getTreatmentRec(cur_rec).getTreatment(cur_treat).getPrice() + db.getClinic().getTreatmentMeta(db.getClinic().searchType(patient.getTreatmentRec(cur_rec).getTreatment(cur_treat).getType())).getFpp()*discount; patient.getTreatmentRec(cur_rec).getTreatment(cur_treat).setPrice(tmp_price); //update price Tlbl_total.setText(Float.toString(tmp_price)); Tlbl_Sub_total.setText(Float.toString(tmp_sub_price)); } else{ JOptionPane.showMessageDialog(null, "Please select a Treatment type from the Type of treatment list","Body Parts", JOptionPane.WARNING_MESSAGE); } } else{ JOptionPane.showMessageDialog(null, "Please enter body part","Body Parts", JOptionPane.WARNING_MESSAGE); } }else{ JOptionPane.showMessageDialog(null, "No body parts should be entered.","Body Parts", JOptionPane.WARNING_MESSAGE); TbT_text.setText(null); } } }); TbB_save.setFont(new Font("Arial", Font.PLAIN, 20)); TbB_save.setBounds(39, 90, 79, 33); JP_bodyPart.add(TbB_save); } JButton TbB_clear = new JButton("Clear"); TbB_clear.setFont(new Font("Arial", Font.PLAIN, 20)); TbB_clear.setBounds(157, 90, 90, 33); JP_bodyPart.add(TbB_clear); JLabel lbl_remark = new JLabel("Remark:"); lbl_remark.setFont(new Font("Arial", Font.PLAIN, 20)); lbl_remark.setBounds(10, 15, 85, 24); JP_remark.add(lbl_remark); JButton TB_patient = new JButton("Patient"); TB_patient.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { cardLayout.show(contentPane, "Patient"); } }); TB_patient.setFont(new Font("Arial", Font.PLAIN, 20)); TB_patient.setBackground(new Color(255, 192, 203)); TB_patient.setBounds(808, 566, 143, 47); treatmentPane.add(TB_patient); JButton TB_save = new JButton("Save"); TB_save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { patient.getTreatmentRec(patient.getTreatmentRecSize()-1).setRemarks(TTP_remark.getText()); } }); TB_save.setFont(new Font("Arial", Font.PLAIN, 20)); TB_save.setBounds(529, 565, 143, 48); treatmentPane.add(TB_save); JLabel lbl_total = new JLabel("Total"); lbl_total.setFont(new Font("Arial", Font.PLAIN, 20)); lbl_total.setBounds(10, 48, 123, 24); JP_fee.add(lbl_total); JLabel lblSubtotal = new JLabel("Sub-Total"); lblSubtotal.setFont(new Font("Arial", Font.PLAIN, 20)); lblSubtotal.setBounds(10, 14, 123, 24); JP_fee.add(lblSubtotal); }
9
public static LayerBox getInstance() { if (instance_ == null) instance_ = new LayerBox(); return instance_; }
1
public final Path getPath(final String titleMsg, final FileFilter filter, final File initialDirectory) { final JFileChooser chooser; final JLabel title = new JLabel(titleMsg); this.mainFrame.isAlwaysOnTop(); chooser = new JFileChooser(initialDirectory); chooser.setDialogTitle(title.getText()); chooser.setDialogType(JFileChooser.OPEN_DIALOG); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.removeChoosableFileFilter(chooser.getChoosableFileFilters()[0]); chooser.setFileFilter(filter); chooser.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { synchronized (Button.class) { if (GUI.this.pressed != null) { return; } if (e.getActionCommand().equals("ApproveSelection")) { GUI.this.pressed = Button.YES; } else { GUI.this.pressed = Button.NO; } Button.class.notifyAll(); } } }); final boolean aot = this.mainFrame.isAlwaysOnTop(); this.mainFrame.setAlwaysOnTop(false); this.mainFrame.getContentPane().removeAll(); this.mainFrame.add(chooser); this.mainFrame.add(title, BorderLayout.NORTH); waitForButton(" TODO getPath()"); this.mainFrame.setAlwaysOnTop(aot); if (this.pressed != Button.YES) { return null; } final File file = chooser.getSelectedFile(); if (file == null) { return null; } return Path.getPath(file.toString()); }
4
public static void listEmployees(EntityManager entityManager) { TypedQuery<Employee> query = entityManager.createQuery( "select e from Employee e", Employee.class); List<Employee> resultList = query.getResultList(); entityManager.close(); for (Employee employee : resultList) { System.out.println(employee.toString()); } }
1
public void updateMenu() { _highScoreInt.setText(String.valueOf(Fenetre._score.getHigh())); _currentScoreInt.setText(String.valueOf(Fenetre._score.getCurrent())); remove(_next); remove(_credits); if (Fenetre._level.nextLvlExist()) { add(_next); } else { add(_credits); } }
1
public static ArrayList<Song> initialDownload(String userName) { ArrayList<Song> allSongs=new ArrayList<Song>(); ArrayList<String> dates= new ArrayList<String>(); ArrayList<String> names= new ArrayList<String>(); ArrayList<String> artists = new ArrayList<String>(); Elements dateList; Elements nameList; Elements artistList; Element name; Element artist; Element date; String lastDate; String user= userName; TimeCalculator calc= new TimeCalculator(); System.out.println("Going to try and download your listening history now."); try { Document doc= Jsoup.connect("http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&limit=200&user="+user+"&api_key=2f8ae0c603413f99dd8e7d92a5bb430c").get(); while (doc.hasText()) { nameList = doc.getElementsByTag("name"); artistList = doc.getElementsByTag("artist"); dateList = doc.getElementsByTag("date"); for (int i = 0; i < dateList.size(); i++) { // 0=current song, size-1=oldest song name = nameList.get(i); artist = artistList.get(i); date=dateList.get(i); names.add(name.ownText()); artists.add(artist.ownText()); dates.add(date.ownText()); } if(dates.size()>0) { lastDate=dates.get(dates.size()-1); System.out.println(lastDate); lastTime=calc.calculte(lastDate); String url="http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&limit=200&user="+user+"&to="+lastTime+"&api_key=2f8ae0c603413f99dd8e7d92a5bb430c"; doc= Jsoup.connect(url).get(); } else { System.out.println("Error with downloading dates."); break; } } System.out.println("Finnished downloading your listening history."); System.out.println("Now preparing your library."); getSongLibrary(allSongs, dates, names, artists); } catch(Exception e){ System.out.println("Last.fm connection error"); System.out.println("Please restart the program."); File test = new File("library.txt"); test.delete(); System.exit(0); } if(dates.size()>0) lastTime= calc.calculte(dates.get(0)); return allSongs; }
5
@Override public String onAdvEvent(String event, L2Npc npc, L2PcInstance player) { if (event.equalsIgnoreCase("polymorph Mad Cow") && npc != null && player != null) { if (MAD_COW_POLYMORPH.containsKey(npc.getNpcId())) { // remove the feed info from the previous mob if (_FeedInfo.get(npc.getObjectId()) == player.getObjectId()) _FeedInfo.remove(npc.getObjectId()); // despawn the mad cow npc.deleteMe(); // spawn the new mob L2Attackable nextNpc = (L2Attackable) addSpawn(MAD_COW_POLYMORPH.get(npc.getNpcId()), npc, false, 0, false); // register the player in the feedinfo for the mob that just spawned _FeedInfo.put(nextNpc.getObjectId(), player.getObjectId()); attack(nextNpc, player); } } return super.onAdvEvent(event, npc, player); }
5
public static Point extractPoint(String buffer) { int[] values = extractIntegers(buffer); if (values.length == 2) { return new Point(values[0], values[1]); } return null; }
1
private static Paint createButtonPaint(AbstractButton button, int lineBorderWidth, boolean isDarkColorScheme) { boolean isPressed = button.getModel().isPressed(); Color topPressedColor = isDarkColorScheme ? WidgetBaseColors.DARK_ACTIVE_SELECTED_TOP_COLOR : WidgetBaseColors.LIGHT_ACTIVE_SELECTED_TOP_COLOR; Color topUnpressedColor = isDarkColorScheme ? WidgetBaseColors.DARK_ACTIVE_TOP_COLOR : WidgetBaseColors.LIGHT_ACTIVE_TOP_COLOR; Color bottomPressedColor = isDarkColorScheme ? WidgetBaseColors.DARK_ACTIVE_SELECTED_BOTTOM_COLOR : WidgetBaseColors.LIGHT_ACTIVE_SELECTED_BOTTOM_COLOR; Color bottomUnpressedColor = isDarkColorScheme ? WidgetBaseColors.DARK_ACTIVE_BOTTOM_COLOR : WidgetBaseColors.LIGHT_ACTIVE_BOTTOM_COLOR; Color topColor = isPressed ? topPressedColor : topUnpressedColor; Color bottomColor = isPressed ? bottomPressedColor : bottomUnpressedColor; int bottomY = button.getHeight() - lineBorderWidth * 2; return new GradientPaint(0, lineBorderWidth, topColor, 0, bottomY, bottomColor); }
6
private void goLeft(ColorPatch patch, int x, int y) { if ( --x >= 0 ) { Color color = pixel(x, y); if ( isIncluded(x, y) ) { if ( patch.getColor().distance(color, Color.RGB_DISTANCE) < tolerance ) { patch.add(color); goLeft(patch, x, y); } } exclude(x, y); } }
3
private void processKeyRelease(KeyEvent e) { int keyCode = e.getKeyCode(); keys[keyCode] = false; if (gameController.isNewCharacterOpen()) { } else if (keyCode == Settings.buttonMoveLeft) { keyLeftPressed = false; if (!keyRightPressed) { gameController.stopXMove(); } } else if (keyCode == Settings.buttonMoveRight) { keyRightPressed = false; if (!keyLeftPressed) { gameController.stopXMove(); } } else if (keyCode == Settings.buttonJump) { keySpacePressed = false; gameController.stopJump(); } else if (keyCode == Settings.buttonAction) { keyGatherPressed = false; gameController.stopActions(); } else if (keyCode == Settings.buttonRobot) { keyRobotPressed = false; } else if (keyCode == KeyEvent.VK_SHIFT) { gameController.shiftRelease(); } }
9
public synchronized void clearAll() { for (Key key : keys) { key.clear(); } }
1
public static boolean generatorCollectionP(Stella_Object collection) { if (((Boolean)(Logic.$REVERSEPOLARITYp$.get())).booleanValue() && (!Logic.closedTermP(collection))) { return (false); } { Surrogate testValue000 = Stella_Object.safePrimaryType(collection); if (Surrogate.subtypeOfP(testValue000, Logic.SGT_LOGIC_DESCRIPTION)) { { Description collection000 = ((Description)(collection)); return ((!Stella_Object.isaP(collection000, Logic.SGT_LOGIC_NAMED_DESCRIPTION)) || NamedDescription.relationSupportsExtensionP(((NamedDescription)(collection000)))); } } else if (Surrogate.subtypeOfP(testValue000, Logic.SGT_LOGIC_PATTERN_VARIABLE)) { { PatternVariable collection000 = ((PatternVariable)(collection)); { Stella_Object boundtovalue = Logic.argumentBoundTo(collection000); if (boundtovalue != null) { return (Logic.generatorCollectionP(boundtovalue)); } else if (collection000.definingProposition != null) { return (true); } else { return (false); } } } } else if (Surrogate.subtypeOfSurrogateP(testValue000)) { { Surrogate collection000 = ((Surrogate)(collection)); return (NamedDescription.relationSupportsExtensionP(Logic.getDescription(collection000))); } } else { return (true); } } }
8
@Override public String getPostalCode() { return super.getPostalCode(); }
0
@SuppressWarnings("deprecation") public static boolean czyGraczMaItemy(String p) { boolean czyMa = true; Player pp = Bukkit.getPlayer(p); if (!pp.getInventory().contains(new ItemStack(Material.DIAMOND, 64))) { czyMa = false; } if (!pp.getInventory().contains(new ItemStack(Material.GOLD_INGOT, 64))) { czyMa = false; } if (!pp.getInventory().contains(new ItemStack(Material.getMaterial(289), 64))) { czyMa = false; } if (!pp.getInventory().contains(new ItemStack(Material.SUGAR_CANE, 64))) { czyMa = false; } if (!pp.getInventory().contains(new ItemStack(Material.BRICK, 64))) { czyMa = false; } if (!pp.getInventory().contains(new ItemStack(Material.EMERALD, 64))) { czyMa = false; } if (!pp.getInventory().contains(new ItemStack(Material.SAPLING, 64))) { czyMa = false; } if (!pp.getInventory().contains(new ItemStack(Material.getMaterial(39), 64))) { czyMa = false; } return czyMa; }
8
public Document getDocument() {return this.doc;}
0
public boolean shouldPaint(){ return myKeeper == null ? true: !myKeeper.sensitive; }
1
public void loadConfig() { boolean bSaveFile = false; if (m_Plugin.getDataFolder().exists() == false) { m_Plugin.getDataFolder().mkdir(); } File configFile = new File(m_Plugin.getDataFolder(), m_ConfigFile); if (configFile.exists() == true) { try { m_ConfigData.load(configFile); } catch (Exception e) { bSaveFile = true; e.printStackTrace(); } } else { bSaveFile = true; } if (m_ConfigData.contains("LastXPos") == true) m_LastXPos = m_ConfigData.getInt("LastXPos"); if (m_ConfigData.contains("LastYPos") == true) m_LastYPos = m_ConfigData.getInt("LastYPos"); if (m_ConfigData.contains("LastZPos") == true) m_LastZPos = m_ConfigData.getInt("LastZPos"); if (bSaveFile == true) { saveConfig(); } }
7
public static Object[] decodeValues(String str) throws DecodeException { Object[] res; int i=0; int beginning = i; while (str.charAt(i) != '>') { i++; } String[] types = str.substring(beginning, i).split(":"); i++; beginning = i; if (str.charAt(i) == '<') { i++; while (i < str.length()) { i++; } String[] tab = str.substring(beginning+1, i).split(":"); res = new Object[tab.length]; for (int x=0; x<tab.length; x++) { switch(types[x]) { case "int": res[x] = Integer.valueOf(tab[x]); break; case "dbl": res[x] = Double.valueOf(tab[x]); break; case "str": res[x] = tab[x]; break; case "chr": res[x] = tab[x].charAt(0); break; case "nul": res[x] = null; break; } } } else { res = null; throw new DecodeException(); } return res; }
9
public void execute(DocumentMap dm) { init(dm); while (true) { if ((limit != 0) && (candidates.size() == limit)) { return; } candidate = indexGlobal.nextSubscript(candidate); if (candidate.equals("")) { break; } if (query.apply(candidate)) { continue; } if (uniqueIndex) { candidates.add(indexGlobal.getString(candidate)); } else { ValueList indexList = indexGlobal.getList(candidate); for (int i=0;i<indexList.length();i++) { candidates.add(indexList.getNextString()); } } } }
7
@Override public void execute(ByteStream stream) { int i = 0; while (true) { if (this.amount >= 0 && i >= this.amount) { break; } if (this.until != null) { if (Arrays.equals(stream.readBytes(this.until.length), this.until)) { break; } else { stream.advance(-this.until.length); } } this.strategy.execute(stream); i++; } }
5
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(ConsultarJuego.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ConsultarJuego.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ConsultarJuego.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ConsultarJuego.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 ConsultarJuego().setVisible(true); } }); }
6
@Override public ArrayList<String> getItems(String userId) { System.out.println("Hello from SessionBean getItems"); ArrayList<String> items = new ArrayList<String>(); TypedQuery<Item> itemsByUserQuery = emgr.createNamedQuery( "Item.findAllByUser", Item.class); itemsByUserQuery.setParameter("userName", userId); List<Item> obtainedItems = (List<Item>) itemsByUserQuery .getResultList(); for (int i = 0; i < obtainedItems.size(); i++) { items.add(obtainedItems.get(i).getItemId() + ":" + obtainedItems.get(i).getItemName() + ":" + obtainedItems.get(i).getItemModel()); } return items; }
1
public boolean setTimer(Timer t) { boolean test = false; if (test || m_test) { System.out.println("FileManager :: setTimer() BEGIN"); } m_timer = t; if (test || m_test) { System.out.println("FileManager :: setTimer() END"); } return true; }
4
private final void method653() { synchronized (this) { for (int i = 0; i < anInt5387; i++) { int i_629_ = anIntArray5356[i]; anIntArray5356[i] = anIntArray5312[i]; anIntArray5312[i] = -i_629_; if (aClass360Array5360[i] != null) { i_629_ = ((Class360) aClass360Array5360[i]).anInt4430; ((Class360) aClass360Array5360[i]).anInt4430 = ((Class360) aClass360Array5360[i]).anInt4427; ((Class360) aClass360Array5360[i]).anInt4427 = -i_629_; } } if (aClass41Array5385 != null) { for (int i = 0; i < anInt5351; i++) { if (aClass41Array5385[i] != null) { int i_630_ = ((Class41) aClass41Array5385[i]).anInt561; ((Class41) aClass41Array5385[i]).anInt561 = ((Class41) aClass41Array5385[i]).anInt559; ((Class41) aClass41Array5385[i]).anInt559 = -i_630_; } } } for (int i = anInt5387; i < anInt5340; i++) { int i_631_ = anIntArray5356[i]; anIntArray5356[i] = anIntArray5312[i]; anIntArray5312[i] = -i_631_; } anInt5354 = 0; aBoolean5323 = false; } }
6
final boolean method2121(int i, Source source, int i_3_) { anInt4745++; if (i != 25625) method2126((byte) -74); if (i_3_ > anInt4739) { method2126((byte) -36); if (anInt4746 <= 0) throw new RuntimeException("ARGH!"); OpenGL.glBindBufferARB(anInt4755, anInt4746); OpenGL.glBufferDataARBa(anInt4755, i_3_, source.getAddress(), !aBoolean4750 ? 35044 : 35040); ((NativeToolkit) ((Class285) this).aClass377_4759).anInt8063 += i_3_ - anInt4747; anInt4739 = i_3_; } else if (anInt4746 > 0) { OpenGL.glBindBufferARB(anInt4755, anInt4746); OpenGL.glBufferSubDataARBa(anInt4755, 0, anInt4747, source.getAddress()); ((NativeToolkit) ((Class285) this).aClass377_4759).anInt8063 += i_3_ - anInt4747; } else throw new RuntimeException("ARGH!"); anInt4747 = i_3_; return true; }
5
static public String ParseSrcPos() { if (Pos == null) { return null; } if (Pos.length() >= 3) { String srcpos = Pos.subSequence(0, 3).toString(); if (ParsePosition.IsPos(srcpos)) { Pos = Pos.subSequence(3, Pos.length()).toString(); return srcpos; } } if (Pos.length() >= 2) { String srcpos = Pos.subSequence(0, 2).toString(); if (ParsePosition.IsPos(srcpos)) { Pos = Pos.subSequence(2, Pos.length()).toString(); return srcpos; } } return null; }
5
@Override public void ParseIn(Connection Main, Server Environment) { Room Room = Environment.RoomManager.GetRoom(Main.Data.CurrentRoom); if (Room == null) { return; } RoomItem Item = Room.GetItem(Main.DecodeInt()); if (Item == null) { return; } int id = Room.WiredManager.GetIdWired(Item); if (id == 9999) { return; } int count = Main.DecodeInt(); // options if(count > 0) { if(Room.WiredManager.WiredOptions[id]==null || Room.WiredManager.WiredOptions[id].length != count) { Room.WiredManager.WiredOptions[id] = new int[count]; } for(int i=0;i<count;i++) { Room.WiredManager.WiredOptions[id][i] = Main.DecodeInt(); } } Room.WiredManager.WiredData[id] = Main.DecodeString(); count = Main.DecodeInt(); // Childs Count for(int i=0;i<count;i++) { Room.WiredManager.AddChild(id, i, Room.GetItem(Main.DecodeInt())); // Furni id } Main.DecodeInt(); }
8
public void addAllNewProductionsToGrammar(Grammar oldGrammar, Grammar newGrammar, VariableDependencyGraph graph) { GrammarChecker gc = new GrammarChecker(); String[] variables = oldGrammar.getVariables(); for (int k = 0; k < variables.length; k++) { String v1 = variables[k]; String[] dep = getDependencies(v1, oldGrammar, graph); for (int i = 0; i < dep.length; i++) { Production[] prods = GrammarChecker .getNonUnitProductionsOnVariable(dep[i], oldGrammar); newGrammar.addProductions(getNewProductions(v1, prods)); } } }
2
public static int is_periodic(String suc) throws ArrayIndexOutOfBoundsException{ int i, begin, end, beginAux, endAux, repetitions; begin=0; for (i = 1; i < suc.length(); i++) { repetitions=1; if (suc.charAt(0) == suc.charAt(i)){ end=i; beginAux=i; endAux=i*2; //Solamente se entra para comprobar las subsecuencias que contienen el periodo completo while(endAux <= suc.length() && (equal(suc.substring(begin, end),suc.substring(beginAux, endAux)))){ repetitions++; beginAux+=i; endAux+=i; } //Solamente se entra si las dos ultimas subsecuencias coincidieron if ((endAux > suc.length()) || (equal(suc.substring(begin, end),suc.substring(beginAux, endAux)))){ /*Comparar la ultima subsecuencia aunque no contenga el periodo entero (tambien seria valido). Si esta coincide y anteriormente hubo un minimo de 2 repeticiones del periodo se devuelve la longitud del periodo, en caso contrario se devuelve -1*/ if(suc.substring(begin, suc.substring(beginAux).length()).compareTo(suc.substring(beginAux))==0){ if(repetitions>=2){ System.out.println("El periodo se repite: "+repetitions+" veces"); String aux="El periodo obtenido es: "; String concat = aux.concat(suc.substring(begin, end)); System.out.println(concat); return i; } else return -1; } } } } return -1; }
8
public void setup( String filename ,METSMetadata gmd ) throws Exception { super.setup( filename, gmd ); BufferedReader fin = new BufferedReader(new InputStreamReader( new FileInputStream( filename ) ) ) ; String inchi1 = fin.readLine(); String inchi2 = fin.readLine(); fin.close(); if( inchi1 != null && inchi1.startsWith( "InChI=" ) ) { global_md.add_identifier( inchi1 ); global_md.add_subject( "InChI", inchi1 ); } if( inchi2!=null && inchi2.startsWith( "InChIKey=" ) ) { // global_md.identifier= inchi2; global_md.add_identifier( inchi2 ); global_md.add_subject( "InChIKey", inchi2 ); } }
4
public void enterToDatabase(ArrayList<File> songs){ for(int i=0; i<songs.size(); i++){ File song = songs.get(i); String artist = tagger.getArtist(song); String title = tagger.getTitle(song); String bpm = tagger.getBPM(song); String album = tagger.getAlbum(song); boolean badartist = true; boolean badtitle = true; boolean badbpm = true; boolean badalbum = true; if(title.equals("")){ title = song.getName();//If somehow this song has no title from echonest then set //it to file name badtitle = false; } if(artist.equals("")){ badartist = false; } if(bpm.equals("") || bpm.equals("-1")){ badbpm = false; } if(album.equals("")){ badalbum = false; } DBSong newSong = new DBSong(0, title, badtitle, song.getAbsolutePath(), true, album, badalbum, artist, badartist, 0, true, 0, true, Integer.parseInt(bpm), badbpm); dbmodel.insertSong(newSong); //dbmodel.insertSong(title, song.getAbsolutePath(), tagger.getAlbum(song), artist, 0, 0, Integer.parseInt(bpm)); } }
6
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(MotivoRejeitarAlocacao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MotivoRejeitarAlocacao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MotivoRejeitarAlocacao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MotivoRejeitarAlocacao.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 MotivoRejeitarAlocacao().setVisible(true); } }); }
6
public static void main(String[] args) throws Exception { ExecutorService exec = Executors.newCachedThreadPool(); ServerSocket server = new ServerSocket(8080); InputStream socketInput = new Socket("localhost", 8080).getInputStream(); exec.execute(new IOBlocked(socketInput)); exec.execute(new IOBlocked(System.in)); TimeUnit.MILLISECONDS.sleep(100); System.out.println("Shutting down all threads"); exec.shutdownNow(); TimeUnit.SECONDS.sleep(1); System.out.println("Closing " + socketInput.getClass().getName()); socketInput.close(); // Releases blocked thread TimeUnit.SECONDS.sleep(1); System.out.println("Closing " + System.in.getClass().getName()); System.in.close(); // Releases blocked thread }
0
public GameMap getIndex(World world) { for (GameMap map : this.maps.values()) { if (map.getWorld() == world) { return map; } } return null; }
2
@Test public void onKahdenPotenssiToimii() { assertEquals(true, h.onKahdenPotenssi(4) && h.onKahdenPotenssi(16) && h.onKahdenPotenssi(25) && h.onKahdenPotenssi(36) && h.onKahdenPotenssi(49) && h.onKahdenPotenssi(64) && h.onKahdenPotenssi(81) && h.onKahdenPotenssi(100)); }
7
public void setStatus(int status) { Status = status; }
0
@Override public void init() { super.init(); int offset = 0; grbit = ByteTools.readInt( getByteAt( offset++ ), getByteAt( offset++ ), getByteAt( offset++ ), getByteAt( offset++ ) ); short strLen = ByteTools.readShort( getByteAt( offset ), getByteAt( offset + 1 ) ); byte strGrbit = getByteAt( offset + 2 ); if( (strGrbit & 0x1) == 0x1 ) { strLen *= 2; } strLen += 3; byte[] namebytes = getBytesAt( offset, strLen ); offset += strLen; dTitlePrompt = new Unicodestring(); dTitlePrompt.init( namebytes, false ); strLen = ByteTools.readShort( getByteAt( offset ), getByteAt( offset + 1 ) ); strGrbit = getByteAt( offset + 2 ); if( (strGrbit & 0x1) == 0x1 ) { strLen *= 2; } strLen += 3; namebytes = getBytesAt( offset, strLen ); offset += strLen; dTitleError = new Unicodestring(); dTitleError.init( namebytes, false ); strLen = ByteTools.readShort( getByteAt( offset ), getByteAt( offset + 1 ) ); strGrbit = getByteAt( offset + 2 ); if( (strGrbit & 0x1) == 0x1 ) { strLen *= 2; } strLen += 3; namebytes = getBytesAt( offset, strLen ); offset += strLen; dTextPrompt = new Unicodestring(); dTextPrompt.init( namebytes, false ); strLen = ByteTools.readShort( getByteAt( offset ), getByteAt( offset + 1 ) ); strGrbit = getByteAt( offset + 2 ); if( (strGrbit & 0x1) == 0x1 ) { strLen *= 2; } strLen += 3; namebytes = getBytesAt( offset, strLen ); offset += strLen; dTextError = new Unicodestring(); dTextError.init( namebytes, false ); int sz1 = ByteTools.readShort( getByteAt( offset++ ), getByteAt( offset++ ) ); // unknown bytes garbageByteOne[0] = getByteAt( offset++ ); garbageByteOne[1] = getByteAt( offset++ ); byte[] formulaBytes = getBytesAt( offset, sz1 ); firstCond = ExpressionParser.parseExpression( formulaBytes, this ); offset += sz1; int sz2 = ByteTools.readShort( getByteAt( offset++ ), getByteAt( offset++ ) ); // unknown bytes garbageByteTwo[0] = getByteAt( offset++ ); garbageByteTwo[1] = getByteAt( offset++ ); formulaBytes = getBytesAt( offset, sz2 ); secondCond = ExpressionParser.parseExpression( formulaBytes, this ); offset += sz2; numLocs = getByteAt( offset++ ); cRangeList = new ArrayList(); for( int i = 0; i < numLocs; i++ ) { byte[] b = new byte[1]; b[0] = 0x0; b = ByteTools.append( b, getBytesAt( offset, 8 ) ); PtgArea p = new PtgArea( false ); p.setParentRec( this ); p.init( b ); cRangeList.add( p ); offset += 8; } // set all the grbit fields valType = (byte) ((grbit & BITMASK_VALTYPE)); errStyle = (byte) ((grbit & BITMASK_ERRSTYLE) >> 4); IMEMode = (short) ((grbit & BITMASK_MDIMEMODE) >> 10); fStrLookup = ((grbit & BITMASK_FSTRLOOKUP) == BITMASK_FSTRLOOKUP); fAllowBlank = ((grbit & BITMASK_FALLOWBLANK) == BITMASK_FALLOWBLANK); fSuppressCombo = ((grbit & BITMASK_FSUPRESSCOMBO) == BITMASK_FSUPRESSCOMBO); fShowInputMsg = ((BITMASK_FSHOWINPUTMSG) == BITMASK_FSHOWINPUTMSG); fShowErrMsg = ((grbit & BITMASK_FSHOWERRORMSG) == BITMASK_FSHOWERRORMSG); typOperator = (byte) ((grbit & BITMASK_TYPOPERATOR) >> 20); }
5
@Override public Course deleteCourse(long courseId) { for(int i = 0; i < courses.size(); i++){ if(courses.get(i).getId() == courseId){ return courses.remove(i); } } return null; }
2
public static Stella_Object access_PLModuleFile_Slot_Value(PLModuleFile self, Symbol slotname, Stella_Object value, boolean setvalueP) { if (slotname == GuiServer.SYM_GUI_SERVER_KBName) { if (setvalueP) { self.KBName = ((StringWrapper)(value)).wrapperValue; } else { value = StringWrapper.wrapString(self.KBName); } } else if (slotname == GuiServer.SYM_GUI_SERVER_ModuleName) { if (setvalueP) { self.ModuleName = ((StringWrapper)(value)).wrapperValue; } else { value = StringWrapper.wrapString(self.ModuleName); } } else if (slotname == GuiServer.SYM_GUI_SERVER_KBDescription) { if (setvalueP) { self.KBDescription = ((StringWrapper)(value)).wrapperValue; } else { value = StringWrapper.wrapString(self.KBDescription); } } else if (slotname == GuiServer.SYM_GUI_SERVER_FileName) { if (setvalueP) { self.FileName = ((StringWrapper)(value)).wrapperValue; } else { value = StringWrapper.wrapString(self.FileName); } } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + slotname + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } return (value); }
8
@Override public void sort(int[] array) { if (bucketCount <= 0) { throw new IllegalArgumentException("Invalid bucket count"); } if (array.length <= 1) { return; } int high = array[0]; int low = array[0]; for (int i = 1; i < array.length; i++) { //find the range of input elements if (array[i] > high) { high = array[i]; } if (array[i] < low) { low = array[i]; } } double interval = ((double) (high - low + 1)) / bucketCount; //range of one bucket ArrayList<Integer> buckets[] = new ArrayList[bucketCount]; for (int i = 0; i < bucketCount; i++) { //initialize buckets buckets[i] = new ArrayList(); } for (int i = 0; i < array.length; i++) { //partition the input array int index = (int) ((array[i] - low) / interval); buckets[index].add(array[i]); } int idx = 0; for (int i = 0; i < buckets.length; i++) { Collections.sort(buckets[i]); //mergeSort for (int j = 0; j < buckets[i].size(); j++) { //merge the buckets array[idx++] = buckets[i].get(j); } } }
9
public void enviarConsulta(String db, String query) { String queryJSON = QueryManager.crearQuery(db, query); try { socketConServidor = new Socket(servidor, puerto); DataInputStream ois = new DataInputStream( socketConServidor.getInputStream()); DataOutputStream oos = new DataOutputStream( socketConServidor.getOutputStream()); oos.writeUTF(queryJSON); System.out.println("DEBUG: CONSULTA" + queryJSON + "ENVIADA"); String respuestaJSON = ois.readUTF(); System.out.println("DEBUG: RESPUESTA" + respuestaJSON + "RECIBIDA"); List<String> respuestaEnLista; if (QueryManager.chequearError(respuestaJSON)) respuestaEnLista = QueryManager.decodificarError(respuestaJSON); else if (QueryManager.chequearActualizacion(respuestaJSON)) respuestaEnLista = QueryManager .decodificarActualizacion(respuestaJSON); else respuestaEnLista = QueryManager .decodificarRespuesta(respuestaJSON); controlador.pasarRespuestaALaVista(respuestaEnLista); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
4
public void readOrders() { String line; if (fileName == null) { System.err.println("No file name set for order list. Data read aborted."); return; } try { File file = new File(fileName); Scanner scanner = new Scanner(file, "iso-8859-1"); String[] sline; // Read number of orders line = (scanner.nextLine()); orders = Integer.parseInt(line.trim()); // Debug printout: network size data System.out.println("Orders: " + orders); // Read nodes as number, x, y for (int i = 0; i < orders; i++) { line = scanner.nextLine(); //split space separated data on line sline = line.split(" "); if ("A".equals(sline[0].trim())) { orderStart[i] = 0; // Let the A shelf be represented by 0 } else { orderStart[i] = Integer.parseInt(sline[0].trim()); } if ("A".equals(sline[1].trim())) { orderEnd[i] = 0; } else { orderEnd[i] = Integer.parseInt(sline[1].trim()); } } // Debug printout: print data for node 1 System.out.println("Order 1: " + orderStart[0] + " " + orderEnd[0]); ordersRead = true; // Indicate that all network data is in place in the DataStore } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
5
private static Player askSelectExistingPlayer(List<Player> selectedPlayers) { System.out.println("Please select one of the existing players:"); List<Integer> selectedPlayerNumbers = new ArrayList<>(); for (Map.Entry<Integer, Player> entry : players.entrySet()) { if (!selectedPlayers.contains(entry.getValue())) { System.out.println("("+entry.getKey()+") "+entry.getValue().getName()); } else { selectedPlayerNumbers.add(entry.getKey()); System.out.println("(selected) "+entry.getValue().getName()); } } int choice = 0; do { System.out.print("Please enter your choice: "); String input = scanner.nextLine(); try { choice = Integer.parseInt(input); if (choice <= 0 || choice > players.size() || selectedPlayerNumbers.contains(choice)) { throw new NumberFormatException(); } } catch (NumberFormatException nfe) { System.err.println(INCORRECT_NUMBER); } } while (choice <= 0 || choice > players.size() || selectedPlayerNumbers.contains(choice)); return players.get(choice); }
9
public Game() {// Constructor UPF.f.addKeyListener(this); UPF.f.requestFocusInWindow(); // Background sBackground = new JLabel(new ImageIcon("resources/gameBKG.jpg")); sBackground.setBounds(14, 46, 253, 445); // Return to menu button toMenu = new JButton("Menu"); toMenu.setFont(menuFont); toMenu.setBounds(183, 54, 80, 30); toMenu.addActionListener(this); // Instructions insRightTop = new JLabel(new ImageIcon("resources/insTopRight.png")); insLeftTop = new JLabel(new ImageIcon("resources/insTopLeft.png")); insRightBot = new JLabel(new ImageIcon("resources/insBotRight.png")); insLeftBot = new JLabel(new ImageIcon("resources/insBotLeft.png")); insRightTop.setBounds(143, 92, 120, 176); insLeftTop.setBounds(21, 92, 120, 176); insRightBot.setBounds(143, 271, 120, 176); insLeftBot.setBounds(21, 271, 120, 176); insRightTop.setVisible(false); insLeftTop.setVisible(false); insRightBot.setVisible(false); insLeftBot.setVisible(false); // Nets net1.setBounds(100, 78, 82, 36); net2.setBounds(100, 424, 82, 36); // Bars ImageIcon barI = new ImageIcon("resources/bar.png"); for (int i = 0; i < 4; i++) { bar[i * 2] = new JLabel(barI); bar[i * 2 + 1] = new JLabel(barI); bar[i * 2].setBounds(14, move.y1[i] + 2, 254, 5); //y1 bar[i * 2 + 1].setBounds(14, move.y2[i] + 2, 254, 5); //y2 } // Goal message goal = new JLabel("GOAL!", SwingConstants.CENTER); goal.setBounds(14, 230, 253, 90); goal.setFont(goalFont); goal.setVisible(false); // Win message win = new JLabel("", SwingConstants.CENTER); win.setBounds(14, 150, 253, 200); win.setFont(winFont); win.setVisible(false); // Start Countdown countdown = new JLabel("", SwingConstants.CENTER); countdown.setBounds(14, 230, 253, 72); countdown.setForeground(Color.yellow); countdown.setVisible(false); // Player1 ImageIcon player; player = new ImageIcon("resources/player1.png"); for (int i = 0; i != 10; i++) { player1[i] = new JLabel(player); player1[i].setSize(9, 9);// 12 } // Player2 player = new ImageIcon("resources/player2.png"); for (int i = 0; i != 10; i++) { player2[i] = new JLabel(player); player2[i].setSize(9, 9);// 12 } // Ball ball = new JLabel(new ImageIcon("resources/ball.png")); ball.setBounds(136, 265, 7, 7); ball.setVisible(false); // Scores scoreDash.setForeground(Color.yellow); scoreDash.setFont(score); scoreBlue = new JLabel("0"); scoreBlue.setForeground(Color.blue); scoreBlue.setFont(score); scoreRed = new JLabel("0"); scoreRed.setForeground(Color.red); scoreRed.setFont(score); scoreBlue.setBounds(52, 51, 15, 24); scoreDash.setBounds(67, 51, 8, 24); scoreRed.setBounds(79, 51, 15, 24); // Ad button UPF.ad.addActionListener(this); // Adding UPF.lp.add(sBackground, new Integer(1)); UPF.lp.add(net1, new Integer(2)); UPF.lp.add(net2, new Integer(2)); for (int i = 0; i != 8; i++) UPF.lp.add(bar[i], new Integer(4)); for (int i = 0; i != 10; i++) { UPF.lp.add(player1[i], new Integer(5)); UPF.lp.add(player2[i], new Integer(5)); } UPF.lp.add(ball, new Integer(3)); UPF.lp.add(goal, new Integer(6)); UPF.lp.add(win, new Integer(6)); UPF.lp.add(insRightTop, new Integer(6)); UPF.lp.add(insLeftTop, new Integer(6)); UPF.lp.add(insRightBot, new Integer(6)); UPF.lp.add(insLeftBot, new Integer(6)); UPF.lp.add(countdown, new Integer(6)); UPF.lp.add(scoreDash, new Integer(6)); UPF.lp.add(scoreBlue, new Integer(6)); UPF.lp.add(scoreRed, new Integer(6)); UPF.lp.add(toMenu, new Integer(6)); UPF.f.repaint(); resetAll(); //Resets all variables to their initial values new Thread(new RunGame()).start(); //Starts the thread that moves the ball new Thread(new MovePlayers()).start(); //Starts the thread that allows user to move players }
5
public void doNext() { CombatLog log; int dmg; double procChance; Alteration voltaicSlash = engine.getPlayer().getAlterations().get("voltaicSlash"); MathTools math = new MathTools(); log = CombatLog.getInstance(); log.write(engine.getTimeStr() + this.getName() + " "); dmg = engine.spellDamage(1.85,0.01,0,0,0.165,0.205,1610,true); // Cracking Blast Skill if (engine.getLastCrit() && (engine.getTalentRank("cracklingBlasts") > 0)) dmg *= 1 + 0.1 * engine.getTalentRank("cracklingBlasts"); // Voltaic Slash buff if (voltaicSlash != null){ dmg *= 1 + 0.15 * voltaicSlash.getNumberOfStack(); engine.getPlayer().removeAlteration("voltaicSlash"); } if (dmg > 0){ log.writeln(" for " + dmg + " damage."); engine.dealDamage(dmg); } // Chain Shock procChance = engine.getTalentRank("chainShock"); if (math.chance(procChance)) { log.write(engine.getTimeStr() + this.getName() + "(Bonus) "); dmg = engine.spellDamage(0.925,0.01,0,0,0.073,0.113,1610,true); if (engine.getLastCrit() && engine.getTalentRank("cracklingBlasts") > 0) dmg *= 1 + 0.1 * engine.getTalentRank("cracklingBlasts"); if (dmg > 0){ log.writeln(" for " + dmg + " damage."); engine.dealDamage(dmg); } } }
8
private void itmMnuAtividadeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itmMnuAtividadeActionPerformed // Menu - Cadastro > ItemMenu - Atividade UsuarioBO userBO = new UsuarioBO(); Usuario Encarregadoexistente = null; try { Encarregadoexistente = userBO.selectTodosEncarregado(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao selecionar o Encarregado", "Cadastro de Atividade", JOptionPane.ERROR_MESSAGE); } if (Encarregadoexistente == null) { JOptionPane.showMessageDialog(null, "Não existe Encarregados cadastrados\n" + "É necessário cadastrar no minimo um Encarregado !!!", "Cadastro de Atividade", JOptionPane.ERROR_MESSAGE); } else { Projeto projetExistente = null; ProjetoBO projetBO = new ProjetoBO(); try { projetExistente = projetBO.selectTodosProjeto(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao selecionar o Projeto", "Cadastro de Atividade", JOptionPane.ERROR_MESSAGE); } if (projetExistente == null) { JOptionPane.showMessageDialog(null, "Não existe Projetos cadastrados\n" + "É necessário cadastrar no minimo um Projeto !!!", "Cadastro de Atividade", JOptionPane.ERROR_MESSAGE); } else { //Instancia uma tela de cadastro de Encarregado //Se o usuario que esta logado for Um diretor ou um Gerente; //caso não seja um diretor nem Gerente é exibida uma mensagem ao usuario do sistema. //Obs: Somente diretor e gerente podem cadastrar Encarregados. if (usuarioLogado.getTipo().equals("Gerente")) { CadastroAtividadeForm cadastroAtividade = new CadastroAtividadeForm(usuarioLogado); cadastroAtividade.setVisible(true); centralizaForm(cadastroAtividade); JDP1.add(cadastroAtividade); } else { JOptionPane.showMessageDialog(null, "Você não possui previlégios para acessar \n " + "a Tela de Cadastros de Atividades!!!", "Cadastro de Encarregado", JOptionPane.ERROR_MESSAGE); } } } }//GEN-LAST:event_itmMnuAtividadeActionPerformed
5
public static void main(String [] args){ List<Thread> threads= new ArrayList<Thread>(); /** * 500 threads are created to perform this adding up */ for(int i=0; i<500; i++){ Runnable task=new MyRunnable(10000000L + i); Thread worker=new Thread(task); worker.setName(String.valueOf(i)); worker.start(); threads.add(worker); } /** * Keep a list of all threads activates and check if they are still running-this will allow to keep track of how * many threads are currently running */ int running=0; do { running=0; for(Thread thread:threads){ if(thread.isAlive()){ running++; } } System.out.println("We have "+running+ " threads"); }while(running>0); }
4
public void doEvent(int eventNumber){ if(eventNumber >= MIN_DIALOG || eventNumber <= MAX_DIALOG){ displayNextDialog(eventNumber); }else if(eventNumber == 101){ //do something }else if(eventNumber >= 102 || eventNumber <= 110){ areaTransitionEvent(eventNumber); }else if(eventNumber >= 111 || eventNumber <= 120){ openStoreEvent(eventNumber); }else{ //do something } }
7
public boolean isSorted() { int length = this.array.length, i; length--; for (i = 0; i < length; i++) { if (this.array[i].compareTo(this.array[i + 1]) < 0 || this.array[i].equals(this.array[i + 1])) { continue; } else { break; } } if (i == length) { return true; } else { return false; } }
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(JavaToSVG.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(JavaToSVG.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(JavaToSVG.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(JavaToSVG.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 JavaToSVG().setVisible(true); } }); }
6
public Value get(Key key) { Node current = root; int cmp = key.compareTo((Key) root); while (current != null) { if (cmp > 0) { current = root.right(); } else if (cmp < 0) { current = root.left(); } else { return (Value) current.getValue(); } } return null; }
3
protected Method getAccessor(Object obj, Field field, boolean isGetter) { String name = field.getName(); name = name.substring(0, 1).toUpperCase() + name.substring(1); if (!isGetter) { name = "set" + name; } else if (boolean.class.isAssignableFrom(field.getType())) { name = "is" + name; } else { name = "get" + name; } Method method = (accessors != null) ? accessors.get(name) : null; if (method == null) { try { if (isGetter) { method = getMethod(obj, name, null); } else { method = getMethod(obj, name, new Class[] { field.getType() }); } } catch (Exception e1) { // ignore } // Adds accessor to cache if (method != null) { if (accessors == null) { accessors = new Hashtable<String, Method>(); } accessors.put(name, method); } } return method; }
8
private void assignPosToPif() { int index = 0; for (pif p : PIF) { int pos = 0; if (p.code == 0) { pos = getSTPosition(p.token, identifiersST); pif n = new pif(); n.code = p.code; n.token = p.token; n.positionST = pos; PIF.set(index, n); } else if (p.code == 1) { pos = getSTPosition(p.token, constantsST); pif n = new pif(); n.code = p.code; n.token = p.token; n.positionST = pos; PIF.set(index, n); } else { } index++; } }
3
private void verifyNodeBasics(Attributes attributes) { /* id="7263630a-3284-4f46-8137-eef38adb5649" * nameResId="@string/keyboard" * description="Created by Menny Even Danan" * index="1" */ String id = attributes.getValue("id"); if ( id == null || id.length() == 0 || id.contains("change_me")) { try { UUID uuid = UUID.fromString(id); if (uuid == null) throw new RuntimeException();//so I'll catch it. } catch(Exception e) { throw new InvalidPackConfiguration(mFileName, "Node "+mNodeName+" has an invalid ID!"); } } verifyValidStringResId(attributes, "nameResId"); verifyValidAttribute(attributes, "description"); }
5
public void resizeAll() { File[] files = new File(inputDirectory).listFiles(); for (int i = 0; i < files.length; i++) { try { if (files[i].getName().endsWith(".jpg")) { resize(files[i]); } } catch (Exception e) { e.printStackTrace(); } } }
3
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse resl) { HttpSession session = req.getSession(); LogonForm user = (LogonForm) session.getAttribute("user"); if(user != null ) { session.removeAttribute("user"); session.invalidate(); return mapping.findForward("success"); } else { return mapping.findForward("failure"); } }
1
final public boolean delete(final K key) { int index = computeHash(keyData(key)) % size ; if (index < 0) index += size ; if (table[index] == null) return false ; Entry <K, V> link = table[index] ; if (link.next == null) { table[index] = null ; return true ; } Entry <K, V> prior = null ; for (; link != null ; link = link.next, prior = link) if (equals(link.key, key)) { if (prior != null) prior.next = link.next ; else table[index] = link.next ; return true ; } return false ; }
6
private static Farbe waehleFarbe(int spielerAnzahl) { Farbe farbe = null; if (spielerAnzahl > 2 || Farbe.ROT.isIstFrei() && Farbe.BLAU.isIstFrei() && Farbe.GRUEN.isIstFrei() && Farbe.SCHWARZ.isIstFrei()) { farbe = farbeAussuchen(); if (farbe.isIstFrei()) { farbe.setIstFrei(false); } else { System.out.println("Die gewählte Farbe ist bereits vergeben!"); farbe = waehleFarbe(spielerAnzahl); } } else { farbe = farbeZuweisen(); } return farbe; }
6
private char nextChar() { if (hasInput()) return input.charAt(position++); else return (char) -1; }
1
public boolean isGetClass() { MethodAnalyzer mana = getMethodAnalyzer(); if (mana == null) return false; SyntheticAnalyzer synth = getMethodAnalyzer().getSynthetic(); return (synth != null && synth.getKind() == SyntheticAnalyzer.GETCLASS); }
2
@SuppressWarnings("rawtypes") @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TKey other = (TKey) obj; if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } if (namespace == null) { if (other.namespace != null) { return false; } } else if (!namespace.equals(other.namespace)) { return false; } return true; }
9
public double getDouble(){ try{ return Double.parseDouble( value ); } catch( NumberFormatException ex ){ throw new XException( ex ); } }
1
public String parseAtcocode( InputStream in ) throws JsonParseException { JsonParser jp = null; try { jp = jsonFactory.createParser( in ); while ( jp.nextToken() != JsonToken.END_OBJECT ) { String fieldName = jp.getCurrentName(); if ( "atcocode".equals( fieldName )) { jp.nextToken(); return jp.getText(); } } throw new JsonParseException( TAG, "no atcocode found." ); } catch ( IOException e ) { throw new JsonParseException( TAG, e.getMessage() ); } finally { try { if ( jp != null ) jp.close(); if ( in != null ) in.close(); } catch ( IOException e ) {} } }
6
public static void main(String[] args) { if (args.length < 2) { System.out.println("Number of Argument " + args.length +" is smaller than 2! Exiting!!"); System.exit(0); } URL url = null; InputStream inputStream = null; FileWriter fileWriter = null; try { url = new URL(args[0]); /*args[0] is the url*/ // open the input stream and connect it into other streams for easy reading inputStream = url.openStream(); InputStreamReader bufferedInputStream = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(bufferedInputStream); System.out.println("Open connection to: " + args[0]); fileWriter = new FileWriter(args[1]); /*args[1] is the file name */ System.out.println("Open file: " + args[1]); System.out.println("starting to write into file...."); String line = bufferedReader.readLine(); while (line != null) { fileWriter.write(line); line = bufferedReader.readLine(); } System.out.println("Finished write to file!"); } catch (IOException e) { e.printStackTrace(); } finally { System.out.println("Closing resources..."); // close resources if (fileWriter != null) { try { fileWriter.close(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } System.out.println("Resources closed..."); } }
7
private void removeAVL(TreeNode startingNode, String searchingKey) { currentSearchHeight++; if (startingNode == null) { System.out.println("\nKey " + searchingKey + " not found."); } else { if (startingNode.value.compareTo(searchingKey) > 0) { removeAVL(startingNode.left, searchingKey); } else if (startingNode.value.compareTo(searchingKey) < 0) { removeAVL(startingNode.right, searchingKey); } else if (startingNode.value.equals(searchingKey)) { removeFoundNode(startingNode); System.out.println("\nValue " + searchingKey + " removed successfully at tree height " + currentSearchHeight + "."); } } }
4
public void insertarOrdenado(int dato) { if (this.estaOrdenada()) { Nodo nuevo = new Nodo(dato); Nodo nodo = this.nodoInicial; if (this.nodoInicial == null) this.nodoInicial = new Nodo(dato); else { if (dato <= nodo.getDato()) this.insertarInicio(dato); else while (nodo != null) { if (nodo.getSiguiente() != null) { if (nodo.getDato() <= dato && nodo.getSiguiente().getDato() >= dato) { nuevo.setSiguiente(nodo.getSiguiente()); nodo.setSiguiente(nuevo); return; } } else { nodo.setSiguiente(nuevo); return; } nodo = nodo.getSiguiente(); } } } }
7
public void DescargarParche(){ try{ FileReader ArchivoConfiguracion = new FileReader("Configuracion.txt"); BufferedReader _ArchivoConfiguracion = new BufferedReader(ArchivoConfiguracion); String LineaInformacion = ""; String RutaCarpetaWoW = ""; int Linea = 0; while((LineaInformacion = _ArchivoConfiguracion.readLine())!= null){ if(Linea == 2){ RutaCarpetaWoW = LineaInformacion; break; } Linea++; } ArchivoConfiguracion.close(); _ArchivoConfiguracion.close(); String[] _RutaCarpetaWoW = RutaCarpetaWoW.split(">"); String RutaCarpetaWoWFinal = _RutaCarpetaWoW[1]; String _RutaCarpetaWoWFinal = RutaCarpetaWoWFinal.replace("wow.exe", "") + "Data"; File Directorio = new File(_RutaCarpetaWoWFinal); if(!Directorio.exists()){ if(!Directorio.mkdir()){ JOptionPane.showMessageDialog(null, "No se pudo crear la carpeta Data dónde se incluirá el parche, intenta crearla manualmente en la raíz de tu carpeta dónde se encuentra el archivo wow.exe", "Error", JOptionPane.PLAIN_MESSAGE); } } File ArchivoParche = new File(_RutaCarpetaWoWFinal + "/" + Config.Configuracion(8)); try{ URLConnection Conexion = new URL(Config.Configuracion(7)).openConnection(); Conexion.connect(); JOptionPane.showMessageDialog(null, "Empezando la descarga del parche", "Descargando...", JOptionPane.PLAIN_MESSAGE); InputStream Entrada = Conexion.getInputStream(); OutputStream Salida = new FileOutputStream(ArchivoParche); int Bytes = 0; while(Bytes != -1){ Bytes = Entrada.read(); if(Bytes != -1){ Salida.write(Bytes); } } Salida.close(); Entrada.close(); JOptionPane.showMessageDialog(null, "Descarga finalizada", "Éxito", JOptionPane.PLAIN_MESSAGE); }catch(MalformedURLException e){ JOptionPane.showMessageDialog(null, "Error, la URL solicitada es inválida, no se puede descargar el parche", "Error", JOptionPane.PLAIN_MESSAGE); }catch(IOException e){ e.printStackTrace(); } }catch(Exception e){ JOptionPane.showMessageDialog(null, "No se encontró el archivo Configuracion.txt[3]", "Error", JOptionPane.PLAIN_MESSAGE); } }
9
public static void main(String args[]) { Thread t = Thread.currentThread(); System.out.println("Current thread: " + t); // change the name of the thread t.setName("My Thread"); System.out.println("After name change: " + t); try { for(int n = 5; n > 0; n--) { System.out.println(n); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted"); } }
2
@Test public void gameStateTransitionTest() { City_Graph city_graph2 = new City_Graph(); city_graph2.loadMap("res/test.mp"); Move move = new Move("R 2"); city_graph2 = city_graph2.gameStateTransition(move); assertEquals(city_graph2.convertGameStateToString(),"CNRR"); }
0
public Queue<String> tanqueXMLUnit (){ try { path = new File(".").getCanonicalPath(); FileInputStream file = new FileInputStream(new File(path + "/xml/papabicho.xml")); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document xmlDocument = builder.parse(file); XPath xPath = XPathFactory.newInstance().newXPath(); System.out.println("************************************"); String expression01 = "/Units/Unit[@class='Tanque']"; NodeList nodeList; Node node01 = (Node) xPath.compile(expression01) .evaluate(xmlDocument, XPathConstants.NODE); if(null != node01) { nodeList = node01.getChildNodes(); for (int i = 0;null!=nodeList && i < nodeList.getLength(); i++){ Node nod = nodeList.item(i); if(nod.getNodeType() == Node.ELEMENT_NODE){ System.out.println(nodeList.item(i).getNodeName() + " : " + nod.getFirstChild().getNodeValue()); list.append(nod.getFirstChild().getNodeValue()); } } } System.out.println("************************************"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } return list; }
9
private static boolean insertPatient(Patient bean, PreparedStatement stmt) throws SQLException{ stmt.setString(1, bean.getFirstName()); stmt.setString(2, bean.getLastName()); stmt.setDate(3, bean.getDob()); stmt.setString(4, bean.getPrimaryDoc()); stmt.setString(5, bean.getPhone()); stmt.setString(6, bean.getAddress()); stmt.setString(7, bean.getCity()); stmt.setString(8, bean.getState()); stmt.setString(9, bean.getZip()); int affected = stmt.executeUpdate(); if(affected == 1){ System.out.println("new patient added successfully"); }else{ System.out.println("error adding patient"); return false; } return true; }
1
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Coordinate other = (Coordinate) obj; if (c != other.c) return false; if (r != other.r) return false; return true; }
5