text
stringlengths
14
410k
label
int32
0
9
public void construct(String file_name) { try { BufferedReader br = new BufferedReader(new FileReader(file_name)); String line, cell = ""; String[] tokens; boolean first_line = true; while ((line = br.readLine()) != null) { tokens = line.split("\\s"); int i = 0; if (first_line) { m_builder.set_width_and_height(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1])); i = 2; first_line = false; } for (; i < tokens.length; ++i) { if (tokens[i].equals("")) { m_builder.build_cell(cell); cell = ""; m_builder.start_row(); } else if (tokens[i].equals("")) { m_builder.build_cell(cell); cell = ""; } else { cell += " " + tokens[i]; } } } m_builder.build_cell(cell); br.close(); } catch (Exception ex) { ex.printStackTrace(); } }
6
@SuppressWarnings("unchecked") @Test public void QueryStudent(){ Session session = HibernateUtil.currentSession(); Transaction tx = session.beginTransaction(); List<Student> slist = new ArrayList<Student>(); String hql = "select s from Student as s"; Query q = session.createQuery(hql); slist = q.list(); Student s = null; Book b = null; for(int i=0;i<slist.size();i++){ s = slist.get(i); System.out.println("学生姓名:"+s.getsName()+";年龄"+s.getsAge()); Set<?> book = s.getBook(); Iterator<?> it = book.iterator(); while(it.hasNext()){ b = (Book) it.next(); System.out.println("书本名字:"+b.getbName()+";价格:"+b.getbPrice()); } } tx.commit(); HibernateUtil.closeSession(); }
4
public String toString() { return "FROM:" + boardIndexFrom + " TOP CARD INDEX: " + toMoveTop + (boardIndexTo == -1 ? "" : " TO " + boardIndexTo); }
1
private static void addPeakCalls(HashMap<String, List<Holder>> map ) throws Exception { for(String contig : map.keySet()) { List<Holder> list = map.get(contig); for(int x=0 ; x < list.size(); x++) { Holder h = list.get(x); Holder lastH = x >0 ? list.get(x-1) : null; if( h.regressionSlope == null ) { h.phase = Phase.NONE; } else { if( Math.abs(h.regressionSlope) <= SLOPE_THRESHOLD) { if( lastH == null) h.phase = Phase.NON_PEAK; else if( lastH.phase == Phase.UP_PEAK || lastH.phase == Phase.PEAK_TOP) h.phase = Phase.PEAK_TOP; else h.phase = Phase.NON_PEAK; } else { if( h.regressionSlope >0) h.phase = Phase.UP_PEAK; else h.phase = Phase.DOWN_PEAK; } } } } }
9
public static void UpperPlaceOfPublication(){ try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try{ conn.setAutoCommit(false); PreparedStatement stmnt = conn.prepareStatement("UPDATE Books set place_of_publication = CONCAT( UPPER( LEFT( place_of_publication, 1 ) ) , SUBSTRING( place_of_publication, 2 ))"); stmnt.execute(); conn.commit(); conn.setAutoCommit(true); }catch(SQLException e){ e.printStackTrace(); } }
4
public void writeFlightReportToXML(FlightReport report) { try { if(!fileWriter.checkIfFileExistsOrCreateNew(FlightReportPath)){ createFlightReportToXMLFile(report); } // create document from existing file DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(FlightReportPath); Element reportElement = doc.getDocumentElement(); // set data to root - element Attr ReportDate = doc.createAttribute("date"); ReportDate.setValue(report.getDateStamp().toString()); reportElement.setAttributeNode(ReportDate); // flightroute elements Element flightrouteElement = doc.createElement("flightroute"); reportElement.appendChild(flightrouteElement); for (int i = 0; i < report.getAllFlights().size(); i++) { // set attribute to Flighroute element: Attr idAttribute = doc.createAttribute("id"); idAttribute.setValue(report.getAllFlights().get(i).getFlightRoute().getFlightRouteNr()); flightrouteElement.setAttributeNode(idAttribute); Attr destinationAttribute = doc.createAttribute("destination"); destinationAttribute.setValue(report.getAllFlights().get(i).getFlightRoute().getDestination()); flightrouteElement.setAttributeNode(destinationAttribute); //set ID attribute to Trolley element: for (int j = 0; j < report.getAllFlights().get(i).getTrolleysOnFlight().size(); j++) { // trolley elements Element trolleyElement = doc.createElement("trolley"); flightrouteElement.appendChild(trolleyElement); Attr trolleyIdAttribute = doc.createAttribute("id"); trolleyIdAttribute.setValue(report.getAllFlights().get(i).getTrolleysOnFlight().get(j).getTrolleyId() + ""); trolleyElement.setAttributeNode(trolleyIdAttribute); Attr trolleyTotalWeightAttribute = doc.createAttribute("payload"); trolleyTotalWeightAttribute.setValue(report.getAllFlights().get(i).getTrolleysOnFlight().get(j).getPayLoad()+ ""); trolleyElement.setAttributeNode(trolleyTotalWeightAttribute); } } TransformAndFormatXML(doc); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } catch (SAXException ex) { Logger.getLogger(XMLFileParser.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(XMLFileParser.class.getName()).log(Level.SEVERE, null, ex); } }
7
public static void makeCompactGrid(Container parent, int rows, int cols, int initialX, int initialY, int xPad, int yPad) { SpringLayout layout; try { layout = (SpringLayout)parent.getLayout(); } catch (ClassCastException exc) { System.err.println("The first argument to makeCompactGrid must use SpringLayout."); return; } //Align all cells in each column and make them the same width. Spring x = Spring.constant(initialX); for (int c = 0; c < cols; c++) { Spring width = Spring.constant(0); for (int r = 0; r < rows; r++) { width = Spring.max(width, getConstraintsForCell(r, c, parent, cols). getWidth()); } for (int r = 0; r < rows; r++) { SpringLayout.Constraints constraints = getConstraintsForCell(r, c, parent, cols); constraints.setX(x); constraints.setWidth(width); } x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad))); } //Align all cells in each row and make them the same height. Spring y = Spring.constant(initialY); for (int r = 0; r < rows; r++) { Spring height = Spring.constant(0); for (int c = 0; c < cols; c++) { height = Spring.max(height, getConstraintsForCell(r, c, parent, cols). getHeight()); } for (int c = 0; c < cols; c++) { SpringLayout.Constraints constraints = getConstraintsForCell(r, c, parent, cols); constraints.setY(y); constraints.setHeight(height); } y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad))); } //Set the parent's size. SpringLayout.Constraints pCons = layout.getConstraints(parent); pCons.setConstraint(SpringLayout.SOUTH, y); pCons.setConstraint(SpringLayout.EAST, x); }
7
private void key(KeyEvent event, boolean pressed) { if (this.hasFocus()) { if (event.getKeyCode() == KeyEvent.VK_ALT && event.isControlDown() && isFullscreen) { // Special case for Ctrl-Alt-Ins to be mapped to // Ctrl-Alt-Delete. // stream_.keyEvent(pressed, // keyMap.getMappedKey(KeyEvent.VK_DELETE)); // Exitfullscreen screen.dispose(); isFullscreen = false; // screen = null; } else if (event.getKeyCode() == KeyEvent.VK_ALT && event.isControlDown()) { /* For now disabling Ctrl-Alt fullscreen support final Container root = getParent().getParent(); root.remove(getParent()); VNCFullscreen fc = new VNCFullscreen((JPanel) getParent(), this, true, getParent().getBackground()); fc.addWindowListener(new WindowListener() { public void windowActivated(WindowEvent e) { }; public void windowClosed(WindowEvent e) { root.add(getParent()); setMaxHeight(getParent().getHeight()); setMaxWidth(getParent().getWidth()); root.invalidate(); root.validate(); invalidate(); repaint(); requestFocusInWindow(); }; public void windowClosing(WindowEvent e) { }; public void windowDeactivated(WindowEvent e) { ((VNCFullscreen) e.getComponent()).dispose(); }; public void windowDeiconified(WindowEvent e) { }; public void windowIconified(WindowEvent e) { }; public void windowOpened(WindowEvent e) { }; }); requestFocusInWindow(); */ } else { int keysym = keyMap.getKeysym(event); if (keysym != -1) { stream_.keyEvent(pressed, keysym); } } event.consume(); } }
7
public Tpv(int idTpv, GregorianCalendar fecha, GregorianCalendar hora, Cliente cliente, double total, double entrega) { this.idTpv = idTpv; this.fecha = fecha; this.hora = hora; this.cliente = cliente; this.total = total; this.entrega = entrega; }
0
static void indexDocs(IndexWriter writer, File file) throws IOException { // do not try to index files that cannot be read if (file.canRead()) { if (file.isDirectory()) { String[] files = file.list(); // an IO error could occur if (files != null) { for (int i = 0; i < files.length; i++) { indexDocs(writer, new File(file, files[i])); } } } else { FileInputStream fis; try { fis = new FileInputStream(file); } catch (FileNotFoundException fnfe) { // at least on windows, some temporary files raise this // exception with an "access denied" message // checking if the file can be read doesn't help return; } try { // make a new, empty document Document doc = new Document(); // Add the path of the file as a field named "path". Use a // field that is indexed (i.e. searchable), but don't // tokenize // the field into separate words and don't index term // frequency // or positional information: Field pathField = new StringField("path", file.getPath(), Field.Store.YES); doc.add(pathField); Field relativePathField = new StringField("shortPath", getRelativePath(file.getPath()), Field.Store.YES); doc.add(relativePathField); // Add the last modified date of the file a field named // "modified". // Use a LongField that is indexed (i.e. efficiently // filterable with // NumericRangeFilter). This indexes to milli-second // resolution, which // is often too fine. You could instead create a number // based on // year/month/day/hour/minutes/seconds, down the resolution // you require. // For example the long value 2011021714 would mean // February 17, 2011, 2-3 PM. doc.add(new LongField("modified", file.lastModified(), Field.Store.NO)); // Add the contents of the file to a field named "contents". // Specify a Reader, // so that the text of the file is tokenized and indexed, // but not stored. // Note that FileReader expects the file to be in UTF-8 // encoding. // If that's not the case searching for special characters // will fail. if (file.getName().endsWith(".txt")) doc.add(new TextField("contents", new BufferedReader(new InputStreamReader(fis, "UTF-8")))); if (file.getName().endsWith(".html")) { doc.add(new TextField("contents", html2String(fis), Field.Store.YES)); doc.add(new StringField("title", getHTMLTitle(file), Field.Store.YES)); } if (writer.getConfig().getOpenMode() == OpenMode.CREATE) { // New index, so we just add the document (no old // document can be there): System.out.println("adding " + file); writer.addDocument(doc); } else { // Existing index (an old copy of this document may have // been indexed) so // we use updateDocument instead to replace the old one // matching the exact // path, if present: System.out.println("updating " + file); try { writer.updateDocument(new Term("path", file.getPath()), doc); } catch (Exception e) { // TODO e.printStackTrace(); } } } finally { fis.close(); } } } }
9
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed String criterio = ""; boolean isCompra = false; BigDecimal rangoMax = BigDecimal.ZERO; BigDecimal rangoMin = BigDecimal.ZERO; if(rbtCompra.isSelected()) { criterio = "Tipo"; isCompra = true; } else if(rbtVenta.isSelected()) criterio = "Tipo"; else if(rbtRangoMonto.isSelected()) { criterio = "Monto"; List<BigDecimal> rango = obtenerPanelRangos(); if (rango == null) JOptionPane.showMessageDialog(null, "Favor indicar los rangos de búsqueda."); else { rangoMin = rango.get(0); rangoMax = rango.get(1); System.out.println("MINIMO: " + rangoMin + " MAXIMO " + rangoMax); } } else if(rbtRangoTipoCambio.isSelected()) { criterio = "TipoCambio"; List<BigDecimal> rango = obtenerPanelRangos(); if (rango == null) JOptionPane.showMessageDialog(null, "Favor indicar los rangos de búsqueda."); else { rangoMin = rango.get(0); rangoMax = rango.get(1); System.out.println("MINIMO: " + rangoMin + " MAXIMO " + rangoMax); } } else { criterio = "Vacio"; JOptionPane.showMessageDialog(null, "Favor seleccionar una opción."); } if(!criterio.equals("Vacio")) { DAOFactory sqlserverFactory = DAOFactory.getDAOFactory(DAOFactory.SQLSERVER); ParticipanteDAO participanteDAO = sqlserverFactory.getParticipanteDAO(); int result = participanteDAO.buscarOfertas(criterio, rangoMin, rangoMax, isCompra, tablaOfertas); if(result < 0) JOptionPane.showMessageDialog(null, "Ha ocurrido un error."); } }//GEN-LAST:event_jButton1ActionPerformed
8
public boolean canGoAtDirection(Direction direction, Location from) { switch (direction) { case UP: return isWalkablePath(from.getX(), from.getY() - 1); case DOWN: return isWalkablePath(from.getX(), from.getY() + 1); case LEFT: return isWalkablePath(from.getX() - 1, from.getY()); case RIGHT: return isWalkablePath(from.getX() + 1, from.getY()); default: return isWalkablePath(from.getX(), from.getY() - 1); } }
4
public static PVector resolveTopRight(PVector v) { PVector result = new PVector(); if (((v.heading() > (float)(Math.PI/4)) && (v.heading() <= (float)Math.PI)) || ((v.heading() > (float)-Math.PI) && (v.heading() < (float)(-3*Math.PI/4)))) // NB brackets round second PI expression before float cast { result.x = -(float) (v.mag() * Math.cos(Math.PI/4)); result.y = (float) (v.mag() * Math.sin(Math.PI/4)); } return result; }
4
@Override public JFormCollection load() { if (loaded) return this; String body = null; try { body = JHttpClientUtil.postText( context.getUrl() + JHttpClientUtil.Forms.URL, JHttpClientUtil.Forms.GetFormCollection.replace("{listName}", list.getId().toString()), JHttpClientClient.getWebserviceSopa() ); } catch (Exception ex) { throw new RuntimeException(ex); } Document document; try { document = DocumentBuilderFactory .newInstance() .newDocumentBuilder() .parse(new ByteArrayInputStream(body.getBytes())); } catch (Exception ex) { throw new RuntimeException(ex); } NodeList nodes = document.getElementsByTagName("Form"); for (int i = 0; i < nodes.getLength(); i++) { Element node = (Element) nodes.item(i); String url = node.getAttribute("Url"); if (url == null) continue; JForm form = getFormByUrl(url); if (form == null) { form = new JForm(context, web, list); form.putAttributes(node.getAttributes()); add(form); } else { form.putAttributes(node.getAttributes()); } } // Find default for (JForm form : forms) { if (!"DisplayForm".equalsIgnoreCase(form.getType())) continue; if (form.load().isDefault()) break; } loaded = true; return this; }
9
@SuppressWarnings("unchecked") public void start() { if(hasStarted()) { throw new IllegalStateException("Machine has already started."); } if(stateGraph == null) { throw new IllegalStateException("No state graph specified."); } if(stateGraph.getStartState()==null) { throw new IllegalStateException("No start state specified."); } stateGraph.onStart(); enterState(null, stateGraph.getStartState()); }
3
private boolean jj_3_76() { if (jj_scan_token(EXCLAM)) return true; return false; }
1
public boolean start() { stopWaiting = false; if (startServerSocket()) { new Thread(new Runnable() { @Override public void run() { waitForConnections(); } }, "wait for connections").start(); return true; } return false; }
1
public static void addToProductionWithUsefulVariableSet( Production production, Set set) { set.add(production); }
0
@Override public void getInput() { int selection = -1; boolean isValid = false; do { this.displayMenu(); Scanner input = SnakeWithPartner.getInFile(); do { try { selection = input.nextInt(); isValid = true; } catch (NumberFormatException numx) { System.out.println("Invalid Input. Please input a valid number."); isValid = false; } } while (!isValid); switch (selection) { case 1: this.gameOverMenuControl.repeatGame(); break; case 2: this.gameOverMenuControl.goToMain(); break; case 3: this.gameOverMenuControl.goToHighScores(); case 0: break; default: System.out.println("Please enter a valid menu item:"); continue; } } while (selection != 0); }
7
public void render() { BufferStrategy bs = getBufferStrategy(); if (bs == null) { createBufferStrategy(3); return; } screen.clear(); int xScroll = player.x - screen.width / 2; int yScroll = player.y - screen.height / 2; level.render(xScroll, yScroll, screen); player.render(screen); for (int i = 0; i < pixels.length; i++) { pixels[i] = screen.pixels[i]; } Graphics g = bs.getDrawGraphics(); g.fillRect(0, 0, getWidth(), getHeight()); g.drawImage(image, 0, 0, getWidth(), getHeight(), null); g.setColor(Color.white); g.setFont(new Font ("verdana", 0, 10)); g.drawString("x: " + player.x + ", Y: " + player.y, 1, 10); //g.fillRect(Mouse.getX() - 32, Mouse.getY() - 32, 64, 64); //Random random2 = new Random(); if (key.taunt){ g.drawString("Where did everyone go?", 550, 210); } if (Mouse.getButton() != -1) g.drawString("button: " + Mouse.getButton(), 80, 80); if (Mouse.getButton() == 3) g.drawString("pew pew pew... this is fun", 550, 210); g.dispose(); bs.show(); }
5
public static void output() { System.out.println("hello wold !"); }
0
private void registerListeners() { // Add volume listener. mediaPlayer.addMediaPlayerEventListener(new MediaPlayerEventAdapter() { @Override public void playing(MediaPlayer mediaPlayer) { updateVolume(mediaPlayer.getVolume()); } }); // Add position slider listener positionSlider.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if(mediaPlayer.isPlaying()) { mousePressedPlaying = true; mediaPlayer.pause(); } else { mousePressedPlaying = false; } setSliderBasedPosition(); } @Override public void mouseReleased(MouseEvent e) { setSliderBasedPosition(); updateUIState(); } }); // add listener to rewind button rewindButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { skip(-SKIP_TIME_MS); } }); // add listener to stop button stopButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { mediaPlayer.stop(); playButton.setIcon(img3); } }); // add listener to play button playButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (playButton.getIcon()==img3){ mediaPlayer.play(); playButton.setIcon(img2); } else { playButton.setIcon(img3); //VideoPlayer.setPause(); mediaPlayer.pause(); } } }); // Add listener to fast forward button. fastForwardButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { skip(SKIP_TIME_MS); } }); // Add listener to volume slider. volumeSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { JSlider source = (JSlider)e.getSource(); // if(!source.getValueIsAdjusting()) { mediaPlayer.setVolume(source.getValue()); // } } }); // Add listener for toggling full screen (NOTE fullscreen not working currently.) fullScreenButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { mediaPlayer.toggleFullScreen(); } }); // Add listener for looping. loop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (loopOn==false){ loopOn=true; mediaPlayer.setRepeat(true); loopLabel.setText("Loop On"); } else{ loopOn=false; mediaPlayer.setRepeat(false); loopLabel.setText("Loop Off"); } } }); }
3
@Override public String getColumnName(int columnIndex) { switch(columnIndex) { case 0: return "Ranking"; case 1: return "Team #"; case 2: return "Team Name"; case 3: return "Round 1"; case 4: return "Round 2"; case 5: return "Round 3"; case 6: return "Round 4"; case 7: return "Highest"; } return null; }
8
private static void getAllTestNgTests(List<String> urlsOrFiles) throws Exception { List<TestResultData> testNgResultData = parseTestNgResultFromFilesOrUrls(urlsOrFiles); List<String> testNgTests = (List<String>) CollectionUtils .collect(testNgResultData, new BeanToPropertyValueTransformer("testName")); Collections.sort(testNgTests); File csvFile = new File("testNgDdTests.csv"); BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(csvFile)); for (String testNgTestName : testNgTests) { if (testNgTestName.contains("-")) { bw.write("com.vmware.qe.vcloud.tests.server."+testNgTestName); bw.write("\n"); } } } catch (Exception e) { throw e; } finally { try { bw.close(); } catch (Exception e) { e.printStackTrace(); } } }
4
public static pgrid.service.corba.exchange.ExchangeHandle narrow (org.omg.CORBA.Object obj) { if (obj == null) return null; else if (obj instanceof pgrid.service.corba.exchange.ExchangeHandle) return (pgrid.service.corba.exchange.ExchangeHandle)obj; else if (!obj._is_a (id ())) throw new org.omg.CORBA.BAD_PARAM (); else { org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); pgrid.service.corba.exchange._ExchangeHandleStub stub = new pgrid.service.corba.exchange._ExchangeHandleStub (); stub._set_delegate(delegate); return stub; } }
3
public static void main(String[] args) { if(args == null || args.length !=3) { System.err.println("usage: java Replace <instring> <what> <with>"); System.exit(1); } System.out.println("creating Replace object r ..."); Replace r = new Replace(args[0]); System.out.println("r after method replaceFirst: \t" + r.replaceFirst(args[1], args[2])); System.out.println("r has number replacements: \t" + r.getTotalNumberOfReplacements()); System.out.println("static method replaceFirst: \t" + replaceFirst(args[0],args[1], args[2])); System.out.println("r has number replacements: \t" + r.getTotalNumberOfReplacements()); System.out.println("r after method replaceLast: \t" + r.replaceLast(args[1], args[2])); System.out.println("r has number replacements: \t" + r.getTotalNumberOfReplacements()); System.out.println("r after method replaceAll: \t" + r.replaceAll(args[1], args[2])); System.out.println("r has number replacements: \t" + r.getTotalNumberOfReplacements()); System.out.println("================= history ================="); for(int i = 0; i < r.replaceDataStack.size(); i++) { System.out.print("at position "); System.out.print(((Object[])(r.replaceDataStack.elementAt(i)))[0].toString()); System.out.print("\t what: "); System.out.print(((Object[])(r.replaceDataStack.elementAt(i)))[1].toString()); System.out.print(" with: "); System.out.println(((Object[])(r.replaceDataStack.elementAt(i)))[2].toString()); } System.out.println("================= undo ================="); while(r.unDoLast()) { System.out.println("after method unDoLast: \t" + r.currentString); System.out.println("r has number replacements:\t" + r.getTotalNumberOfReplacements()); } }
4
public int getpointValue() {//Accesses the Card's point value return pointValue; }
0
@Override public boolean equals(Object obj) { if (obj == this) { return true; } return obj instanceof LengthValue && super.equals(obj); }
2
static final void method365(Class318_Sub1 class318_sub1, Class348_Sub1[] class348_sub1s) { if (Mob.aBoolean10221) { int i = class318_sub1.method2384(class348_sub1s, 49); Class9.aHa171.method3642(i, class348_sub1s); } if (Class332.aSArray4142 == aa_Sub1.aSArray5191) { boolean bool = false; boolean bool_11_ = false; int i; int i_12_; if (class318_sub1 instanceof Entity) { i = (((Entity) (Entity) class318_sub1) .aShort8743); i_12_ = ((Entity) (Entity) class318_sub1).aShort8750; } else { i = (((Class318_Sub1) class318_sub1).xHash >> Class362.anInt4459); i_12_ = (((Class318_Sub1) class318_sub1).anInt6388 >> Class362.anInt4459); } Class9.aHa171.EA((Class348_Sub1_Sub1.aSArray8801[0].method3986 (((Class318_Sub1) class318_sub1).xHash, ((Class318_Sub1) class318_sub1).anInt6388, (byte) -118)), Class367_Sub8.method3547(i, i_12_), Class318_Sub1_Sub5.method2483(i, i_12_), Class199.method1457(i, i_12_)); } Class318_Sub4 class318_sub4 = class318_sub1.method2386(1, Class9.aHa171); if (class318_sub4 != null) { if (((Class318_Sub1) class318_sub1).aBoolean6391) { Class318_Sub3[] class318_sub3s = ((Class318_Sub4) class318_sub4).aClass318_Sub3Array6414; for (int i = 0; i < class318_sub3s.length; i++) { Class318_Sub3 class318_sub3 = class318_sub3s[i]; if (((Class318_Sub3) class318_sub3).aBoolean6401) Class338.method2663 (-5590, (((Class318_Sub3) class318_sub3).anInt6405 - ((Class318_Sub3) class318_sub3).anInt6403), (((Class318_Sub3) class318_sub3).anInt6406 + ((Class318_Sub3) class318_sub3).anInt6403), (((Class318_Sub3) class318_sub3).anInt6402 - ((Class318_Sub3) class318_sub3).anInt6403), (((Class318_Sub3) class318_sub3).anInt6404 + ((Class318_Sub3) class318_sub3).anInt6403)); } } if (((Class318_Sub4) class318_sub4).aBoolean6409) { ((Class318_Sub4) class318_sub4).aClass318_Sub1_6410 = class318_sub1; if (Class348_Sub40_Sub5.aBoolean9121) { synchronized (Class71.aClass76_1208) { Class71.aClass76_1208.method774(class318_sub4, 18802); } } else Class71.aClass76_1208.method774(class318_sub4, 18802); } else Class59_Sub1_Sub1.method560(class318_sub4, 18); } }
9
public void tookDamage(double damageTaken) { if(invincibility<=0){ game.isDamaged(); invincibility=invTime; armour-=damageTaken; if(armour<=0){ Random r = new Random(); Color c; int numSparks; if(Spark.glowEnabled){ numSparks=Spark.glowSparks; } else { numSparks=Spark.normalSparks; } for(int i = 0; i<numSparks;i++){ switch(r.nextInt(3)){ case 0:c=Color.RED; break; case 1:c=Color.ORANGE; break; case 2:c=Color.RED; break; default:c=Color.RED; } double angle = r.nextInt(360); int distance = r.nextInt(200); int xPos = (int) (x+(Math.cos(angle)*distance)); int yPos = (int) (y+(Math.sin(angle)*distance)); game.addSpark((int) (x+(sprite.getWidth()/2)),(int) (y+(sprite.getHeight()/2)), 10,xPos,yPos,20, c,true); } game.removeEntity(this); game.notifyDeath(); } } }
7
public void detectCols() { for (int i = 5; i > 2; i--) { detectCol(i); } }
1
public void paint(Graphics gr1d, Object destinationComponent, Boolean b) { final Graphics2D gr = (Graphics2D) gr1d; gr.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); final int n = G.getVerticesCount(); if (n == 0) return; AbstractGraphRenderer.getCurrentGraphRenderer(gd.getBlackboard()).ignoreRepaints(new Runnable() { @SuppressWarnings({ "unchecked" }) public void run() { // boolean[] marks = new boolean[n]; Vertex V[] = G.getVertexArray(); final Vertex parent[] = new Vertex[n]; // consider the hole structure as a tree AlgorithmUtils.BFSrun(G, V[0], new AlgorithmUtils.BFSListener() { @Override public void visit(BaseVertex v, BaseVertex p) { parent[v.getId()] = (Vertex) p; } }); for (Vertex v : G) { if (v.getId() == 0) continue; if (v.getColor() == 0) { Vertex v1 = parent[v.getId()]; if (v1 == null || v1.getColor() != 0) continue; Vertex v2 = parent[v1.getId()]; if (v2 == null || v2.getColor() != 0) continue; // generate the curve between v1, v2 and v3 GraphPoint p1 = GraphPoint.mul(v.getLocation(),G.getZoomFactor()); GraphPoint p2 = GraphPoint.mul(v1.getLocation(),G.getZoomFactor()); GraphPoint p3 = GraphPoint.mul(v2.getLocation(),G.getZoomFactor()); Integer w1 = G.getEdge(v, v1).getWeight();// (Integer) Integer w2 = G.getEdge(v1, v2).getWeight();// (Integer) Integer w3 = 1; int startWidth = w1; int endWidth = w3; int middleWidth = w2; if(!v.equals(G.getVertex(0))){ startWidth = w3; endWidth = w1; middleWidth = w2; } double teta1 = AlgorithmUtils.getAngle(p1, p2); double teta2 = AlgorithmUtils.getAngle(p1, p3); double teta3 = AlgorithmUtils.getAngle(p2, p3); java.awt.geom.QuadCurve2D c1 = new QuadCurve2D.Double(p1.x - startWidth * Math.sin(teta1), p1.y + startWidth * Math.cos(teta1), p2.x - middleWidth * Math.sin(teta2), p2.y + middleWidth * Math.cos(teta2), p3.x - endWidth * Math.sin(teta3), p3.y + endWidth * Math.cos(teta3)); java.awt.geom.QuadCurve2D c2 = new QuadCurve2D.Double(p3.x + endWidth * Math.sin(teta3), p3.y - endWidth * Math.cos(teta3), p2.x + middleWidth * Math.sin(teta2), p2.y - middleWidth * Math.cos(teta2), p1.x + startWidth * Math.sin(teta1), p1.y - startWidth * Math.cos(teta1)); GeneralPath gp = new GeneralPath(c1); gp.append(c2, true); gp.closePath(); gr.setColor(color); // fill the curve gr.fill(gp); } } } }, false /* dont repaint after */); }
9
private void findNextTime(int timeUnit, int timeUnitCount) { switch (timeUnit) { case SECOND: calendar.add(Calendar.SECOND, timeUnitCount); break; case MINUTE: calendar.add(Calendar.MINUTE, timeUnitCount); break; case HOUR: calendar.add(Calendar.HOUR_OF_DAY, timeUnitCount); break; case DAY: calendar.add(Calendar.DAY_OF_MONTH, timeUnitCount); break; case WEEK: calendar.add(Calendar.DAY_OF_MONTH, 7 * timeUnitCount); break; case MONTH: calendar.add(Calendar.MONTH, timeUnitCount); break; case YEAR: calendar.add(Calendar.YEAR, timeUnitCount); break; } }
7
public static void printBattleProgress() { b1.allowedToPaintExp=true; //System.out.println(enemy[enemyIndex].toHPOnlyString()+" Remaining Pokemon:"+ //Mechanics.remainingPokemon(enemy, enemyNumOfPokemon)); //System.out.println(user[userIndex].toBattleString()); System.out.print("Waiting for command..."); if(Mechanics.moveDisabled[0]>-1&&Mechanics.moveDisabled[0]<4) { b1.addText(user[userIndex].move[Mechanics.moveDisabled[0]]+" is disabled!"); } userCmd=-1; while (!superDuperBoolean) { try { Thread.sleep(15); } catch(Exception ignored) { } } superDuperBoolean = false; }
4
public void testRemove() { int element_count = 10; TIntList a = new TIntArrayList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } assertEquals( 6, a.get( 5 ) ); assertTrue( a.remove( 5 ) ); for ( int i = 0; i < 4; i++ ) { int expected = i + 1; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } for ( int i = 4; i < a.size(); i++ ) { int expected = i + 2; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } // Can't remove again from THIS list because it's not present. assertFalse( a.remove( 5 ) ); assertEquals( 6, a.removeAt( 4 ) ); for ( int i = 0; i < 4; i++ ) { int expected = i + 1; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } for ( int i = 4; i < a.size(); i++ ) { int expected = i + 3; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } a.insert( 4, 6 ); // Add a value twice, can remove it twice assertTrue( a.add( 5 ) ); assertTrue( a.add( 5 ) ); assertTrue( a.remove( 5 ) ); assertTrue( a.remove( 5 ) ); assertFalse( a.remove( 5 ) ); a.insert( 4, 5 ); assertTrue( a.add( 5 ) ); for ( int i = 0; i < 5; i++ ) { int expected = i + 1; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } for ( int i = 5; i < a.size() - 1; i++ ) { int expected = i + 1; assertTrue( "index " + i + " expected " + expected + ", list: " + a, a.get( i ) == expected ); } assertEquals( 5, a.get( a.size() - 1 ) ); assertTrue( a.remove( 5 ) ); assertEquals( element_count, a.size() ); for ( int i = 0; i < 4; i++ ) { int expected = i + 1; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } for ( int i = 4; i < a.size() - 1; i++ ) { int expected = i + 2; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } assertEquals( 5, a.get( a.size() - 1 ) ); }
9
public char getTipo(String nombre){ getLista g = new getLista(); ListaClientes = g.getListaCliente(); ListaProveedores = g.getListaProveedor(); for(int i = 0;i<ListaClientes.size();i++){ if(ListaClientes.get(i).getNick().equals(nombre)){ return 'c'; } if(ListaProveedores.get(i).getNick().equals(nombre)){ return 'p'; } } return 'n'; }
3
public List<Graph> getErrorToConfidenceGraph() { Map<Double, Integer> timeMap = new HashMap<Double, Integer>(); Map<Double, Integer> stepsMap = new HashMap<Double, Integer>(); Map<Double, Integer> timeCount = new HashMap<Double, Integer>(); Map<Double, Integer> stepsCount = new HashMap<Double, Integer>(); Graph time = new Graph("Time Confidence", "Confidence", "Probability correct", lineLabel); Graph steps = new Graph("Steps Confidence", "Confidence", "Probability correct", lineLabel); for (Error e : errors) { double conf = (int)(e.getConfidence() * 10) / (double)10; if(e.getUnit() == PredictionUnit.Milliseconds) { if(!timeMap.containsKey(conf)) { timeMap.put(conf, 0); timeCount.put(conf, 0); } if(e.getError() <= timeThreshold) { timeMap.put(conf, timeMap.get(conf) + 1); } timeCount.put(conf, timeCount.get(conf) + 1); } else { if(!stepsMap.containsKey(conf)) { stepsMap.put(conf, 0); stepsCount.put(conf, 0); } if(e.getError() < stepsThreshold) { stepsMap.put(conf, stepsMap.get(conf) + 1); } stepsCount.put(conf, stepsCount.get(conf) + 1); } } for(double c : timeMap.keySet()) { time.addDataPoint(c, timeMap.get(c) / (double)timeCount.get(c)); } for(double c : stepsMap.keySet()) { steps.addDataPoint(c, stepsMap.get(c) / (double)stepsCount.get(c)); } List<Graph> result = new ArrayList<Graph>(); result.add(steps); result.add(time); return result; }
8
public RegularTransitionTool(AutomatonPane view, AutomatonDrawer drawer, FSAToREController controller) { super(view, drawer); this.controller = controller; }
0
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); try { String metodo = request.getParameter("metodo"); // Cadastrar ///////////////////////////////////////////////////// if (metodo.equals("cadastrar")){ //Pegando os parametros do request String nome = request.getParameter("nome"); String email = request.getParameter("email"); Long telefone = Long.parseLong(request.getParameter("telefone")); String dataEmTexto = request.getParameter("data"); //Monta um objeto contato TbCliente cliente = new TbCliente(); cliente.setNome(nome); cliente.setEmail(email); cliente.setTelefone(telefone); cliente.setDatanascimento(new java.sql.Date( new java.text.SimpleDateFormat("dd/mm/yyyy").parse(dataEmTexto).getTime())); // Assim dispensa usar o import para ParseException //Grave nessa conexão!!! DAOTbCliente dao = new DAOTbCliente(); if (dao.adicionar(cliente)) { //Imprime messagem comfirmando o cadastro out.println("<html>"); out.println("<body>"); out.println("<h1>O cadastro foi concluido!</h1></br>"); out.println("Cliente " + cliente.getNome() + " adicionado com sucesso</br>"); out.println("<br><br><a href='../pagesJsp2_Col/index.jsp'>Voltar para CRUD Hibernate + JSP + Servlet 'coletiva'</a>"); out.println("</body>"); out.println("</html>"); } else{ //Exibe mensagem de erro. out.println("<html>"); out.println("<body>"); out.println("Erro ao realizar cadastro!</br>"); out.println("Tente novamente"); out.println("</body>"); out.println("</html>"); } }// Fim Cadastrar // Preecheer formulário ////////////////////////////////////////// else if (metodo.equals("preencherForm")){ //Pegando os parametros do request Integer id = Integer.parseInt(request.getParameter("id_cliente")); //Pesquisando cliente para preecher o form DAOTbCliente dao = new DAOTbCliente(); TbCliente cliente = dao.consultarPorId(id); //Convertendo data SQL para String String dataString = new java.text.SimpleDateFormat("dd/MM/yyyy").format(cliente.getDatanascimento()); out.println("<h4>Formulário para atualização de dados<br/>"); out.println("Deve-se preencher todos os campos.</h4>"); out.println("<form method='post' action='atualizar'>" + "Cod. Cliente: <input type='text' name='id_cliente' value='"+cliente.getIdCliente()+"' readonly='readonly' /> <br/>" + "Nome: <input type='text' name='nome' value='"+cliente.getNome()+"' /> <br/>" + "Email: <input type='text' name='email' value='"+cliente.getEmail()+"' /> <br/>" + "Telefone: <input type='text' name='telefone' value='"+cliente.getTelefone()+"' />(Apenas numeros) <br/>" + "Data de nascimento: <input type='text' name='data' value='"+dataString+"' />dd/mm/yyyy (Formado da data) <br/>" + "<input type='submit' value='Atualizar'/>" + "</form>"); out.println("<br><a href='../pagesJsp2_Col/index.jsp'>Cancelar</a>"); out.println("</body>"); out.println("</html>"); }// Fim Preecheer // Atualizar ///////////////////////////////////////////////////// else if (metodo.equals("atualizar")){ Integer id = Integer.parseInt(request.getParameter("id_cliente")); String nome = request.getParameter("nome"); String email = request.getParameter("email"); Long telefone = Long.parseLong(request.getParameter("telefone")); String dataEmTexto = request.getParameter("data"); //Monta um objeto contato TbCliente cliente = new TbCliente(); cliente.setIdCliente(id);//Id do cliente a ser alterado cliente.setNome(nome); cliente.setEmail(email); cliente.setTelefone(telefone); cliente.setDatanascimento(new java.sql.Date( new java.text.SimpleDateFormat("dd/mm/yyyy").parse(dataEmTexto).getTime())); DAOTbCliente dao = new DAOTbCliente(); if (dao.alterar(cliente)) { //Imprime messagem comfirmando atualização out.println("<html>"); out.println("<body>"); out.println("<h1>O cadastro foi atualizado!</h1></br>"); out.println("Cliente " + cliente.getNome() + " atualizado com sucesso</br>"); out.println("<br><br><a href='../pagesJsp2_Col/index.jsp'>Voltar para CRUD Hibernate + JSP + Servlet 'coletiva'</a>"); out.println("</body>"); out.println("</html>"); } else{ //Exibe mensagem de erro. out.println("<html>"); out.println("<body>"); out.println("Erro ao realizar a atualização!</br>"); out.println("Tente novamente"); out.println("</body>"); out.println("</html>"); } }// Fim Atualizar // Excluir /////////////////////////////////////////////////////// else if (metodo.equals("excluir")){ //Id do cliente a ser deletado Integer id = Integer.parseInt(request.getParameter("id_cliente")); //Busca o cliente e monta vo DAOTbCliente dao = new DAOTbCliente(); TbCliente cliente = dao.consultarPorId(id); //Envia vo do cliente para o método exclir if (dao.deletar(cliente)) { //Imprime messagem comfirmando exclusão out.println("<html>"); out.println("<body>"); out.println("<h1>O cliente foi deletado!</h1></br>"); out.println("Cliente " + cliente.getNome() + " deletado com sucesso</br>"); out.println("<br><br><a href='../pagesJsp2_Col/index.jsp'>Voltar para CRUD Hibernate + JSP + Servlet 'coletiva'</a>"); out.println("</body>"); out.println("</html>"); } else{ //Exibe mensagem de erro. out.println("<html>"); out.println("<body>"); out.println("Erro ao deletar cliente!</br>"); out.println("Tente novamente"); out.println("</body>"); out.println("</html>"); } }// Fim Excluir } catch (Exception e) { out.print("Erro" + e.getMessage()); } }
8
@Override public boolean addAll( Collection<? extends E> collection ) { boolean changed = false; for (E element : collection) { changed |= add( element ); } return changed; }
2
public static JSONValue parse(TokenReader tokens, String token) throws IOException, ParseException { JSONObject result = new JSONObject(); if ((token = tokens.next()).equals("}")) { return result; } do { String key = JSONString.parse(tokens, token).toString(); tokens.parseAssert((token = tokens.next()).equals(":"), "Separating ':' expected!"); result.put(key, JSONValue.parse(tokens, tokens.next())); if (!(token = tokens.next()).equals(",")) { break; } token = tokens.next(); } while (true); tokens.parseAssert(token.equals("}"), "Closing '}' expected!"); return result; }
3
public int compareTo(HandRank handRank) { int compare = getRank().compareTo(handRank.getRank()); if (compare != 0) { return compare; } Cards myHand = getHand(); Cards theirHand = handRank.getHand(); for (int i = 0; i < HAND_SIZE; i++) { if (myHand.size() > i) { Card card1 = myHand.get(i); Card card2 = theirHand.get(i); compare = card1.compareTo(card2); if (compare != 0) return compare; } } return 0; }
4
public void serializeFile(String filename) { try { FileOutputStream file = new FileOutputStream(filename); ObjectOutputStream o = new ObjectOutputStream(file); o.writeObject(this); o.close(); } catch (IOException e) { System.err.println(e); } }
1
public String getEmailPer() { return emailPer; }
0
private static void sortSameSuitCards(CardArray cards, CardArray suitCards) { int[] cardsNums = new int[suitCards.size()]; int y = 0; // index for (Card i : suitCards) { cardsNums[y] = i.num(); y++; } Arrays.sort(cardsNums); for (int n : cardsNums) { for (Card i : suitCards) { if (i.num() == n) cards.add(i); } } }
4
public boolean equals(Object o) { if (!(o instanceof FilterChain)) { return false; } FilterChain otherChain = (FilterChain) o; int size = filters.size(); if (size != otherChain.getFilters().size()) { return false; } for (int i = 0; i < size; ++i) { if (!(filters.elementAt(i).equals( otherChain.getFilters().elementAt(i)))) { return false; } } return true; }
4
public void setBrakes(int brakes) { this.brakes = brakes; }
0
private void IDLE(Vector3f direction, float distance) { Vector2f lineStart = new Vector2f(transform.getTranslation().getX(), transform.getTranslation().getZ()); Vector2f castDirection = new Vector2f(direction.getX(),direction.getZ()); Vector2f lineEnd = lineStart.add(castDirection.mul(1000.0f)); Vector2f colVector = Game.getLevel().checkIntersection(lineStart, lineEnd, false); Vector2f playerIntersectVector = Game.getLevel().lineInterSectRect(lineStart,lineEnd, new Vector2f(Transform.getCamera().getPos().getX(), Transform.getCamera().getPos().getZ()), new Vector2f(Player.PLAYER_SIZE, Player.PLAYER_SIZE)); if(playerIntersectVector != null && (colVector == null || playerIntersectVector.sub(lineStart).length() < colVector.sub(lineStart).length())) { state = STATE_CHASE; } }
3
public boolean isAValidDirectory() { try { return args[0] != null; } catch (ArrayIndexOutOfBoundsException e) { return false; } }
1
private void setState(ModelStates state) { Point windowPoint = currentWindow == null ? new Point(50, 50) : currentWindow.getLocation(); switch (state) { case loginsingup: currentWindow = loginsingup; loginsingup.setLocation(windowPoint);// set window is a custom // location endgamewindow.setVisible(false); gameboard.setVisible(false); lobby.setVisible(false); newgame.setVisible(false); break; case lobby: currentWindow = lobby; lobby.setLocation(windowPoint); // set window in a custom // location endgamewindow.setVisible(false); gameboard.setVisible(false); loginsingup.setVisible(false); newgame.setVisible(false); break; case newgame: currentWindow = newgame; newgame.setLocation(windowPoint); // set window in a custom // location endgamewindow.setVisible(false); gameboard.setVisible(false); loginsingup.setVisible(false); lobby.setVisible(false); break; case gameboard: currentWindow = gameboard; gameboard.setLocation(windowPoint); endgamewindow.setVisible(false); lobby.setVisible(false); loginsingup.setVisible(false); newgame.setVisible(false); break; case endgame: currentWindow = endgamewindow; endgamewindow.setLocation(windowPoint); lobby.setVisible(false); gameboard.setVisible(false); loginsingup.setVisible(false); newgame.setVisible(false); break; default: break; } // set the state of the machine this.state = state; currentWindow.setVisible(true); }
6
public Enemy setEnemy(int layerPosition,int x, int y, int damage, int health, int gravity, String name[], boolean canColide){ String namePath[] = new String[name.length]; for (int i =0; i< name.length; i++){ namePath[i] = "res/images/" + name[i]; } if(name[0].compareTo("Jumper_0.png")==0){ listOfEnemies[layerPosition] = new Jumper(x, y, damage, health, gravity, namePath, canColide); } else if(name[0].compareTo("Bumbler_0.png")==0){ listOfEnemies[layerPosition] = new Bumbler(x, y, damage, health, gravity, namePath, canColide); } else if(name[0].compareTo("Floater_0.png")==0){ listOfEnemies[layerPosition] = new Floater(x, y, damage, health, gravity, namePath, canColide); } else if(name[0].compareTo("Patrol_0.png")==0){ listOfEnemies[layerPosition] = new Patrol(x, y, damage, health, gravity, namePath, canColide); } else listOfEnemies[layerPosition] = new Jumper(x, y, damage, health, gravity, namePath, canColide); return listOfEnemies[layerPosition]; }
5
private static ArrayList<String> getDataFromMap(String key) { if (null == key || "N".equalsIgnoreCase(key) || "".equals(key)) return null; String[] temp = key.split("、"); ArrayList<String> resultList = new ArrayList<String>(); if(temp.length > 1){ for(String t : temp){ resultList.addAll(getData(t)); } }else{ resultList.addAll(getData(key)); } return resultList; }
5
private boolean checkFeetCollision(Cell[][] tiles){ int feetX = feetBox.getX()/Cell.CELL_WIDTH; for(int i = 0; i < tiles.length; i++){ if(tiles[i][feetX] != null && feetBox.checkCollision(tiles[i][feetX].getHitbox())){ return true; } } return false; }
3
@Override public boolean onCommand(CommandSender sender, Command command, String sabel, String[] args) { if (Utils.commandCheck(sender, command, "maleficus")) { Player player = (Player) sender; if (args.length == 0) { player.sendMessage(Utils.center("--- §6[§fMaleficus§6]§f ---")); player.sendMessage(" §6[§fVersion§6] §f" + Maleficus.getInstance().getDescription().getVersion()); player.sendMessage(" §6[§fAuthor§6] §fSkepter"); player.sendMessage(""); player.sendMessage(Utils.center("--- §6[§fCommands§6]§f ---")); player.sendMessage(" §6/maleficus §f- "); player.sendMessage(" §6/power §f- "); player.sendMessage(" §6/anima §f- Displays how much Anima and SubAnima you have"); player.sendMessage(" §6/level §f- Displays what level you are at"); }else if(args[0].equalsIgnoreCase("stats")) { player.sendMessage("Anima: " + MPlayer.getAnima(player)); player.sendMessage("SubAnima: " + MPlayer.getSubAnima(player)); player.sendMessage("Level: " + MPlayer.getLevel(player)); player.sendMessage("SubLevel: " + MPlayer.getSubLevel(player)); player.sendMessage("Element: " + MPlayer.getElement(player).toString()); player.sendMessage("Config: " + MPlayer.getPlayer(player).getKeys(false)); } else if(args[0].equalsIgnoreCase("admin")) { if(args[1].equalsIgnoreCase("setanima")) { MPlayer.setAnima(player, Integer.parseInt(args[2])); } else if(args[1].equalsIgnoreCase("setlevel")) { MPlayer.setLevel(player, Integer.parseInt(args[2])); } else if(args[1].equalsIgnoreCase("setsublevel")) { MPlayer.setSubLevel(player, Integer.parseInt(args[2])); } else if(args[1].equalsIgnoreCase("setsubanima")) { MPlayer.setSubAnima(player, Integer.parseInt(args[2])); } } return true; } return false; }
8
private void addToCounts(Instance instance) { double [] countsPointer; if(instance.classIsMissing()) return; // ignore instances with missing class int classVal = (int)instance.classValue(); double weight = instance.weight(); m_ClassCounts[classVal] += weight; m_SumInstances += weight; // store instance's att val indexes in an array, b/c accessing it // in loop(s) is more efficient int [] attIndex = new int[m_NumAttributes]; for(int i = 0; i < m_NumAttributes; i++) { if(i == m_ClassIndex) attIndex[i] = -1; // we don't use the class attribute in counts else { if(instance.isMissing(i)) attIndex[i] = m_StartAttIndex[i] + m_NumAttValues[i]; else attIndex[i] = m_StartAttIndex[i] + (int)instance.value(i); } } for(int Att1 = 0; Att1 < m_NumAttributes; Att1++) { if(attIndex[Att1] == -1) continue; // avoid pointless looping as Att1 is currently the class attribute m_Frequencies[attIndex[Att1]] += weight; // if this is a missing value, we don't want to increase sumforcounts if(!instance.isMissing(Att1)) m_SumForCounts[classVal][Att1] += weight; // save time by referencing this now, rather than do it repeatedly in the loop countsPointer = m_CondiCounts[classVal][attIndex[Att1]]; for(int Att2 = 0; Att2 < m_NumAttributes; Att2++) { if(attIndex[Att2] != -1) { countsPointer[attIndex[Att2]] += weight; } } } }
9
public Map<Player, Player> Command_refuse(Map<Player, Player> Map) { tpMap = Map; StringBuilder message = new StringBuilder(); for(int i = 0; i < args.length ; i++) { message.append(args[i]); message.append(" "); } for(Entry<Player, Player> entry : tpMap.entrySet()) { Player key = entry.getKey(); Player value = entry.getValue(); if(key == player) { value.sendMessage(ChatColor.RED + key.getName() + " a refusé votre invitation."); if(args.length > 0) { value.sendMessage(ChatColor.RED + "[Justification :] " + ChatColor.WHITE + message.toString()); } else { value.sendMessage(ChatColor.RED + "[Justification :] Aucune"); } tpMap.remove(key); return tpMap; } else if(value == player) { key.sendMessage(ChatColor.RED + value.getName() + " a refusé votre invition."); if(args.length > 0) { key.sendMessage(ChatColor.RED + "[Justification :] " + ChatColor.WHITE + message.toString()); } else { key.sendMessage(ChatColor.RED + "[Justification :] Aucune"); } tpMap.remove(key); return tpMap; } } player.sendMessage(ChatColor.RED + "Personne ne vous a demandé une téléportation"); return tpMap; }
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof XPosition)) return false; XPosition other = (XPosition) obj; if (column != other.column) return false; if (line != other.line) return false; if (pos != other.pos) return false; if (source == null) { if (other.source != null) return false; } else if (!source.equals(other.source)) return false; return true; }
8
public boolean comprobarAdmin(String nick, String password){ beansAdministrador admin = buscarAdmin(nick); if(admin != null){ if(admin.getPassword().equals(password)){ setAdmin(admin); return true; } } return false; }
2
public MealyMachine() { super(); }
0
public void saveGameInformation(Game currentGame) { PrintWriter gameWriter; String saveFile = "saveFile.txt"; try { gameWriter = new PrintWriter(saveFile); gameWriter.append(currentGame.getGameTitle() + "\r\n"); gameWriter.append(Integer.toString(currentGame.getFunRanking()) + "\r\n"); for (int count = 0; count < currentGame.getGameRules().size(); count++) { gameWriter.append(currentGame.getGameRules().get(count) + "\r\n"); } gameWriter.append(";" + "\r\n"); // Allows us to later split the game around // that character. gameWriter.close(); } catch (FileNotFoundException noFileExists) { JOptionPane.showMessageDialog(appFrame, "Could not Create the save file."); JOptionPane.showMessageDialog(appFrame, noFileExists.getMessage()); } }
2
private double findSplitNumericNumeric(int index) throws Exception { double bestVal = Double.MAX_VALUE, currVal, currCutPoint; int numMissing = 0; double[] sumsSquares = new double[3], sumOfWeights = new double[3]; double[][] bestDist = new double[3][1]; double totalSum = 0, totalSumOfWeights = 0; // Compute counts for all the values for (int i = 0; i < m_Instances.numInstances(); i++) { Instance inst = m_Instances.instance(i); if (!inst.isMissing(index)) { m_Distribution[1][0] += inst.classValue() * inst.weight(); sumsSquares[1] += inst.classValue() * inst.classValue() * inst.weight(); sumOfWeights[1] += inst.weight(); } else { m_Distribution[2][0] += inst.classValue() * inst.weight(); sumsSquares[2] += inst.classValue() * inst.classValue() * inst.weight(); sumOfWeights[2] += inst.weight(); numMissing++; } totalSumOfWeights += inst.weight(); totalSum += inst.classValue() * inst.weight(); } // Check if the total weight is zero if (totalSumOfWeights <= 0) { return bestVal; } // Sort instances m_Instances.sort(index); // Make split counts for each possible split and evaluate for (int i = 0; i < m_Instances.numInstances() - (numMissing + 1); i++) { Instance inst = m_Instances.instance(i); Instance instPlusOne = m_Instances.instance(i + 1); m_Distribution[0][0] += inst.classValue() * inst.weight(); sumsSquares[0] += inst.classValue() * inst.classValue() * inst.weight(); sumOfWeights[0] += inst.weight(); m_Distribution[1][0] -= inst.classValue() * inst.weight(); sumsSquares[1] -= inst.classValue() * inst.classValue() * inst.weight(); sumOfWeights[1] -= inst.weight(); if (inst.value(index) < instPlusOne.value(index)) { currCutPoint = (inst.value(index) + instPlusOne.value(index)) / 2.0; currVal = variance(m_Distribution, sumsSquares, sumOfWeights); if (currVal < bestVal) { m_SplitPoint = currCutPoint; bestVal = currVal; for (int j = 0; j < 3; j++) { if (sumOfWeights[j] > 0) { bestDist[j][0] = m_Distribution[j][0] / sumOfWeights[j]; } else { bestDist[j][0] = totalSum / totalSumOfWeights; } } } } } m_Distribution = bestDist; return bestVal; }
8
@Override public void run() { //say our server is starting logger.debug("Server starting"); //set this in case it was set to false keepRunning = true; //set up some buffer for ourselves byte[] recvData = new byte[64]; logger.debug("About to enter server control loop"); //we have a socket, we should do something with the socket while ( keepRunning ) { try { recvData = new byte[64]; DatagramPacket recvPacket = new DatagramPacket(recvData, recvData.length); socket.receive(recvPacket); this.clientInetAddress = recvPacket.getAddress(); String sentence = new String( recvPacket.getData() ); sentence = sentence.trim(); //take off the padding crap from the byte array /** * take the inbound sentence, give it to a new request thread, and send it on its merry way * The request object if need be can send off a response to the client */ Request req = new Request(); req.setLogger(logger); req.handle(sentence, this); if ( req.hasResponse() ) { this.client.send(req.getResponse()); } } catch (Exception e) { e.printStackTrace(); //drop out of the while loop logger.debug("Leaving server loop unexpectedly"); break; } } logger.debug("Server will no longer be responsive to packets"); try { socket.close(); } catch (Exception e) { e.printStackTrace(); logger.debug("Problem stopping socket"); } }
4
public static CustomButton makeTextExplorerLauchButton( final String buttonTitle) { final CustomButton a = new CustomButton(buttonTitle); a.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if (!Database.loaded) return; JFrame jf = new JFrame(buttonTitle); jf.setSize(900, 500); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JTextArea wordStat = new JTextArea(); JScrollPane compareTickers = JComponentFactory .makeTextScroll(wordStat); jf.add(compareTickers); showFullSetWithDescriptions(); TreeMap<Integer, ArrayList<String>> orderResults = new TreeMap<Integer, ArrayList<String>>(); for (Entry<String, Integer> ent : Database.WORD_STATS .entrySet()) { String word = ent.getKey(); Integer count = ent.getValue(); if (orderResults.containsKey(count)) { orderResults.get(count).add(word); } else { ArrayList<String> startArray = new ArrayList<String>(); startArray.add(word); orderResults.put(count, startArray); } } for (Entry<Integer, ArrayList<String>> ent : orderResults .entrySet()) { wordStat.append("\n\n" + ent.getKey() + "\n" + ent.getValue()); } ArrayList<Float> avgs = new ArrayList<Float>(); ArrayList<Float> totals = new ArrayList<Float>(); for (String txt : Database.DESCRIPTIONS.values()) { txt = txt.replaceAll("_", " "); totals.add(calculateWordRankTotal(txt)); avgs.add(calculateWordRankAverage(txt)); } StatInfo totalStats = new StatInfo(totals); StatInfo avgsStats = new StatInfo(avgs); } private void showFullSetWithDescriptions() { JFrame jf = new JFrame(buttonTitle); jf.setSize(900, 500); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JTextArea descriptions = new JTextArea(); JScrollPane compareTickers = JComponentFactory .makeTextScroll(descriptions); jf.add(compareTickers); for (String ticker : Database.dbSet) { descriptions.append("\n" + ticker + " " + Database.DESCRIPTIONS.get(ticker)); } } private float calculateWordRankTotal(String text) { float rank = 0; String[] words = Database.simplifyText(text).split(" "); for (String word : words) { rank += 1.0 / Database.WORD_STATS.get(word); } return rank; } private float calculateWordRankAverage(String text) { float rank = 0; String[] words = Database.simplifyText(text).split(" "); for (String word : words) { rank += 1.0 / Database.WORD_STATS.get(word); } return rank / words.length; } } ); return a; }
8
@Override public void takeInfo(InfoPacket info) throws Exception { super.takeSuperInfo(info); Iterator<Pair<?>> i = info.namedValues.iterator(); Pair<?> pair = null; Label label = null; while(i.hasNext()){ pair = i.next(); label = pair.getLabel(); switch (label){ case RPMs: RPM = (Double) pair.second(); default: break; } } }
4
public void setImgPath_CommandBtnArrow(Path img, Imagetype type) { switch (type) { case KEYFOCUS: this.imgComArrow_KFoc = handleImage(img, UIResNumbers.COMBTNARROW_KFOC.getNum()); if (this.imgComArrow_KFoc == null) { this.imgComArrow_KFoc = UIDefaultImagePaths.COMBTNARROW_KFOC.getPath(); deleteImage(UIResNumbers.COMBTNARROW_KFOC.getNum()); } break; case MOUSEFOCUS: this.imgComArrow_MFoc = handleImage(img, UIResNumbers.COMBTNARROW_MFOC.getNum()); if (this.imgComArrow_MFoc == null) { this.imgComArrow_MFoc = UIDefaultImagePaths.COMBTNARROW_MFOC.getPath(); deleteImage(UIResNumbers.COMBTNARROW_MFOC.getNum()); } break; case PRESSED: this.imgComArrow_Pre = handleImage(img, UIResNumbers.COMBTNARROW_PRE.getNum()); if (this.imgComArrow_Pre == null) { this.imgComArrow_Pre = UIDefaultImagePaths.COMBTNARROW_PRE.getPath(); deleteImage(UIResNumbers.COMBTNARROW_PRE.getNum()); } break; case DEFAULT: this.imgComArrow_Def = handleImage(img, UIResNumbers.COMBTNARROW_DEF.getNum()); if (this.imgComArrow_Def == null) { this.imgComArrow_Def = UIDefaultImagePaths.COMBTNARROW_DEF.getPath(); deleteImage(UIResNumbers.COMBTNARROW_DEF.getNum()); } break; default: throw new IllegalArgumentException(); } somethingChanged(); }
8
private void getLinkList() { try { List<Link> links; DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeBytes(ServerFrame.getLinkListCmd + "\n"); ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); links = (List<Link>) ois.readObject(); updateLinkListComboBox.removeAllItems(); dropLinkComboBox.removeAllItems(); if(!links.isEmpty()) { for(Link l : links) { LinkListViewHelper helper = new LinkListViewHelper(l); updateLinkListComboBox.addItem(helper); dropLinkComboBox.addItem(helper); } } } catch(Exception e) { connect(); } }
3
private double calcOutput(int targetLayer,int position){ int[] relPos; int absPos = this.calcAbsolutePosition(targetLayer, position); double[] input = new double[addedNeurons]; double[] weights = new double[addedNeurons]; boolean inputNeuron=true; for(int row = 0; row < addedNeurons;row++){ if(weightMatrix[row][absPos] != 0){ inputNeuron = false; relPos = calcRelativePosition(row); weights[row] = weightMatrix[row][absPos]; input[row] = calcOutput(relPos[0],relPos[1]); }else{ weights[row] = 0; input[row] = 0; } } if (inputNeuron){ //Input Neurons don't have any edges connect to them and have an output preseted //that output is saved in lastOutput. return neuronLayer[targetLayer].get(position).getLastOutput(); }else{ //All the other Neurons calculate their output with the calcOutput function. return neuronLayer[targetLayer].get(position).calcOutput(input, weights); } }
3
void guess(String solution){ int count = 0; count++; int a = getA(solution, "1234"); int b = getB(solution, "1234"); if (a == 4) { } updateAnsSet("1234", a, b); String step = String.valueOf(count); outcome = ""; outcome = outcome + "Step" + step + ": " + "1234 " + a +"A" + b + "B\n"; for (int i = 0; i < checkSet.length; i++) { if (!checkSet[i]) { continue; } count++; a = getA(solution, answerSet[i]); b = getB(solution, answerSet[i]); step = String.valueOf(count); outcome = outcome + "Step" + step + ": " + answerSet[i] + " " + a +"A" + b + "B\n"; if (a == 4) { break; } updateAnsSet(answerSet[i], a, b); } }
4
public void llenarCombobox() { String to = System.getProperty("user.dir"); // recupero el directorio del proyecto String separator = System.getProperty("file.separator"); //recupero el separador ex: Windows= '\' , Linux='/' to = to + separator + "src" + separator + "src" + separator; // concateno la ruta destino File f = new File(to); this.txtfilename.removeAllItems(); if (f.exists()) { // Directorio existe File[] ficheros = f.listFiles(); for (int x = 0; x < ficheros.length; x++) { this.txtfilename.addItem(ficheros[x].getName()); } } else { //Directorio no existe } }
2
public void run() { while (canContinue()) { // System.out.println(word.getWord()); printHangman(); printLetters(); System.out.print("\n\nPlease guess a letter!:"); String guess = sc.next(); char guessChar = validate(guess); word.checkGuess(guessChar); } printHangman(); printLetters(); System.out.println(word.printWinOrLose()); }
1
public HostInfo getHostByName(String name) { return this.hosts.get(name); }
0
public void loot(Item item, Stage stage) { // Get slot of item to loot int slot = 0; if(item instanceof WeaponItem) slot = item.getWeaponSlot(); else if(item instanceof ArmorItem) slot = item.getArmorSlot(); // If player can equip, equip if(stage.player.getEquipment().canEquip(item, slot)) { stage.player.getEquipment().equip(item); // Remove item from source and rebuild loot table source.getContainer().removeItem(item); fillLootTable(); this.setSelected(this.getSelected()); checkRemove(stage); } else if(stage.player.getEquipment().canHold()) { if(hold == null) { hold = (HoldBox) stage.player.getEquipment().holdItemPrompt(item, stage); hold.setSource(stage.player); stage.script.addText(hold); } else { stage.player.getEquipment().holdItem(item); // Remove item from source and rebuild loot table source.getContainer().removeItem(item); fillLootTable(); this.setSelected(this.getSelected()); checkRemove(stage); } } else { Textbox text = new PlainText(false, 2.0f, false); text.buildText("You have no room for that!"); text.setSource(stage.player); stage.script.addText(text); } }
5
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TracksHaveHashtags that = (TracksHaveHashtags) o; if (hashtagId != that.hashtagId) return false; if (trackId != that.trackId) return false; return true; }
5
@Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o == null ) { return false; } if ( !(o instanceof Degree) ) { return false; } final Degree other = (Degree) o; return type.equals( other.getType() ); }
3
public void removeMeanFriends() { // YOUR CODE HERE // Remove all the friends who don't have you as a friend. // You may want to use the find method. ArrayList<Person> meanFriends = new ArrayList<Person>(); for (Person each : friends) { if (each.find(this) == -1) { meanFriends.add(each); } } for (Person each : meanFriends) { friends.remove(this.find(each)); } }
3
private Map<String, BoundField> getBoundFields(Gson context, TypeToken<?> type, Class<?> raw) { Map<String, BoundField> result = new LinkedHashMap<String, BoundField>(); if (raw.isInterface()) { return result; } Type declaredType = type.getType(); while (raw != Object.class) { Field[] fields = raw.getDeclaredFields(); for (Field field : fields) { boolean serialize = excludeField(field, true); boolean deserialize = excludeField(field, false); if (!serialize && !deserialize) { continue; } field.setAccessible(true); Type fieldType = $Gson$Types.resolve(type.getType(), raw, field.getGenericType()); BoundField boundField = createBoundField(context, field, getFieldName(field), TypeToken.get(fieldType), serialize, deserialize); BoundField previous = result.put(boundField.name, boundField); if (previous != null) { throw new IllegalArgumentException(declaredType + " declares multiple JSON fields named " + previous.name); } } type = TypeToken.get($Gson$Types.resolve(type.getType(), raw, raw.getGenericSuperclass())); raw = type.getRawType(); } return result; }
8
public Void visitUnit(UnitTree tree) { String name = options.getOutputName(); if (name == null) { name = tree.getSource(); int dot = name.lastIndexOf('.'); if (dot > 0) name = name.substring(0, dot); } File file = new File(options.getOutputDir(), name+".java"); try { output = new PrintStream(file); } catch (IOException ioe) { //cry like a baby } if (options.needDebugInfo()) { output.println("/* Generated from \""+tree.getSource()+"\" */"); } output.println(); output.println("import java.io.IOException;"); output.println(); output.println("public class "+name+" {"); output.println("\tpublic static void main(String[] args) throws IOException {"); output.println("\t\tfinal int ARRAY_SIZE = "+options.getRange()+";"); output.println("\t\tbyte[] array = new byte[ARRAY_SIZE];"); output.println("\t\tint position = 0;"); output.println("\t\tint ch;"); for (Tree t : tree.getChildren()) { t.accept(this, 2); } output.println("\t\tSystem.out.flush();"); output.println("\t}"); output.println("}"); output.flush(); output.close(); System.err.println("File "+name+".java written"); return null; }
5
public String authenticate(String userName, String password) throws ConnectException, InvalidLoginException { Connection con = ConnectionService.getConnection(); try { String query = "select * from Login where username=?"; PreparedStatement preparestatement = con.prepareStatement(query); preparestatement.setString(1, userName); ResultSet rs = preparestatement.executeQuery(); if (null != rs) { rs.next(); if (rs.getString(2).equals(password)) return rs.getString(3); else throw new InvalidLoginException("Invalid password"); } } catch (SQLException e) { throw new ConnectException(e.getMessage()); } finally { if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } return "failure"; }
5
public void updateReactToPyroState(double s_elapsed) { can_growl = true; if (!target_unit.isInMap()) { initState(RobotPilotState.INACTIVE); can_growl = true; } else if (target_object_room.equals(current_room)) { if (!target_unit.getRoom().equals(target_object_room)) { initState(RobotPilotState.INACTIVE); } else if (target_unit.isCloaked()) { initState(RobotPilotState.REACT_TO_CLOAKED_PYRO); } } else { if (!target_unit.getRoom().equals(target_object_room) || !MapUtils.canSeeObjectInNeighborRoom(bound_object, target_unit, target_object_room_info.getKey())) { initState(RobotPilotState.INACTIVE); } else if (target_unit.isCloaked()) { initState(RobotPilotState.REACT_TO_CLOAKED_PYRO); } } }
7
@Override void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild) { // Replace child if(this._caso_ == oldChild) { setCaso((TCaso) newChild); return; } if(this._valor_ == oldChild) { setValor((PValor) newChild); return; } for(ListIterator<PComando> i = this._comando_.listIterator(); i.hasNext();) { if(i.next() == oldChild) { if(newChild != null) { i.set((PComando) newChild); newChild.parent(this); oldChild.parent(null); return; } i.remove(); oldChild.parent(null); return; } } throw new RuntimeException("Not a child."); }
5
public void divideNo(No x, int i, No y) { int t = (int) Math.floor((ordem - 1) / 2); //cria nó z No z = new No(ordem); z.setFolha(y.isFolha()); z.setN(t); //passa as t ultimas chaves de y para z for (int j = 0; j < t; j++) { if ((ordem - 1) % 2 == 0) { z.getChave().set(j, y.getChave().get(j + t)); } else { z.getChave().set(j, y.getChave().get(j + t + 1)); } y.setN(y.getN() - 1); } //se y nao for folha, pasa os t+1 últimos flhos de y para z if (!y.isFolha()) { for (int j = 0; j < t + 1; j++) { if ((ordem - 1) % 2 == 0) { z.getFilho().set(j, y.getFilho().get(j + t)); } else { z.getFilho().set(j, y.getFilho().get(j + t + 1)); } } } y.setN(t);//seta a nova quantidade de chaves de y //descola os filhos de x uma posição para a direita for (int j = x.getN(); j > i; j--) { x.getFilho().set(j + 1, x.getFilho().get(j)); } x.getFilho().set(i + 1, z);//seta z como filho de x na posição i+1 //desloca as chaves de x uma posição para a direita, para podermos subir uma chave de y for (int j = x.getN(); j > i; j--) { x.getChave().set(j, x.getChave().get(j - 1)); } //"sobe" uma chave de y para z if ((ordem - 1) % 2 == 0) { x.getChave().set(i, y.getChave().get(t - 1)); y.setN(y.getN() - 1); } else { x.getChave().set(i, y.getChave().get(t)); } //incrementa o numero de chaves de x x.setN(x.getN() + 1); }
8
public Move findbest(Game g) throws GameException { try { boolean max; int bestVal; // if first player, then find the max value // otherwise find the min value if (g.whoseTurn() == Game.FIRST_PLAYER) { max = true; bestVal = Integer.MIN_VALUE; // running max, starts at bottom } else { max = false; bestVal = Integer.MAX_VALUE; } Move bestMove = null; Iterator<Move> moves = g.getMoves(); while (moves.hasNext()) { int value; Move m = moves.next(); Game cp = g.copy(); cp.make(m); value = getValue(cp); System.out.println("val = " + value); if ((max && value >= bestVal) || (!max && value <= bestVal)) { bestVal = value; bestMove = m; } } return bestMove; } catch (Exception e) { throw new GameException(e.getMessage()); } }
7
private void initializeLogger() { this.log = Logger.getLogger(this.getClass().getName()); try { FileHandler fh = new FileHandler(this.getClass().getName() .replace("class ", "") + ".log"); fh.setFormatter(new SimpleFormatter()); this.log.addHandler(fh); } catch (SecurityException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if (this.verbose == 0) this.log.setUseParentHandlers(false); else this.log.setUseParentHandlers(true); this.log.setLevel(Level.ALL); }
3
public State stateCreate(Point point) { if (currentStep != CREATE_SINGLE_FINAL) { outOfOrder(); return null; } State[] finals = automaton.getFinalStates(); drawer.clearSelected(); for (int i = 0; i < finals.length; i++) { automaton.removeFinalState(finals[i]); drawer.addSelected(finals[i]); } State newState = automaton.createState(point); automaton.addFinalState(newState); frame.repaint(); nextStep(); return newState; }
2
protected void update() { //Arc lenght angle double arcAngleLengthInRadians = Math.toRadians(getLength()); //Angle rotation of the item double startAngleInRadians = Math.toRadians(getStartAngle() + ANGLE_TO_START_AT_ZERO_DEGREE); moveTo.setX(getInnerRadius() * Math.cos(startAngleInRadians)); moveTo.setY(getInnerRadius() * Math.sin(startAngleInRadians)); lineTo.setX(getOuterRadius() * Math.cos(startAngleInRadians)); lineTo.setY(getOuterRadius() * Math.sin(startAngleInRadians)); arcTo.setX(getOuterRadius() * Math.cos(startAngleInRadians+arcAngleLengthInRadians - Math.asin(getGap() / getOuterRadius()))); arcTo.setY(getOuterRadius() * Math.sin(startAngleInRadians+arcAngleLengthInRadians - Math.asin(getGap() / getOuterRadius()))); arcTo.setRadiusX(getOuterRadius()); arcTo.setRadiusY(getOuterRadius()); arcTo.setSweepFlag(true); arcTo.setLargeArcFlag(getLength() > 180); lineTo2.setX(getInnerRadius() * Math.cos(startAngleInRadians+arcAngleLengthInRadians - Math.asin(getGap() / getInnerRadius()))); lineTo2.setY(getInnerRadius() * Math.sin(startAngleInRadians+arcAngleLengthInRadians - Math.asin(getGap() / getInnerRadius()))); arcToInner.setX(getInnerRadius() * Math.cos(startAngleInRadians)); arcToInner.setY(getInnerRadius() * Math.sin(startAngleInRadians)); arcToInner.setRadiusX(getInnerRadius()); arcToInner.setRadiusY(getInnerRadius()); arcToInner.setSweepFlag(false); arcToInner.setLargeArcFlag(getLength() > 180); double centerRadius = (getOuterRadius() + getInnerRadius()) / 2; Point2D centerOfPath = new Point2D(centerRadius*Math.cos(startAngleInRadians + arcAngleLengthInRadians/2), centerRadius*Math.sin(startAngleInRadians + arcAngleLengthInRadians/2)); if(this.getImage() != null) { double width = this.getImage().getBoundsInLocal().getWidth(); double height =this.getImage().getBoundsInLocal().getHeight(); this.getImage().relocate(centerOfPath.getX() - width/2, centerOfPath.getY()-height/2); } if(this.getText() != null && !this.getText().isEmpty()) { double width = this.textShape.getBoundsInLocal().getWidth(); double height =this.textShape.getBoundsInLocal().getHeight(); this.textShape.relocate(centerOfPath.getX() - width / 2, centerOfPath.getY() - height / 2); double rotationAngle = getStartAngle() + ((getOuterRadius() - getInnerRadius()) / 2); if(getStartAngle() > 75 && getStartAngle() < 270) { rotationAngle += 180; } this.textShape.setRotate(rotationAngle); } }
5
public String resolveFilename(String filename) { if (filename.startsWith("/") || filename.startsWith("\\")) filename = filename.substring(1); if (!usingMod) { return mainDirName + filename; } String[] splitPath = splitParent(filename); if (modFile) { // EU3-style mod if (replaced.contains(splitPath[0])) { // Case 1: Directory is replaced. // Return the file in the moddir, even if it doesn't exist. return modDirName + filename; } else if (extended.contains(splitPath[0])) { // Case 2: Directory is extended. // Check if the file exists in the moddir. if (new File(modDirName + filename).exists()) { // It does, so return it. return modDirName + filename; } else { // It doesn't, so return the file in the main dir. return mainDirName + filename; } } else { // Case 3: Directory is not modded. // Return the file in the main dir. return mainDirName + filename; } } else { // EU2-style mod if (new File(modDirName + filename).exists()) return modDirName + filename; else return mainDirName + filename; } }
8
private void antialias(int ch, int gr) { int sb18, ss, sb18lim; gr_info_s gr_info = (si.ch[ch].gr[gr]); // 31 alias-reduction operations between each pair of sub-bands // with 8 butterflies between each pair if ((gr_info.window_switching_flag !=0) && (gr_info.block_type == 2) && !(gr_info.mixed_block_flag != 0) ) return; if ((gr_info.window_switching_flag !=0) && (gr_info.mixed_block_flag != 0)&& (gr_info.block_type == 2)) { sb18lim = 18; } else { sb18lim = 558; } for (sb18=0; sb18 < sb18lim; sb18+=18) { for (ss=0;ss<8;ss++) { int src_idx1 = sb18 + 17 - ss; int src_idx2 = sb18 + 18 + ss; float bu = out_1d[src_idx1]; float bd = out_1d[src_idx2]; out_1d[src_idx1] = (bu * cs[ss]) - (bd * ca[ss]); out_1d[src_idx2] = (bd * cs[ss]) + (bu * ca[ss]); } } }
8
public boolean finish() { if (!started) return false; boolean ok = true; started = false; try { out.write(0x3b); // gif trailer out.flush(); if (closeStream) { out.close(); } } catch (IOException e) { ok = false; } // reset for subsequent use transIndex = 0; out = null; image = null; pixels = null; indexedPixels = null; colorTab = null; closeStream = false; firstFrame = true; return ok; }
3
public List<Stock> getStocks(List<String> symbols) throws SymbolNotFoundInNasdaq { // save data to tmp list, after update done, point with service list to // tmp... List<Stock> ret = new LinkedList<Stock>(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < symbols.size(); i++) { // if(i > 100) break; sb.append(ESCAPING); sb.append(symbols.get(i)); sb.append(ESCAPING); sb.append(","); // on batch size limit - send an HTTP request to fetch next symbols // batch. if (i != 0 && i % STOCK_UPDATE_BATCH_SIZE == 0) { try { ret.addAll(doCall(sb)); } finally { // reset string builder. sb = new StringBuilder(); } } } // deal with last batch if (sb.length() > 0) ret.addAll(doCall(sb)); return ret; }
4
public void createTables() throws Exception { if (!MineAuction.enabled) return; Connection c = null; Statement s = null; c = MineAuction.db.openConnection(); s = c.createStatement(); if (plugin.getResource("create.sql") == null) { if (MineAuction.enabled) { Log.error("Unable to find create.sql, disabling plugin"); MineAuction.plugin.onDisable(); return; } } String[] queries = CharStreams.toString( new InputStreamReader(plugin.getResource("create.sql"))).split( ";"); for (String query : queries) { if (query != null && query != "") s.execute(query); } }
6
private void createGUI() { JPanel mainPanel = new JPanel(new BorderLayout()); JPanel topPanel = new JPanel(new MigLayout("fill")); // Панель быстрого поиска JPanel searchPanel = new JPanel(new MigLayout("fill")); searchPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Быстрый поиск")); final JTextField receptionCodeSearchTextField = new JTextField(10); receptionCodeSearchTextField.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String filterString = receptionCodeSearchTextField.getText(); controller.searchByReceptionCode(filterString); receptionCodeSearchTextField.requestFocus(); } }); JButton applyReceptionCodeSearchButton = new JButton(); applyReceptionCodeSearchButton.setIcon(ResourcesUtil.getIcon("accept.png")); applyReceptionCodeSearchButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String filterString = receptionCodeSearchTextField.getText(); controller.searchByReceptionCode(filterString); receptionCodeSearchTextField.requestFocus(); } }); JButton resetReceptionCodeSearchButton = new JButton(); resetReceptionCodeSearchButton.setIcon(ResourcesUtil.getIcon("delete.png")); resetReceptionCodeSearchButton.setToolTipText("Очистить"); resetReceptionCodeSearchButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { receptionCodeSearchTextField.setText(""); controller.searchByReceptionCode(""); } }); // final JTextField rosreestrCodeSearchTextField = new JTextField(10); // rosreestrCodeSearchTextField.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // String filterString = rosreestrCodeSearchTextField.getText(); // controller.searchByRosreestrCode(filterString); // rosreestrCodeSearchTextField.requestFocus(); // } // }); // JButton applyRosreestrCodeSearchButton = new JButton(); // applyRosreestrCodeSearchButton.setIcon(ResourcesUtil.getIcon("accept.png")); // applyRosreestrCodeSearchButton.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // String filterString = rosreestrCodeSearchTextField.getText(); // controller.searchByRosreestrCode(filterString); // rosreestrCodeSearchTextField.requestFocus(); // } // }); // JButton resetRosreestrCodeSearchButton = new JButton(); // resetRosreestrCodeSearchButton.setIcon(ResourcesUtil.getIcon("delete.png")); // resetRosreestrCodeSearchButton.setToolTipText("Очистить"); // resetRosreestrCodeSearchButton.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // rosreestrCodeSearchTextField.setText(""); // controller.searchByRosreestrCode(""); // } // }); searchPanel.add(new JLabel("Код дела")); searchPanel.add(receptionCodeSearchTextField); searchPanel.add(applyReceptionCodeSearchButton); searchPanel.add(resetReceptionCodeSearchButton, "wrap"); // searchPanel.add(new JLabel("Код Росреестра")); // searchPanel.add(rosreestrCodeSearchTextField); // searchPanel.add(applyRosreestrCodeSearchButton); // searchPanel.add(resetRosreestrCodeSearchButton, "wrap"); JPanel filterPanel = new JPanel(new MigLayout("fill")); filterPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Фильтр")); // делаем лист для отображения и измененения набора фильтров filterListModel = new FilterListModel(); final JList filterList = new JList(filterListModel); filterList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); filterList.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent lse) { if(lse.getValueIsAdjusting() == false) { selectedFilterIndex = filterList.getSelectedIndex(); if (DEBUG) System.out.println("selected filter item: " + selectedFilterIndex); if (selectedFilterIndex != -1) { selectedFilter = controller.getFilters().get(selectedFilterIndex); } else { selectedFilter = null; } } } }); filterList.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); if (e.getClickCount()==2) { controller.editFilter(selectedFilterIndex); } } }); JScrollPane filterListScrollPane = new JScrollPane(filterList); ////// кнопки управления набором фильтров final JPopupMenu filtersPopupMenu = new JPopupMenu(); // кнопка добавления final JButton addFilterButton = new JButton(); addFilterButton.setIcon(ResourcesUtil.getIcon("add.png")); addFilterButton.setToolTipText("Добавить"); addFilterButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { filtersPopupMenu.show(addFilterButton, addFilterButton.getWidth(), 0); } }); // Пункт меню - добавление фильтра по дате открытия JMenuItem openDateFilterMenuItem = new JMenuItem("По дате открытия"); openDateFilterMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { controller.addFilter(ReceptionsFiltersEnum.OPEN_DATE); } }); // Пункт меню - добавление фильтра по коду филиала; JMenuItem filialFilterMenuItem = new JMenuItem("По коду филиала"); filialFilterMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { controller.addFilter(ReceptionsFiltersEnum.FILIAL); } }); // Пункт меню - добавление фильтра по предварительной записи JMenuItem byRecordFilterMenuItem = new JMenuItem("По предв записи"); byRecordFilterMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { controller.addFilter(ReceptionsFiltersEnum.BY_RECORD); } }); // Пункт меню - добавление фильтра по состоянию JMenuItem statusFilterMenuItem = new JMenuItem("По состоянию"); statusFilterMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { controller.addFilter(ReceptionsFiltersEnum.STATUS); } }); // Пункт меню - добавление фильтра по услугам JMenuItem serviceFilterMenuItem = new JMenuItem("По услуге"); serviceFilterMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { controller.addFilter(ReceptionsFiltersEnum.SERVICE); } }); // Пункт меню - добавление фильтра по операторам JMenuItem operatorFilterMenuItem = new JMenuItem("По оператору"); operatorFilterMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { controller.addFilter(ReceptionsFiltersEnum.OPERATOR); } }); // Пункт меню - добавление фильтра по операторам JMenuItem flMenuItem = new JMenuItem("По физ лицу"); flMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { controller.addFilter(ReceptionsFiltersEnum.FL); } }); // Пункт меню - добавление фильтра по операторам JMenuItem ulMenuItem = new JMenuItem("По юр лицу"); ulMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { controller.addFilter(ReceptionsFiltersEnum.UL); } }); // Пункт меню - добавление фильтра по дате на выдачу результата JMenuItem toIssueDateFilterMenuItem = new JMenuItem("По дате на выдачу"); toIssueDateFilterMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { controller.addFilter(ReceptionsFiltersEnum.TO_ISSUE_DATE); } }); // Пункт меню - добавление фильтра по месту получения результата JMenuItem resultInMFCFilterMenuItem = new JMenuItem("По месту получения результата"); resultInMFCFilterMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { controller.addFilter(ReceptionsFiltersEnum.RESULT_IN_MFC); } }); // собираем всплывающее меню добавления фильтра filtersPopupMenu.add(openDateFilterMenuItem); filtersPopupMenu.add(filialFilterMenuItem); filtersPopupMenu.add(byRecordFilterMenuItem); filtersPopupMenu.add(statusFilterMenuItem); filtersPopupMenu.add(serviceFilterMenuItem); filtersPopupMenu.add(operatorFilterMenuItem); filtersPopupMenu.add(flMenuItem); filtersPopupMenu.add(ulMenuItem); filtersPopupMenu.add(toIssueDateFilterMenuItem); filtersPopupMenu.add(resultInMFCFilterMenuItem); // кнопка реадктирования JButton editFilterButton = new JButton(); editFilterButton.setIcon(ResourcesUtil.getIcon("pencil.png")); editFilterButton.setToolTipText("Изменить"); editFilterButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { controller.editFilter(selectedFilterIndex); } }); // кнопка удаления фильтра JButton removeFilterButton = new JButton(); removeFilterButton.setIcon(ResourcesUtil.getIcon("delete.png")); removeFilterButton.setToolTipText("Удалить"); removeFilterButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { controller.removeFilter(selectedFilterIndex); } }); // кнопка очистки фильтра JButton resetFiltersButton = new JButton("Очистить"); resetFiltersButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { controller.resetFilters(); receptionCodeSearchTextField.setText(""); // rosreestrCodeSearchTextField.setText(""); } }); /// Применить фильтры JButton applyFiltersButton = new JButton("Применить"); applyFiltersButton.setIcon(ResourcesUtil.getIcon("tick.png")); applyFiltersButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { controller.applyFilters(); reestrTableModel.fireTableDataChanged(); //setReestrTableColumnsWidth(); } }); /// Перечитать из БД и применить фильтры JButton readFromDBButton = new JButton("Перечитать"); readFromDBButton.setIcon(ResourcesUtil.getIcon("database_refresh.png")); readFromDBButton.setToolTipText("Перечитать из базы данных"); readFromDBButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { controller.readFromDBAndApplyFilters(); } }); JButton exportButton = new JButton("Выгрузить список"); exportButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { controller.createXLSFromReestrTable(); } }); // Собираем панель фильтра filterPanel.add(new JLabel("Фильтры: "), "wrap"); filterPanel.add(filterListScrollPane, "push, spany 2, w 500, h 80"); filterPanel.add(readFromDBButton, "wrap"); filterPanel.add(applyFiltersButton,"pushy, grow, wrap"); filterPanel.add(addFilterButton, "split"); filterPanel.add(editFilterButton); filterPanel.add(removeFilterButton); filterPanel.add(resetFiltersButton, "wrap"); filterPanel.add(exportButton,"span, right, wrap"); topPanel.add(searchPanel); topPanel.add(filterPanel); // Панель данных JPanel dataPanel = new JPanel(new MigLayout("fill, nogrid")); final JButton columnsButton = new JButton(); columnsButton.setIcon(ResourcesUtil.getIcon("wrench.png")); columnsButton.setToolTipText("Изменить набор отображаемых колонок"); columnsButton.setPreferredSize(new Dimension(16,16)); columnsButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { controller.openColumnsDialog(); reestrTableModel.fireTableStructureChanged(); } }); //////// Основная таблица для приемов reestrTableModel = new ReestrTableModel(); reestrTable = new JTable(reestrTableModel); //добавляем кнопку изменения столбцов reestrTable.getTableHeader().setLayout(new BorderLayout()); reestrTable.getTableHeader().add(columnsButton, BorderLayout.EAST); reestrTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent lse) { if (reestrTable.getSelectedRows().length==0) { openReceptionAction.setEnabled(false); changeReceptionsStatusAction.setEnabled(false); removeReceptionsAction.setEnabled(false); } else if (reestrTable.getSelectedRows().length==1) { openReceptionAction.setEnabled(true); changeReceptionsStatusAction.setEnabled(true); removeReceptionsAction.setEnabled(true); removeReceptionsAction.putValue(Action.NAME, "Удалить запрос"); } else { openReceptionAction.setEnabled(false); changeReceptionsStatusAction.setEnabled(true); removeReceptionsAction.setEnabled(true); removeReceptionsAction.putValue(Action.NAME, "Удалить запросы"); } } }); /// добавление реакции на двойной клик - открытие приема на просмотр reestrTable.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent ev) { if (ev.getClickCount() == 2) { int selectedReceptionIndex = reestrTable.getSelectedRow(); controller.openReceptionDialog(selectedReceptionIndex); reestrTableModel.fireTableDataChanged(); } } }); JScrollPane reestrTableScrollPane = new JScrollPane(reestrTable); ///////////// всплывающее меню для таблицы JPopupMenu reestrPopupMenu = new JPopupMenu(); openReceptionAction = new OpenReceptionAction(); openReceptionAction.setEnabled(false); JMenuItem openReceptionMenuItem = new JMenuItem(openReceptionAction); changeReceptionsStatusAction = new ChangeReceptionsStatusAction(); changeReceptionsStatusAction.setEnabled(false); JMenu setReceptionStatusMenu = new JMenu(changeReceptionsStatusAction); List<ReceptionStatus> statuses = ReceptionStatusesModel.getInstance().getReceptionStatuses(); for (ReceptionStatus status: statuses) { ChangeReceptionsStatusAction action = new ChangeReceptionsStatusAction(status); JMenuItem statusMenuItem = new JMenuItem(action); setReceptionStatusMenu.add(statusMenuItem); } removeReceptionsAction = new RemoveReceptionsAction(); removeReceptionsAction.setEnabled(false); JMenuItem removeReceptionsMenuItem = new JMenuItem(removeReceptionsAction); reestrPopupMenu.add(openReceptionMenuItem); reestrPopupMenu.add(setReceptionStatusMenu); reestrPopupMenu.add(removeReceptionsMenuItem); reestrTable.setComponentPopupMenu(reestrPopupMenu); dataPanel.add(reestrTableScrollPane, "push, grow"); // Панель кнопок JPanel buttonPanel = new JPanel(); JButton okButton = new JButton("Ok"); this.getRootPane().setDefaultButton(okButton); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { setVisible(false); } }); buttonPanel.add(okButton); mainPanel.add(topPanel, BorderLayout.NORTH); mainPanel.add(dataPanel, BorderLayout.CENTER); mainPanel.add(buttonPanel, BorderLayout.SOUTH); this.setContentPane(mainPanel); this.pack(); this.setExtendedState(JFrame.MAXIMIZED_BOTH); }
8
public static void main(String[] args) { // int [] arr={2,7,13,19}; // System.out.println(new NthUglyNumber().nthSuperUglyNumber(12,arr)); String s="我钱懿斐"; System.out.println(s.length()); }
0
public Archive getSelectedArchive() { if (showOpenDialog(component) == 0) { File selectedFile = getSelectedFile(); if (selectedFile.getName().endsWith(".class")) return new ClassFile(selectedFile); else try { return new JavaArchive(new JarFile(selectedFile)); } catch (IOException e) { e.printStackTrace(); } } return null; }
3
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof TaxonObservationFilterElementType)) { return false; } TaxonObservationFilterElementType other = (TaxonObservationFilterElementType) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
5
public static void main(String[] args) { Reader in = new Reader(); Writer out = new Writer(); int n,m,k,v; while (true) { try { n = in.nextInt(); m = in.nextInt(); } catch (Exception e) { break; } ArrayList<Integer>[] data = new ArrayList[1000001]; for (int i = 0; i < data.length; i++) { data[i] = new ArrayList<Integer>(); } for (int i = 1; i <= n; i++) { data[in.nextInt()].add(i); } for (int i = 0; i < m; i++) { k = in.nextInt(); v = in.nextInt(); int r = k-1<data[v].size()?data[v].get(k-1):0; out.println(r); } }//End of While out.close(); }
6
public static void main(String[] args) { // TODO code application logic here // 2. Mira esta serie: 2, 2, 4, 12, 48, ... la semilla de esta serie fue el número 2 Mira esta serie:. 3, 3, 6, 18, 72, ... la semilla de esta serie fue el número 3. //Cree una función que recibe dos enteros: x, y y. Si alguno de ellos es 0 o negativo, o si son mayores que 255, la función debe devolver -1 //La función debe devolver el elemento y de las series generadas por x. //Por ejemplo, si la serie recibe x = 3, y = 4, es conveniente devolver 72, porque 72 es el cuarto elemento de la serie generado cuando x = 3. //La función recibirá 2 enteros, y devuelve un entero. int x,y,z; x=Integer.parseInt(JOptionPane.showInputDialog("Ingrese un valor entero en X")); y=Integer.parseInt(JOptionPane.showInputDialog("Ingrese un valor entero en Y")); if (x<=0 || x>255) { z=-1; JOptionPane.showMessageDialog(null,"Resultado es"+z); } else { int[] array=new int[y]; array[0]=x; for (int i = 1; i < array.length; i++) { x=x*(i+1); array[i]=x; System.out.println(i+" "+array[i]); } for (int i = 0; i < array.length; i++) { if(i==(y-1)) { z=array[i]; JOptionPane.showMessageDialog(null,"Resultado "+z); } } } }
5
public String toString() { StringBuilder out = new StringBuilder(); for (TraverseMode mode : TraverseMode.values()) { int mask = getMaskForMode(mode); if (mask != 0 && (modes & mask) == mask) { if (out.length() != 0) { out.append(","); } out.append(mode); } } return out.toString(); //return "TraverseMode (" + out + ")"; }
4
@Test public void testSerial() { System.out.println("ASD"); LineTextField f = new LineTextField(); f.setFieldName("HELLO"); f.setMaxChars(100); try { FileOutputStream fos = new FileOutputStream("testfile"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(f); oos.flush(); oos.close(); Field read; FileInputStream fis = new FileInputStream("testfile"); ObjectInputStream ois = new ObjectInputStream(fis); read = (LineTextField)ois.readObject(); ois.close(); if(read instanceof LineTextField) { System.out.println(f.getFieldName()); } } catch(Exception e) {} }
2
private void mongoCreator() throws UnknownHostException { DBHandler db = new DBHandler(); MongoHandler dbmon = new MongoHandler(); DB dbmongo = dbmon.connect(); dbmongo.dropDatabase(); db.openConnection(); Statement st; String cadena[]; String cadena2; try { st = db.getCon().createStatement(); //Colección por marca de cámara ResultSet rs = st.executeQuery("SELECT CATEGORIES.VALUE_NAME AS CAMERA_BRAND, IMAGES.IMG_PATH, IMAGES.IMG_NAME , IMAGES.EXTENSION FROM ASOCIATED, IMAGES, CATEGORIES WHERE ASOCIATED.ID_IMG = IMAGES.ID_IMG AND ASOCIATED.VALUE_NAME = CATEGORIES.VALUE_NAME AND CATEGORIES.CAT_NAME like 'Exif IFD0' and CATEGORIES.TAG_NAME like 'Make'"); JSONArray ja; ja = ResultSetConverter.convert(rs); DBObject dbObject; DBCollection collection = dbmongo.getCollection("CameraBrands"); cadena2 = (ja.toString().substring(1, ja.toString().length() - 1)); cadena2 = cadena2.replaceAll("},", "}<<->>"); cadena = cadena2.split("<<->>"); System.out.println(cadena2); for (String lenguaje : cadena) { dbObject = (DBObject) JSON.parse(lenguaje); collection.insert(dbObject); } st = db.getCon().createStatement(); //Coleccion modelo de cámara rs = st.executeQuery("SELECT CATEGORIES.VALUE_NAME AS CAMERA_MODEL, IMAGES.IMG_PATH, IMAGES.IMG_NAME , IMAGES.EXTENSION FROM ASOCIATED, IMAGES, CATEGORIES WHERE ASOCIATED.ID_IMG = IMAGES.ID_IMG AND ASOCIATED.VALUE_NAME = CATEGORIES.VALUE_NAME AND CATEGORIES.CAT_NAME like 'Exif IFD0' and CATEGORIES.TAG_NAME like 'Model'"); ja = ResultSetConverter.convert(rs); collection = dbmongo.getCollection("CameraModels"); cadena2 = (ja.toString().substring(1, ja.toString().length() - 1)); cadena2 = cadena2.replaceAll("},", "}<<->>"); cadena = cadena2.split("<<->>"); System.out.println(cadena2); for (String lenguaje : cadena) { dbObject = (DBObject) JSON.parse(lenguaje); collection.insert(dbObject); } //Coleccion por ISO rs = st.executeQuery("SELECT CATEGORIES.VALUE_NAME AS ISO_VALUE, IMAGES.IMG_PATH, IMAGES.IMG_NAME , IMAGES.EXTENSION FROM ASOCIATED, IMAGES, CATEGORIES WHERE ASOCIATED.ID_IMG = IMAGES.ID_IMG AND ASOCIATED.VALUE_NAME = CATEGORIES.VALUE_NAME AND CATEGORIES.CAT_NAME like 'Exif SubIFD' and CATEGORIES.TAG_NAME like 'ISO Speed Ratings'"); ja = ResultSetConverter.convert(rs); collection = dbmongo.getCollection("SearchByISO"); cadena2 = (ja.toString().substring(1, ja.toString().length() - 1)); cadena2 = cadena2.replaceAll("},", "}<<->>"); cadena2 = cadena2.replaceAll("(\"ISO_VALUE\"[:])(\")([0-9]+)(\")", "$1$3"); cadena = cadena2.split("<<->>"); System.out.println("DDD "+ cadena2); for (String lenguaje : cadena) { dbObject = (DBObject) JSON.parse(lenguaje); collection.insert(dbObject); } //Coleccion por Shutter Speed rs = st.executeQuery("SELECT CATEGORIES.VALUE_NAME AS SHUTTER_VALUE, IMAGES.IMG_PATH, IMAGES.IMG_NAME , IMAGES.EXTENSION FROM ASOCIATED, IMAGES, CATEGORIES WHERE ASOCIATED.ID_IMG = IMAGES.ID_IMG AND ASOCIATED.VALUE_NAME = CATEGORIES.VALUE_NAME AND CATEGORIES.CAT_NAME like 'Exif SubIFD' and CATEGORIES.TAG_NAME like 'Shutter Speed Value'"); ja = ResultSetConverter.convert(rs); collection = dbmongo.getCollection("Shutter_Speed"); cadena2 = (ja.toString().substring(1, ja.toString().length() - 1)); cadena2 = cadena2.replaceAll("},", "}<<->>"); cadena = cadena2.split("<<->>"); System.out.println(cadena2); for (String lenguaje : cadena) { dbObject = (DBObject) JSON.parse(lenguaje); collection.insert(dbObject); } //Coleccion por distintas posibles Shutter Speed rs = st.executeQuery("SELECT DISTINCT CATEGORIES.VALUE_NAME AS SHUTTERSPEED FROM ASOCIATED, IMAGES, CATEGORIES WHERE ASOCIATED.ID_IMG = IMAGES.ID_IMG AND ASOCIATED.VALUE_NAME = CATEGORIES.VALUE_NAME AND CATEGORIES.CAT_NAME like 'Exif SubIFD' and CATEGORIES.TAG_NAME like 'Shutter Speed Value'"); ja = ResultSetConverter.convert(rs); collection = dbmongo.getCollection("Possible_shutterSpeeds"); cadena2 = (ja.toString().substring(1, ja.toString().length() - 1)); cadena2 = cadena2.replaceAll("},", "}<<->>"); cadena = cadena2.split("<<->>"); System.out.println(cadena2); for (String lenguaje : cadena) { dbObject = (DBObject) JSON.parse(lenguaje); collection.insert(dbObject); } //Coleccion por Date created rs = st.executeQuery("SELECT CATEGORIES.VALUE_NAME AS DATE_VALUE, IMAGES.IMG_PATH, IMAGES.IMG_NAME , IMAGES.EXTENSION FROM ASOCIATED, IMAGES, CATEGORIES WHERE ASOCIATED.ID_IMG = IMAGES.ID_IMG AND ASOCIATED.VALUE_NAME = CATEGORIES.VALUE_NAME AND CATEGORIES.CAT_NAME like 'Exif SubIFD' and CATEGORIES.TAG_NAME like 'Date/Time Original'"); ja = ResultSetConverter.convert(rs); collection = dbmongo.getCollection("Date_created"); cadena2 = (ja.toString().substring(1, ja.toString().length() - 1)); cadena2 = cadena2.replaceAll("},", "}<<->>"); cadena2 = cadena2.replaceAll("(\"DATE_VALUE\"[:]\")([0-9]{4})[:]([0-9]{2})[:]([0-9]{2})([\\s][0-9]{2}[:][0-9]{2}[:][0-9]{2}\")", "$1$2-$3-$4\""); System.out.println("ddd" + cadena2); cadena = cadena2.split("<<->>"); for (String lenguaje : cadena) { dbObject = (DBObject) JSON.parse(lenguaje); collection.insert(dbObject); } //Coleccion por GPS rs = st.executeQuery("SELECT CATEGORIES.VALUE_NAME AS GPS_VALUE, IMAGES.ID_IMG, IMAGES.IMG_PATH, IMAGES.IMG_NAME , IMAGES.EXTENSION FROM ASOCIATED, IMAGES, CATEGORIES WHERE ASOCIATED.ID_IMG = IMAGES.ID_IMG AND ASOCIATED.VALUE_NAME = CATEGORIES.VALUE_NAME AND CATEGORIES.CAT_NAME like 'GPS%' and (CATEGORIES.TAG_NAME like 'GPS Latitude' or CATEGORIES.TAG_NAME like 'GPS Longitude' or CATEGORIES.TAG_NAME like 'GPS Latitude Ref' or CATEGORIES.TAG_NAME like 'GPS Longitude Ref')order by IMAGES.ID_IMG, CATEGORIES.TAG_NAME"); ja = ResultSetConverter.convert(rs); collection = dbmongo.getCollection("GPSFotos"); cadena2 = (ja.toString().substring(1, ja.toString().length() - 1)); cadena2 = cadena2.replaceAll("},", "}<<->>"); cadena = cadena2.split("<<->>"); System.out.println(cadena2); for (String lenguaje : cadena) { dbObject = (DBObject) JSON.parse(lenguaje); collection.insert(dbObject); } st.close(); System.out.println("Mongo creada"); } catch (SQLException ex) { System.err.println("SQL Error.\n" + ex); } }
8
static public TreeMap<Integer, TreeSet<Integer>> stringToGraph(String str) { TreeMap<Integer, TreeSet<Integer> > tmpNoeuds = new TreeMap<Integer, TreeSet<Integer> >(); StringTokenizer tokenizer = new StringTokenizer(str); while (tokenizer.hasMoreTokens()) { Integer token = Integer.parseInt(tokenizer.nextToken()); Integer token1 = Integer.parseInt(tokenizer.nextToken()); addBadColor(token,token1,tmpNoeuds); } return tmpNoeuds; }
1