text
stringlengths
14
410k
label
int32
0
9
public boolean isBoxInFrustum(double par1, double par3, double par5, double par7, double par9, double par11) { for (int i = 0; i < 6; i++) { if ((double)frustum[i][0] * par1 + (double)frustum[i][1] * par3 + (double)frustum[i][2] * par5 + (double)frustum[i][3] <= 0.0D && (double)frustum[i][0] * par7 + (double)frustum[i][1] * par3 + (double)frustum[i][2] * par5 + (double)frustum[i][3] <= 0.0D && (double)frustum[i][0] * par1 + (double)frustum[i][1] * par9 + (double)frustum[i][2] * par5 + (double)frustum[i][3] <= 0.0D && (double)frustum[i][0] * par7 + (double)frustum[i][1] * par9 + (double)frustum[i][2] * par5 + (double)frustum[i][3] <= 0.0D && (double)frustum[i][0] * par1 + (double)frustum[i][1] * par3 + (double)frustum[i][2] * par11 + (double)frustum[i][3] <= 0.0D && (double)frustum[i][0] * par7 + (double)frustum[i][1] * par3 + (double)frustum[i][2] * par11 + (double)frustum[i][3] <= 0.0D && (double)frustum[i][0] * par1 + (double)frustum[i][1] * par9 + (double)frustum[i][2] * par11 + (double)frustum[i][3] <= 0.0D && (double)frustum[i][0] * par7 + (double)frustum[i][1] * par9 + (double)frustum[i][2] * par11 + (double)frustum[i][3] <= 0.0D) { return false; } } return true; }
9
private boolean jj_3R_56() { Token xsp; xsp = jj_scanpos; if (jj_3_38()) { jj_scanpos = xsp; if (jj_3_39()) { jj_scanpos = xsp; if (jj_3_40()) { jj_scanpos = xsp; if (jj_3_41()) { jj_scanpos = xsp; if (jj_3_42()) { jj_scanpos = xsp; if (jj_3_43()) return true; } } } } } return false; }
6
public InitStmt(final LocalExpr[] targets) { this.targets = new LocalExpr[targets.length]; for (int i = 0; i < targets.length; i++) { this.targets[i] = targets[i]; this.targets[i].setParent(this); } }
1
private double recursiveDeterminant(Matrix matrix) { int n = matrix.getHeight(); if (n == 1) { return matrix.get(0, 0); } double res = 0.; for (int i = 0; i < n; i++) { Matrix newMatrix = new Matrix(n - 1, n - 1); for (int j = 0; j < n; j++) { for (int k = 1; k < n; k++) { if (j != i) { newMatrix.set(j < i ? j : j - 1, k - 1, matrix.get(j, k)); } } } res += ((i % 2 == 0 ? 1 : -1) * matrix.get(i, 0) * recursiveDeterminant(newMatrix)); } return res; }
7
public Integer getIdHistorialClinico() { return idHistorialClinico; }
0
public boolean actionTendSpecimen(Actor actor, Fauna fauna) { final float upgrade = station.structure.upgradeLevel( SurveyStation.CAPTIVE_BREEDING ) ; float success = 1 + (upgrade / 2f) ; if (actor.traits.test(XENOZOOLOGY, ROUTINE_DC, 1)) success++ ; if (actor.traits.test(DOMESTICS , SIMPLE_DC , 1)) success++ ; float inc = success * 10f / World.STANDARD_DAY_LENGTH ; Item basis = Item.withReference(REPLICANTS, fauna) ; basis = station.stocks.matchFor(basis) ; if (basis == null) { basis = Item.with(REPLICANTS, fauna, inc / 5, 0) ; fauna.health.setupHealth(0, 1, 0) ; station.stocks.addItem(basis) ; } else if (basis.amount < 1) { ///I.say("Increment is: "+inc) ; station.stocks.addItem(Item.withAmount(basis, inc / 5)) ; } else { final Item eaten = Item.withAmount(CARBS, inc * 2) ; if (station.stocks.hasItem(eaten)) { station.stocks.removeItem(eaten) ; } else inc /= 5 ; ///I.say("Increment is: "+inc) ; float oldAge = fauna.health.ageLevel() ; fauna.health.setMaturity(oldAge + inc) ; } ///I.say("Age stage/upgrade: "+fauna.health.agingStage()+"/"+upgrade) ; if (fauna.health.agingStage() >= upgrade) { station.stocks.removeItem(basis) ; final World world = actor.world() ; fauna.assignBase(actor.base()) ; fauna.enterWorldAt(station, world) ; fauna.goAboard(station, world) ; } return true ; }
6
public void associar(String principal,String secundari) throws Excepcio { boolean sec=false,prin=false; LlocSecundari llocSec=null; LlocPrincipal llocPrin=null; Iterator<Lloc> it = llocs.iterator(); Lloc l; while (it.hasNext() && (!sec || !prin)) { l=it.next(); if (l instanceof LlocSecundari) { if (l.obtNom().equals(secundari)) { sec=true; llocSec = (LlocSecundari) l; } } else if (l instanceof LlocPrincipal) { if (l.obtNom().equals(principal)) { prin=true; llocPrin = (LlocPrincipal) l; } } } if (!sec || !prin) throw new Excepcio("Error logic:\"associar\"."); else { llocPrin.afegirSecundari(llocSec); llocSec.principal=llocPrin; } }
9
protected static boolean implementsAllIfaces(ClassInfo clazz, ClassInfo[] ifaces, ClassInfo[] otherIfaces) { big: for (int i = 0; i < otherIfaces.length; i++) { ClassInfo iface = otherIfaces[i]; if (clazz != null && iface.implementedBy(clazz)) continue big; for (int j = 0; j < ifaces.length; j++) { if (iface.implementedBy(ifaces[j])) continue big; } return false; } return true; }
5
public void sendBundle(Bundle bundle) { ServalNode uplinkNode = null; if (!capabilities.isEmpty()) { // Elect ourselves to send it uplinkNode = this; } else { // Check if anybody in the mesh (i.e. neighbours) have the capability to transmit it List<ServalNode> capableNeighbours = new ArrayList<>(); for (ServalNode neighbor : mesh.getNodes()) { if (!neighbor.capabilities.isEmpty()) { capableNeighbours.add(neighbor); } } // Sunshine scenario: a neighbour can upload the packet immediately if (!capableNeighbours.isEmpty()) { // Choose a random neighbour uplinkNode = capableNeighbours.get(new Random().nextInt(capableNeighbours.size())); } } // Upload the packet immediately if (uplinkNode != null) { sendBundleOverUplink(bundle); } // Otherwise try store-and-forwarding it to an uplink else { mesh.broadcast(bundle); } }
5
public int battleCalc(BaseClass test1,BaseClass test2){ if(test1.atk>test2.def){ System.out.println("atk"); damage=test1.atk-test2.def; if(isCritical(test1)){ damage=damage*2; System.out.println("CRIT"); } } if(test1.atk<test2.def){ damage=test2.def-test1.atk; if(isCritical(test2)){ damage=damage*-2; } } if(test1.atk==test2.def){ double randNumber = Math.random(); double d = randNumber * 2; int randomInt = (int)d; if(randomInt==1){ damage=1; } else { damage=0; } } return damage; }
6
public void visit_lsub(final Instruction inst) { stackHeight -= 4; if (stackHeight < minStackHeight) { minStackHeight = stackHeight; } stackHeight += 2; }
1
public int CloseDocument() { //Controllo se il documento è stato creato if (this._MyDocument != null) { //Ciclo per il numero di capitoli for (int i = 0; i < this._ChapterList.size(); i++) { try { //Aggiungo i capitoli al documento this._MyDocument.add(this._ChapterList.get(i)); //Se ci sono problemi perchè il documento non è stato aperto } catch (DocumentException ex) { return -10; } } //Se il docuemnto è aperto lo chiudo if (this._MyDocument.isOpen()) { this._MyDocument.close(); return 1; //Se il documento non è aperto } else { return -1; } //Se il documento non è stato creato } else { return -2; } }
4
public static void main(String args[]){ CashBox pCashBox = new CashBox(); Selector pSelector = new Selector(); int drink; int money; int sugar; String choice; Scanner in = new Scanner(System.in); System.out.println("Insert coins: "); money = in.nextInt(); if (money!=0){ pCashBox.deposit(money); } System.out.println("\tSelect drinks: "); System.out.println("\tEnter 1 if you want black coffee."); System.out.println("\tEnter 2 if you want coffee with creamer."); System.out.println("\tEnter 3 if you want a bouillon."); drink = in.nextInt(); if (drink==1){ System.out.println("\tDo you want to add? sugar?"); System.out.println("\tEnter 1 if you want to add sugar."); System.out.println("\tEnter 2 if you dont want to add sugar."); sugar = in.nextInt(); if (sugar==1){ choice = "black coffee with sugar"; pSelector.select(choice, pCashBox); } else if(sugar==2){ choice = "black coffee no sugar"; pSelector.select(choice, pCashBox); } } else if (drink==2){ System.out.println("\tDo you want to add? sugar?"); System.out.println("\tEnter 1 if you want to add sugar."); System.out.println("\tEnter 2 if you dont want to add sugar."); sugar = in.nextInt(); if (sugar==1){ choice = "white coffee with sugar"; pSelector.select(choice, pCashBox); } else if(sugar==2){ choice = "white coffee no sugar"; pSelector.select(choice, pCashBox); } } else if (drink==3){ choice = "bouillon"; pSelector.select(choice, pCashBox); } }
8
public Model getModel() { Model model = (Model) SpotAnimation.cache.get(id); if (model != null) { return model; } model = Model.getModel(modelId); if (model == null) { return null; } for (int i = 0; i < 6; i++) { if (srcColors[0] != 0) { model.swapColors(srcColors[i], destColors[i]); } } SpotAnimation.cache.put(model, id); return model; }
4
@Override public Cell<V> cell(int row, int column) { if (exists(row, column)) { SortedSet<Cell<V>> tail = cells.tailSet(finder(row, column)); if (tail.size() > 0) { Cell<V> cell = tail.first(); if (cell.getRow() == row && cell.getColumn() == column) { return cell; } } } return null; }
4
@Override public Object getValue() { PropertyTree parent=this.getParent(); Object gt=parent.queryBestResult(MediaProperty.REPLAYGAIN_TRACK_GAIN); Float gainTrack=StringUtils.toFloat(gt); Object ga=parent.queryBestResult(MediaProperty.REPLAYGAIN_ALBUM_GAIN); Float gainAlbum=StringUtils.toFloat(ga); Object rl=parent.queryBestResult(MediaProperty.REPLAYGAIN_REFERENCE_LOUDNESS); Float referenceLoudness=StringUtils.toFloat(rl); Object pt=parent.queryBestResult(MediaProperty.REPLAYGAIN_TRACK_PEAK); Double peakTrack=StringUtils.toDouble(pt); Object pa=parent.queryBestResult(MediaProperty.REPLAYGAIN_ALBUM_PEAK); Double peakAlbum=StringUtils.toDouble(pa); if(gainTrack==null && gainAlbum==null && referenceLoudness==null && peakTrack==null && peakAlbum==null) { return null; } /* if(gainTrack!=null && gainAlbum==null) { log(Level.WARNING,"incomplete ReplayGain data"); }*/ return new ReplayGain(gainTrack,gainAlbum,peakTrack,peakAlbum,referenceLoudness); }
5
public int getCurrentLineNumber() { return currentLineNumber; }
0
public static String numberToString(Number number) throws JSONException { if (number == null) { throw new JSONException("Null pointer"); } testValidity(number); // Shave off trailing zeros and decimal point, if possible. String string = number.toString(); if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); } if (string.endsWith(".")) { string = string.substring(0, string.length() - 1); } } return string; }
6
private void binOP(int idx) throws CompilationException { if (idx==9) unary(); else binOP(idx+1); int t; if (Debug.enabled) Debug.check((idx>=0)&&(idx<=9)); int v=(int)(idx<5?(0xA539CC68C652L>>>(idx*10)): (0x820820E6A928L>>>((idx-5)*10))); // m1= // 5, 5, 7, 7, 6, 6, 17, 17, 18, 18 // 00101,00101,00111,00111,00110,00110,10001,10001,10010,10010 // 00 1010 0101 0011 1001 1100 1100 0110 1000 1100 0110 0101 0010 // 0 A 5 3 9 C C 6 8 C 6 5 2 // 0x0A539CC68C652L // m2= // 4, 2, 1, 0, 16, 14, 13, 10, 9, 8 // 00100,00010,00001,00000,10000,01110,01101,01010,01001,01000 // 00 1000 0010 0000 1000 0010 0000 1110 0110 1010 1001 0010 1000 // 0 8 2 0 8 2 0 E 6 A 9 2 8 // 0x0820820E6A928L while ( ((t=type)>=(v & 0x1F)) && (t<=((v>>>5) & 0x1F)) ) { int ecol=ct_column; nextToken(); if (idx==9) unary(); else binOP(idx+1); err_col=ecol; // make use that token types and binary OPs coincide paramOPs.push(new OPbinary(paramOPs,t)); }; };
7
public boolean passesTest(Instance inst) throws Exception { if (inst.isMissing(m_AttIndex)) return false; // missing values fail boolean isNominal = inst.attribute(m_AttIndex).isNominal(); double attribVal = inst.value(m_AttIndex); if (!m_Not) { if (isNominal) { if (((int) attribVal) != ((int) m_Split)) return false; } else if (attribVal >= m_Split) return false; } else { if (isNominal) { if (((int) attribVal) == ((int) m_Split)) return false; } else if (attribVal < m_Split) return false; } return true; }
8
public static boolean areInOrder(Double a, Double b, Double c){ if(b > a && c > b) return true; if(b < a && c < b) return true; return false; }
4
private void clearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearActionPerformed // TODO add your handling code here: //Cuando la pestaña de Nueva Variable desde cero está seleccionada: if (jTabbedPane1.getSelectedIndex() == 0) { name1.setText(""); value.setText(""); } //Cuando la pestaña de Nueva Variable desde texto está seleccionada: else if (jTabbedPane1.getSelectedIndex() == 1){ name2.setText(""); relative.setSelected(true); wToggle.setSelected(true); init.setText(""); end.setText(""); otherField.setText("..."); } }//GEN-LAST:event_clearActionPerformed
2
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = ""; StringBuilder out = new StringBuilder(); while ((line = in.readLine()) != null && line.length() != 0) { String[] words = line.trim().split("[ ]+"); char[] word; int n = words.length; int w[] = new int[n], c; for (int i = 0; i < n; i++) { word = words[i].toCharArray(); for (int h = 0; h < word.length; h++) w[i] = (w[i] << 5) + (word[h] - 'a' + 1); } Arrays.sort(w); c = w[0]; boolean colision = false; while (true) { colision = false; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (fd(c, w[i]) % n == fd(c, w[j]) % n) { c = Math.min((fd(c, w[j]) + 1) * w[j],(fd(c, w[i]) + 1) * w[i]); colision = true; break; } } } if (!colision) break; } out.append(line + "\n" + c + "\n\n"); } System.out.print(out); }
9
@Override public boolean include(Entry<? extends modelTable, ? extends Integer> entry) { Task task = (Task) TaskFactory.getInstance().get(entry.getIdentifier()); if (filter == null) { return task.getModelStatus().isEndUserStatus(); } else { return (filter.include(task) && task.getModelStatus().isEndUserStatus()); } }
4
public SimulatedPulseOx(SimulatedPatient patient, Spawner spawn, InitialJFrame app) { super("Simulated PulseOx"); this.patient = patient; application = app; spawner = spawn; title = new JLabel(" Simulated PulseOx"); title.setFont(new Font("Arial", Font.PLAIN, 38)); title.setForeground(Color.WHITE); title.setBackground(Color.BLACK); setSize(defaultWidth, defaultHeight); getContentPane().setBackground(Color.BLACK); setLayout(new GridLayout(3, 1)); Q2 = new JButton("Q2 - NOT ASSOCIATED (Press to Associate over Q2)"); Q2.addActionListener(this); associatedQ2 = false; Q2.setBackground(red); Q2.setFocusPainted(false); patientConnect = new JButton("Connect to Patient"); patientConnect.addActionListener(this); patientConnect.setBackground(purple); patientConnect.setFocusPainted(false); connected = false; spawned = false; add(title); add(Q2); add(patientConnect); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); WindowAdapter exitListener = new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { int confirm = JOptionPane.showOptionDialog(null, "Are You Sure You Want To Close Simulated PulseOx?", "Exit Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); if (confirm == 0) { generator.interrupt(); spawner.pulseOximeterClosed(); if (application.isQ2Associated().equals(true)) application.toggleQ2(); dispose(); } } }; addWindowListener(exitListener); }
2
public Control(int rId) { if (rId > 0) { // Settings zu beginn laden _settings = new MySqlDatabaseHelper().getSettings(rId); } }
1
public List getMessByTime(String beginTme, String endTime,String rescueStatus) { String hql = ""; if(beginTme!=null&&!beginTme.trim().equals("")){ if(endTime!=null&&!endTime.trim().equals("")){ hql = "from Rescueapply r where r.applytime >=:beginTime and r.applytime <=:endTime" + rescueStatus; return this.sessionFactory.getCurrentSession().createQuery(hql).setParameter("beginTime",beginTme).setParameter("endTime",endTime).list(); } else{ hql = "from Rescueapply r where r.applytime >=:beginTime" + rescueStatus; return this.sessionFactory.getCurrentSession().createQuery(hql).setParameter("beginTime",beginTme).list(); } }else{ if(endTime!=null&&!endTime.trim().equals("")){ hql = "from Rescueapply r where r.applytime <=:endTime" + rescueStatus; return this.sessionFactory.getCurrentSession().createQuery(hql).setParameter("endTime",endTime).list(); }else{ return null; } } }
6
public static Economy initEco(LegendPlugin self){ Plugin test = self.getServer().getPluginManager().getPlugin("Vault"); Economy eco; if(test != null && test instanceof Vault){ self.logger().info("Succesfully hooked to Vault !"); }else{ self.logger().info("Could not find Vault. Disabling..."); self.getPluginLoader().disablePlugin(self); return null; } RegisteredServiceProvider<Economy> rsp = self.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); if(rsp == null){ self.logger().info("Could not find any economy plugin. Disabling..."); self.getPluginLoader().disablePlugin(self); return null; } eco = rsp.getProvider(); return eco; }
3
public boolean equals(Object ob) { if (super.equals(ob)) { Chocolate other = (Chocolate) ob; if (milky != other.milky) return false; } return true; }
2
public void testConstructor_Object5() throws Throwable { IntervalConverter oldConv = ConverterManager.getInstance().getIntervalConverter(""); IntervalConverter conv = new IntervalConverter() { public boolean isReadableInterval(Object object, Chronology chrono) { return false; } public void setInto(ReadWritableInterval interval, Object object, Chronology chrono) { interval.setChronology(chrono); interval.setInterval(1234L, 5678L); } public Class<?> getSupportedType() { return String.class; } }; try { ConverterManager.getInstance().addIntervalConverter(conv); DateTime dt1 = new DateTime(2004, 6, 9, 0, 0, 0, 0); DateTime dt2 = new DateTime(2005, 7, 10, 1, 1, 1, 1); MutableInterval test = new MutableInterval(dt1.toString() + '/' + dt2.toString()); assertEquals(1234L, test.getStartMillis()); assertEquals(5678L, test.getEndMillis()); } finally { ConverterManager.getInstance().addIntervalConverter(oldConv); } }
1
private boolean isRaceWon(int totalDistanceCovered){ boolean isRaceWon=false; if((Racer.winner==null)&&(totalDistanceCovered==100)){ String winnerName = Thread.currentThread().getName(); Racer.winner = winnerName; System.out.println("Winner is : "+Racer.winner); isRaceWon=true; }else if(Racer.winner==null){ isRaceWon=false; }else if(Racer.winner!=null){ isRaceWon=true; } return isRaceWon; }
4
public boolean getDown(){ return moveDown; }
0
public final long getLong(int index) throws JSONException { Object o = get(index); return o instanceof Number ? ((Number)o).longValue() : (long)getDouble(index); }
1
public void setStrength(double strength) { this.strength = strength; }
0
public Object[][] rechercherEmplois(Region reg, Set<Competence> lesComps) { ArrayList<OffreAffiche> lesOfrAffiche = new ArrayList(); Object[][] resultat; OffreNoyauFonctionnel.printOutOffres(); ArrayList<Emploi> lstEmplois = OffreNoyauFonctionnel.getTblEmplois().get(reg.getRegnom()); // System.out.println(OffreNoyauFonctionnel.getTblEmplois().size() + "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++NF.java"); // System.out.println(lstEmplois + "|" + lstEmplois + "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++NF.java"); //System.out.println("lstEmplois size: " + lstEmplois.size() + "+++++++++++++NF.java"); if (lstEmplois != null) { for (Emploi emploi : lstEmplois) { //System.out.println("Emploi titre: " + emploi.getTitre() + " NF.java"); boolean hasComp = false; for (Competence comp : lesComps) { //System.out.print("#" + comp.getNomComp() + "#"); //System.out.println("end#"); // seulement ajouter une fois if (!hasComp) { //System.out.println("2#############################"); //emploi.printOut(); if (emploi.getTblComps().containsKey(comp)) { OffreAffiche ofrAffiche = new OffreAffiche(); ofrAffiche.setTitre(emploi.getTitre()); //System.out.println("emploi titre:" + emploi.getTitre() + "NF.java"); System.out.println(emploi.scoreCompetencesHash(lesComps)); ofrAffiche.setScoreTotal(emploi.scoreCompetencesHash(lesComps)); // TODO double score = emploi.scoreCompetencesHash(lesComps); String scoreAd = String.format("%.2f", (score / 1) * 100) + "%"; ofrAffiche.setAdquation(scoreAd); ofrAffiche.setRegion(emploi.getReg().getRegnom()); lesOfrAffiche.add(ofrAffiche); hasComp = true; } } } } } Collections.sort(lesOfrAffiche); int afficheSize = lesOfrAffiche.size(); resultat = new Object[afficheSize][4]; for (int i = 0; i < afficheSize; i++) { // for (int j = 0; j < lesEmplois.size(); j++) { // max = lesEmplois.get(0); // if ((lesEmplois.get(j).scoreCompetencesHash(lesComps)) < (lesEmplois.get(j + 1).scoreCompetencesHash(lesComps))) { // max = lesEmplois.get(j + 1); // } // } resultat[i][0] = lesOfrAffiche.get(i).getTitre(); resultat[i][1] = lesOfrAffiche.get(i).getScoreTotal(); resultat[i][2] = lesOfrAffiche.get(i).getAdquation(); resultat[i][3] = lesOfrAffiche.get(i).getRegion(); // lesEmplois.remove(i); } return resultat; }
6
public boolean displayModesMatch(DisplayMode mode1, DisplayMode mode2) { if (mode1.getWidth() != mode2.getWidth() || mode1.getHeight() != mode2.getHeight()) { return false; } if (mode1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && mode2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && mode1.getBitDepth() != mode2.getBitDepth()) { return false; } if (mode1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && mode2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && mode1.getRefreshRate() != mode2.getRefreshRate()) { return false; } return true; }
8
public static void main(String[] args) { sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); org.hibernate.Transaction tr = session.beginTransaction(); List<Employee> empList = new LinkedList<>(); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); try { empList.add(new Employee(returnDepartment("Sales"), "FDS", "QSD", sdf.parse("05/08/1981"),"7584561")); empList.add(new Employee(returnDepartment("Sales"), "WIE", "QWE", sdf.parse("29/12/1983"),"2547685")); empList.add(new Employee(returnDepartment("HRD"), "ASD", "IOU", sdf.parse("23/11/1982"),"8764532")); empList.add(new Employee(returnDepartment("HRD"), "BNA", "LKA", sdf.parse("02/06/1983"),"2347963")); empList.add(new Employee(returnDepartment("Marketing"), "ASJ", "LJS", sdf.parse("14/05/1982"),"9412475")); empList.add(new Employee(returnDepartment("Marketing"), "ERQ", "WQE", sdf.parse("18/01/1980"),"1036981")); empList.add(new Employee(returnDepartment("Accounting"), "ABC", "LKJ", sdf.parse("21/02/1981"),"3245716")); empList.add(new Employee(returnDepartment("Accounting"), "KJS", "MNS", sdf.parse("12/06/1982"),"2343553")); empList.add(new Employee(returnDepartment("Administration"), "SDF", "FDG", sdf.parse("25/09/1981"),"1234123")); empList.add(new Employee(returnDepartment("Administration"), "WER", "JTY", sdf.parse("09/07/1983"),"5634221")); } catch (ParseException e) { e.printStackTrace(); } for(Employee e : empList) { session.merge(e); } String strSql ="from Employee o"; Query query = session.createQuery(strSql); List<?> lst = query.list(); for(Iterator<?> it=lst.iterator();it.hasNext();) { Employee emp=(Employee)it.next(); System.out.println("Employee ID:" + emp.getEmployeeId()); System.out.println("First Name: " + emp.getFirstname()); System.out.println("Last Name: " + emp.getLastname()); System.out.println("Cell Phone Number: " + emp.getCellPhone()); System.out.println("Date of Birth: " + emp.getBirthDate().toString()); System.out.println("Works in: Department ID: " + emp.getDepartment().getDepartmentId() + " | Department Name: " + emp.getDepartment().getDeptName()); System.out.println(); } tr.commit(); System.out.println("Data displayed"); sf.close(); }
5
public void clearFinal() { // Avoid concurrent modification exceptions. ArrayList list = new ArrayList(); list.addAll(configurationToButtonMap.values()); Iterator it = list.iterator(); while (it.hasNext()) { ConfigurationButton button = (ConfigurationButton) it.next(); if (button.state == ConfigurationButton.ACCEPT || button.state == ConfigurationButton.REJECT) remove(button.getConfiguration()); } }
3
public void addProperty(String property) { boolean excluded = property.startsWith("!"); if (excluded) { property = property.substring(1); } if (property.contains(".")) { String prefix = property.substring(0, property.indexOf('.')); String suffix = property.substring(property.indexOf('.') + 1); NestedPropertyFilter nestedFilter = nestedProperties.get(prefix); if (nestedFilter == null) { nestedFilter = new NestedPropertyFilter(); nestedProperties.put(prefix, nestedFilter); } if (excluded) { nestedFilter.addProperty("!" + suffix); } else { nestedFilter.addProperty(suffix); includedProperties.add(prefix); } } else if (excluded) { excludedProperties.add(property); } else { includedProperties.add(property); } }
5
public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> map) { List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> m1, Map.Entry<String, Integer> m2) { return (m2.getValue()).compareTo(m1.getValue()); } }); HashMap<String, Integer> result = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> entry : list) { result.put(entry.getKey(), entry.getValue()); } return result; }
1
public Period getArrivalTime() { return this._arrivalTime; }
0
public boolean isChoked() { return this.choked; }
0
public void setName(String value) { this._name = value; }
0
public HttpRequest(String url, Map<String, String> params) { if (url == null) { throw new RuntimeException("Request URL cannot be null"); } this.url = url; if (params != null) { this.url += "?" + urlEncode(params); } }
2
@Override public void mouseEntered(MouseEvent e) { }
0
public void setLeftUser(Integer[] leftUser) { this.leftUser = leftUser; for (Integer i : this.leftUser) { userIDtoMatchLoaded.remove(i); } }
1
public static boolean equateTokenList(List<Token> a, List<Token> b) { if(a.size()!=b.size()) return false; int i=0; for(Token t : b) { if(!t.equals(a.get(i))) { return false; } i++; } return true; }
3
public static NodeList addNumbers(Node head1, Node head2) { NodeList addition = new NodeList(); int carry = 0; while(head1 != null || head2 != null) { int result = carry + ((head1 != null) ? head1.data : 0) + ((head2 != null) ? head2.data : 0); carry = 0; if(result/10 == 1) carry = 1; addition.insert(result % 10); if(head1 != null) head1 = head1.next; if(head2 != null) head2 = head2.next; } if(carry == 1) addition.insert(carry); return addition; }
8
private void pickRandomDirection() { int rand = Game.random.nextInt(8); switch(rand) { case 0: d = Direction.NORTH; break; case 1: d = Direction.SOUTH; break; case 2: d = Direction.EAST; break; case 3: d = Direction.WEST; break; case 4: d = Direction.NORTHEAST; break; case 5: d = Direction.NORTHWEST; break; case 6: d = Direction.SOUTHEAST; break; case 7: d = Direction.SOUTHWEST; break; } }
8
void decodeServiceStateData(OMMFilterEntry serviceFilterEntry) { OMMData serviceFilterEntryData = serviceFilterEntry.getData(); if (serviceFilterEntryData.getType() == OMMTypes.ELEMENT_LIST) { for (Iterator<?> eliter = ((OMMElementList)serviceFilterEntryData).iterator(); eliter .hasNext();) { OMMElementEntry eentry = (OMMElementEntry)eliter.next(); OMMData edata = eentry.getData(); if (eentry.getName().compareTo(RDMService.SvcState.ServiceState) == 0) { // do nothing - not used in scenario // _serviceState = (int)((OMMNumeric)edata).getLongValue(); } else if (eentry.getName().compareTo(RDMService.SvcState.AcceptingRequests) == 0) { // cache it _acceptingRequests = (int)((OMMNumeric)edata).getLongValue(); } else if (eentry.getName().compareTo(RDMService.SvcState.Status) == 0) { // do nothing - not used in scenario // _stateStatus = (OMMState)edata; } } } }
6
private JSONWriter append(String string) throws JSONException { if (string == null) { throw new JSONException("Null pointer"); } if (this.mode == 'o' || this.mode == 'a') { try { if (this.comma && this.mode == 'a') { this.writer.write(','); } this.writer.write(string); } catch (IOException e) { throw new JSONException(e); } if (this.mode == 'o') { this.mode = 'k'; } this.comma = true; return this; } throw new JSONException("Value out of sequence."); }
7
public static void findMiniMax(int[] input){ int min = 0; int max = 0; if(input.length%2 ==0){ if(input[0] <= input[1]){ min = input[0]; max = input[1]; } else { min = input[0]; max = input[0]; } } for(int i=3; i< input.length; i+=2) { if(input[i] < input[i-1]){ if(input[i] < min){ min = input[i]; } if(input[i-1] > max){ max = input[i-1]; } } else { if(input[i-1] < min){ min = input[i-1]; } if(input[i] > max){ max = input[i]; } } } System.out.println("Min : "+min+" Max : "+max); }
8
public Patient(Integer id){ if(id != null){ this.setId(id); String q = "SELECT patients.id," + "patients.last_name," + "patients.middle_name," + "patients.first_name," + "patients.age," + "patients.gender," + "patients.birth_date," + "patients.snils," + "patients.code," + "patients.sp_categ," + "patients.registration," + "patients.registration_house," + "patients.registration_apt," + "patients.residence," + "patients.residence_house," + "patients.residence_apt," + "patients.notes," + "patients.unknown," + "patients.work_place," + "documents.id as doc_id," + "documents.type," + "documents.series," + "documents.number," + "documents.date_i," + "documents.date_e," + "documents.active," + "documents.notes as doc_notes," + "sp_categ.name as cat_name," + "sp_categ.id as cat_id " + "FROM patients " + "LEFT JOIN documents ON documents.patient = patients.id " + "LEFT JOIN sp_categ ON sp_categ.id = patients.sp_categ " + "WHERE patients.id = ?"; try { PreparedStatement statement = Patient.getConnection().prepareStatement(q); statement.setInt(1, this.getId()); ResultSet resultSet = statement.executeQuery(); if(resultSet.next()){ this.setGender(Patient.getGenderString(resultSet.getInt("gender"))); this.setFirstName(resultSet.getString("first_name")); this.setMiddleName(resultSet.getString("middle_name")); this.setLastName(resultSet.getString("last_name")); this.setAge(resultSet.getInt("age")); this.setBirthDate(resultSet.getDate("birth_date")); this.setUnknown(resultSet.getBoolean("unknown")); this.setNotes(resultSet.getString("notes")); this.setSnils(resultSet.getString("snils")); this.setCategory(new Category(resultSet.getString("cat_name"), resultSet.getInt("cat_id"))); this.setWorkplace(resultSet.getString("work_place")); this.setRegAddress(new Address(resultSet.getString("registration"), resultSet.getString("registration_house"), resultSet.getString("registration_apt"))); this.setResAddress(new Address(resultSet.getString("residence"), resultSet.getString("residence_house"), resultSet.getString("residence_apt"))); //setting documents if(resultSet.getInt("type") == Passport.getType()){ //this is passport Passport p = new Passport(resultSet.getString("series"), resultSet.getString("number")); p.setActive(resultSet.getBoolean("active")); p.setId(resultSet.getInt("doc_id")); p.setIssueDate(resultSet.getDate("date_i")); p.setNotes(resultSet.getString("doc_notes")); p.setPatient(this); this.setPassport(p); } else if(resultSet.getInt("type") == Policy.getType()){ //this is policy Policy p = new Policy(resultSet.getString("series"), resultSet.getString("number")); p.setActive(resultSet.getBoolean("active")); p.setExpiryDate(resultSet.getDate("date_e")); p.setId(resultSet.getInt("doc_id")); p.setIssueDate(resultSet.getDate("date_i")); p.setNotes(resultSet.getString("doc_notes")); p.setPatient(this); this.setPolicy(p); } } if(resultSet.next()){ if(resultSet.getInt("type") == Passport.getType()){ //this is passport Passport p = new Passport(resultSet.getString("series"), resultSet.getString("number")); p.setActive(resultSet.getBoolean("active")); p.setId(resultSet.getInt("doc_id")); p.setIssueDate(resultSet.getDate("date_i")); p.setNotes(resultSet.getString("doc_notes")); p.setPatient(this); this.setPassport(p); } else { //this is policy Policy p = new Policy(resultSet.getString("series"), resultSet.getString("number")); p.setActive(resultSet.getBoolean("active")); p.setExpiryDate(resultSet.getDate("date_e")); p.setId(resultSet.getInt("doc_id")); p.setIssueDate(resultSet.getDate("date_i")); p.setNotes(resultSet.getString("doc_notes")); p.setPatient(this); this.setPolicy(p); } } } catch (SQLException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }
7
public void buildClassifier(Instances data) throws Exception { // Make sure K value is in range if (m_KValue > data.numAttributes() - 1) m_KValue = data.numAttributes() - 1; if (m_KValue < 1) m_KValue = (int) Utils.log2(data.numAttributes()) + 1; // can classifier handle the data? getCapabilities().testWithFail(data); // remove instances with missing class data = new Instances(data); data.deleteWithMissingClass(); // only class? -> build ZeroR model if (data.numAttributes() == 1) { System.err .println("Cannot build model (only class attribute present in data!), " + "using ZeroR model instead!"); m_ZeroR = new weka.classifiers.rules.ZeroR(); m_ZeroR.buildClassifier(data); return; } else { m_ZeroR = null; } // Figure out appropriate datasets Instances train = null; Instances backfit = null; Random rand = data.getRandomNumberGenerator(m_randomSeed); if (m_NumFolds <= 0) { train = data; } else { data.randomize(rand); data.stratify(m_NumFolds); train = data.trainCV(m_NumFolds, 1, rand); backfit = data.testCV(m_NumFolds, 1); } // Create the attribute indices window int[] attIndicesWindow = new int[data.numAttributes() - 1]; int j = 0; for (int i = 0; i < attIndicesWindow.length; i++) { if (j == data.classIndex()) j++; // do not include the class attIndicesWindow[i] = j++; } // Compute initial class counts double[] classProbs = new double[train.numClasses()]; for (int i = 0; i < train.numInstances(); i++) { Instance inst = train.instance(i); classProbs[(int) inst.classValue()] += inst.weight(); } // Build tree buildTree(train, classProbs, new Instances(data, 0), m_MinNum, m_Debug, attIndicesWindow, rand, 0, getAllowUnclassifiedInstances()); // Backfit if required if (backfit != null) { backfitData(backfit); } }
8
public void execute() { // List of new nodes with predecessors (as bfs state): nodes where we might still add a successor without going beyond the maxDistance. Queue<BFSState<N, E>> greyNodes = new LinkedList<BFSState<N, E>>(); // Set of nodes that have are certain to lie within the max distance: we cannot add another node without going beyond the mxDistance. Set<BFSState<N, E>> blackNodes = new HashSet<BFSState<N, E>>(); BFSState<N, E> ws = new BFSState<N, E>(this.source); ws.distance = 0.f; greyNodes.add(ws); while (!greyNodes.isEmpty()) { BFSState<N, E> wu = greyNodes.remove(); // TODO : Is the context set correctly here? contextualReachability.setContext(wu); Iterator<InternalNode<N, E>> outEdges = this.graph.getOutGoingEdges(wu.internalNode, contextualReachability); while (outEdges.hasNext()) { InternalNode<N, E> v = outEdges.next(); BFSState<N, E> wv = new BFSState<N, E>(v); if (!greyNodes.contains(wv) && !blackNodes.contains(wv)) { wv.distance = wu.distance + wu.internalNode.getWeightTo(v, weightIndex); if (wv.distance <= maxDistance) { wv.setPredecessor(wu); greyNodes.add(wv); } } } blackNodes.add(wu); } this.result = new GraphTreeImpl<N, E>(ws); }
5
public void visitInitStmt(final InitStmt stmt) { for (int i = 0; i < stmt.targets.length; i++) { if (stmt.targets[i] == from) { stmt.targets[i] = (LocalExpr) to; ((LocalExpr) to).setParent(stmt); return; } } stmt.visitChildren(this); }
2
@Override public void parse() throws IllegalArgumentException { try { setTimeStampFormat(TimeStampFormat.getTimeStampFormat(buffer[0])); } catch (IllegalArgumentException ex) { // ignore the bad value and set it to milliseconds so we can continue parsing the tag setTimeStampFormat(TimeStampFormat.MS); } int index = 1; int bpm = 0; int timeStamp = 0; tempoChanges = new Vector<TempoChange>(); while ((index + 5) < buffer.length) { if (buffer[index] == (byte)0x00 && buffer[index] == (byte)0x01) bpm = buffer[index]; else bpm = (buffer[index] == (byte)0xFF ? 255 + buffer[index + 1] : buffer[index]); index += (buffer[index] == (byte)0xFF ? 2 : 1); timeStamp = ((buffer[index] & 0xFF ) << 24) + ((buffer[index + 1] & 0xFF) << 16) + ((buffer[index + 2] & 0xFF) << 8) + (buffer[index + 3] & 0xFF); tempoChanges.add(new TempoChange(bpm, timeStamp)); index += 4; } dirty = false; // we just read in the frame info, so the frame body's internal byte buffer is up to date }
6
SocketCredentials ( int[] data ) { this.data = (byte) data[ 0 ]; if ( data.length == 4 ) { this.pid = data[ 1 ]; this.uid = data[ 2 ]; this.gid = data[ 3 ]; } else { this.pid = -1; this.uid = -1; this.gid = -1; } }
1
@Override public boolean pieceMovement(Point startPosition, Point endPosition) { Point difference = new Point(); difference.setLocation(endPosition.getX() - startPosition.getX(), endPosition.getY() - startPosition.getY()); if((Math.abs(difference.getX()) == 0 && Math.abs(difference.getY()) > 0) || (Math.abs(difference.getY()) == 0 && Math.abs(difference.getX()) > 0) || (Math.abs(difference.getX()) == Math.abs(difference.getY()))){ return true; } return false; }
5
@Override public List<Apartamento> Buscar(Apartamento obj) { String consulta = "select ap from Apartamento ap"; String filtro = ""; HashMap<String, Object> parametros = new HashMap<String, Object>(); if (obj.getTipo()!= null) { if (filtro.length() > 0) { filtro = filtro + " and "; } filtro = " ap.tipo =: tipo"; parametros.put("tipo", obj.getTipo()); } if (obj.getFilial()!= null) { if (filtro.length() > 0) { filtro = filtro + " and "; } filtro = " ap.filial =: filial"; parametros.put("filial", obj.getFilial()); } if (obj.getIdApartamento()!= null) { if (filtro.length() > 0) { filtro = filtro + " and "; } filtro = " ap.idapartamento =: idapartamento"; parametros.put("idapartamento", obj.getIdApartamento()); } if (filtro.length() > 0) { consulta = consulta + " where " + filtro; } Query query = manager.createQuery(consulta); for (String par : parametros.keySet()) { query.setParameter(par, parametros.get(par)); } return query.getResultList(); }
8
public static void main(String[] args) { RealSubject realSubject = new RealSubject(); InvocationHandler handler = new ProxyDynamicSubject(realSubject); Class<?> classType = handler.getClass(); //下面代码一次性生产代理对象 Subject subject = (Subject) Proxy.newProxyInstance(classType.getClassLoader(), realSubject.getClass().getInterfaces(), handler); subject.request(); }
1
public void renderUpdate() { if(!wasHalf) MrVago.update(); contentPane.remove(panel); panel = new JPanel(); panel.setBackground(Color.WHITE); panel.setBounds(12, 12, 294, 305); contentPane.add(panel); panel.setLayout(null); contentPane.remove(panel_2); panel_2 = new JPanel(); panel_2.setBackground(Color.WHITE); panel_2.setBounds(318, 114, 170, 203); contentPane.add(panel_2); panel_2.setLayout(null); JLabel roundLabel = new JLabel("Round: "); roundLabel.setBounds(12, 12, 70, 15); panel.add(roundLabel); JLabel roundNumber = new JLabel(Integer.toString(MrVago.getRound())); roundNumber.setBounds(94, 12, 70, 15); panel.add(roundNumber); JLabel prizeLabel = new JLabel("Prize:"); prizeLabel.setBounds(12, 39, 70, 15); panel.add(prizeLabel); JLabel prizeNumber = new JLabel(Integer.toString(MrVago .getCurrentPlayer().getScore())); prizeNumber.setBounds(94, 39, 70, 15); panel.add(prizeNumber); JLabel questionLabel = new JLabel(MrVago.getActQuestion().getQuestion()); questionLabel.setBounds(12, 85, 70, 15); panel.add(questionLabel); button1String = MrVago.getActQuestion().getDisplayAnswers().get(0) .getAnswer(); JButton button1 = new JButton(button1String); button1.setBounds(12, 135, 270, 25); panel.add(button1); button1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { if (button1String.equals(MrVago.getActQuestion().getCorrect() .getAnswer())) { if (MrVago.getRound() != 15) renderUpdate(); else renderWin(); } else { renderFail(); } } }); button2String = MrVago.getActQuestion().getDisplayAnswers().get(1) .getAnswer(); JButton button2 = new JButton(button2String); button2.setBounds(12, 172, 270, 25); panel.add(button2); button2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { if (button2String.equals(MrVago.getActQuestion().getCorrect() .getAnswer())) { if (MrVago.getRound() != 15) renderUpdate(); else renderWin(); } else { renderFail(); } } }); button3String = MrVago.getActQuestion().getDisplayAnswers().get(2) .getAnswer(); JButton button3 = new JButton(button3String); button3.setBounds(12, 209, 270, 25); panel.add(button3); button3.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { if (button3String.equals(MrVago.getActQuestion().getCorrect() .getAnswer())) { if (MrVago.getRound() != 15) renderUpdate(); else renderWin(); } else { renderFail(); } } }); button4String = MrVago.getActQuestion().getDisplayAnswers().get(3) .getAnswer(); JButton button4 = new JButton(button4String); button4.setBounds(12, 246, 270, 25); panel.add(button4); button4.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { if (button4String.equals(MrVago.getActQuestion().getCorrect() .getAnswer())) { if (MrVago.getRound() != 15) renderUpdate(); else renderWin(); } else { renderFail(); } } }); validate(); repaint(); }
9
private void validateFilePath(String filePath, String[] ext) throws IOException { try { //Creating a new file instance. File dir = new File(filePath); String targetImageFormat; boolean isSupportedImage = false; //Check if the specified file exists if (dir.exists()) { //Create an iterator for image reader. ImageInputStream iis = ImageIO.createImageInputStream(dir); Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); iis.flush(); iis.close(); //Check if the image has data to be read. //If not, then throw an error and terminate the //program. if (!readers.hasNext()) { System.out.println("Exception while reading target image." + dir); System.exit(0); } //Else, read the properties of the image else { ImageReader reader = readers.next(); //Special Case: //Java Advanced Image Library reads TIFF image format //as "tif". //Therefore, if the a TIFF file is encountered //during the execution of the code then, set the //variable name as "tiff". if (reader.getFormatName().equals("tif")) { targetImageFormat = "tiff"; } //For any other format, use the string returned //by the Imagereader else { targetImageFormat = reader.getFormatName(); } //Check if image format is one of the supported //legal format. for (int i = 0; i < ext.length; i++) { if (ext[i].equalsIgnoreCase(targetImageFormat)) { isSupportedImage = true; break; } else { isSupportedImage = false; } } //If the target image passes the validation //then set the required variables. if (isSupportedImage) { Main.setTARGET_IMG_DIR(filePath); Main.setTARGET_IMG_FORMAT(targetImageFormat .toLowerCase()); } //If the validation fails, then throw a message and //terminate the program. else { System.out.println("No file with " + ext[0] + " or " + ext[1] + " or " + ext[2] + " or " + ext[3] + " or " + ext[4] + " or " + ext[5] + " was found in. " + dir); System.exit(0); } } } //If the target image does not exists, then throw an appropriate //message and terminate the program. else { System.out.println("Target image does not exists in the path: " + dir); System.exit(0); } } catch (Exception e) { System.out.println("Invalid Target Image path."); System.exit(0); } }
7
public static List<Direction> get90DegreeDiretions(Direction d) { List<Direction> l = new ArrayList<>(); for (Direction e : Direction.values()) if (e.ordinal() != d.ordinal() && e.ordinal() != (d.ordinal() + 3) % 6) l.add(e); System.out.println(l); return l; }
3
protected void reiniciar() { // TODO Auto-generated method stub textFieldName.setText(""); textFieldActivity.setText(""); comboBoxArea.setSelectedItem(CompanyType.Selecciona); formattedTextField.setText(""); formattedTextFieldRNC.setText(""); textFieldEmail.setText(""); formattedTextFieldFax.setText(""); formattedTextFieldPhone.setText(""); formattedTextFieldPostal.setText(""); textFieldWeb.setText(""); comboBoxCountry.setSelectedItem("<Selecciona>"); comboBoxSector.setSelectedItem("<Selecciona>"); textFieldRegion.setText(""); textFieldCity.setText(""); textFieldRoad.setText(""); error.setText(""); textField.setText(""); }
0
private void okPressed(){ String singular = singularField.getText().trim().toLowerCase(); String plural = pluralField.getText().trim().toLowerCase(); if(singular.equals("")){ JOptionPane.showMessageDialog(dialog, "You need to supply a singular name for the ingredient.\n" + "The two names can be identical", "Invalid name", JOptionPane.ERROR_MESSAGE); singularField.requestFocusInWindow(); return; } if(plural.equals("")){ JOptionPane.showMessageDialog(dialog, "You need to supply a plural name for the ingredient.\n" + "The two names can be identical", "Invalid name", JOptionPane.ERROR_MESSAGE); pluralField.requestFocusInWindow(); return; } Ingredient tmpIngredient = new Ingredient(singular, plural, commonCheckBox.isSelected()); if(oldIngredient != null){ db.updateIngredient(oldIngredient, tmpIngredient); } else if(ingredients.contains(tmpIngredient)){ JOptionPane.showMessageDialog(dialog, "There already exists an ingredient with this (singular) name", "Ingredient exists", JOptionPane.INFORMATION_MESSAGE); return; } db.addIngredient(tmpIngredient); result = tmpIngredient; dialog.dispose(); }
4
@Override public boolean isAllowedToBorrow(Loan loan, StockController stockController) { if (stockController.numberOfLoans(this) < 7) { if (loan.getQuantity() < 25) { if (CalendarController.differenceDate(loan.getStart(), loan.getEnd()) < 15) { if (CalendarController.differenceDate( new GregorianCalendar(), loan.getStart()) < 15) { return true; } } } } return false; }
4
public OptionGui() throws IOException { this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); this.setIconImage(new ImageUtil().getLogo()); //this.setLocationRelativeTo(null); setTitle(("Settings")); setBounds(100, 100, 506, 391); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); { lblDownloadDirectory = new JLabel(("Download Directory")); } txtDownload = new JTextField(); txtDownload.setColumns(10); txtDownload.setText(opt.getDownloadPath()); JButton button = new JButton("..."); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new java.io.File(".")); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); chooser.setAcceptAllFileFilterUsed(false); if (chooser.showDialog(null, ("Select download path")) == JFileChooser.APPROVE_OPTION) { txtDownload.setText(chooser.getSelectedFile().getAbsolutePath()); } } }); final JSpinner spinner = new JSpinner(); spinner.setModel(new SpinnerNumberModel(new Byte((byte) opt.getMaxDownloads()), new Byte((byte) 1), new Byte((byte) 5), new Byte((byte) 1))); JLabel lblSimoultaneousDownloads = new JLabel(("Simultaneous Downloads (high value maybe can ban you from GrooveShark)")); final JCheckBox chckbxAutoCheckUpdat = new JCheckBox(("Auto check update at startup"), opt.getUpdate()); txtTemplate = new JTextField(opt.getFileTemplate()); txtTemplate.setColumns(10); JLabel lblFileNameTemplate = new JLabel("File name template (Reserved words: %Track%, %Title%, %Artist%, %Album%)"); JButton btnTestTemplate = new JButton("Test Template"); btnTestTemplate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { HashMap<String,String> mp3 = new HashMap<String,String>(); mp3.put("TrackNum", "02"); mp3.put("SongName", "Symphony No. 5"); mp3.put("ArtistName", "Beethoven"); mp3.put("AlbumName", "Classical Best Of"); mp3.put("Year", "1800"); GrooveJaar.showMessage("Your downloads will saved as: "+GrooveJaar.makeTitle(mp3,txtTemplate.getText())); } }); JLabel lblIfFileExits = new JLabel("If file exits"); comboBox = new JComboBox<String>(); comboBox.setModel(new DefaultComboBoxModel<String>(new String[] {"Ask Action", "Overwrite", "Skip"})); chkBitrateSize = new JCheckBox("Auto get bitrate and size",opt.autoBitrateSize()); GroupLayout gl_contentPanel = new GroupLayout(contentPanel); gl_contentPanel.setHorizontalGroup( gl_contentPanel.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPanel.createSequentialGroup() .addContainerGap() .addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPanel.createSequentialGroup() .addComponent(lblFileNameTemplate, GroupLayout.DEFAULT_SIZE, 468, Short.MAX_VALUE) .addContainerGap()) .addGroup(gl_contentPanel.createSequentialGroup() .addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPanel.createSequentialGroup() .addComponent(txtDownload, GroupLayout.DEFAULT_SIZE, 428, Short.MAX_VALUE) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(button, GroupLayout.PREFERRED_SIZE, 36, GroupLayout.PREFERRED_SIZE)) .addComponent(lblDownloadDirectory)) .addGap(8)) .addGroup(gl_contentPanel.createSequentialGroup() .addComponent(spinner, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addContainerGap(441, Short.MAX_VALUE)) .addComponent(lblSimoultaneousDownloads) .addGroup(gl_contentPanel.createSequentialGroup() .addComponent(txtTemplate, 361, 361, 361) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(btnTestTemplate) .addContainerGap()) .addGroup(gl_contentPanel.createSequentialGroup() .addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING) .addComponent(lblIfFileExits, GroupLayout.PREFERRED_SIZE, 159, GroupLayout.PREFERRED_SIZE) .addGroup(gl_contentPanel.createSequentialGroup() .addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.RELATED, 84, GroupLayout.PREFERRED_SIZE))) .addContainerGap(319, Short.MAX_VALUE)) .addGroup(gl_contentPanel.createSequentialGroup() .addComponent(chkBitrateSize) .addContainerGap(303, Short.MAX_VALUE)) .addGroup(gl_contentPanel.createSequentialGroup() .addComponent(chckbxAutoCheckUpdat, GroupLayout.PREFERRED_SIZE, 178, GroupLayout.PREFERRED_SIZE) .addContainerGap()))) ); gl_contentPanel.setVerticalGroup( gl_contentPanel.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPanel.createSequentialGroup() .addContainerGap() .addComponent(lblDownloadDirectory) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(gl_contentPanel.createParallelGroup(Alignment.BASELINE) .addComponent(txtDownload, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(button)) .addPreferredGap(ComponentPlacement.UNRELATED) .addComponent(lblSimoultaneousDownloads) .addGap(7) .addComponent(spinner, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addGap(18) .addComponent(lblFileNameTemplate) .addPreferredGap(ComponentPlacement.UNRELATED) .addGroup(gl_contentPanel.createParallelGroup(Alignment.BASELINE) .addComponent(txtTemplate, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(btnTestTemplate)) .addGap(18) .addComponent(lblIfFileExits) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.RELATED, 16, Short.MAX_VALUE) .addComponent(chkBitrateSize) .addGap(18) .addComponent(chckbxAutoCheckUpdat)) ); contentPanel.setLayout(gl_contentPanel); { JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { JButton okButton = new JButton(("Save")); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { opt.save("downloadPath",txtDownload.getText()); opt.save("maxDownloads",String.valueOf(spinner.getValue())); opt.save("autoUpdate", chckbxAutoCheckUpdat.isSelected() ? "true" : "false"); opt.save("template", txtTemplate.getText()); opt.save("ifExist", (String)comboBox.getSelectedItem()); opt.save("autoBitrateSize", chkBitrateSize.isSelected() ? "true" : "false"); GrooveJaar.initOptions(); OptionGui.this.dispose(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }); okButton.setActionCommand("OK"); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } { JButton cancelButton = new JButton(("Cancel")); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { OptionGui.this.dispose(); } }); cancelButton.setActionCommand("Cancel"); buttonPane.add(cancelButton); } } }
5
@Override public void endElement(String uri, String localName, String qName) throws SAXException { String tipo = getTipo(); if(tipo.equals("getCPU")){//tag atual. Ex.: <host...> switch(qName){ //Cria um novo objeto token quando a tag eh encontrada case "name": docList.add(doc); break; case "tenant": docList.add(doc); break; default: break; }//fim switch } else if(tipo.equals("getHosts")){ switch(qName){ //tag atual. Ex.: <host...> case "host": docList.add(doc); break; default: break; }//fim switch }//fim if }//fim endElement
5
public void addWay(int pos, long wayId) { if (poligons.size() > pos && !ways.get(pos).contains(wayId)) ways.get(pos).add(wayId); }
2
@Override public void mouseClicked(MouseEvent e) { if (!follow && e.getButton() == MouseEvent.BUTTON1) { for (int i = -20; i <= 20; i++) { for (int i2 = -20; i2 <= 20; i2++) { final Tile t = Players.getLocal().getLocation().derive(i, i2); if (t.contains(e.getPoint())) { if (!t.equals(tile)) { updateTile(t); } } } } } }
6
public WorldFillTask(Server theServer, Player player, String worldName, int fillDistance, int chunksPerRun, int tickFrequency) { this.server = theServer; this.notifyPlayer = player; this.fillDistance = fillDistance; this.tickFrequency = tickFrequency; this.chunksPerRun = chunksPerRun; this.world = server.getWorld(worldName); if (this.world == null) { if (worldName.isEmpty()) sendMessage("You must specify a world!"); else sendMessage("World \"" + worldName + "\" not found!"); this.stop(); return; } this.border = (Config.Border(worldName) == null) ? null : Config.Border(worldName).copy(); if (this.border == null) { sendMessage("No border found for world \"" + worldName + "\"!"); this.stop(); return; } // load up a new WorldFileData for the world in question, used to scan region files for which chunks are already fully generated and such worldData = WorldFileData.create(world, notifyPlayer); if (worldData == null) { this.stop(); return; } this.border.setRadiusX(border.getRadiusX() + fillDistance); this.border.setRadiusZ(border.getRadiusZ() + fillDistance); this.x = CoordXZ.blockToChunk((int)border.getX()); this.z = CoordXZ.blockToChunk((int)border.getZ()); int chunkWidthX = (int) Math.ceil((double)((border.getRadiusX() + 16) * 2) / 16); int chunkWidthZ = (int) Math.ceil((double)((border.getRadiusZ() + 16) * 2) / 16); int biggerWidth = (chunkWidthX > chunkWidthZ) ? chunkWidthX : chunkWidthZ; //We need to calculate the reportTarget with the bigger with, since the spiral will only stop if it has a size of biggerWidth x biggerWidth this.reportTarget = (biggerWidth * biggerWidth) + biggerWidth + 1; //This would be another way to calculate reportTarget, it assumes that we don't need time to check if the chunk is outside and then skip it (it calculates the area of the rectangle/ellipse) //this.reportTarget = (this.border.getShape()) ? ((int) Math.ceil(chunkWidthX * chunkWidthZ / 4 * Math.PI + 2 * chunkWidthX)) : (chunkWidthX * chunkWidthZ); // Area of the ellipse just to be safe area of the rectangle // keep track of the chunks which are already loaded when the task starts, to not unload them Chunk[] originals = world.getLoadedChunks(); for (Chunk original : originals) { originalChunks.add(new CoordXZ(original.getX(), original.getZ())); } this.readyToGo = true; }
7
@EventHandler public void onPlayerInteract(PlayerInteractEvent event) { if (!event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { return; } final SpoutPlayer player = SpoutManager.getPlayer(event.getPlayer()); if (SHIFT_HELD.containsKey(player.getUniqueId())) { if (!SHIFT_HELD.get(player.getUniqueId())) { return; } final Block block = event.getClickedBlock(); if (!(block.getState() instanceof Sign)) { return; } if (!PortablesPlugin.getHooks().getPermissions().has(player.getWorld(), player.getName(), "portables.sign.use")) { player.sendNotification("Portables", "Cannot edit signs!", Material.LAVA_BUCKET); return; } if (PortablesPlugin.getHooks().isResidenceEnabled()) { final ClaimedResidence res = Residence.getResidenceManager().getByLoc(block.getLocation()); if (res != null) { if (!res.getPermissions().playerHas(player.getName(), "build", true)) { return; } } } player.openSignEditGUI((Sign) block.getState()); } }
8
private void findGoalSprites(GameDescription game){ ArrayList<TerminationData> terminations = game.getTerminationConditions(); for(TerminationData td:terminations){ for(String sprite:td.sprites){ if(!goalSprites.contains(sprite)){ goalSprites.add(sprite); } } } }
3
public void compute() { if (hit || shooter == null) return; Battleground battleground = (Battleground)shooter.getArena(); Tanq target = battleground.getCollider(this); if (target != null) { hit = true; getBody().setAppliedForce(new Vector3D(0, 0, 0)); target.notifyInjury(getOwner()); getOwner().notifyScored(target); // When target is hit, explode Movie m = new Movie() { public void notifyEndMovie() { suicide(); } }; m.setRepeating(false); m.add("images/BulletStrike01.png"); m.add("images/BulletStrike02.png"); m.add("images/BulletStrike03.png"); m.add("images/BulletStrike04.png"); m.add("images/BulletStrike05.png"); m.add(""); setMovie(m); } }
3
public void setCognome(String cognome) { this.cognome = cognome; }
0
public void setCurrentValues() { if (recent.isSelected()) { recent.doClick(); } else { bookmark.doClick(); } if (page.getSelectedText() != null) { int start = page.getSelectionStart(); int end = page.getSelectionEnd(); page.moveCaretPosition(end); page.requestFocusInWindow(); page.select(start, end); } caretPosition = page.getCaretPosition(); if (caretPosition >= 0) { Element elem = page.getStyledDocument().getCharacterElement(caretPosition - 1 < 0 ? 0 : caretPosition - 1); if (elem != null) { int startOffset = elem.getStartOffset(); int endOffset = elem.getEndOffset(); AttributeSet a = elem.getAttributes(); String href = (String) a.getAttribute(HTML.Attribute.HREF); if (href != null) { urlField.setText(href); try { textLabel.setText(page.getText(startOffset, endOffset - startOffset)); } catch (BadLocationException e) { textLabel.setText(null); urlField.setText(null); } page.requestFocusInWindow(); page.select(startOffset, endOffset); urlField.setEnabled(true); clearButton.setEnabled(true); urlList.setEnabled(true); newWindowCheckBox.setEnabled(true); } else { String t = page.getSelectedText(); boolean b = t != null; textLabel.setText(b ? t : "No text is selected."); urlField.setText(null); urlList.clearSelection(); urlField.setEnabled(b); clearButton.setEnabled(b); urlList.setEnabled(b); newWindowCheckBox.setEnabled(b); } setNewWindowOptions(a); } } }
8
private void addIgnore(long encodedName) { try { if (encodedName == 0L) { return; } if (ignoreCount >= 100) { pushMessage("Your ignore list is full. Max of 100 hit", 0, ""); return; } String s = TextUtil.formatName(TextUtil.longToName(encodedName)); for (int j = 0; j < ignoreCount; j++) { if (ignoreListAsLongs[j] == encodedName) { pushMessage(s + " is already on your ignore list", 0, ""); return; } } for (int k = 0; k < friendsCount; k++) { if (friendsNamesAsLongs[k] == encodedName) { pushMessage("Please remove " + s + " from your friend list first", 0, ""); return; } } ignoreListAsLongs[ignoreCount++] = encodedName; needDrawTabArea = true; outputStream.writeOpcode(133); outputStream.writeLong(encodedName); return; } catch (RuntimeException runtimeexception) { Signlink.reporterror("45688, " + encodedName + ", " + 4 + ", " + runtimeexception.toString()); } throw new RuntimeException(); }
7
public static void run_task_manager(File tasks) { System.out.println("System task manager is initialized ..."); Scanner scanner = new Scanner(new InputStreamReader(System.in)); TaskManager manager = new TaskManager(tasks); manager.runTask(); while(true) { if(manager.isDone()) { System.out.println("\nAll tasks are done, Have a nice day..."); scanner.close(); return; } String input = scanner.nextLine(); if(input.equals("task")) { System.out.println("\nCurrent task: " + manager.getTask()); } else if(input.equals("run")) { manager.runTask(); } else if(input.equals("next")) { System.out.println("\nNext task: " + manager.nextTask()); } else if(input.equals("exit")) { System.out.println("\nSystem task manager has exited ..."); scanner.close(); return; } while(manager.getTask().getTaskName().equals("user_comm")) { input = scanner.nextLine(); if(input.equals("done")) { System.out.println("\nUser command connection has been shut down..."); manager.runTask(); break; } else manager.sendComm(input); } } }
8
private boolean uhattuYlhaalta(int pelaajaNumero, int x, int y) { int i = 1; while(x-i >= 0 && kentta[x-i][y].onTyhja()) i++; if(x-i < 0) return false; if(kentta[x-i][y].getNappula().omistajanPelinumero() != pelaajaNumero) { if(i == 1 && kentta[x-i][y].getNappula().getClass() == new Kuningas().getClass()) return true; if(kentta[x-i][y].getNappula().getClass() == new Kuningatar().getClass()) return true; if(kentta[x-i][y].getNappula().getClass() == new Torni().getClass()) return true; } return false; }
8
private void printNode(ITrieNode node, HashMap<Integer,Integer> frontier) { StringBuffer msg = new StringBuffer(String.valueOf(node.id)); msg.append(" ").append(node.value).append(" weight ").append(node.weight); msg.append("=>").append(node.getWeight(frontier)); System.out.println(msg.toString()); if (this.children == null) { return; } for (ITrieNode t: node.children.values()) { printNode(t, frontier); } }
2
public Book isAvailable(Book book, Connection con) { boolean hasToCreate = false; if (con == null) { try { con = DBConnection.getConnection(); hasToCreate = true; } catch (Exception e) { e.printStackTrace(); } } try { MasterBook masterbook = MasterBookDAL.findMasterBook( book.getMasterbook(), con); book.setMasterbook(masterbook); if (masterbook != null) { pstmt = con.prepareStatement(BOOKS_CHECK_STATUS); pstmt.setInt(1, book.getMasterbook().getIsbn()); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { book.setBookID(rs.getInt(1)); book.setStatus(rs.getBoolean(2)); } pstmt = con.prepareStatement(BOOKS_GET_DATES); pstmt.setInt(1, book.getBookID()); pstmt.executeQuery(); if (rs.next()) { book.setIssuedate(rs.getTimestamp(1)); book.setDuedate(rs.getTimestamp(2)); } return book; } } catch (Exception e) { e.printStackTrace(); } finally { if (hasToCreate) DBConnection.closeObjects(null, con, pstmt); } return (null); }
7
@Override protected Class findClass(String name) throws ClassNotFoundException { synchronized (fileManager) { Output output = fileManager.map.remove(name); if (output != null) { byte[] array = output.toByteArray(); return defineClass(name, array, 0, array.length); } } return super.findClass(name); }
1
protected static void manageInputCommandForServer(ServerInfo serverInfo) { BufferedReader commandReader = new BufferedReader(new InputStreamReader(System.in)); log.info("CREATE BufferedReader"); Thread chatServerThread = null; String commandLine = null; // manage server commands while (true) { System.out.print("command: "); commandLine = readInputCommadForServer(commandReader); if (commandLine.startsWith(ServerCommand.START.getName())) { chatServerThread = startChatServer(chatServerThread, serverInfo); } else if (commandLine.startsWith(ServerCommand.EXIT.getName())) { if (chatServerThread != null) stopChatServer(chatServerThread); log.info("Break command loop"); break; } else {// TODO stop, change port ... command log.info("unsupported, incorrect or not well formed command: " + commandLine); System.out.println("unsupported, incorrect or not well formed command"); } } }
4
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); try{ Connection adaugareEvenimentConn = null; ResultSet adaugareEvenimentResult = null; Statement adaugareEvenimentStatement = null; PreparedStatement adaugareEvenimentPStatement = null; String adaugareEvenimentQuery = "insert into eveniment (denumire,data,prezentator,idProiect) values (?, ?, ?, ?)"; String idProiectQuery = "select idProiect from proiect where denumire='"+session.getAttribute("denumireProiect")+"'"; try{ adaugareEvenimentConn=ConnectionManager.getConnection(); adaugareEvenimentStatement=adaugareEvenimentConn.createStatement(); adaugareEvenimentResult=adaugareEvenimentStatement.executeQuery(idProiectQuery); String idProiect = null; if(adaugareEvenimentResult.next()){ idProiect = adaugareEvenimentResult.getString("idProiect"); } String dataEvenimentInput = request.getParameter("dataEveniment"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date dataEveniment = format.parse(dataEvenimentInput); java.sql.Date dataEv = new java.sql.Date(dataEveniment.getTime()); adaugareEvenimentPStatement=adaugareEvenimentConn.prepareStatement(adaugareEvenimentQuery); adaugareEvenimentPStatement.setString(1,request.getParameter("denumireEveniment")); adaugareEvenimentPStatement.setDate(2,dataEv); adaugareEvenimentPStatement.setString(3,request.getParameter("prezentatorEveniment")); adaugareEvenimentPStatement.setInt(4,Integer.parseInt(idProiect)); adaugareEvenimentPStatement.executeUpdate(); }catch(Exception ex){System.out.println("Error getting idProiect/inserting Eveniment: "+ex);} finally{ if(adaugareEvenimentResult!=null){ try{ adaugareEvenimentResult.close(); }catch(Exception e){} adaugareEvenimentResult=null; } if(adaugareEvenimentStatement!=null){ try{ adaugareEvenimentStatement.close(); }catch(Exception e){} adaugareEvenimentStatement=null; } if(adaugareEvenimentConn!=null){ try{ adaugareEvenimentConn.close(); }catch(Exception e){} adaugareEvenimentConn=null; } } String referer = request.getHeader("Referer"); response.sendRedirect(referer); }catch(Throwable theException){System.out.println("Exception is"+theException);} }
9
public static String excutePost(String targetURL, String urlParameters) { HttpsURLConnection connection = null; try { URL url = new URL(targetURL); connection = (HttpsURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.connect(); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); StringBuffer response = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); String str1 = response.toString(); return str1; } catch (Exception e) { e.printStackTrace(); return null; } finally { if (connection != null) connection.disconnect(); } }
3
public String distribute( String input ) { try { return (String) ( this.disMethod.invoke( this.distributor.newInstance(), input)); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } return null; }
4
@Test public void test2() throws PersistitException { System.out.print("test2 "); final Exchange ex = _persistit.getExchange("persistit", "TransactionTest3", true); ex.clear().append("test2").remove(Key.GTEQ); final String[] expectedKeys = { "{\"test2\",\"a\",0}", "{\"test2\",\"a\",1}", "{\"test2\",\"a\",2}", "{\"test2\",\"a\",3}", "{\"test2\",\"a\",4}", "{\"test2\",\"a\",5}", "{\"test2\",\"a\",7}", "{\"test2\",\"a\",8}", "{\"test2\",\"b\",0}", "{\"test2\",\"b\",1}", "{\"test2\",\"b\",2}", "{\"test2\",\"b\",4}", "{\"test2\",\"b\",5}", "{\"test2\",\"b\",6}", "{\"test2\",\"b\",7}", "{\"test2\",\"b\",8}", }; for (int i = 0; i < 10; i++) { ex.getValue().put("String value #" + i + " for test2"); ex.clear().append("test2").append("a").append(i).store(); ex.clear().append("test2").append("b").append(i).store(); } final Transaction txn = ex.getTransaction(); txn.begin(); try { for (int i = 3; i < 10; i += 3) { ex.clear().append("test2").append("a").append(i).remove(Key.GTEQ); ex.clear().append("test2").append("b").append(i).remove(Key.GTEQ); } ex.getValue().put("String value #" + 3 + " for test2 - pending"); ex.clear().append("test2").append("a").append(3).store(); ex.getValue().put("String value #" + 6 + " for test2 - pending"); ex.clear().append("test2").append("b").append(6).store(); ex.clear().append("test2"); for (int index = 0; ex.traverse(Key.GT, true) && (index < expectedKeys.length); index++) { assertEquals(expectedKeys[index], ex.getKey().toString()); } final boolean removed1 = ex.clear().append("test2").append("a").remove(Key.GTEQ); assertTrue(removed1); boolean removed2 = ex.clear().append("test2").append("c").remove(Key.GTEQ); assertTrue(!removed2); ex.clear().append("test2"); for (int index = 8; ex.traverse(Key.GT, true) && (index < expectedKeys.length); index++) { assertEquals(expectedKeys[index], ex.getKey().toString()); } txn.commit(); } catch (final AssertionFailedError e) { System.out.println("Assertion failed: " + e); e.printStackTrace(); } finally { txn.end(); } ex.clear().append("test2"); for (int index = 8; ex.traverse(Key.GT, true) && (index < expectedKeys.length); index++) { assertEquals(expectedKeys[index], ex.getKey().toString()); } System.out.println("- done"); }
9
public void run(){ if(lobbycount >= 1){ lobbycount--; game.setLobbyCount(lobbycount); for(CookieSlapPlayer cp : game.getPlayers().values()){ cp.getPlayer().setLevel(lobbycount); cp.getScoreboard().setScore("Starting in", game.getLobbyCount()); } ScoreboardUtils.get().setScoreAll(game, "Queue", game.getPlayers().size()); game.getSign().update(game.getMap(), false); if(lobbycount % 10 == 0){ CookieSlap.getCookieSlap().chat.bc("&7Starting In &6" + lobbycount + "&6.", game); } if((lobbycount <= 5) && (lobbycount >= 1) && (lobbycount != 0)){ CookieSlap.getCookieSlap().chat.bc("&7Starting In &6" + lobbycount + "&6.", game); } } else { if(game.getPlayers().size() > 1){ Bukkit.getScheduler().cancelTask(game.getCounterID()); CookieSlap.getCookieSlap().game.startGame(game); } else { CookieSlap.getCookieSlap().chat.bc("&cNot Enough Players", game); Bukkit.getScheduler().cancelTask(game.getCounterID()); game.setLobbyCount(31); game.setStarting(false); game.getSign().update(game.getMap(), false); } } }
7
private String formatStateLabel(State state) { StringBuilder formatted = new StringBuilder(); if(direction.equals("TD") || direction.equals("DT")) { formatted.append('{'); } formatted.append(ensureTextIsValid(state.getName())); String description = state.getDescription(); if (StringUtils.isNotBlank(description)) { formatted.append("\\n|"); formatted.append(ensureTextIsValid(description)); } if(direction.equals("TD") || direction.equals("DT")) { formatted.append('}'); } return formatted.toString(); }
5
public void test_08() { int nmerSize = 32; String seqStr[] = { "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" // , "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac" // Prepend 'c', append 'g' }; SuffixIndexerNmer<DnaSequence> seqIndex = new SuffixIndexerNmer<DnaSequence>(new DnaSubsequenceComparator<DnaSequence>(true, 0), nmerSize); for( int i = 0; i < seqStr.length; i++ ) { DnaSequence bseq = new DnaSequence(seqStr[i]); if( !seqIndex.overlap(bseq) ) seqIndex.add(bseq); // Add or overlap } assertEquals("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac", seqIndex.get(1).getSequence()); }
2
protected List<Object> getFeatureArrayFromMethods(Object o) { List<Object> features = new ArrayList<Object>(); Method[] methods = o.getClass().getMethods(); for(Method m : methods) { Annotation annotation = m.getAnnotation(NumericFeature.class); if(annotation == null) { annotation = m.getAnnotation(TextFeature.class); } if (annotation != null) { m.setAccessible(true); try { features.add(m.invoke(o)); } catch (NumberFormatException e) { LOG.error(e); } catch (IllegalArgumentException e) { LOG.error(e); } catch (IllegalAccessException e) { LOG.error(e); } catch (InvocationTargetException e) { LOG.error(e); } } } return features; }
7
public static void main(String[] args) throws IOException, FileNotFoundException{ long startTime = System.currentTimeMillis(); BufferedReader br = new BufferedReader(new FileReader("clustering_big.txt")); String line = br.readLine(); n = Integer.parseInt(line.split("(\\s)+")[0]); numBits = Integer.parseInt(line.split("(\\s)+")[1]); while((line = br.readLine())!= null){ BitSet b = getBitSet(line); clusters.put(b, new ArrayList()); for (int kk = 0; kk < 3; kk++ ){ clusters.get(b).add(b); // first ele in the list is bitset itself clusters.get(b).add(0); // second ele is the rank of this bitset } } // the duplicates will be auto merged. // scan each bitset in the hashmap for (BitSet bitEntry : clusters.keySet()){ //get all bitsets for all at distance of 1 or 2 from s ArrayList<BitSet> members = getMembers(bitEntry); for (BitSet bitMember : members){ union(bitEntry,bitMember); } } int count = 0; //parent of a parent is itself..each cluster has a single parent. for(Map.Entry<BitSet, ArrayList> e : clusters.entrySet()){ if (e.getKey().equals(e.getValue().get(0))){ count++; } } long stopTime = System.currentTimeMillis(); System.out.println(" running time: " + (stopTime-startTime)); //6118 System.out.println(" num clusters " + count); }
6
public static void restart() throws IOException { try { // java binary String java = System.getProperty("java.home") + System.getProperty("file.separator") + "bin" + System.getProperty("file.separator") + "java"; // vm arguments List<String> vmArguments = ManagementFactory.getRuntimeMXBean().getInputArguments(); StringBuffer vmArgsOneLine = new StringBuffer(); for (String arg : vmArguments) { // if it's the agent argument : we ignore it otherwise the // address of the old application and the new one will be in conflict if (!arg.contains("-agentlib")) { vmArgsOneLine.append(arg); vmArgsOneLine.append(" "); } } // init the command to execute, add the vm args final StringBuffer cmd = new StringBuffer(java + " " + vmArgsOneLine); // program main and program arguments String[] mainCommand = System.getProperty(SUN_JAVA_COMMAND).split(" "); // program main is a jar if (mainCommand[0].endsWith(".jar")) { // if it's a jar, add -jar mainJar cmd.append("-jar ").append(new File(mainCommand[0]).getPath()); } else { // else it's a .class, add the classpath and mainClass cmd.append("-cp ").append(System.getProperty("java.class.path")).append(" ").append(mainCommand[0]); } // finally add program arguments for (int i = 1; i < mainCommand.length; i++) { cmd.append(" "); cmd.append(mainCommand[i]); } // execute the command in a shutdown hook, to be sure that all the // resources have been disposed before restarting the application Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { Runtime.getRuntime().exec(cmd.toString()); } catch (IOException e) { } } }); // exit System.exit(0); } catch (Exception e) { // something went wrong throw new IOException("Error while trying to restart the application", e); } }
6
public static TileLoader getInstance(){ if(instance == null){ instance = new TileLoader(); } return instance; }
1
@Test public void numberOfFigureOnBoard() { HashSet<String> boards = new HashSet<>(); boards.add("nnnnnn\n" + "nnnnnn\n" + "nnnnnn\n" + "nnnnnn\n" + "nnnnnn\n" + "nnnnnn\n"); HashMap<String, Integer> figureQuantityMap = new HashMap<>(); figureQuantityMap.put(BISHOP.toString(), 3); FiguresChain figuresChain = new Bishop(figureQuantityMap); Set<String> result = figuresChain.placeFigures(boards.stream()).collect(Collectors.toSet()); assertThat("there are no boards", result.size() > 0, is(true)); assertTrue("all elements are not present on each board", result.stream() .allMatch(board -> !board.contains(KING.getFigureAsString()) && !board.contains(QUEEN.getFigureAsString()) && !board.contains(ROOK.getFigureAsString()) && !board.contains(BISHOP.getFigureAsString()) && board.contains(KNIGHT.getFigureAsString()) && leftOnlyFigures(board).length() == 36 )); }
5
public long ipToLong(byte[] address) { if (address.length != 4) { throw new IllegalArgumentException("byte array must be of length 4"); } long ipNum = 0; long multiplier = 1; for (int i = 3; i >= 0; i--) { int byteVal = (address[i] + 256) % 256; ipNum += byteVal*multiplier; multiplier *= 256; } return ipNum; }
2
public boolean isAncestor(mxGraphHierarchyNode otherNode) { // Firstly, the hash code of this node needs to be shorter than the // other node if (otherNode != null && hashCode != null && otherNode.hashCode != null && hashCode.length < otherNode.hashCode.length) { if (hashCode == otherNode.hashCode) { return true; } if (hashCode == null) { return false; } // Secondly, this hash code must match the start of the other // node's hash code. Arrays.equals cannot be used here since // the arrays are different length, and we do not want to // perform another array copy. for (int i = 0; i < hashCode.length; i++) { if (hashCode[i] != otherNode.hashCode[i]) { return false; } } return true; } return false; }
8
public double[] randomRehearsalSerialLearning(double[][] baseinputs, double[][] baseoutputs, double[][] serialinputs, double[][] serialoutputs, double maxerror, int bufferSize) { Random r = new Random(); double[] outputs = new double[serialinputs.length + 1]; double error = maxerror + 1; int counter = 0; // train base population while (maxerror < error && counter++ < quitCounter) { for (int i = 0; i < baseinputs.length; i++) { Pattern trial = new Pattern(baseinputs[i], baseoutputs[i]); pass(trial); updateAllWeights(trial); } error = populationError(outputs(baseinputs), baseoutputs); } outputs[0] = error; for (int i = 0; i < serialinputs.length; i++) { double[][] rehearseinputs = new double[bufferSize + 1][]; double[][] rehearseoutputs = new double[bufferSize + 1][]; for (int j = 0; j < rehearseinputs.length - 1; j++) { int n = r.nextInt(rehearseinputs.length); rehearseinputs[j] = baseinputs[n]; rehearseoutputs[j] = baseoutputs[n]; } rehearseinputs[rehearseinputs.length-1] = serialinputs[i]; rehearseoutputs[rehearseoutputs.length-1] = serialoutputs[i]; error = maxerror + 1; counter = 0; while (maxerror < error && counter++ < quitCounter) { for (int j = 0; j < rehearseinputs.length; j++) { Pattern trial = new Pattern(rehearseinputs[j], rehearseoutputs[j]); pass(trial); updateAllWeights(trial); } error = populationError(outputs(rehearseinputs), rehearseoutputs); } double poperror = populationError(outputs(baseinputs), baseoutputs); outputs[i+1] = poperror; } return outputs; }
8
@SuppressWarnings("static-access") @Override public void mousePressed(MouseEvent e) { if(e.getButton() == e.BUTTON1){ Buttons1 button = (Buttons1)e.getSource(); button.pressed(1); } else if(e.getButton() == e.BUTTON2){ Buttons1 button = (Buttons1)e.getSource(); button.pressed(2); } else if(e.getButton() == e.BUTTON3){ Buttons1 button = (Buttons1)e.getSource(); button.pressed(3); } }
3