text
stringlengths
14
410k
label
int32
0
9
public int getBaseLevel(int skill) { int[] skills = ctx.getClient().getSkillBases(); if (skills == null || skills.length == 0 || skill < 0 || skill >= skills.length) { return -1; } return skills[skill]; }
4
@Override public void removeProperty(String path) { if (path.startsWith(".")) path = path.substring(1); // VERY EXPENSIVE MemoryConfiguration temp = new MemoryConfiguration(); setOptions(temp); Map<String, Object> values = config.getValues(true); if (values.containsKey(path)) values.remove(path); else{ final String altPath = "."+path; if (values.containsKey(altPath)) values.remove(altPath); } for ( String _p : values.keySet()){ Object v = values.get(_p); if (v == null) continue; else if (v instanceof ConfigurationSection) continue; String p; if (_p.startsWith(".")) p = _p.substring(1); else p = _p; if (p.startsWith(path)) continue; temp.set(p, v); } config = temp; }
8
public void mouseExited(MouseEvent mouseEvent) { Iterator<PComponent> it = components.iterator(); while (it.hasNext()) { PComponent comp = it.next(); if (shouldHandleMouse) { if (comp.shouldHandleMouse()) comp.mouseExited(mouseEvent); } else { if (comp instanceof PFrame) { for (PComponent component : ((PFrame) comp).getComponents()) if (component.forceMouse()) component.mouseExited(mouseEvent); } else if (comp.forceMouse()) comp.mouseExited(mouseEvent); } } }
7
public void startNewLevel() { spaceReleased = false; // Create sprite objects ferdie = new CapnFerdinandLongwhiskers(this, capt, 50, 249); doggies = new ArrayList<RoyalNavySeadog>(); Random rm = new Random(); for (int i = 0; i < level*5; i++) { boolean overlap = true; int x = 0; int y = 0; // Ensure dogs don't overlap while(overlap) { x = rm.nextInt(MAXX - 64 - 128) + 128; y = rm.nextInt(VHEIGHT-MINY-64)+MINY; overlap = false; for (RoyalNavySeadog dog : doggies) { if (dog.collisionBox().intersects(new Rectangle(x, y, 64, 64))) { overlap = true; break; } } } doggies.add(new RoyalNavySeadog(this, dog, x, y)); } booties = new ArrayList<Booty>(); for (int i = 0; i < level*10; i++) { booties.add(new Booty(this, chest, rm.nextInt(MAXX - 64), rm.nextInt(VHEIGHT-MINY-64)+MINY)); } acornBooties = new ArrayList<AcornBooty>(); for (int i = 0; i < level*10; i++) { acornBooties.add(new AcornBooty(this, acornImg, rm.nextInt(MAXX - 64), rm.nextInt(VHEIGHT-MINY-64)+MINY)); } bullets = new ArrayList<SquirrelBullet>(); dogBullets = new ArrayList<DogBullet>(); }
6
@Override public Map<String, Object> extract(RequestAttributes attributes, boolean trace, boolean log) { System.out.println("extract"); Map<String, Object> map = super.extract(attributes, trace, log); System.out.println(map); return map; }
0
public Solution search(State init, int goalN, String strategy, boolean visualize) { GenericSearch searcher = null; switch (strategy) { case "DF": searcher = new DFSSearch(this, visualize); break; case "BF": searcher = new BFSSearch(this, visualize); break; case "ID": searcher = new IDSearch(this, visualize); break; case "GR1": searcher = new GRSearch(this, 1, visualize); break; case "GR2": searcher = new GRSearch(this, 2, visualize); break; case "AS1": searcher = new ASSearch(this, 1, visualize); break; case "AS2": searcher = new ASSearch(this, 2, visualize); break; } return searcher.search(init, goalN); }
7
public void putAll( Map<? extends Integer, ? extends V> map ) { Iterator<? extends Entry<? extends Integer,? extends V>> it = map.entrySet().iterator(); for ( int i = map.size(); i-- > 0; ) { Entry<? extends Integer,? extends V> e = it.next(); this.put( e.getKey(), e.getValue() ); } }
8
private void asignarEtiquetasEImagenes() { _columnasImage.actualizarPregunta("<html>"+_preguntas.get(_posicion).getPregunta()+"</html>"); for (int i = 0; i < _columnaBRevuelta.size(); i++) { _columnasImage.asignarImagen(_columnaBRevuelta.get(i).getRespuesta(), i); _columnasImage.asignarColumnaLetras(_columnaAActual.get(i).getRespuesta(), i); } _columnasImage.limpiarCampos(); for (int i = 0; i < _respuestaUsuario.get(_posicion).size(); i++) { for (int j = 0; j < _columnaBRevuelta.size(); j++) { if (_respuestaUsuario.get(_posicion).get(i) == _columnaBRevuelta.get(j).getRespuesta()) { _columnasImage.asignarRespuestas(String.valueOf(i + 1), j); } } } }
4
public void setPower(double power) { if (power < 0 && getPotValue() >= FULL_FORWARD_POSITION || power > 0 && getPotValue() < FULL_BACKWARD_POSITION || Math.abs(power) < .1) { power = 0; } motor.set(power); }
5
public Layer getLayer() { return layer; }
0
public String getOption( String op ) { // TODO: auto, lblAlign, lblOffset if( op.equals( "crossesAt" ) ) { return String.valueOf( catCross ); } if( op.equals( "orientation" ) ) { return (fReverse) ? "maxMin" : "minMax"; } if( op.equals( "crosses" ) ) { if( fMaxCross ) { return "max"; } if( fBetween ) { return "autoZero"; // correct?? } return "min"; // correct?? } if( op.equals( "tickMarkSkip" ) ) //val= how many tick marks to skip before next one is drawn -- catMark -- catsterrange only? { return String.valueOf( catMark ); } if( op.equals( "tickLblSkip" ) ) { return String.valueOf( catLabel ); } return null; }
8
public static void main(String[] args) throws Exception { System.setProperty("webdriver.chrome.driver", "D:\\Download\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.manage().window().maximize(); File bankNames = new File("E:\\Ashok\\Dropbox\\MyDetails\\pinfinder\\railwaycodes\\stationcodes.xls"); FileInputStream file = new FileInputStream(bankNames); // Get the workbook instance for XLS file HSSFWorkbook bankWorkBook = new HSSFWorkbook(file); // Get first sheet from the workbook HSSFSheet banksheet = bankWorkBook.getSheetAt(0); // Iterate through each rows from first sheet Iterator<Row> rowIterator = banksheet.iterator(); HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Trains"); boolean flag = true; int i = 0; int j = 3; while (rowIterator.hasNext()) { Row row = rowIterator.next(); if (flag) { flag = false; continue; } if(row.getRowNum() <= 2000) { continue; } String stationCode = row.getCell(0).getStringCellValue().trim(); System.out.println(row.getRowNum() + "---" + stationCode); driver.get("https://www.cleartrip.com/trains/stations/" + stationCode); WebElement table = driver.findElements(By.className("results")).get(1); List<WebElement> trs = table.findElements(By.tagName("tr")); for (WebElement tr : trs) { List<WebElement> tds = tr.findElements(By.tagName("td")); HSSFRow trainRow = sheet.createRow(i); trainRow.createCell(0).setCellValue(stationCode); trainRow.createCell(1).setCellValue(tds.get(0).getText()); trainRow.createCell(2).setCellValue(tds.get(1).getText()); trainRow.createCell(3).setCellValue(tds.get(2).getText()); trainRow.createCell(4).setCellValue(tds.get(3).getText()); trainRow.createCell(5).setCellValue(tds.get(4).getText()); trainRow.createCell(6).setCellValue(tds.get(5).getText()); trainRow.createCell(7).setCellValue(tds.get(6).getText()); trainRow.createCell(8).setCellValue(tds.get(7).getText()); trainRow.createCell(9).setCellValue(tds.get(8).getText()); trainRow.createCell(10).setCellValue(tds.get(9).getText()); trainRow.createCell(11).setCellValue(tds.get(10).getText()); i++; } if (row.getRowNum() != 0 && row.getRowNum() % 1000 == 0) { HSSFRow row1 = workbook.getSheetAt(0).getRow(0); for (int colNum = 0; colNum < row1.getLastCellNum(); colNum++) { workbook.getSheetAt(0).autoSizeColumn(colNum); } FileOutputStream out = new FileOutputStream(new File( "E:\\Ashok\\Dropbox\\MyDetails\\pinfinder\\railwaycodes\\trainspassingviastation_" + j + ".xls")); workbook.write(out); out.close(); System.out.println(j + " Excel written successfully.."); i = 0; j++; workbook = new HSSFWorkbook(); sheet = workbook.createSheet("Trains"); } } FileOutputStream out = new FileOutputStream(new File( "E:\\Ashok\\Dropbox\\MyDetails\\pinfinder\\railwaycodes\\trainspassingviastation_" + j + ".xls")); workbook.write(out); out.close(); }
7
private void busqAsuntoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_busqAsuntoActionPerformed // TODO add your handling code here: CitaPorAsunto cA = new CitaPorAsunto(); while (cA.extraerAsunto().length()==0 && JOptionPane.showConfirmDialog(this, cA, "Buscar una cita por asunto", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE)!=JOptionPane.CANCEL_OPTION) { if (cA.extraerAsunto().length()==0) { JOptionPane.showMessageDialog(cA, "Debe introducir un asunto.", "Informacion", WIDTH); } } if( AgendaPrincGrafica.agenda.esVacia() ) { JOptionPane.showMessageDialog(cA, "La agenda esta vacia.", "Informacion", WIDTH); } else if (cA.extraerAsunto().length()>0){ Mostrador m = new Mostrador (AgendaPrincGrafica.agenda.mostrarCita(cA.extraerAsunto())); JOptionPane.showMessageDialog(cA, m, "Cita buscada", WIDTH); } }//GEN-LAST:event_busqAsuntoActionPerformed
5
private void initPilotList() { try{ RecentLaunchSelections recent = RecentLaunchSelections.getRecentLaunchSelections(); pilotNames = DatabaseUtilities.DatabaseDataObjectUtilities.getPilots(); List<Pilot> recentPilots = recent.getRecentPilot(); for (int i = 0; i < recentPilots.size(); i++){ pilotNames.add(0, recentPilots.get(i)); } }catch(SQLException e) { } catch (ClassNotFoundException ex) { // TODO change exception case } catch(Exception exp){ exp.printStackTrace(); } }
4
public long CurrentFilePosition() { long position; try { position = file.getFilePointer(); } catch (IOException ioe) { position = -1; } return position; }
1
@Override public void run() { try { // Eclipse doesn't support System.console() BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); ConfigManager config = NetBase.theNetBase().config(); try { ElapsedTime.clear(); String targetIP = config.getProperty("net.server.ip"); if ( targetIP == null ) { System.out.print("Enter the server's ip, or empty line to exit: "); targetIP = console.readLine(); if ( targetIP == null || targetIP.trim().isEmpty() ) return; } System.out.print("Enter the server's TCP port, or empty line to exit: "); String targetTCPPortStr = console.readLine(); if ( targetTCPPortStr == null || targetTCPPortStr.trim().isEmpty() ) return; int targetTCPPort = Integer.parseInt( targetTCPPortStr ); System.out.print("Enter number of trials: "); String trialStr = console.readLine(); int nTrials = Integer.parseInt(trialStr); int socketTimeout = config.getAsInt("net.timeout.socket", 2000); if ( targetTCPPort != 0 ) { ElapsedTimeInterval tcpmhResult = ping(EchoServiceBase.HEADER_STR, targetIP, targetTCPPort, socketTimeout, nTrials); if ( tcpmhResult != null ) System.out.println(String.format("%.2f msec (%d failures)", tcpmhResult.mean(), tcpmhResult.nAborted())); System.out.println("Raw measurement info: " + ElapsedTime.statString()); } } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); } } catch (Exception e) { System.out.println("PingTCPMessageHandler.run() caught exception: " + e.getMessage()); } }
9
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(janProvaTitulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(janProvaTitulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(janProvaTitulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(janProvaTitulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new janProvaTitulos().setVisible(true); } }); }
6
public static void main(String[] args) throws Exception { List<SeperatorDefinition> seps = new ArrayList<SeperatorDefinition>(); buildCoreSet(Release.ReturnToRavnica, seps); buildBasicSet(Release.Magic2013, seps); buildBasicMultiColor(Release.Magic2013, seps); buildBasicSet(Release.AvacynRestored, seps); buildBasicMultiColor(Release.AvacynRestored, seps); for(MagicColor c: MagicColor.values()) if (c.isBaseColor()) buildSpecialSeperator(seps, Arrays.asList(c), Arrays.asList("Basic Land")); for(MagicColor c: Arrays.asList( MagicColor.BlackGreen, MagicColor.BlackRed, MagicColor.BlueRed, MagicColor.GreenWhite, MagicColor.WhiteBlue )) buildSpecialSeperator(Release.ReturnToRavnica, seps, c); buildSpecialSeperator(seps, Arrays.asList(MagicColor.Colorless), Arrays.asList(SymbolFactory.getIcon(Release.Gatecrash, Rarity.Common))); buildSpecialSeperator(seps, Arrays.asList(MagicColor.Colorless), Arrays.asList(SymbolFactory.getIcon(Release.Gatecrash, Rarity.Uncommon))); buildSpecialSeperator(seps, Arrays.asList(MagicColor.Colorless), Arrays.asList(SymbolFactory.getIcon(Release.Gatecrash, Rarity.Rare), SymbolFactory.getIcon(Release.Gatecrash, Rarity.Mystic))); buildSpecialSeperator(seps, Arrays.asList("Unsorted"), Arrays.asList("Misc")); Paper paper = new Paper(); paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight()); PageFormat format = new PageFormat(); format.setPaper(paper); Book pages = new Book(); pages.append(new MagicPaperPrintable(seps), format, (int)Math.ceil(seps.size() / 6d)); PrinterJob job = PrinterJob.getPrinterJob(); job.setPageable(pages); if (!job.printDialog()) return; job.print(); }
4
public URL getURL() throws MalformedURLException { URL url = null; try { url = new URL(getURLString()); } catch (MalformedURLException mue) { throw mue; } return url; }
1
protected void fireEditingStopped() { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == CellEditorListener.class) { ((CellEditorListener) listeners[i + 1]) .editingStopped(new ChangeEvent(this)); } } }
2
Options(SmallWorld sw, GUICanvas cv, MenuItem mi) { smallWorld = sw; menuItem = mi; canvas = cv; // Set up layout. setSize(300,650); gridBag = new GridBagLayout(); setLayout(gridBag); c = new GridBagConstraints(); c.anchor = GridBagConstraints.SOUTHWEST; c.insets = new Insets(5, 5, 5, 5); c.ipadx = 2; c.ipady = 2; c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; c.gridwidth = 1; c.gridheight = 1; agentsField = new TextField("10",10); gridBag.setConstraints(agentsField, c); add(agentsField); c.gridx = 1; c.gridwidth = 1; c.gridheight = 1; Label label = new Label("Number of Ring World Agents"); gridBag.setConstraints(label, c); add(label); c.gridx = 0; c.gridy++; c.gridwidth = 1; c.gridheight = 1; widthField = new TextField("300",10); gridBag.setConstraints(widthField, c); add(widthField); c.gridx = 1; c.gridwidth = 1; c.gridheight = 1; label = new Label("Width of field"); gridBag.setConstraints(label, c); add(label); c.gridx = 0; c.gridy++; c.gridwidth = 1; c.gridheight = 1; heightField = new TextField("400",10); gridBag.setConstraints(heightField, c); add(heightField); c.gridx = 1; c.gridwidth = 1; c.gridheight = 1; label = new Label("Height of field"); gridBag.setConstraints(label, c); add(label); c.gridx = 0; c.gridy++; c.gridwidth = 1; c.gridheight = 1; runsField = new TextField("10",10); gridBag.setConstraints(runsField, c); add(runsField); c.gridx = 1; c.gridwidth = 1; c.gridheight = 1; label = new Label("Number of iterations"); gridBag.setConstraints(label, c); add(label); c.gridx = 0; c.gridy++; c.gridwidth = 1; c.gridheight = 1; kField = new TextField("4.0",10); gridBag.setConstraints(kField, c); add(kField); c.gridx = 1; c.gridwidth = 1; c.gridheight = 1; label = new Label("Value of k"); gridBag.setConstraints(label, c); add(label); c.gridx = 0; c.gridy++; c.gridwidth = 1; c.gridheight = 1; alphaField = new TextField("15.0",10); gridBag.setConstraints(alphaField, c); add(alphaField); c.gridx = 1; c.gridwidth = 1; c.gridheight = 1; label = new Label("Value of alpha"); gridBag.setConstraints(label, c); add(label); c.gridx = 0; c.gridy++; c.gridwidth = 1; c.gridheight = 1; constantField = new TextField("0.0000000001",10); gridBag.setConstraints(constantField, c); add(constantField); c.gridx = 1; c.gridwidth = 1; c.gridheight = 1; label = new Label("Value of constant"); gridBag.setConstraints(label, c); add(label); c.gridx = 0; c.gridy++; c.gridwidth = 1; c.gridheight = 1; redAgent = new Scrollbar(Scrollbar.HORIZONTAL, 255, 1, 0, 255); gridBag.setConstraints(redAgent, c); add(redAgent); c.gridx = 1; c.gridwidth = 1; c.gridheight = 1; label = new Label("Red level for Agents"); gridBag.setConstraints(label, c); add(label); c.gridx = 0; c.gridy++; c.gridwidth = 1; c.gridheight = 1; greenAgent = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, 255); gridBag.setConstraints(greenAgent, c); add(greenAgent); c.gridx = 1; c.gridwidth = 1; c.gridheight = 1; label = new Label("Green level for Agents"); gridBag.setConstraints(label, c); add(label); c.gridx = 0; c.gridy++; c.gridwidth = 1; c.gridheight = 1; blueAgent = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, 255); gridBag.setConstraints(blueAgent, c); add(blueAgent); c.gridx = 1; c.gridwidth = 1; c.gridheight = 1; label = new Label("Blue level for Agents"); gridBag.setConstraints(label, c); add(label); c.gridx = 0; c.gridy++; c.gridwidth = 1; c.gridheight = 1; redLine = new Scrollbar(Scrollbar.HORIZONTAL, 125, 1, 0, 255); gridBag.setConstraints(redLine, c); add(redLine); c.gridx = 1; c.gridwidth = 1; c.gridheight = 1; label = new Label("Red level for lines"); gridBag.setConstraints(label, c); add(label); c.gridx = 0; c.gridy++; c.gridwidth = 1; c.gridheight = 1; greenLine = new Scrollbar(Scrollbar.HORIZONTAL, 125, 1, 0, 255); gridBag.setConstraints(greenLine, c); add(greenLine); c.gridx = 1; c.gridwidth = 1; c.gridheight = 1; label = new Label("Green level for lines"); gridBag.setConstraints(label, c); add(label); c.gridx = 0; c.gridy++; c.gridwidth = 1; c.gridheight = 1; blueLine = new Scrollbar(Scrollbar.HORIZONTAL, 125, 1, 0, 255); gridBag.setConstraints(blueLine, c); add(blueLine); c.gridx = 1; c.gridwidth = 1; c.gridheight = 1; label = new Label("Blue level for lines"); gridBag.setConstraints(label, c); add(label); cbg = new CheckboxGroup(); c.gridx = 0; c.gridy++; c.gridwidth = 2; c.gridheight = 1; colour = new Checkbox("Use scrollbars to colour", cbg, true); gridBag.setConstraints(colour, c); add(colour); c.gridx = 0; c.gridy++; c.gridwidth = 2; c.gridheight = 1; random = new Checkbox("Use random colours", cbg, false); gridBag.setConstraints(random, c); add(random); c.gridx = 0; c.gridy++; c.gridwidth = 2; c.gridheight = 1; values = new Checkbox("Use agent values to colour", cbg, false); gridBag.setConstraints(values, c); add(values); c.gridx = 0; c.gridy++; c.gridwidth = 1; c.gridheight = 1; ok = new Button("Ok"); gridBag.setConstraints(ok, c); ok.addActionListener(this); add(ok); c.gridx = 1; c.gridwidth = 1; c.gridheight = 1; cancel = new Button("Cancel"); gridBag.setConstraints(cancel, c); cancel.addActionListener(this); add(cancel); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e) { setVisible(false); } }); } // End of constructor.
0
public void ajouter(Entree e,String s) throws DoubleDeclarationException { if(listeBloc.get(region_actuelle).containsKey(e) && listeBloc.get(region_actuelle).get(e).getType().equals(s)){ GestionnaireSemantique.getInstance().add(new DoubleDeclarationException(" a la ligne "+e.getLine()+" : "+e.getNom()+" est deja declaree")); }else{ Symbole sym; if(!s.equals("classe") && !s.equals("fonction")) sym = new Symbole(s,deplacement+=4); else{ sym = new Symbole(s,0); } if(region_actuelle.getBloc()==1) sym.setGlobal(true); listeBloc.get(region_actuelle).put(e, sym); } }
5
private Decal getFreeDecal() { long min=Long.MAX_VALUE; Decal decal=null; for (int i=0; i<MAX_DECALS; i++) { if (!decals[i].getVisibility()) { return decals[i]; } if (decals[i].getDecalID()<min) { min=decals[i].getDecalID(); decal=decals[i]; } } return decal; }
3
public void selectPreviousRow() { int rowCount = activityListModel.getRowCount(); if (previousRow >= 0 && rowCount > 0) { if (rowCount > previousRow) { tblActivities.getSelectionModel().setSelectionInterval(previousRow, previousRow); } else if (rowCount == previousRow) { tblActivities.getSelectionModel().setSelectionInterval(previousRow - 1, previousRow - 1); } else { int row = rowCount - 1; tblActivities.getSelectionModel().setSelectionInterval(row, row); } } }
4
public boolean matches( Class<?> clazz ) { return true; }
1
public CuttingResult getReward(Tilia x){ int side = x.getSide(); //Check if you have computed this before if(!tabel.containsKey(side)){ ArrayList<Integer> pieces = new ArrayList<Integer>(); pieces.add(x.getSide()); // First two variables in CuttingResult are not used CuttingResult best = new CuttingResult(0, 0, x.getReward(), pieces); // Try possible cuts for (int i =1 ; i < x.getSide() ; i++){ ArrayList<Integer> pieces_tmp = new ArrayList<Integer>(); long sum =0; //Try different cuts for (Tilia tilia : x.cut(i)){ //Process smaller pieces CuttingResult temp = getReward(tilia); for(int j=0; j < temp.getPieces().size();j++){ pieces_tmp.add(temp.getPieces().get(j)); } sum+=temp.getReward(); } //Select optimal result if (sum > best.getReward()){ best.setPieces(pieces_tmp); best.setReward(sum); } } // Save optimal result tabel.put(side, best); return best; } else return tabel.get(side); }
5
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Card other = (Card) obj; if (this.value != other.value && (this.value == null || !this.value.equals(other.value))) { return false; } if (this.type != other.type && (this.type == null || !this.type.equals(other.type))) { return false; } return true; }
8
void getServer() { try { ServerSocket serverSocket=new ServerSocket(9999); //׽ System.out.println("׽~"); while(true) { Socket socket=serverSocket.accept(); //ȴ new write_Thread(socket).start(); //߳ socketMan.add(socket); // ׽ socketMan.sendClientCount(); //ǰ׽ } }catch(Exception e){ e.printStackTrace(); } }
2
private void readObject(ObjectInputStream stream) throws java.io.IOException, java.lang.ClassNotFoundException { stream.defaultReadObject(); isProperList = stream.readBoolean(); if (!isProperList) { dottedElement = (E) stream.readObject(); } }
1
private int checkHtml(final StringBuilder out, final String in, int start) { final StringBuilder temp = new StringBuilder(); int pos; // Check for auto links temp.setLength(0); pos = Utils.readUntil(temp, in, start + 1, ':', ' ', '>', '\n'); if(pos != -1 && in.charAt(pos) == ':' && HTML.isLinkPrefix(temp.toString())) { pos = Utils.readUntil(temp, in, pos, '>'); if(pos != -1) { final String link = temp.toString(); this.config.decorator.openLink(out); out.append(" href=\""); Utils.appendValue(out, link, 0, link.length()); out.append("\">"); Utils.appendValue(out, link, 0, link.length()); out.append("</a>"); return pos; } } // Check for mailto or adress auto link temp.setLength(0); pos = Utils.readUntil(temp, in, start + 1, '@', ' ', '>', '\n'); if(pos != -1 && in.charAt(pos) == '@') { pos = Utils.readUntil(temp, in, pos, '>'); if(pos != -1) { final String link = temp.toString(); this.config.decorator.openLink(out); out.append(" href=\""); //address auto links if(link.startsWith("@")) { String slink = link.substring(1); String url = "https://maps.google.com/maps?q="+slink.replace(' ', '+'); out.append(url); out.append("\">"); out.append(slink); } //mailto auto links else { Utils.appendMailto(out, "mailto:", 0, 7); Utils.appendMailto(out, link, 0, link.length()); out.append("\">"); Utils.appendMailto(out, link, 0, link.length()); } out.append("</a>"); return pos; } } // Check for inline html if(start + 2 < in.length()) { temp.setLength(0); return Utils.readXML(out, in, start, this.config.safeMode); } return -1; }
9
public int somme() { int s = 0; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { s += (matrixb[i][j] ? 1 : 0); } } return s; }
3
public void setDefaultsForNodeType() { CyRow row1, row2; CyNode node = nodeView.getModel(); double port1EfficiencyVal = 1.0; int numOfInputsVal = 1; double timeRampVal = 1.0; double relativeConcVal = 1.0; double decayVal = 0.0001; double initialOutputVal = 0.0; double intOutputNodeThreshVal = 0.5; double upperBoundVal = 1.0; double currOutputVal = 0.0; double nextOutputVal = 0.0; row1 = ColumnsCreator.DefaultNodeTable.getRow(node.getSUID()); row2 = ColumnsCreator.HiddenNodeTable.getRow(node.getSUID()); List<Double> portEfficiency = new ArrayList<Double>(); if(type.equals(KINASE)) { port1EfficiencyVal = 1.0; numOfInputsVal = 1; timeRampVal = 1.0; relativeConcVal = 1.0; decayVal = 0.0001; initialOutputVal = 0.0; intOutputNodeThreshVal = 0.5; upperBoundVal = 1.0; currOutputVal = 0.0; nextOutputVal = 0.0; } else if(type.equals(GTPASE)) { port1EfficiencyVal = 1.0; numOfInputsVal = 1; timeRampVal = 1.0; relativeConcVal = 1.0; decayVal = 0.0001; initialOutputVal = 0.0; intOutputNodeThreshVal = 0.5; upperBoundVal = 1.0; currOutputVal = 0.0; nextOutputVal = 0.0; } else if(type.equals(MOLECULES)) { port1EfficiencyVal = 1.0; numOfInputsVal = 1; timeRampVal = 1.0; relativeConcVal = 1.0; decayVal = 0.0001; initialOutputVal = 0.0; intOutputNodeThreshVal = 0.5; upperBoundVal = 1.0; currOutputVal = 0.0; nextOutputVal = 0.0; } else if(type.equals(RECEPTOR)) { port1EfficiencyVal = 1.0; numOfInputsVal = 1; timeRampVal = 1.0; relativeConcVal = 1.0; decayVal = 0.0001; initialOutputVal = 0.0; intOutputNodeThreshVal = 0.5; upperBoundVal = 1.0; currOutputVal = 0.0; nextOutputVal = 0.0; } else if(type.equals(RECEPTOR_T_KINASE)) { port1EfficiencyVal = 1.0; numOfInputsVal = 1; timeRampVal = 1.0; relativeConcVal = 1.0; decayVal = 0.0001; initialOutputVal = 0.0; intOutputNodeThreshVal = 0.5; upperBoundVal = 1.0; currOutputVal = 0.0; nextOutputVal = 0.0; } else if(type.equals(PHOSPHATASE)) { port1EfficiencyVal = 1.0; numOfInputsVal = 1; timeRampVal = 1.0; relativeConcVal = 1.0; decayVal = 0.0001; initialOutputVal = 0.0; intOutputNodeThreshVal = 0.5; upperBoundVal = 1.0; currOutputVal = 0.0; nextOutputVal = 0.0; } portEfficiency.add(port1EfficiencyVal); row1.set(ColumnsCreator.NODE_TYPE, type); row1.set(ColumnsCreator.NUM_OF_INPUTS, numOfInputsVal); row1.set(ColumnsCreator.TIME_RAMP, timeRampVal); row1.set(ColumnsCreator.RELATIVE_CONCENTRATION, relativeConcVal); row1.set(ColumnsCreator.DECAY, decayVal); row1.set(ColumnsCreator.INITIAL_OUTPUT_VALUE, initialOutputVal); row1.set(ColumnsCreator.PORT_EFFICIENCY, portEfficiency); row1.set(ColumnsCreator.INTEGER_OUTPUT_NODE_THRESH, intOutputNodeThreshVal); row1.set(ColumnsCreator.UPPER_BOUND, upperBoundVal); row1.set(ColumnsCreator.CURR_OUTPUT, currOutputVal); row2.set(ColumnsCreator.NEXT_OUTPUT, nextOutputVal); }
6
public int threeSumClosest(int[] num, int target) { int record = 0; int min = Integer.MAX_VALUE; int length = num.length; Arrays.sort(num); for (int i = 0; i < length; i++) { //except num[0], start is the second number, end is the last number int start = i + 1; int end = length - 1; while (start < end) { //get the sum int sum = num[i] + num[start] + num[end]; //the same, samply return if (sum == target) { min = 0; record = sum; break; } //less than, move the start, add bigger number if (sum < target) { //if the min is not the smaller, change the min, and record the sum if (target - sum < min) { min = target - sum; record = sum; } start++; } //bigger than, move the end, add smaller number else if (sum > target) { //if the min is not the smaller, change the min, and record the sum if (sum - target < min) { min = sum - target; record = sum; } end--; } } //avoid the duplicate number while (i < length - 1 && num[i] == num[i + 1]) { i++; } } return record; }
9
public Object invokeConstructor(Reference ref, Object[] params) throws InterpreterException, InvocationTargetException { Constructor c; try { String[] paramTypeSigs = TypeSignature.getParameterTypes(ref .getType()); Class clazz = TypeSignature.getClass(ref.getClazz()); Class[] paramTypes = new Class[paramTypeSigs.length]; for (int i = 0; i < paramTypeSigs.length; i++) { params[i] = toReflectType(paramTypeSigs[i], params[i]); paramTypes[i] = TypeSignature.getClass(paramTypeSigs[i]); } try { c = clazz.getConstructor(paramTypes); } catch (NoSuchMethodException ex) { c = clazz.getDeclaredConstructor(paramTypes); } } catch (ClassNotFoundException ex) { throw new InterpreterException(ref + ": Class not found"); } catch (NoSuchMethodException ex) { throw new InterpreterException("Constructor " + ref + " not found"); } catch (SecurityException ex) { throw new InterpreterException(ref + ": Security exception"); } try { return c.newInstance(params); } catch (IllegalAccessException ex) { throw new InterpreterException("Constructor " + ref + " not accessible"); } catch (InstantiationException ex) { throw new InterpreterException("InstantiationException in " + ref + "."); } }
7
static void insertion_sort(int num[]) { int number; for (int i=0;i<num.length-1;i++) { number=num[i+1]; for(int j=i;j>=0;j--) { if(number<num[j]) { num[j+1]=num[j]; num[j]=number; } } } for (int i:num) { System.out.println(i); } }
4
protected String getRightNowTimeStr(final String dateDep, final String secDep, final String dep) { final String month = (Calendar.getInstance().get(Calendar.MONTH) + 1) > 9 // ? String.valueOf(Calendar.getInstance().get(Calendar.MONTH) + 1) // : "0" + (Calendar.getInstance().get(Calendar.MONTH) + 1); return Calendar.getInstance().get(Calendar.YEAR) // + dateDep + month // + dateDep + (Calendar.getInstance().get(Calendar.DATE)) // + dep + (Calendar.getInstance().get(Calendar.HOUR_OF_DAY)) // + secDep + (Calendar.getInstance().get(Calendar.MINUTE)) // + secDep + (Calendar.getInstance().get(Calendar.SECOND)); }
1
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onFoodLevelChange(FoodLevelChangeEvent event) { Entity entity = event.getEntity(); if (entity instanceof Player) { xAuthPlayer xp = plyrMngr.getPlayer(((Player) entity).getName()); if (plyrMngr.isRestricted(xp, event)) event.setCancelled(true); } }
2
public void setOpenEnded( OpenEndedConnectionStrategy openEnded ) { if( openEnded == null ){ openEnded = OpenEndedConnectionStrategy.NULL; } this.openEnded.endConnecting(); this.openEnded.setParent( null ); this.openEnded = openEnded; this.openEnded.setParent( site ); }
1
public void createService(String serviceType, String description, String roomNumber) throws ParseException { //finding roomnumber int rmNumber = Integer.parseInt(roomNumber); Query q = em.createQuery("SELECT t from RoomEntity t"); for (Object o : q.getResultList()) { RoomEntity p = (RoomEntity) o; if (p.getRoomNumber() == rmNumber) { ServiceEntity se = new ServiceEntity(); Date time = new Date(); SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss"); se.create(ft.format(time), serviceType, description); se.setRooms(p); em.merge(se); } } // System.out.println("room number not found"); }
2
private void addComponents(boolean check) { this.add(numberOfFilesLabel); this.add(lineOfCodeLabel); this.add(commentsLabel); this.add(blankLinesLabel); this.add(totalLinesLabel); if (check) { this.add(codeShareLabel); } }
1
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { System.out.println("用户名-------------"+username); UserLogin userLogin = null; if(username != null && !"".equals(username)&& username.indexOf("@") > 0){ userLogin = UserLoginDao.findByEmail(username); username = userLogin.getNick(); }else{ userLogin = UserLoginDao.findByNick(username); } if(userLogin == null){ throw new UsernameNotFoundException("用户不存在"); } System.out.println("user type ---"+userLogin.getUserType()); // String nick = userLogin.getNick(); // String email = userLogin.getEmail(); // String mobile = userLogin.getMobile(); int userType = userLogin.getUserType(); List<GrantedAuthority> resultAuths = new ArrayList<GrantedAuthority>(); // 前台用户 if (userType == 1) { resultAuths.add(new SimpleGrantedAuthority("ROLE_USER")); } else { resultAuths.add(new SimpleGrantedAuthority("ROLE_BACK_USER")); } // return new WrappedUserLogin(userLogin.getId(), email, nick, mobile, userLogin.getPassword(), userType, resultAuths); return new WrappedUserLogin(userLogin, resultAuths); }
5
private static final boolean jjCanMove_2(int hiByte, int i1, int i2, long l1, long l2) { switch(hiByte) { case 0: return ((jjbitVec4[i2] & l2) != 0L); case 48: return ((jjbitVec5[i2] & l2) != 0L); case 49: return ((jjbitVec6[i2] & l2) != 0L); case 51: return ((jjbitVec7[i2] & l2) != 0L); case 61: return ((jjbitVec8[i2] & l2) != 0L); default : if ((jjbitVec3[i1] & l1) != 0L) return true; return false; } }
6
@Override protected boolean doSmall() { Tile obeliskRandom; final GameObject obelisk = ctx.objects.select().id(OBELISK).nearest().poll(); if (obelisk.valid()) { obeliskRandom = ITile.randomize(obelisk.tile(), 2, 2); } else { obeliskRandom = locationAttribute.getObeliskRandom(ctx); } if (obeliskRandom != null && ctx.movement.findPath(obeliskRandom).traverse() || ctx.movement.step(obeliskRandom)) { ctx.sleep(1200); return true; } if (pathToObelisk != null) { pathToObelisk.randomize(2, 2); return pathToObelisk.traverse(); } return false; }
5
public long getThreadUptime() { return threadUptime; }
0
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; WatchKey other = (WatchKey) obj; if (folderPath == null) { if (other.folderPath != null) return false; } else if (!folderPath.equals(other.folderPath)) return false; return true; }
6
public static int[] path(int[] queue) { int esimene = queue[0]; int[] resultPath = new int[queue.length]; resultPath[0] = esimene; int i = 0; int j = 0; int u = 0; for (int k : queue) { if (k < esimene) { i++; } else if (k > esimene) { j++; } else { u++; } } int[] vaiksemad = new int[i]; int[] suuremad = new int[j]; int p = 0; int p2 = 0; for (int k = 0; k < queue.length; k++) { if (queue[k] < esimene) { vaiksemad[p] = queue[k]; p++; } } for (int k = 0; k < queue.length; k++) { if (queue[k] > esimene) { suuremad[p2] = queue[k]; p2++; } } Arrays.sort(vaiksemad); for (int k = vaiksemad.length - 1, o = 1; k >= 0; k--, o++) { resultPath[o] = vaiksemad[k]; } Arrays.sort(suuremad); int asd = i + u; for (int ko = 0; ko < suuremad.length; ko++) { resultPath[asd] = suuremad[ko]; asd++; } return resultPath; }
9
public void discard(Card card) { // remove card from hand if (players[turn].getHand().remove(card)) { discard.add(card); sendAll(PacketCreator.discardNotify(card)); } else { out.println("Discard Error. Card " + card + " was not in player's hand."); System.exit(1); return; } // send foot if empty checkAndSendFoot(); // detect endgame if (players[turn].isInFoot() && players[turn].getHand().isEmpty()) { score[0] += endRoundScore(0); score[1] += endRoundScore(1); if (round < 4) { Packet packet; for (Player p : players) { boolean team = p.getNumber() % 2 == 0; // round + 1 for human readable packet = PacketCreator.endRound(team ? score[0] : score[1], team ? score[1] : score[0], round + 1); p.send(packet); } new Thread() { @Override public void run() { try { Thread.sleep(8000); } catch (InterruptedException e) { } startRound(); } }.start(); } round++; } else { endTurn(); } }
8
public ArticleInfo getArticleInfo(String articleUrl) throws IOException { String id = getId(articleUrl); String type = null; String source = null; Integer year = null; Integer month = null; final HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(articleUrl)); if (connectTimeout != null) { request.setConnectTimeout(connectTimeout); } if (readTimeout != null) { request.setReadTimeout(readTimeout); } final HttpResponse response = request.execute(); try { final BufferedReader reader = new BufferedReader(new InputStreamReader(response.getContent(), "UTF-8")); try { String line; while ((line = reader.readLine()) != null) { if (line.length() > 300) { continue; } final Matcher citeMatcher = CITE_PATTERN.matcher(line); if (citeMatcher.matches()) { if (citeMatcher.groupCount() == 2) { source = citeMatcher.group(1).trim(); final String dateStr = citeMatcher.group(2).trim(); year = getYear(dateStr); month = getMonth(dateStr); } } final Matcher typeMatcher = TYPE_PATTERN.matcher(line); if (typeMatcher.matches()) { if (typeMatcher.groupCount() == 1) { type = typeMatcher.group(1); } } } } finally { reader.close(); } } finally { response.ignore(); } return new ArticleInfo(id, articleUrl, type, source, year, month); }
8
public static void sort_words(String s) { String[] words = s.replace(',', ' ').replaceAll("\\s+", " ").split(" "); Arrays.sort(words); for (String word : words) { System.out.println(word); } }
1
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Status other = (Status) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; }
6
@Override public void actionPerformed(ActionEvent actionEvent) { try { if(actionEvent.getSource() == fileTransferActive) { if(fileTransferActive.getText().compareTo(FTA_START) == 0) { iface.startService(ServiceName.FileTransferActive); fileTransferActive.setText(FTA_STOP); } else { iface.stopService(ServiceName.FileTransferActive); fileTransferActive.setText(FTA_START); } } if(actionEvent.getSource() == fileTransferPassive) { if(fileTransferPassive.getText().compareTo(FTP_START) == 0) { iface.startService(ServiceName.FileTransferPassive); fileTransferPassive.setText(FTP_STOP); } else { iface.stopService(ServiceName.FileTransferPassive); fileTransferPassive.setText(FTP_START); } } if(actionEvent.getSource() == keyboardInteraction) { if(keyboardInteraction.getText().compareTo(KEY_START) == 0) { iface.startService(ServiceName.KeyboardInteraction); keyboardInteraction.setText(KEY_STOP); } else { iface.stopService(ServiceName.KeyboardInteraction); keyboardInteraction.setText(KEY_START); } } } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Service Exception", JOptionPane.ERROR_MESSAGE); } if(actionEvent.getSource() == disconnect) { try { iface.disconnect(); } catch (Exception e) { JOptionPane.showMessageDialog(null,e.getMessage(),"Connection Exception",JOptionPane.ERROR_MESSAGE); } } }
9
public EditorToolBar(final BasicGraphEditor editor, int orientation) { super(orientation); setBorder(BorderFactory.createCompoundBorder(BorderFactory .createEmptyBorder(3, 3, 3, 3), getBorder())); setFloatable(false); add(editor.bind("New", new NewAction(), "/com/mxgraph/examples/swing/images/new.gif")); add(editor.bind("Open", new OpenAction(), "/com/mxgraph/examples/swing/images/open.gif")); add(editor.bind("Save", new SaveAction(false), "/com/mxgraph/examples/swing/images/save.gif")); addSeparator(); add(editor.bind("Print", new PrintAction(), "/com/mxgraph/examples/swing/images/print.gif")); addSeparator(); add(editor.bind("Cut", TransferHandler.getCutAction(), "/com/mxgraph/examples/swing/images/cut.gif")); add(editor.bind("Copy", TransferHandler.getCopyAction(), "/com/mxgraph/examples/swing/images/copy.gif")); add(editor.bind("Paste", TransferHandler.getPasteAction(), "/com/mxgraph/examples/swing/images/paste.gif")); addSeparator(); add(editor.bind("Delete", mxGraphActions.getDeleteAction(), "/com/mxgraph/examples/swing/images/delete.gif")); addSeparator(); add(editor.bind("Undo", new HistoryAction(true), "/com/mxgraph/examples/swing/images/undo.gif")); add(editor.bind("Redo", new HistoryAction(false), "/com/mxgraph/examples/swing/images/redo.gif")); addSeparator(); // Gets the list of available fonts from the local graphics environment // and adds some frequently used fonts at the beginning of the list GraphicsEnvironment env = GraphicsEnvironment .getLocalGraphicsEnvironment(); List<String> fonts = new ArrayList<String>(); fonts.addAll(Arrays.asList(new String[] { "Helvetica", "Verdana", "Times New Roman", "Garamond", "Courier New", "-" })); fonts.addAll(Arrays.asList(env.getAvailableFontFamilyNames())); final JComboBox fontCombo = new JComboBox(fonts.toArray()); fontCombo.setEditable(true); fontCombo.setMinimumSize(new Dimension(120, 0)); fontCombo.setPreferredSize(new Dimension(120, 0)); fontCombo.setMaximumSize(new Dimension(120, 100)); add(fontCombo); fontCombo.addActionListener(new ActionListener() { /** * */ @Override public void actionPerformed(ActionEvent e) { String font = fontCombo.getSelectedItem().toString(); if (font != null && !font.equals("-")) { mxGraph graph = editor.getGraphComponent().getGraph(); graph.setCellStyles(mxConstants.STYLE_FONTFAMILY, font); } } }); final JComboBox sizeCombo = new JComboBox(new Object[] { "6pt", "8pt", "9pt", "10pt", "12pt", "14pt", "18pt", "24pt", "30pt", "36pt", "48pt", "60pt" }); sizeCombo.setEditable(true); sizeCombo.setMinimumSize(new Dimension(65, 0)); sizeCombo.setPreferredSize(new Dimension(65, 0)); sizeCombo.setMaximumSize(new Dimension(65, 100)); add(sizeCombo); sizeCombo.addActionListener(new ActionListener() { /** * */ @Override public void actionPerformed(ActionEvent e) { mxGraph graph = editor.getGraphComponent().getGraph(); graph.setCellStyles(mxConstants.STYLE_FONTSIZE, sizeCombo .getSelectedItem().toString().replace("pt", "")); } }); addSeparator(); add(editor.bind("Bold", new FontStyleAction(true), "/com/mxgraph/examples/swing/images/bold.gif")); add(editor.bind("Italic", new FontStyleAction(false), "/com/mxgraph/examples/swing/images/italic.gif")); addSeparator(); add(editor.bind("Left", new KeyValueAction(mxConstants.STYLE_ALIGN, mxConstants.ALIGN_LEFT), "/com/mxgraph/examples/swing/images/left.gif")); add(editor.bind("Center", new KeyValueAction(mxConstants.STYLE_ALIGN, mxConstants.ALIGN_CENTER), "/com/mxgraph/examples/swing/images/center.gif")); add(editor.bind("Right", new KeyValueAction(mxConstants.STYLE_ALIGN, mxConstants.ALIGN_RIGHT), "/com/mxgraph/examples/swing/images/right.gif")); addSeparator(); add(editor.bind("Font", new ColorAction("Font", mxConstants.STYLE_FONTCOLOR), "/com/mxgraph/examples/swing/images/fontcolor.gif")); add(editor.bind("Stroke", new ColorAction("Stroke", mxConstants.STYLE_STROKECOLOR), "/com/mxgraph/examples/swing/images/linecolor.gif")); add(editor.bind("Fill", new ColorAction("Fill", mxConstants.STYLE_FILLCOLOR), "/com/mxgraph/examples/swing/images/fillcolor.gif")); addSeparator(); final mxGraphView view = editor.getGraphComponent().getGraph() .getView(); final JComboBox zoomCombo = new JComboBox(new Object[] { "400%", "200%", "150%", "100%", "75%", "50%", mxResources.get("page"), mxResources.get("width"), mxResources.get("actualSize") }); zoomCombo.setEditable(true); zoomCombo.setMinimumSize(new Dimension(75, 0)); zoomCombo.setPreferredSize(new Dimension(75, 0)); zoomCombo.setMaximumSize(new Dimension(75, 100)); zoomCombo.setMaximumRowCount(9); add(zoomCombo); // Sets the zoom in the zoom combo the current value mxIEventListener scaleTracker = new mxIEventListener() { /** * */ @Override public void invoke(Object sender, mxEventObject evt) { ignoreZoomChange = true; try { zoomCombo.setSelectedItem((int) Math.round(100 * view .getScale()) + "%"); } finally { ignoreZoomChange = false; } } }; // Installs the scale tracker to update the value in the combo box // if the zoom is changed from outside the combo box view.getGraph().getView().addListener(mxEvent.SCALE, scaleTracker); view.getGraph().getView().addListener(mxEvent.SCALE_AND_TRANSLATE, scaleTracker); // Invokes once to sync with the actual zoom value scaleTracker.invoke(null, null); zoomCombo.addActionListener(new ActionListener() { /** * */ @Override public void actionPerformed(ActionEvent e) { mxGraphComponent graphComponent = editor.getGraphComponent(); // Zoomcombo is changed when the scale is changed in the diagram // but the change is ignored here if (!ignoreZoomChange) { String zoom = zoomCombo.getSelectedItem().toString(); if (zoom.equals(mxResources.get("page"))) { graphComponent.setPageVisible(true); graphComponent .setZoomPolicy(mxGraphComponent.ZOOM_POLICY_PAGE); } else if (zoom.equals(mxResources.get("width"))) { graphComponent.setPageVisible(true); graphComponent .setZoomPolicy(mxGraphComponent.ZOOM_POLICY_WIDTH); } else if (zoom.equals(mxResources.get("actualSize"))) { graphComponent.zoomActual(); } else { try { zoom = zoom.replace("%", ""); double scale = Math.min(16, Math.max(0.01, Double.parseDouble(zoom) / 100)); graphComponent.zoomTo(scale, graphComponent .isCenterZoom()); } catch (Exception ex) { JOptionPane.showMessageDialog(editor, ex .getMessage()); } } } } }); }
7
public CijferOverzichtPanel() { setLayout(new BorderLayout(0, 0)); JList list = new JList(vakLijst); list.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { JList list = (JList) evt.getSource(); if (evt.getClickCount() == 1) { int index = list.locationToIndex(evt.getPoint()); if (index < vakLijst.size() && index >= 0) { Vak vak = vakLijst.get(index); double cijfer; if (Sessie.getIngelogdeGebruiker().isDocent() || Sessie.getIngelogdeGebruiker().isSuperUser()) { User student = (User) comboBox.getSelectedItem(); cijfer = Dao.getInstance() .getCijferVanStudentVanVak(vak.getId(), student.getId()); } else { cijfer = Dao.getInstance() .getCijferVanStudentVanVak( vak.getId(), Sessie.getIngelogdeGebruiker() .getId()); } cijferPanel.setVak(vak.getNaam()); cijferPanel.setCijfer("" + cijfer); cijferPanel.setDocent(vak.getDocent().getNaam()); } } } }); add(list, BorderLayout.WEST); list.setPreferredSize(new Dimension(250, 500)); cijferPanel = new CijferPanel(); add(cijferPanel, BorderLayout.CENTER); if (Sessie.getIngelogdeGebruiker().heeftPermissie( PermissieHelper.permissies.get("INZIENEIGENSTUDENTEN")) || Sessie.getIngelogdeGebruiker().heeftPermissie( PermissieHelper.permissies.get("INZIENALLESTUDENTEN"))) { comboBox = new JComboBox(); comboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (comboBox.getSelectedItem() instanceof User) { User student = (User) comboBox.getSelectedItem(); vakLijst.clear(); List<Vak> vakken = Dao.getInstance() .getVakkenVanStudent(student.getId()); for (Vak vak : vakken) { vakLijst.addElement(vak); } cijferPanel.clear(); } else { vakLijst.clear(); cijferPanel.clear(); } } }); add(comboBox, BorderLayout.NORTH); } refreshPanel(); }
9
public void actionPerformed(ActionEvent e) { String[] cmd = e.getActionCommand().split(" "); switch (cmd[0]) { // lexically listed case "Accept": gui.acceptAnswer(); break; case "Dictionary": (new Dictionary()).run(); break; case "Exit": System.exit(0); break; case "Game": gui.startGame(new Game(cmd[1])); break; case "Menu": gui.returnToMenu(); break; case "New": gui.restartGame(new Game(cmd[1])); break; case "Next": gui.nextQuestion(); break; case "Previous": gui.previousQuestion(); break; case "Word": gui.addWordToInput(cmd[1]); break; default: System.out.println("Error: ActionEvent \'" + cmd[0] + "\' not catered for."); break; } }
9
private int search(TreeNode root, String query, int d, int length){ if(root == null) return length; if(root.value != null) length = d; if(d == query.length()) return length; char c = query.charAt(d); return search(root.next[c], query, d + 1, length); }
3
public boolean playSpecialTile(String name, Location loc){ Player p = getPlayer(name); if(!p.equals(getCurrentPlayer())){ return false;//not your turn! } if(!gameBoard.isValidLocation(loc) || gameBoard.hasTile(loc) || loc.getTile() == null || !(loc.getTile() instanceof SpecialTile)){ return false; } if(p.removeSpecialTile(loc.getTile())){ gameBoard.setSpecialTile(loc); return true; } return false; }
6
private void addInsideCurve(int end, int newRadius) { if (restricted.isSelected()) { int sectionBeginning = road.sectionBeginning(); road.addInsideCurve(end, false, newRadius); if (sectionLongerThanSmax(end, sectionBeginning)) return; } else { road.addInsideCurve(end, true, newRadius); } }
2
private void insertRec(TreeNode preNode, TreeNode node) { if(preNode.val > node.val){ if(preNode.left == null) preNode.left = node; else insertRec(preNode.left,node); }else{ if(preNode.right == null) preNode.right = node; else insertRec(preNode.right,node); } }
3
@Override public int getMetricInternal() { int add = EflUtil.runToAddressLimit(0, 0, 10, curGb.pokemon.owPlayerInputCheckAAddress); // after IsSpriteOrSignInFrontOfPlayer call if(add == 0) { System.out.println("OverworldInteract: IsSpriteOrSignInFrontOfPlayer call not found"); return 0; } int id = curGb.readMemory(curGb.pokemon.owInteractionTargetAddress); // text ID of entity talked to if(textID != -1 && textID != id) { System.out.println("WARNING: text ID "+id+" does not match expected ID "+textID); return 0; } add = EflUtil.runToAddressLimit(0, 0, 10, curGb.pokemon.owInteractionSuccessfulAddress, curGb.pokemon.owLoopAddress); // before DisplayTextID call if(add != curGb.pokemon.owInteractionSuccessfulAddress) { System.out.println("ERROR: talking to "+textID+" failed"); return 0; } return 1; }
4
public void paintComponent(Graphics g){ super.paintComponent(g); this.g=g; for (int i=0; i<model.getAssociationList().size(); i++){ drawAssociation(i,g); } for (int i=0; i<model.objectsListSize(); i++){ int positionX=model.getObjectUmlAtIndex(i).getX(); int positionY=model.getObjectUmlAtIndex(i).getY(); ObjectUML obj = model.getObjectUmlAtIndex(i); //Choose the color according to the type of the object Color color=new Color(228,228,228); TypeObject typeObj = model.getObjectUmlAtIndex(i).getObjectType(); if (typeObj==TypeObject.CLASS) color =new Color(228,228,228); else if (typeObj==TypeObject.INTERFACE) color = new Color(183,229,255); else if (typeObj==TypeObject.ABSTRACT_CLASS) color = new Color(255,183,183); g.setColor(color); g.fillRect(positionX, positionY, maxLength(i, g)+40, 30); //Draw square grey on the left top g.setColor(Color.GRAY); g.fillRect(positionX, positionY, 10, 10); g.setColor(Color.BLACK); g.drawRect(positionX, positionY, 10, 10); //Draw square grey on the right top (quit zone) g.setColor(Color.RED); g.fillRect(positionX+maxLength(i, g)+30, positionY, 10, 10); g.setColor(Color.BLACK); g.drawRect(positionX+maxLength(i, g)+30, positionY, 10, 10); g.drawString("x", positionX+maxLength(i, g)+32, positionY+9); g.setColor(Color.BLACK); g.drawRect(positionX, positionY,maxLength(i, g)+40 , 30); //Warning => The position in the method is the point in the left bottom of the text if (model.getNameSelected()==i) g.setColor(Color.RED); else g.setColor(Color.BLACK); g.drawString(obj.getName(), positionX+20, positionY+20); //Write if the class if abstract or a interface g.setColor(Color.BLACK); if (obj.getObjectType()==TypeObject.INTERFACE){ g.drawString("<<Interface>>", positionX+10, positionY -5); } else if(obj.getObjectType()==TypeObject.ABSTRACT_CLASS){ g.drawString("Abstract", positionX+20, positionY-5); } positionY=positionY+30; positionY=drawAttribute(obj, i, g, color, positionX,positionY); positionY=drawMethod(obj, i, g, color, positionX, positionY); } }
8
public void handleEntityDamageByEntity(EntityDamageByEntityEvent e) { if(!isStarted) { e.setCancelled(true); return; } Snowball s = (Snowball)e.getDamager(); Player player = (Player)e.getEntity(); Player shooter = (Player)s.getShooter(); World w = s.getWorld(); if(!mm.hasPlayer(player.getName()) || !mm.hasPlayer(shooter.getName())) { return; } if(player.getName().equals(shooter.getName())) { e.setCancelled(true); return; } DodgeballPlayer mp = mm.getMinigamePlayer(player.getName()); DodgeballPlayer ms = mm.getMinigamePlayer(shooter.getName()); if(mp.getTeam() == ms.getTeam()) { e.setCancelled(true); return; } //Location itemPos = player.getLocation(); //w.dropItemNaturally(itemPos.add(0, 1, 0), new ItemStack(Material.SNOW_BALL, 1));//item is dropped onProjectileHitEvent s.remove(); setPlayerAtRandomLocation(player); --mp.health; mp.update(mm, getPlayerTeamArea(mp), SPECTATE_AREA, player.getLocation()); }
5
private void flattenAppend(Object value) { if(value==null) return; if(value instanceof Object[]) { for( Object o : (Object[])value) flattenAppend(o); } else if(value instanceof Collection<?>) { for( Object o : (Collection<?>)value) flattenAppend(o); } else super.add(value); }
7
public void start(){ timer.start(); downloadThread = new Thread(new Runnable() { @Override public void run() { BufferedInputStream in = null; FileOutputStream fout = null; long downloaded = 0; for(FileDownloadItem info : items){ try { if(!info.getSaveFile().getParentFile().exists()) info.getSaveFile().getParentFile().mkdirs(); URLConnection connection = info.getDownloadUrl().openConnection(); in = new BufferedInputStream(connection.getInputStream()); fout = new FileOutputStream(info.getSaveFile()); byte data[] = new byte[1024]; int count; while ((count = in.read(data, 0, 1024)) != -1) { fout.write(data, 0, count); downloaded += count; onDownload(new FileDownloadEvent(info.getSaveFile(), info.getDownloadUrl(), connection.getContentLengthLong(), downloaded, false, false, FileDownloader.this)); } } catch (IOException e) { e.printStackTrace(); } finally { try{ if (in != null) in.close(); if (fout != null) fout.close(); downloaded = 0; }catch (Exception e) { // TODO: handle exception } } } timer.stop(); onComplete(new ActionEvent(FileDownloader.this, 0, "")); } }); downloadThread.start(); }
7
public static double max(double[] vals) { double max = vals[0]; for (double v : vals) { if (v > max) { max = v; } } return max; }
2
public void testClearTarget() { out.println("clearTarget"); final int MAXEXP = 5; final int STEPS = 10; instance = new TabuIndex(MAXEXP); String[] tgts = new String[MAXEXP]; String[] srcs = new String[MAXEXP]; for (int i = 0; i < MAXEXP; ++i) { srcs[i] = i + "_src"; tgts[i] = i + "_tgt"; } for (int i = 0; i < MAXEXP; ++i) { for (int j = 0; j < MAXEXP; ++j) { instance.setTabu(srcs[i], tgts[j], i); } } instance.clearTarget(tgts[0]); for (int step = 0; step < STEPS; ++step) { for (int i = 0; i < MAXEXP; ++i) { for (int j = 0; j < MAXEXP; ++j) { if (i < step || j == 0) { assertFalse(instance.isTabu(srcs[i], tgts[j])); } else { assertTrue(instance.isTabu(srcs[i], tgts[j])); } } } instance.step(); } }
8
@Override public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException { testLevel.Render(); for(int i = 0 ; i < this.fish.size() ; i++) { this.fish.get(i).render(g); } player.render(g); //GUI g.setColor(Color.black); g.drawString(("Fish eaten: " + this.player.getScore()), gc.getWidth() - 150, 20); g.drawString(("Health: " + this.player.getHealth()), gc.getWidth() - 150, 35); }
1
public static String makeSpace( int spaceCount, String word ) { int i = spaceCount - word.length(); String spaces = " "; while ( i > 0 ) { spaces = spaces.concat( " " ); i--; } return spaces; }
1
public List<RequestWrapper> getReferRequestWrappers() { return referRequestWrappers; }
0
public String addHost() { try { URL whatismyip = new URL("http://checkip.amazonaws.com/"); BufferedReader in = new BufferedReader(new InputStreamReader( whatismyip.openStream())); String ip = in.readLine(); //you get the IP as a String //System.out.println(ip); int an = JOptionPane.showConfirmDialog(connect, "Host the server through the internet?", "Server Type?", JOptionPane.YES_NO_OPTION); if (an!=0) { ip = InetAddress.getLocalHost().getHostAddress(); } String yes = JOptionPane.showInputDialog("Server Name?"); if (yes!=null) { serverName=yes.replaceAll("[^A-Za-z0-9\\s]","").replaceAll(" ", ""); CTD.addServer(serverName.length()>0?serverName:"SERVER", ip); return ip; } else { serverName="SERVER"; CTD.addServer(serverName.length()>0?serverName:"SERVER", ip); //ip = InetAddress.getLocalHost().getHostAddress(); } return "NO"; } catch (IOException | HeadlessException ex) { //Logger.getLogger(APPLET.class.getName()).log(Level.SEVERE, null, ex); return "localhost"; } }
5
public static void main(String args[]){ File fileForParse = new File("/home/desiresdesigner/ITMO/ИсследоваиеАлгоитмовПартионирования/3 HashMap/4del"); double sum = 0; double number = 0; try { BufferedReader in = new BufferedReader(new FileReader(fileForParse.getAbsoluteFile())); try { String s; sum = Integer.parseInt(in.readLine()); ++number; while ((s = in.readLine()) != null) { long newNum = Long.parseLong(s); double difference = Math.abs((sum + newNum)/(number+1) - sum/number); //double difference = ((sum + newNum)/(number+1)) / (sum/number); if (difference < 10000){ //if (difference < 2){ sum += newNum; ++number; } } } finally { in.close(); } } catch(IOException e) { throw new RuntimeException(e); } System.out.println((double)sum/number); }
3
public void processCommands() { try { if (!commands.isEmpty()) { while (step == false && index < commands.size()) { parseLine(commands.get(index)); index++; } if (index >= commands.size()) frame.postMessage("Drawing Complete. " + "No further drawing commands available.\n"); } } catch (ParseException e) { frame.postMessage("Parse Exception: " + e.getMessage() +"\n"); return; } catch (FileNotFoundException e) { frame.postMessage("FileNotFound Exception: " + e.getMessage() +"\n"); } }
6
public void setArea(String area) { Area = area; }
0
public int inserir(Livro l){ Connection conn = null; PreparedStatement pstm = null; int retorno = -1; try{ conn = ConnectionFactory.getConnection(); pstm = conn.prepareStatement(INSERT, Statement.RETURN_GENERATED_KEYS); pstm.setString(1, l.getTitulo()); pstm.setString(2, l.getSubtitulo()); pstm.setString(3, l.getPalavrasChave()); pstm.setDouble(4, l.getPreco()); pstm.setDouble(5, l.getRoyalty()); pstm.setString(6, l.getResumo()); pstm.setInt(7, l.getEdicao()); pstm.setDouble(8, l.getVolume()); pstm.setInt(9, l.getQtEstoque()); pstm.setInt(10, l.getIsbn()); pstm.setInt(11, l.getEditor().getId_editor()); pstm.setInt(12, l.getLoja().getId_loja()); pstm.setInt(13, l.getAutor().getId_autor()); pstm.execute(); try(ResultSet rs = pstm.getGeneratedKeys()){ if(rs.next()){ retorno = rs.getInt(1); } } }catch(Exception e){ JOptionPane.showMessageDialog(null,"Erro ao adicionar um cadastro "+ e); }finally{ try{ ConnectionFactory.closeConnection(conn, pstm); }catch (Exception e){ JOptionPane.showMessageDialog(null,"Erro ao desconectar com o banco " + e); } } return retorno; }
3
private String seekMatchingWords(String keywordWord, LinkedList<String> word, LinkedList<String> possibleWord) { for(int j = 0; j < word.size(); j++) { if(keywordWord.equals(word.get(j))) { return word.get(j); } } int shortestDistance = 3; String wordWithShortestDistance = ""; for(int j = 0; j < possibleWord.size(); j++) { Levenshtein levenshtein = new Levenshtein(keywordWord, possibleWord.get(j)); if(levenshtein.getDistance() < shortestDistance) { wordWithShortestDistance = possibleWord.get(j); } } return wordWithShortestDistance; }
4
public void readTable(Map table) { Identifier rep = getRepresentative(); if (!rep.wasAliased) { String newAlias = (String) table.get(getFullName()); if (newAlias != null) { rep.wasAliased = true; rep.setAlias(newAlias); } } for (Iterator i = getChilds(); i.hasNext();) ((Identifier) i.next()).readTable(table); }
3
public float distance(final float xp, final float yp) { final float xd = (xp < xpos) ? (xpos - xp) : ((xp > xmax) ? (xp - xmax) : 0), yd = (yp < ypos) ? (ypos - yp) : ((yp > ymax) ? (yp - ymax) : 0) ; return (float) Math.sqrt((xd * xd) + (yd * yd)) ; }
4
public String readUnicodeString() throws IOException { int off = 0; int len = readInt(); byte[] s = new byte[len]; while (off < len) { off += read(s, off, len - off); } String retval = new String(s, "UTF-8"); if (trace == API_TRACE_DETAILED) { debugNote("readUnicodeString: " + retval); } return retval; }
2
private boolean smashQuest(Quest q, int id){ if(q.getID() == 5 && q.isStarted()){ if(engine.getPlayer().getBounds().intersects(new Rectangle(320,244,96,96)) && engine.getPlayer().isAttacking()) { System.out.println("hej"); // conditions is fulfilled q.setNumberDone(100); q.updateStatus(); engine.getWorld().getCurrentMap().getBackTiles().get(211).setId(57); engine.getWorld().getCurrentMap().getBlockTiles().remove(60); return true; } } // not completed return false; }
4
public static String diceText(int id) { switch (id) { case 15086: return "a six-sided"; case 15088: return "two six-sided"; case 15090: return "an eight-sided"; case 15092: return "a ten-sided"; case 15094: return "a twelve-sided"; case 15096: return "a a twenty-sided"; case 15098: return "the percentile"; case 15100: return "a four-sided"; } return ""; }
8
public static User getLatest(Connection con) { User user = null; try { ResultSet result = con.createStatement().executeQuery( "SELECT ID FROM " + tableInfo.tableName + " ORDER BY LastLog DESC { LIMIT 1 }"); result.next(); user = new User(con, result.getString(1)); result.close(); } catch(SQLException sqle) { if (sqle.getSQLState().equals("42X05")) // table does not exist DBObject.createTable(con, tableInfo); } return user; }
2
public static boolean[][] trim( boolean[][] m ){ int minx = m.length; int miny = m[0].length; int maxx = 0; int maxy = 0; for (int x = 0; x < m.length; x++) { for (int y = 0; y < m[0].length; y++) { if( !m[x][y] ){ continue; } if( x < minx ) minx = x; if( y < miny ) miny = y; if( x > maxx ) maxx = x; if( y > maxy ) maxy = y; } } boolean[][] ret = init( maxx-minx+1, maxy-miny+1 ); for (int x = 0; x < ret.length; x++) { for (int y = 0; y < ret[0].length; y++) { ret[x][y] = m[minx+x][miny+y]; } } return ret; }
9
private static List<String> getFieldNameWithListDataType(){ List<String> result = new ArrayList<>(); //CompanyA, refer 1.1 Field[] fields2 = CompanyA.class.getDeclaredFields(); for(Field f : fields2){ // use equals to compare the data type. if(f.getType().equals(List.class)){ result.add(f.getName()); } } return result; }
2
public void checkCollisions() throws SlickException{ // loop all pickables for (Iterator<Pickable> iterator = pickables.iterator(); iterator.hasNext();) { Pickable p = iterator.next(); if (p.getBounds().intersects(player.getBounds())) { if(!p.value.equals("exit")){ level.destroyColors(p.value); Sounds.pup1.play(); iterator.remove(); } else{ if(pickables.size() < 2){ initLevel(++currentLevel); Sounds.exit.play(); iterator.remove(); } } } } // loop mobs and check if collide with player for (Iterator<Mob> iterator = mobs.iterator(); iterator.hasNext();) { Mob m = iterator.next(); if(m.getBounds().intersects(player.getBounds())){ Sounds.die.play(); player.alive = false; } } }
6
public SelectIterable(Iterable<T> source, Selector<T, TResult> selector) { this._source = source; this._selector = selector; }
0
public PriorityQueue<Node> makeChildren(){ PriorityQueue<Node> newChildren = new PriorityQueue<Node>(); Person p = currentPeople.get(0); // System.out.println("*********************Person: " + p.getName()); for(int i = 0; i < data.size(); i++){ if(p.getHeadsGroup() != null || p.getHeadsProject() != null || p.getManager()){ // only put heads into empty rooms if(data.get(i).getPerson1() == null){ Assignment a = new Assignment(data.get(i)); a.assertPerson(p); a.setHead(true); Node temp = new Node(a, data, currentPeople); temp.setParent(this); goodness(temp); newChildren.add(temp); } } else if(!data.get(i).isHead()&& data.get(i).getPerson2() == null && !data.get(i).isHead()){ //dont make child if head already in room Assignment a = new Assignment(data.get(i)); a.assertPerson(p); Node temp = new Node(a, data, currentPeople); temp.setParent(this); goodness(temp); newChildren.add(temp); } } children = newChildren; return newChildren; }
8
public String testStop(String appKey, String userKey, String testId) { try { appKey = URLEncoder.encode(appKey, "UTF-8"); userKey = URLEncoder.encode(userKey, "UTF-8"); testId = URLEncoder.encode(testId, "UTF-8"); } catch (UnsupportedEncodingException e) { BmLog.error(e); } return String.format("%s/api/rest/blazemeter/testStop/?app_key=%s&user_key=%s&test_id=%s", SERVER_URL, appKey, userKey, testId); }
1
static public byte[] decode(final String base32) { int i, index, lookup, offset, digit; byte[] bytes = new byte[base32.length() * 5 / 8]; for (i = 0, index = 0, offset = 0; i < base32.length(); i++) { lookup = base32.charAt(i) - '0'; /* Skip chars outside the lookup table */ if (lookup < 0 || lookup >= base32Lookup.length) { continue; } digit = base32Lookup[lookup]; /* If this digit is not in the table, ignore it */ if (digit == 0xFF) { continue; } if (index <= 3) { index = (index + 5) % 8; if (index == 0) { bytes[offset] |= digit; offset++; if (offset >= bytes.length) break; } else { bytes[offset] |= digit << (8 - index); } } else { index = (index + 5) % 8; bytes[offset] |= (digit >>> index); offset++; if (offset >= bytes.length) { break; } bytes[offset] |= digit << (8 - index); } } return bytes; }
8
public static Reference getReference(String className, String name, String type) { int hash = className.hashCode() ^ name.hashCode() ^ type.hashCode(); Iterator iter = unifier.iterateHashCode(hash); while (iter.hasNext()) { Reference ref = (Reference) iter.next(); if (ref.clazz.equals(className) && ref.name.equals(name) && ref.type.equals(type)) return ref; } Reference ref = new Reference(className, name, type); unifier.put(hash, ref); return ref; }
4
public void findMinimumVertexCover() { for(int i=1;i<=leftVertices;i++) { if(Pair[i]!=0) //Vertices part of matching { ArrayList<Integer> adjacencyList = biGraph.getOutEdges(i); for(int n : adjacencyList) { if(rightFreeVertices.contains(n)) { leftVertexCoverVertices.add(i); break; } else // In both cases we are adding because any one side can be added to vertex cover list { leftVertexCoverVertices.add(i); } } //System.out.println("Left : "+(i)+" "+(Pair[i]-leftVertices)); } } System.out.println(); for(int j=leftVertices+1;j<Pair.length;j++) { if(Pair[j]!=0) { ArrayList<Integer> adjacencyList = biGraph.getOutEdges(j); for(int n : adjacencyList) { if(leftFreeVertices.contains(n)) { rightVertexCoverVertices.add(j); break; } } //if(!rightVertexCoverVertices.contains(j)) //rightVertexCoverVertices.add(j); //System.out.println("Right : "+(j-leftVertices)+" "+Pair[j]); } } }
8
public Account(double intitialBalance) { if (intitialBalance > 0) balance = intitialBalance; }
1
@SuppressWarnings("unused") private ArrayList<String> getSimilarLengthResults(String first, int diff) { // Sanity checks if (first == null) return new ArrayList<String>(); if (overkill == null || overkill.isEmpty()) return new ArrayList<String>(); ArrayList<String> sls = new ArrayList<String>(); int strLen = first.length(); for (String candidateXML : this.overkill) { if (candidateXML != null) { String candidate = getGeonamesName(candidateXML); if (candidate != null && candidate.length() <= strLen + diff && candidate.length() >= strLen - diff) { sls.add(candidateXML); } } } return sls; }
8
public void renderColorFont(Image i, int xp, int yp, int tileId, int tileWidth, int color) { xp -= xOff; yp -= yOff; int tw = i.getWidth() / tileWidth; int xt = tileId % tw; int yt = tileId / tw; int tileOffset = xt * tileWidth + yt * tileWidth * i.width; for (int y = 0; y < tileWidth; y++) { if ((y + yp) < 0 || (y + yp) >= height) continue; for(int x = 0; x < tileWidth; x++) { if ((x + xp) < 0 || (x + xp) >= width) continue; int c = i.pixels[x + (y * i.width) + tileOffset]; if(c == 0xffffff) { c = color; } if(c == 0x7f007f) continue; pixels[(x + xp) + (y + yp) * width] = c; } } }
8
@Override public boolean execute(RuleExecutorParam param) { Rule rule = param.getRule(); List<String> values = Util.getValue(param, rule); if (values == null || values.isEmpty()) { return false; } boolean retValue = true; for (String value : values) { String compareValue = rule.getValue(); if (rule.isIgnoreCase()) { value = value.toUpperCase(); compareValue = compareValue.toUpperCase(); } String[] valuesIn = compareValue.split(","); List<String> valuesLis = Arrays.asList(valuesIn); boolean intRetValue = valuesLis.contains(value); if (Operators.NotIn.getValue().equals(rule.getOper())) { intRetValue = !intRetValue; } retValue = retValue && intRetValue; } return retValue; }
6
public boolean contains(int x, int y) { return x >= 0 && y >= 0 && x < bounds.width && y < bounds.height; }
3
@Override public boolean inputUp(float x, float y) { if (enabled && visible && getBounds().contains(x, y)) { if (callback != null) callback.onButtonEvent(this, DynamicButtonCallback.UP); return true; } return false; }
4
public Sprite getSpriteCollision(Ship ship) { // run through the list of Sprites LinkedList <Sprite> sprites = map.getSprites(); for (int i = 0; i < sprites.size(); i++) { Sprite otherSprite = (Sprite)sprites.get(i); if (isCollision(ship, otherSprite)) { // collision found, return the Sprite return otherSprite; } } // no collision found return null; }
2
public static Skolem nthRestComputation(Skolem list, IntegerWrapper narg) { if (!(Logic.enumeratedListP(list))) { return (null); } { int n = narg.wrapperValue; Vector elements = list.definingProposition.arguments; int nelements = elements.length() - 1; List restelements = List.newList(); if (n < 0) { n = nelements + n; } if ((n < 0) || (n > nelements)) { return (null); } { int i = Stella.NULL_INTEGER; int iter000 = n; int upperBound000 = nelements - 1; Cons collect000 = null; for (;iter000 <= upperBound000; iter000 = iter000 + 1) { i = iter000; if (collect000 == null) { { collect000 = Cons.cons((elements.theArray)[i], Stella.NIL); if (restelements.theConsList == Stella.NIL) { restelements.theConsList = collect000; } else { Cons.addConsToEndOfConsList(restelements.theConsList, collect000); } } } else { { collect000.rest = Cons.cons((elements.theArray)[i], Stella.NIL); collect000 = collect000.rest; } } } } return (Logic.createLogicalList(restelements)); } }
7
static void testInput() { // otetaan sata ensimmaista, jarjestetaan characterClassin // mukaan, ja piirretaan iso kuva, josta voi tarkistaa, etta // samat numeroa esittavat kuvat tulevat perakkain. Vector<Image> I100 = new Vector<Image>(); for (int i = 0; i < 100; ++i) { I100.addElement(I.elementAt(i)); } Collections.sort(I100); BufferedImage bi = new BufferedImage(28 * 100, 28, BufferedImage.TYPE_3BYTE_BGR); for (int i = 0; i < 100; ++i) { for (int y = 0; y < 28; ++y) { for (int x = 0; x < 28; ++x) { int ind = y * 28 + x; bi.setRGB(x + i * 28, y, (I100.elementAt(i).vec[ind] > 0.5 ? 0 : 0xffffff)); } } } try { ImageIO.write(bi, "BMP", new File("test100.bmp")); } catch (Exception e) { e.printStackTrace(); } }
6
@SuppressWarnings("unchecked") public boolean removePhoto(String filename, String album) { if (GuiView.control.getCurrentUser().getAlbumList().get(album).getPhotoList().containsKey(filename)) { Iterator it = GuiView.control.getCurrentUser().getAlbumList().entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Album> pairs = (Map.Entry<String, Album>) it.next(); if (pairs.getValue().getPhotoList().containsKey(filename)) pairs.getValue().getPhotoList().get(filename).removeAlbum(album); } GuiView.control.getCurrentUser().getAlbumList().get(album).deletePhoto(filename); return true; } else{ return false; } }
3
public static List<ImageBit> cover(ImageBit ib, ImageBit[][] list, int blockWidth, int blockHeight, BlockType blockType) { // TODO Auto-generated method stub int baseX = ib.getX(); int baseY = ib.getY(); List<ImageBit> coverBits = new LinkedList<ImageBit>(); for (int i = 0; i < blockWidth; i++) { // FIXME if ((i + baseX) > 49) { return null; } for (int j = 0; j < blockHeight; j++) { // FIXME if ((j + baseY) > 49) { return null; } if(list[baseX + i][baseY + j].isCovered()){ return null; } if (list[baseX + i][baseY + j].getRGB() == ib.getRGB()) { coverBits.add(list[baseX + i][baseY + j]); } else { return null; } } } // FIXME if (!coverBits.isEmpty()) { for (ImageBit imageBit : coverBits) { imageBit.setCovered(true); imageBit.setBlockType(blockType); // TODO set lego type,size and sequence and save the lego list. } } return coverBits; }
8