text
stringlengths
14
410k
label
int32
0
9
public Binding getTypeOrPackage(char[] name, int mask) { Binding typeBinding = getBinding0(name, mask); // if (typeBinding != null && typeBinding != LookupEnvironment.TheNotFoundType) { // typeBinding = BinaryTypeBinding.resolveType(typeBinding, environment, false); // no raw conversion for now // if (typeBinding.isNestedType()) // return new ProblemReferenceBinding(name, typeBinding, ProblemReasons.InternalNameProvided); // return typeBinding; // } if (typeBinding!=null) return typeBinding; PackageBinding packageBinding = getPackage0(name); if (packageBinding != null) return packageBinding; if (typeBinding == null && mask!=Binding.PACKAGE) { // have not looked for it before if ((typeBinding = environment.askForBinding(this, name,mask)) != null) { // if (typeBinding.isNestedType()) // return new ProblemReferenceBinding(name, typeBinding, ProblemReasons.InternalNameProvided); return typeBinding; } // Since name could not be found, add a problem binding // to the collections so it will be reported as an error next time. addNotFoundBinding(name, mask); } if (packageBinding == null) { // have not looked for it before if ((packageBinding = findPackage(name)) != null) return packageBinding; } return null; }
7
private void mapChangesAndTheirStats() { overallMarketChange = (int) (100 * ((Database.SUM_MARKET_PRICE_DATA .lastEntry().getValue()[6]) - Database.SUM_MARKET_PRICE_DATA .ceilingEntry(15800f).getValue()[6]) / (Database.SUM_MARKET_PRICE_DATA .ceilingEntry(15800f).getValue()[6])); for (Entry<String, TreeMap<Float, float[]>> ent : TECHNICAL_PRICE_DATA .entrySet()) { TreeMap<Float, float[]> technicals = ent.getValue(); int individualOverallChange = (int) (100 * ((technicals.lastEntry() .getValue()[6] - technicals.firstEntry().getValue()[6]) / (technicals .firstEntry().getValue()[6]))); INDIVIDUAL_OVERALL_CHANGES.put(ent.getKey(), (float) individualOverallChange); } changesStats = new StatInfo(new ArrayList<Float>( INDIVIDUAL_OVERALL_CHANGES.values())); }
1
@Override public void changedMostRecentDocumentTouched(DocumentRepositoryEvent e) { if (e.getDocument() == null) { setEnabled(false); } else { setEnabled(true); } }
1
protected void addOwnUnits() { reportPanel.add(localizedLabel(StringTemplate.template("report.military.forces") .addStringTemplate("%nation%", player.getNationName())), "newline, span, split 2"); reportPanel.add(new JSeparator(JSeparator.HORIZONTAL), "growx"); List<AbstractUnit> units = new ArrayList<AbstractUnit>(); List<AbstractUnit> scoutUnits = new ArrayList<AbstractUnit>(); List<AbstractUnit> dragoonUnits = new ArrayList<AbstractUnit>(); List<AbstractUnit> soldierUnits = new ArrayList<AbstractUnit>(); for (UnitType unitType : getSpecification().getUnitTypeList()) { if (unitType.isAvailableTo(player) && !unitType.hasAbility(Ability.NAVAL_UNIT) && (unitType.hasAbility(Ability.EXPERT_SOLDIER) || unitType.getOffence() > 0)) { if (unitType.hasAbility("model.ability.canBeEquipped")) { scoutUnits.add(new AbstractUnit(unitType, Role.SCOUT, getCount("scouts", unitType))); dragoonUnits.add(new AbstractUnit(unitType, Role.DRAGOON, getCount("dragoons", unitType))); soldierUnits.add(new AbstractUnit(unitType, Role.SOLDIER, getCount("soldiers", unitType))); } else { units.add(new AbstractUnit(unitType, Role.DEFAULT, getCount("others", unitType))); } } } UnitType defaultType = getSpecification().getDefaultUnitType(); dragoonUnits.add(new AbstractUnit(defaultType, Role.DRAGOON, getCount("dragoons", defaultType))); soldierUnits.add(new AbstractUnit(defaultType, Role.SOLDIER, getCount("soldiers", defaultType))); scoutUnits.add(new AbstractUnit(defaultType, Role.SCOUT, getCount("scouts", defaultType))); units.addAll(dragoonUnits); units.addAll(soldierUnits); units.addAll(scoutUnits); for (AbstractUnit unit : units) { reportPanel.add(createUnitTypeLabel(unit), "sg"); } }
7
private clsPersona asignarValoresContacto(){ clsPersona p = new clsPersona(); p.setCodigo(Integer.parseInt(txtCodigo.getText())); p.setNombre(txtNombre.getText()); p.setTelefonoFijo(txtTelefonoFijo.getText()); p.setCelular(txtCelular.getText()); p.setEmail(txtEmail.getText()); if(rbFemenina.isSelected()) { p.setSexo('F'); }else{ p.setSexo('M'); } p.setDia(spinnerDia.getValue().toString()); p.setMes(spinnerMes.getValue().toString()); p.setAnio(spinnerAnio.getValue().toString()); p.setTipoPersona(cmbTipoPersona.getSelectedItem().toString()); if(rbActivo.isSelected()) { p.setEstado('A'); }else{ p.setEstado('I'); } return p; }
2
public String getCiudad() { return ciudad; }
0
public boolean compEntity(EntityType entity, Player play, String sAction, ArrayList<PaymentCache> aPayer) { HashMap<String, ArrayList<EntityType>> hType = _jobsdata.getEntHash(); if(hType.isEmpty()) return false; for (Map.Entry<String, ArrayList<EntityType>> e : hType.entrySet()) { String tier = e.getKey(); ArrayList<EntityType> et = e.getValue(); if(!tier.startsWith(sAction) || et.isEmpty()) continue; if(!et.contains(entity)) continue; PaymentCache payment = new PaymentCache(play, _jobsdata.getTierPays().get(sAction + ".pays"), getInteger(tier.substring(tier.length()-1)), _jobsdata.getBasePay(), _jobsdata.getName().toLowerCase()); aPayer.add(payment); return true; } return false; }
5
private boolean determineCommand(String line) { try { if ((line == null) || (line.trim().equals(""))) { return false; } if (line.startsWith("[SPLINTER_IMPLANT]")) { this.myIMPLANT_ID = 2; try { this.myImplantName = Driver.ARR_IMPLANT_NAME[this.myIMPLANT_ID]; } catch (Exception e) { this.myImplantName = "UNKNOWN"; } Driver.sop("-->>>> Ooooohhh Joy! Looks like we have a " + this.myImplantName + " connected! -->>>> confidence: 100%. Setting up the environment to handle this type of implant"); try { line = line.replace("[SPLINTER_IMPLANT]", ""); } catch (Exception localException1) { } String[] arrAgent = line.split("%%%%%"); this.myImplantInitialLaunchDirectory = arrAgent[0]; this.myHostName = arrAgent[1]; this.myOS = arrAgent[2]; this.myOS_Type = arrAgent[3]; this.myUserName = arrAgent[4]; this.myUserDomain = arrAgent[5]; this.myTempPath = arrAgent[6]; this.myUserProfile = arrAgent[7]; this.myProcessorArchitecture = arrAgent[8]; this.myNumberOfProcessors = arrAgent[9]; this.mySystemRoot = arrAgent[10]; this.myServicePack = arrAgent[11]; this.myNumberOfUsers = arrAgent[12]; this.mySerialNumber = arrAgent[13]; this.myOS_Architecture = arrAgent[14]; this.myCountryCode = arrAgent[15]; this.myVersionNumber = arrAgent[16]; this.myHomeDrive = arrAgent[17]; this.myRandomIdentifier = Driver.getUniqueRandomNumber(); this.myUniqueDelimiter = ("[SPLINTER_IMPLANT@" + this.myRandomIdentifier + "]"); sendCommand_RAW_ToAgent(""+this.myRandomIdentifier); sendCommand_RAW_ToAgent("[SPLINTER_IMPLANT]%%%%%[RELAY_NOTIFICATION_YOU_ARE_CONNECTED_TO_RELAY]"); return true; } if (line.startsWith(this.myUniqueDelimiter)) { return false; } return false; } catch (Exception e) { Driver.eop("determineCommand", this.strMyClassName, e, e.getLocalizedMessage(), false); Driver.sop("Geez!!!! Missed it by that much. Authentication failed for this implant... invalid parameters passed in"); this.myIMPLANT_ID = 0; try { this.myImplantName = Driver.ARR_IMPLANT_NAME[this.myIMPLANT_ID]; } catch (Exception ee) { this.myImplantName = "UNKNOWN"; } } return false; }
8
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed // TODO add your handling code here: // get a file path from the user programmerThread.stop(); hidePanels(lastPane); JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle("Please Specify the File To Open"); File fileToOpen; BufferedReader readIn; String newMap = new String(); int userSelection = userSelection = fileChooser.showOpenDialog(fileChooser); if (userSelection == JFileChooser.APPROVE_OPTION) { try { fileToOpen = fileChooser.getSelectedFile(); readIn = new BufferedReader(new FileReader(fileToOpen)); while(readIn.ready()) { newMap += readIn.readLine(); newMap += '\n'; } } catch (FileNotFoundException ex) { Logger.getLogger(Karel.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Karel.class.getName()).log(Level.SEVERE, null, ex); } //file is now in newMap string, turn string into actual new map! world.setLevelString(newMap); world.worldDeleter(); world.initWorld(); //paint this.repaint(); } }//GEN-LAST:event_jMenuItem2ActionPerformed
4
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (args.length == 0) { if (player == null) { sender.sendMessage(ChatColor.RED+"This command can only be run by a player"); return true; } player.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, 1200, 2)); sender.sendMessage(ChatColor.GOLD + "* " + ChatColor.WHITE + "You have been given Regeneration for " + ChatColor.GREEN + "1" + ChatColor.WHITE + " minute"); return true; } else if (args.length == 1) { Player target = Bukkit.getPlayer(args[0]); if (target == null) { sender.sendMessage(ChatColor.RED + args[0] + " is not online"); return true; } target.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, 1200, 2)); sender.sendMessage(ChatColor.GREEN + "" + target.getDisplayName() + ChatColor.WHITE + " has been given Regeneration for " + ChatColor.GREEN + "1" + ChatColor.WHITE + " minute"); target.sendMessage(ChatColor.GOLD + "* " + ChatColor.WHITE + "You have been given Regeneration for " + ChatColor.GREEN + "1" + ChatColor.WHITE + " minute"); return true; } else if (args.length == 2 && player == null || player.hasPermission("simpleextras.regeneration.other")) { Player target = Bukkit.getPlayer(args[0]); // CHECK IF TARGET EXISTS if (target == null) { sender.sendMessage(ChatColor.RED + args[0] + " is not online"); return true; } String min = args[1]; int mintemp = Integer.parseInt( min ); int mins = 1200 * mintemp; target.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, mins, 2)); sender.sendMessage(ChatColor.GREEN + "" + target.getDisplayName() + ChatColor.WHITE + " has been given Regeneration for " + ChatColor.GREEN + min + ChatColor.WHITE + " minutes"); target.sendMessage(ChatColor.GOLD + "* " + ChatColor.WHITE + "You have been given Regeneration for " + ChatColor.GREEN + min + ChatColor.WHITE + " minutes"); return true; } return true; }
9
private boolean Invalid(char h){ /*update the record*/ boolean invalid=false; // System.out.println("This pkg type is: "+h); if((Character.getNumericValue(h)-1)<1 || (Character.getNumericValue(h)-1)>5){ invalid =true; }else{ statusCodeRecord[Character.getNumericValue(h)-1]++; if(h=='1' || h=='4' || h=='5') invalid =true; } return invalid; }
5
public void paintComponent(Graphics g){ super.paintComponent(g); if(client.shouldQuit()) quit(); if(game.hasStarted() && !quit){ preview.setShouldPaint(false); if(game.shouldRepaint()) game.paint(background.createGraphics()); g.drawImage(background, 0, 0, getWidth(), height, null); new SwingDelayedRepainter(this, 50); } else{ g.setFont(SUIComponent.normal); g.setColor(SUIComponent.focused); String s = msg == null ? client.getMessage() : msg; g.drawString(s, getWidth()/2-g.getFontMetrics().stringWidth(s)/2, 7*getHeight()/8); repaint(50); } if(preview != null) preview.setMap(game.getMap()); }
6
private String[] getRelatedSetting(String tagName) { String[] vals = null; try { NodeList nodeList = m_root.getElementsByTagName( "Related" ); if ( nodeList == null ) { return null; } int len = nodeList.getLength(); vals = new String[len]; for ( int i = 0; i < len; i++ ) { Element child = (Element)nodeList.item(i); NodeList childNodeList = child.getElementsByTagName( tagName ); Element child2 = (Element)childNodeList.item(0); vals[i] = ""; if ( child2 == null ) { continue; } Node node = child2.getFirstChild(); if ( node == null ) { continue; } String val = node.getNodeValue(); if ( val != null ) { vals[i] = val; } } } catch ( Exception e ) { e.printStackTrace(); } return vals; }
6
public Marquee() { setDefaultCloseOperation(EXIT_ON_CLOSE); setPreferredSize(new Dimension(350, 200)); setSize(new Dimension(350, 200)); getContentPane().setBackground(Color.black); scroller = new MyScroller(); getContentPane().add(scroller); pack(); setVisible(true); new Timer(1000, this).start(); }
0
public void run() { while( true ) { System.out.println(TetrisTimer.abc); TetrisTimer.abc++; try { sleep(1000); } catch (InterruptedException e) { System.out.println(getName() + " interrupted."); } } }
2
private OutputStream getCorrectOutputStream(int optionalPresizing) throws IOException { if (isCached) { // create the tmp file if not initiated. if (tempFile == null) { createTempFile(); } // create the new file stream if (fileOutputStream == null) { fileOutputStream = new FileOutputStream(tempFile.getAbsolutePath(), true); } return fileOutputStream; } else { // create the byte array if not initiated if (byteArrayOutputStream == null) { byteArrayOutputStream = new ByteArrayOutputStream(optionalPresizing); } return byteArrayOutputStream; } }
4
private static boolean method518(char c) { return c < 'a' || c > 'z' || c == 'v' || c == 'x' || c == 'j' || c == 'q' || c == 'z'; }
6
private void readRemaining(int flag, int bits) throws EncodingException, NotImplementedException { // For forwards compatibility, read in any other flagged objects to // preserve the integrity of the input stream... if ((flag >> bits) != 0) { for (int o = bits; o < 6; o++) { if (((flag >> o) & 1) != 0) decode(); } } }
3
public void startPower() { System.out.println("模板共性,开启电源"); }
0
public static double sinh(double x) { boolean negate = false; if (x != x) { return x; } if (x > 20.0) { return exp(x)/2.0; } if (x < -20) { return -exp(-x)/2.0; } if (x == 0) { return x; } if (x < 0.0) { x = -x; negate = true; } double result; if (x > 0.25) { double hiPrec[] = new double[2]; exp(x, 0.0, hiPrec); double ya = hiPrec[0] + hiPrec[1]; double yb = -(ya - hiPrec[0] - hiPrec[1]); double temp = ya * HEX_40000000; double yaa = ya + temp - temp; double yab = ya - yaa; // recip = 1/y double recip = 1.0/ya; temp = recip * HEX_40000000; double recipa = recip + temp - temp; double recipb = recip - recipa; // Correct for rounding in division recipb += (1.0 - yaa*recipa - yaa*recipb - yab*recipa - yab*recipb) * recip; // Account for yb recipb += -yb * recip * recip; recipa = -recipa; recipb = -recipb; // y = y + 1/y temp = ya + recipa; yb += -(temp - ya - recipa); ya = temp; temp = ya + recipb; yb += -(temp - ya - recipb); ya = temp; result = ya + yb; result *= 0.5; } else { double hiPrec[] = new double[2]; expm1(x, hiPrec); double ya = hiPrec[0] + hiPrec[1]; double yb = -(ya - hiPrec[0] - hiPrec[1]); /* Compute expm1(-x) = -expm1(x) / (expm1(x) + 1) */ double denom = 1.0 + ya; double denomr = 1.0 / denom; double denomb = -(denom - 1.0 - ya) + yb; double ratio = ya * denomr; double temp = ratio * HEX_40000000; double ra = ratio + temp - temp; double rb = ratio - ra; temp = denom * HEX_40000000; double za = denom + temp - temp; double zb = denom - za; rb += (ya - za*ra - za*rb - zb*ra - zb*rb) * denomr; // Adjust for yb rb += yb*denomr; // numerator rb += -ya * denomb * denomr * denomr; // denominator // y = y - 1/y temp = ya + ra; yb += -(temp - ya - ra); ya = temp; temp = ya + rb; yb += -(temp - ya - rb); ya = temp; result = ya + yb; result *= 0.5; } if (negate) { result = -result; } return result; }
7
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(DatosImagen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(DatosImagen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(DatosImagen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(DatosImagen.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 DatosImagen().setVisible(true); } }); }
6
@Test public void testPersistencyHandler() { PersistenceHandler ph = PersistenceHandler.getInstance(); ph.loadDb(); try { ph.write(new MusicPersisted("/home/andreluiz/a.mp3")); ph.write(new MusicPersisted("/home/andreluiz/b.mp3")); ph.write(new UserPersisted("[email protected]", "1234", 24, 8, 1989)); } catch (CannotReadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TagException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ReadOnlyFileException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidAudioFrameException e) { // TODO Auto-generated catch block e.printStackTrace(); } ph.readMusicBuffer(); ph.readUserBuffer(); User u = ph.getUserBuffer().get(new Email("[email protected]")); System.out.println(Password.comparePasswords(u.getPassword(), "1234")); ph.saveAll(); }
5
@Override public boolean updateItem(Item item) { String itemID = item.getID(); String title = item.getTitle(); String publisher = item.getPublisher(); Calendar date = item.getDate(); Date sqlDate = new Date(date.getTimeInMillis()); Statement stmt = null; try { stmt = con.createStatement(); if (itemID.length() == 9) { // item is a book stmt.executeUpdate("Update Book set Title='" + title + "',Publisher='" + publisher + "', Date='" + sqlDate + "' where ISBN = " + item.getID()); } else if (itemID.length() == 8) { //item is a periodical stmt.executeUpdate("Update Periodical set Title='" + title + "',Publisher='" + publisher + "', Date='" + sqlDate + "' where ISSN = " + item.getID()); } return true; } catch (SQLException e) { e.printStackTrace(); return false; } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
5
public void initialize(InputStream stream) { try { ais = AudioSystem.getAudioInputStream(stream); format = ais.getFormat(); if (format.getChannels() == 1) { if (format.getSampleSizeInBits() == 8) { chanelFormat = EnumChanelFormat.MONO_CHANEL_8BITS; } else if (format.getSampleSizeInBits() == 16) { chanelFormat = EnumChanelFormat.MONO_CHANEL_16BITS; } } else if (format.getChannels() == 2) { if (format.getSampleSizeInBits() == 8) { chanelFormat = EnumChanelFormat.STEREO_CHANEL_8BITS; } else if (format.getSampleSizeInBits() == 16) { chanelFormat = EnumChanelFormat.STEREO_CHANEL_16BITS; } } } catch (UnsupportedAudioFileException e) { GameApplication.engineLogger.severe("Audio file is unsupported"); } catch (IOException e) { GameApplication.engineLogger.severe("IO exception occured while initializing WAVE decoder"); } }
8
public void startGame() { ResourceMapping gameMapping = new ResourceMapping(); for (Player player : freeColClient.getGame().getPlayers()) { addPlayerResources(player.getNationID(), gameMapping); } // Unknown nation is not in getPlayers() list. addPlayerResources(Nation.UNKNOWN_NATION_ID, gameMapping); ResourceManager.addGameMapping(gameMapping); Player myPlayer = freeColClient.getMyPlayer(); if (!freeColClient.isHeadless()) { gui.closeMainPanel(); gui.closeMenus(); gui.closeStatusPanel(); gui.playSound(null); // Stop the long introduction sound gui.playSound("sound.intro." + myPlayer.getNationID()); } freeColClient.askServer().registerMessageHandler(freeColClient.getInGameInputHandler()); if (!freeColClient.isHeadless()) { freeColClient.setInGame(true); gui.setupInGameMenuBar(); } InGameController igc = freeColClient.getInGameController(); gui.setSelectedTile((Tile) myPlayer.getEntryLocation(), false); if (freeColClient.currentPlayerIsMyPlayer()) { igc.nextActiveUnit(); } gui.setUpMouseListenersForCanvas(); if (FreeColDebugger.isInDebugMode() && FreeColDebugger.getDebugRunTurns() > 0) { freeColClient.skipTurns(FreeColDebugger.getDebugRunTurns()); } else if (freeColClient.getGame().getTurn().getNumber() == 1) { ModelMessage message = new ModelMessage(ModelMessage.MessageType.TUTORIAL, "tutorial.startGame", myPlayer); String direction = myPlayer.getNation().startsOnEastCoast() ? "west" : "east"; message.add("%direction%", direction); myPlayer.addModelMessage(message); // force view of tutorial message igc.nextModelMessage(); } }
8
public CheckResultMessage checkTF07(int day) { int r1 = get(20, 2); int c1 = get(21, 2); int r2 = get(23, 2); int c2 = get(24, 2); if (checkVersion(file).equals("2003")) { try { in = new FileInputStream(file); hWorkbook = new HSSFWorkbook(in); if (0 != getValue(r1 + 6, c1 + day, 2).abs().compareTo( getValue(r2 + 1, c2 + day, 2).abs())) { return error("支付机构单个账户报表<" + fileName + ">利息划转:" + day + "日错误"); } in.close(); } catch (Exception e) { } } else { try { in = new FileInputStream(file); xWorkbook = new XSSFWorkbook(in); if (0 != getValue(r1 + 6, c1 + day, 2).abs().compareTo( getValue(r2 + 1, c2 + day, 2).abs())) { return error("支付机构单个账户报表<" + fileName + ">利息划转:" + day + "日错误"); } in.close(); } catch (Exception e) { } } return pass("支付机构单个账户报表<" + fileName + ">利息划转:" + day + "日正确"); }
5
protected String calcBPB_FilSysType() throws UnsupportedEncodingException { byte[] bTemp = new byte[8]; for (int i = 82;i < 90; i++) { bTemp[i-82] = imageBytes[i]; } BPB_FilSysType = new String(bTemp, "UTF-8"); System.out.println(BPB_FilSysType); return BPB_FilSysType; }
1
public boolean validarConexion (String n_url, String n_port, boolean seg_int, String n_usu, String n_cla){ boolean valida = false; if (! n_port.equals("")){ port = n_port; } else{ port = "1433"; } String urlConexion = jdbc+n_url+":"+port+";"; if (seg_int){ urlConexion +="integratedSecurity=true;"; } else{ urlConexion +="user="+n_usu+";password="+n_cla+";"; } try { conn = DriverManager.getConnection(urlConexion); valida = true; conn.close(); } catch (SQLException ex) { //corto la longitud del mensaje y muestro el error //para informar por que no puede conectarce a la BD String error = ""; String[] palabras = ex.getMessage().split(" "); int i = 0; int j = 0; while (i < palabras.length){ while ((i < palabras.length) && (j <= 11)){ error+=" "+palabras[i]; i=i+1; j=j+1; } j=0; error+="\n "; } JOptionPane.showMessageDialog(null,"Código del ERROR: "+ex.getErrorCode()+"\nMensaje del ERROR: "+ error, "Error al intentar establecer la Conexión", JOptionPane.ERROR_MESSAGE); } return valida; }
6
public void loadResults(){ FileInputStream fi = null; BufferedReader br = null; try { fi = new FileInputStream(new File(this.resultsDataFilePath)); br = new BufferedReader(new InputStreamReader(fi)); String line = br.readLine(); while(line != null){ loadGameResult(line); line = br.readLine(); } } catch (FileNotFoundException e) { logger.error("Can't find file :" + this.resultsDataFilePath, e); } catch (IOException e) { logger.error("Failed to read content from file :" + this.resultsDataFilePath, e); } finally { try { if (null != fi) { fi.close(); } if (null != br) { br.close(); } } catch (IOException e) { //e.printStackTrace(); // IGNORE this exception } } }
6
public void selectGameTypeCheck(int select) { input.setText(inputStart); if (select >= gameTypeChecks.length) select = 0; for (int j = 0; j < gameTypeChecks.length; j++) gameTypeChecks[j].setSelected(select == j); if (select == 1) { this.selectDictCheck(2); for (int j = 0; j < dictChecks.length; j++) dictChecks[j].setEnabled(false); } else for (int j = 0; j < dictChecks.length; j++) dictChecks[j].setEnabled(true); this.setBoardBaseColor(); for(int i = 0; i<15; i++) for(int k = 0; k<15; k++) if (!tileColors[i][k].equals(brickColor)) tileColors[i][k] = baseColors[i][k]; }
8
public void testToStandardDuration_months() { Period test = Period.months(1); try { test.toStandardDuration(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.months(-1); try { test.toStandardDuration(); fail(); } catch (UnsupportedOperationException ex) {} test = Period.months(0); assertEquals(0, test.toStandardDuration().getMillis()); }
2
private boolean attCanWithdraw(Territory territory){ if(battle.defTerritory.getNeighbors().contains(territory)){ if(battle.defTerritory instanceof Water){ return (territory instanceof Water) && (territory.getFamily()==null || territory.getFamily()==oppFamily); }else{ return (territory instanceof Land) && (territory.getFamily()==null || territory.getFamily()==oppFamily); } }else{ return false;//or naval withdraw } }
6
private void chooseWorldActionPerformed(java.awt.event.ActionEvent evt) throws Exception { World w = new World(); w.readInWorld(chooseWorld.getSelectedFile().getName()); worlds.add(w); }
0
static public void addLocation(Location newLocation) { Charset charset = Charset.forName("UTF-8"); final File file = new File("VMlocations.ini"); if (!file.exists()) try { file.createNewFile(); } catch (IOException ex) { Logger.getLogger(LocationsManager.class.getName()).log(Level.SEVERE, null, ex); } try (BufferedWriter writer = Files.newBufferedWriter(file.toPath(), charset, StandardOpenOption.APPEND)) { writer.write(newLocation.toExport(), 0, newLocation.toExport().length()); } catch (IOException x) { System.err.format("IOException: %s%n", x); } }
3
static void executeBatch(Batch batch) throws ProcessException { for (int i = 0; i < batch.cmdCmds.size(); i++) { List<String> command = new ArrayList<String>(); command.add(batch.cmdCmds.get(i).path); //Add the arguments for(String argi: batch.cmdCmds.get(i).cmdArgs) { command.add(argi); } ProcessBuilder builder = new ProcessBuilder(); builder.command(command); builder.directory(new File(batch.wdCmd.path)); //Set the input file String fileIn = batch.cmdCmds.get(i).inID; String input = null; if (!(fileIn == null || fileIn.isEmpty())) { if( batch.cmdMap.containsKey(fileIn)) { input = "work/" + batch.cmdMap.get(fileIn).path; builder.redirectInput(new File(input)); } else { throw new ProcessException("IN FileCommand with id: " + fileIn+ " not found"); } } builder.redirectError(new File("error.txt")); //Set the output file String fileOut = batch.cmdCmds.get(i).outID; if (!(fileOut == null || fileOut.isEmpty())) { if( batch.cmdMap.containsKey(fileOut)) { fileOut = "work/" + batch.cmdMap.get(fileOut).path; builder.redirectOutput(new File(fileOut)); } else { throw new ProcessException("Out FileCommand with id: " + fileOut+ " not found"); } } //Start the process try { Process process = builder.start(); System.out.println("Command " + i + " executed"); process.waitFor(); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } System.out.println("Batch Finished!"); }
9
@Override public BuildResult call() throws Exception { // set the name of this thread to the package // name for debugging Thread.currentThread().setName(pkg.getName()); // write the POM to the base dir pkg.writePom(); BuildResult result = new BuildResult(); result.setPackageName(pkg.getName()); List<String> command = Lists.newArrayList(); command.add(getMavenPath()); if(updateSnapshots) { // command.add("-U"); } // hot fix for tests that exceed memory if(pkg.getName().equals("MASS")) { command.add("-DskipTests"); } else { command.add("-Dmaven.test.failure.ignore=true"); } command.add("-DenvClassifier=linux-x86_64"); command.add("-Dignore.gnur.compilation.failure=true"); command.add("clean"); command.add("deploy"); ProcessBuilder builder = new ProcessBuilder(command); builder.directory(pkg.getBaseDir()); builder.redirectErrorStream(true); try { long startTime = System.currentTimeMillis(); Process process = builder.start(); InputStream processOutput = process.getInputStream(); OutputCollector collector = new OutputCollector(processOutput, logFile); collector.setName(pkg + " - output collector"); collector.start(); try { ProcessMonitor monitor = new ProcessMonitor(process); monitor.setName(pkg + " - monitor"); monitor.start(); while(!monitor.isFinished()) { if(System.currentTimeMillis() > (startTime + TIMEOUT_SECONDS * 1000)) { System.out.println(pkg + " build timed out after " + TIMEOUT_SECONDS + " seconds."); process.destroy(); result.setOutcome(BuildOutcome.TIMEOUT); break; } Thread.sleep(1000); } collector.join(); if(result.getOutcome() != BuildOutcome.TIMEOUT) { if(monitor.getExitCode() == 0) { result.setOutcome(BuildOutcome.SUCCESS); } else if(monitor.getExitCode() == 1) { result.setOutcome(BuildOutcome.FAILED); } else { System.out.println(pkg.getName() + " exited with code " + monitor.getExitCode()); result.setOutcome(BuildOutcome.ERROR); } } } finally { Closeables.closeQuietly(processOutput); } } catch (Exception e) { result.setOutcome(BuildOutcome.ERROR); e.printStackTrace(); } return result; }
8
protected int recurse_multiple(MDDManager ddmanager, int[] nodes, int leafcount, MDDVariable bestVar) { if (bestVar.nbval == 2) { int lchild, rchild; int[] lnodes = new int[nodes.length], rnodes = new int[nodes.length]; for (int i=0 ; i<leafcount ; i++) { lnodes[i] = rnodes[i] = nodes[i]; } for (int i=leafcount ; i<nodes.length ; i++) { int node = nodes[i]; if (ddmanager.getNodeVariable(node) == bestVar) { lnodes[i] = ddmanager.getChild(node, 0); rnodes[i] = ddmanager.getChild(node, 1); } else { lnodes[i] = rnodes[i] = node; } } lchild = combine(ddmanager, lnodes, leafcount); rchild = combine(ddmanager, rnodes, leafcount); return bestVar.getNodeFree(lchild, rchild); } else { int[] children = new int[bestVar.nbval]; int[] nextnodes = new int[nodes.length]; for (int v=0 ; v<children.length ; v++) { System.arraycopy(nodes, 0, nextnodes, 0, leafcount); for (int i=leafcount ; i<nodes.length ; i++) { int node = nodes[i]; if (ddmanager.getNodeVariable(node) == bestVar) { nextnodes[i] = ddmanager.getChild(node, v); } else { nextnodes[i] = nodes[i]; } } children[v] = combine(ddmanager, nextnodes, leafcount); } return bestVar.getNodeFree(children); } }
7
@EventHandler public void onPlayerRespawn(PlayerRespawnEvent event) { Arena arena = this.gm.findArenaByPlayer(event.getPlayer()); if (arena == null) return; PlayerInfo p = arena.findPlayer(event.getPlayer()); if (p == null) return; event.setRespawnLocation((Location)arena.mainArea.Spawn.get(p.team.TeamId)); p.level.handleSpawnWithLevel(p.player); Iterator localIterator2; for (Iterator localIterator1 = this.gm.arenas.iterator(); localIterator1.hasNext(); localIterator2.hasNext()) { Arena a = (Arena)localIterator1.next(); localIterator2 = a.teams.iterator(); Team t = (Team)localIterator2.next(); for (PlayerInfo pi : t.player) pi.setNameColor(pi.team.color); } }
4
public AbstractResource getResourceByName(String resourceName) { for (ResConfig rc : this.configurations) for (AbstractResource res : rc.getResources()) if (res.getResourceName().equals(resourceName)) return res; return null; }
3
public void log4dstm2(Object version) { if (version == null) return; Field[] fields = version.getClass().getDeclaredFields(); for (int j = 0; j < fields.length; j++) { fields[j].setAccessible(true); System.out.print(fields[j].getName() + ","); if (fields[j].getType().getName() .equals(java.lang.String.class.getName())) { // String type try { System.out.print(fields[j].get(version)); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (fields[j].getType().getName() .equals(java.lang.Integer.class.getName()) || fields[j].getType().getName().equals("int")) { // Integer type try { System.out.println(fields[j].getInt(version)); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } System.out.println(); }
9
@Override public boolean onCommand(CommandSender arg0, Command arg1, String arg2, String[] arg3) { if (arg0.hasPermission("CreeperWarning.reload")) { plugin.getServer().getPluginManager().disablePlugin(plugin); plugin.getServer().getPluginManager().enablePlugin(plugin); arg0.sendMessage(plugin.NAME + "Reloading!"); } return true; }
1
private void showBasicDialogs(String message) { messageLabel.setText(message); instance.showDialog(); }
0
public static int[][] rotateImage(int[][] image){ int n=image.length; /*The first step*/ for(int i=0;i<n;i++){ for(int j=0;j<n/2;j++){ image[i][j]=image[i][j]+image[i][n-j-1]; image[i][n-j-1]=image[i][j]-image[i][n-j-1]; image[i][j]=image[i][j]-image[i][n-j-1]; } } /*The second step*/ for(int i=0;i<n;i++){ for(int j=0;j<n-i-1;j++){ image[i][j]=image[i][j]+image[n-j-1][n-i-1]; image[n-j-1][n-i-1]=image[i][j]-image[n-j-1][n-i-1]; image[i][j]=image[i][j]-image[n-j-1][n-i-1]; } } return image; }
4
public void setColor(Vector4f color) { this.color = (color != null ? color : new Vector4f(1f,1f,1f,1f)); }
1
@Override public void run() { try{ while(true){ Thread.sleep(waitTime); int newScore = 0; if(MarketUtils.IsMarketOpen){ for(Stock stock : watched){ stock.update(); newScore = 0; for(Strategy strategy : strategyProfile){ newScore += strategy.evaluate(stock); } //If we ever make 15% on a stock, take it. --> //we can never make more then 15k at a time -- this is OK for now if(stock.price > account.getPurchaseValue(stock) * 1.15){ account.sellAllStock(stock); scores.put(stock, 0); } //NOT SURE WE WANT OT DO THIS, currently it just owns score*100000 dollars //worth of stock, if score < 0, then it sells everything. if(newScore < 0 ){ account.sellAllStock(stock); scores.put(stock, newScore); } else if(newScore > scores.get(stock)){ account.buyStock(stock, (10000 * (newScore - scores.get(stock)) / stock.price)); scores.put(stock, newScore); } else if(newScore < scores.get(stock)) { account.sellStock(stock, (5000 * (0-newScore + scores.get(stock)) / stock.price)); } System.out.print(stock.ticker + ": " + stock.price + " : " + newScore + " | "); } System.out.println(); } } } catch (Exception e ){ LoggingUtils.LogToFile(name, "Shit went down, lost a trader :("); } }
9
private void makeImgToBase64(HtmlPage page) throws FailingHttpStatusCodeException, MalformedURLException, IOException { @SuppressWarnings("unchecked") List<HtmlImage> imageList = (List<HtmlImage>) page.getByXPath("//img"); for (HtmlImage image : imageList) { InputStream ins = webClient.getPage("http://ecampus.ucn.dk" + image.getSrcAttribute()).getWebResponse().getContentAsStream(); byte[] imageBytes = new byte[0]; for(byte[] ba = new byte[ins.available()]; ins.read(ba) != -1;) { byte[] baTmp = new byte[imageBytes.length + ba.length]; System.arraycopy(imageBytes, 0, baTmp, 0, imageBytes.length); System.arraycopy(ba, 0, baTmp, imageBytes.length, ba.length); imageBytes = baTmp; } image.setAttribute("src", "data:image/gif;base64," + DatatypeConverter.printBase64Binary(imageBytes)); } }
2
private void placerPostes(Graphics2D g){ g.setStroke(new BasicStroke()) ; for(Poste poste : modele){ g.setColor(Color.gray) ; int xPoste = Parametres.posteX(poste.getPosition().getTravee(),poste.getOrientation()) ; int yPoste = Parametres.posteY(poste.getPosition().getRangee(),poste.getOrientation()) ; int xPersonne = Parametres.personneX(poste.getPosition().getTravee(),poste.getOrientation()) ; int yPersonne = Parametres.personneY(poste.getPosition().getRangee(),poste.getOrientation()) ; if(poste.getOrientation() == Orientation.NORD || poste.getOrientation() == Orientation.SUD){ g.fill3DRect(xPoste,yPoste,Parametres.LONGUEUR_POSTE,Parametres.LARGEUR_POSTE,true) ; } else { g.fill3DRect(xPoste,yPoste,Parametres.LARGEUR_POSTE,Parametres.LONGUEUR_POSTE,true) ; } g.drawOval(xPersonne,yPersonne,Parametres.LARGEUR_PERSONNE,Parametres.LARGEUR_PERSONNE) ; if(poste.peutVoir()){ g.setColor(Color.red) ; } else { g.setColor(Color.green) ; } g.fillOval(xPersonne,yPersonne,20,20) ; System.out.println("Placer postes - Plan"); } }
4
public static void main(String [] args){ try { System.out.println("reading wav file..."); //String dir = "C:/Users/Jeudy7/Desktop/Doc_ITC_teaching_250913/sphinx_4_project/reco/resource/tmp_file_dir/"; String dir = "./resource/tmp_file_dir/"; File directory = new File(dir); //get all the files from a directory File[] fList = directory.listFiles(); List<String> list_fileName=new ArrayList<String>(); Recognition reg = new Recognition(); System.out.println(" list files"); for (File file : fList){ System.out.println("File read :"+file.getName()); //System.out.println("number of file : "+file.list())); Recorder rec = new Recorder(dir+file.getName()); // Recorder r = null; System.out.println("text reco: "+reg.translateSpeech(rec.getAudio())); list_fileName.add(file.getName()); } /* Iterator it=list_fileName.iterator(); System.out.println("Filenames in list : "); while(it.hasNext()) { String value=(String)it.next(); System.out.println("Value :"+value); } */ } catch (LineUnavailableException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } /* hour try { String com; Recorder r = null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Recognition reg = new Recognition(); while(true){ System.out.println("s: to start. c: to stops."); if((com = br.readLine()).equals("s")){ System.out.println("start"); r = new Recorder(); r.start(); }else if(com.equals("c")){ System.out.println("cancel"); r.stopRecord(); r.deleteTmpFile(); System.out.println("text: "+reg.translateSpeech(r.getAudio())); } } } catch (LineUnavailableException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } */ }
4
public JSONObject details(int id, boolean isUser, boolean isForum, boolean isThread) { JSONObject result = new JSONObject(); JSONObject response = null; ResultSet resultSet; try { PreparedStatement stmt = con.prepareStatement("SELECT message, date, likes, dislikes, points, isApproved, isHighlighted, isEdited, isSpam, isDeleted, parent, user, thread, forum FROM posts WHERE id = ?"); stmt.setInt(1, id); resultSet = stmt.executeQuery(); if (resultSet.next()) { response = new JSONObject(); response.put("id", id); response.put("message", resultSet.getString("message")); response.put("date", resultSet.getString("date").split("\\.")[0]); response.put("likes", resultSet.getInt("likes")); response.put("dislikes", resultSet.getInt("dislikes")); response.put("points", resultSet.getInt("points")); response.put("isApproved", resultSet.getBoolean("isApproved")); response.put("isHighlighted", resultSet.getBoolean("isHighlighted")); response.put("isEdited", resultSet.getBoolean("isEdited")); response.put("isSpam", resultSet.getBoolean("isSpam")); response.put("isDeleted", resultSet.getBoolean("isDeleted")); response.put("parent", Api.checkNullValue(resultSet.getInt("parent"))); if (isUser) { response.put("user", UserDAO.details(resultSet.getString("user"), con)); } else { response.put("user", resultSet.getString("user")); } if (isThread) { response.put("thread", ThreadDAO.details(Integer.parseInt(resultSet.getString("thread")), false, false, con)); } else { response.put("thread", resultSet.getInt("thread")); } if (isForum) { response.put("forum", ForumDAO.details(resultSet.getString("forum"), null, con)); } else { response.put("forum", resultSet.getString("forum")); } } if (response != null) { result.put("code", 0); result.put("response", response); } else { result.put("code", 1); result.put("message", "post not found: " + id); } } catch (JSONException | SQLException e) { } return result; }
6
private static void displayAddInventory(BufferedReader reader, VideoStore videoStore) { try { System.out.println("Please enter the title of the video you would like to add inventory to:"); String isbn = getISBNFromTitle(reader, videoStore, reader.readLine()); System.out.println("How much inventory is being added?"); int amount = 0; while(true) { try { amount = Integer.parseInt(reader.readLine()); } catch (Exception ignored) { } if (amount > 0) { break; } } if (videoStore.addInventory(isbn, amount)) { System.out.println("Successfully added inventory."); return; } System.out.println("Unable to successfully add inventory."); } catch (Exception e) { e.printStackTrace(); } }
5
public void escribirCarpetas() throws ReporteJasperException { try { index=0; String separador = System.getProperty("file.separator"); for (int i = 0; i < this.lista.size(); i++) { ReporteJasperVO reporteJasperVO = (ReporteJasperVO) this.lista.get(i); String folder = this.path + separador+USER+(String) reporteJasperVO.getResourceProperty().get(Constantes.PROP_PARENT_FOLDER); //System.out.println("folder:"+folder); File carpeta = new File(folder); if (!carpeta.exists()) { if (carpeta.mkdirs()) { //System.out.println("Carpeta OK"); } else { throw new ReporteJasperException("No fue posible escribir directorio cache label "+carpeta); } } else { //System.out.println("Carpeta EXISTE"); } File fichero = null; String file = folder + separador + reporteJasperVO.getLabel(); fichero = new File(file); if (fichero.createNewFile()) { String url=construirUrl(fichero,reporteJasperVO); } else { throw new ReporteJasperException("No fue posible escribir archivo cache label "+reporteJasperVO.getLabel()); } } } catch (IOException ex) { ex.printStackTrace(); throw new ReporteJasperException(ex.getMessage()); } catch (Exception e) { e.printStackTrace(); throw new ReporteJasperException(e.getMessage()); } }
6
public ReportGenerator(boolean advancedMode, File baseDir, final GenerationProgress gp) { super(); Logger.getLogger(ReportGenerator.class.getName()).entering(ReportGenerator.class.getName(), "ReportGenerator", new Object[] {advancedMode, baseDir, gp}); try { this.advancedMode = advancedMode; this.baseDir = baseDir; this.generationProgressDialog = gp; Logger.getLogger(ReportGenerator.class.getName()).log(Level.INFO, "Starting the html report"); String homeFolder = OSBasics.getHomeDir(); homeFolder = homeFolder.concat(File.separatorChar + "HTMLReport"); deleteHTMLReportDirectory(new File(homeFolder)); new File(homeFolder).mkdir(); reportFolder = homeFolder + File.separatorChar; if (advancedMode) { new File(reportFolder + "thumbnails").mkdir(); } addPropertyChangeListener((PropertyChangeEvent evt) -> { if("progress".equals(evt.getPropertyName())) { int newValue = (Integer) evt.getNewValue(); if (gp.getActionProgressBarValue() > newValue) { return; } gp.setActionProgressBarValue(newValue); } }); } catch (Exception ex) { Logger.getLogger(ReportGenerator.class.getName()).log(Level.SEVERE, "Unknown exception", ex); new InfoInterface(InfoInterface.InfoLevel.ERROR, "unknown"); } Logger.getLogger(ReportGenerator.class.getName()).exiting(ReportGenerator.class.getName(), "ReportGenerator"); }
4
public Double getMaxPrize(String type) { Map<Integer, Reward> rewards = getRewards(type); Double max = 0.0; for(Map.Entry<Integer, Reward> entry : rewards.entrySet()) { Reward reward = entry.getValue(); Double money = reward.getMoney(); if(money > max) { max = money; } } return max; }
2
private int getFrameForReplacement(){ int frameID = -1; for (int i=0; i<this.frames.length && frameID == -1; i++){ if( this.pinCount[i] == 0 ) frameID = i; } // System.out.println( "Replacement frame is " + frameID ); if( frameID != -1 && dirty[frameID] ){ writeBlock(frameID); } return frameID; }
5
public int getId() { return id; }
0
private void extractArguments(String[] args) { String testArgsString = Config.getString("AutoGrader.testArgs"); if (testArgsString == null) { testArgsString = ""; } for (int i=0; i<args.length; ) { String arg = args[i++]; if (arg.length() > 0 && arg.charAt(0) == '-') { if (arg.equals("-#")) { Lib.assertTrue(i < args.length, "-# switch missing argument"); testArgsString = args[i++]; } } } StringTokenizer st = new StringTokenizer(testArgsString, ",\n\t\f\r"); while (st.hasMoreTokens()) { StringTokenizer pair = new StringTokenizer(st.nextToken(), "="); Lib.assertTrue(pair.hasMoreTokens(), "test argument missing key"); String key = pair.nextToken(); Lib.assertTrue(pair.hasMoreTokens(), "test argument missing value"); String value = pair.nextToken(); testArgs.put(key, value); } }
6
@Override public String format(Date fromObject) { try{ return forFormatting.format(fromObject); } catch(Exception e){ } return null; }
1
public String getApplicationName() { return this.applicationName; }
0
public boolean spaceHasOpponent(Position p, int opponentColor) { try { if (opponentColor == Board.white) { if (this.board[p.rank][p.file] > 0) { return true; } } else { if (this.board[p.rank][p.file] < 0) { return true; } } return false; } catch (Exception e) { return false; } }
4
public static final void method544(int i, int j, int k, int l, GameObject gameObject, long l1, GameObject gameObject_1, GameObject gameObject_2) { Class46 class46 = new Class46(); class46.aGameObject_787 = gameObject; class46.anInt791 = j * 128 + 64; class46.anInt794 = k * 128 + 64; class46.anInt788 = l; class46.uid = l1; class46.aGameObject_800 = gameObject_1; class46.aGameObject_789 = gameObject_2; int i1 = 0; Tile tile = ReferenceTable.tiles[i][j][k]; if (tile != null) { for (int j1 = 0; j1 < tile.anInt3339; j1++) { Class5 class5 = tile.aClass5Array3354[j1]; if ((class5.uid & 0x400000L) == 0x400000L) { int k1 = class5.aGameObject_131.getHeight(); if (k1 != -32768 && k1 < i1) { i1 = k1; } } } } class46.anInt799 = -i1; if (ReferenceTable.tiles[i][j][k] == null) { ReferenceTable.tiles[i][j][k] = new Tile(i, j, k); } ReferenceTable.tiles[i][j][k].aClass46_3330 = class46; }
6
@Override public void run() { Map<String, Ban> bans = plugin.getController().getBans(); // empty ban list print info and stop if (bans.isEmpty()) { if (!silent) { String message = MessagesUtil.formatMessage("run_no_bans", null); log.log(Level.INFO, "[TimeBan] {0}", message); } return; } if (!silent) { String message = MessagesUtil.formatMessage("run_check", null); log.log(Level.INFO, "[TimeBan] {0}", message); } // go through list until unban date is in future List<Ban> sortedBans = new ArrayList<Ban>(bans.values()); Collections.sort(sortedBans, new BanComparator(false)); for (Ban b : sortedBans) { if (b.getUntil().before(Calendar.getInstance())) { TimeBanUnbanEvent event = new TimeBanUnbanEvent(b); event.setSilent(silent); Bukkit.getServer().getPluginManager().callEvent(event); } else { break; } } if (!silent) { String message = MessagesUtil.formatMessage("run_check_complete", null); log.log(Level.INFO, "[TimeBan] {0}", message); } }
6
private void finalizeCNFMap(HashMap <Production, Production> map) { for (Production p : myCNFMap.keySet()) { ArrayList <Production> temp=new ArrayList <Production>(); for (Production pp : myCNFMap.get(p)) { temp.add(map.get(pp)); } myCNFMap.put(p, temp); } }
2
@Override public String getColumnName(int columnIndex) { if (columnIndex == DELIVERY_PACKET_ID) { return "№"; } else if (columnIndex == MEMBER_NAME) { return "Кому выдано"; } else if (columnIndex == EVENT) { return "Мероприятие"; } else if (columnIndex == DELIVERY_DATE) { return "Выдано"; } else if (columnIndex == EXPECTED_RETURN_DATE) { return "Возвратить"; } else { logger.warn("Попытка получить значение для несуществующего стообца. " + "Столбец: " + columnIndex); return "Столбец №" + columnIndex; } }
5
public static <T> void ForEach(Iterable<T> parameters, final LoopBody<T> loopBody) { ExecutorService executor = Executors.newFixedThreadPool(iCPU); List<Future<?>> futures = new LinkedList<>(); for (final T param : parameters) { Future<?> future = executor.submit(new Runnable() { public void run() { loopBody.run(param); } }); futures.add(future); } for (Future<?> f : futures) { try { f.get(); } catch (InterruptedException e) { } catch (ExecutionException e) { } } executor.shutdown(); }
7
public MarginKernelPerceptron(String kernelType) { if (kernelType.equals("perceptron_linear_kernel")) { kernel = new LinearKernel(); } else if (kernelType.equals("perceptron_polynomial_kernel")) { int polynomial_kernel_exponent = 2; if (CommandLineUtilities.hasArg("polynomial_kernel_exponent")) { polynomial_kernel_exponent = CommandLineUtilities.getOptionValueAsInt("polynomial_kernel_exponent"); } kernel = new PolynomialKernel(polynomial_kernel_exponent); } iters = 5; if (CommandLineUtilities.hasArg("online_training_iterations")) { iters = CommandLineUtilities.getOptionValueAsInt("online_training_iterations"); } }
4
public void updateSubTypes() { if (parent != null && (GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_TYPES) != 0) GlobalOptions.err.println("local type changed in: " + parent); local.setType(type); }
2
public void setForceImageLocation(String forceName) { switch (forceName) { case "曹操": forceImageLocation = "/resources/caocaoForceColour.png"; break; case "刘备": forceImageLocation = "/resources/liubeiForceColour.png"; break; case "孙权": forceImageLocation = "/resources/sunquanForceColour.png"; break; case "刘表": forceImageLocation = "/resources/liubiaoForceColour.png"; break; default: forceImageLocation = "/resources/caocaoForceColour.png"; break; } }
4
@Override public void onMessage(String strmsg) { //System.out.println(strmsg); // pos updates try { JSONObject jsmsg = new JSONObject(strmsg); JSONObject data = jsmsg.getJSONObject("Data"); switch(jsmsg.getInt("Type")) { case 1: //disconnection String discoUserName = data.getString("n"); this.onlineUsers.remove(discoUserName); //System.out.println("Bot "+ this.botId +" : removed user " + discoUserName + " from local game state"); break; case 2: //pos update this.numPosMsgReceived ++; JSONObject pos = data.getJSONObject("p"); int t = pos.getInt("t"); int l = pos.getInt("l"); if(t == this.topToWatch && l == this.leftToWatch) { // msg tracked to determine client-to-client latency this.latency = (int) (System.currentTimeMillis() - this.latencyStart); } // add user to my local collection of users String coUserName2 = data.getString("n"); if(! (this.onlineUsers.contains(coUserName2))) { this.onlineUsers.add(coUserName2); //System.out.println("Bot "+ this.botId +" : added user " + coUserName2 + " to local game state"); } break; case 3: //on connect: list of all connected users JSONArray users = data.getJSONArray("Users"); JSONObject user; String coUserName3; for(int i = 0; i < users.length(); i++) { user = users.getJSONObject(i); coUserName3 = user.getString("n"); if(! (this.onlineUsers.contains(coUserName3))) { this.onlineUsers.add(coUserName3); //System.out.println("Bot "+ this.botId +" : added user " + coUserName3 + " to local game state"); } } break; default: System.out.println("Error: Type in JSON msg was neither 1, 2, or 3"); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
9
private void setChunk() { for (int x = 0; x < chunks.length; x++) { chunks[x] = new Chunk(3); } }
1
public Direction hitObj(GameObj other) { if (this.willIntersect(other)) { double dx = other.pos_x + other.width /2 - (pos_x + width /2); double dy = other.pos_y + other.height/2 - (pos_y + height/2); double theta = Math.atan2(dy, dx); double diagTheta = Math.atan2(height, width); if ( -diagTheta <= theta && theta <= diagTheta ) { return Direction.RIGHT; } else if ( diagTheta <= theta && theta <= Math.PI - diagTheta ) { return Direction.DOWN; } else if ( Math.PI - diagTheta <= theta || theta <= diagTheta - Math.PI ) { return Direction.LEFT; } else { return Direction.UP; } } else { return null; } }
7
public Date getHireDay() { return hireDay; }
0
@Override public double drawString(String str, SpriteSheet font, double x, double y, double scale, Color color, double wrapX) { double aspect = font.getSpriteAspect(); double maxLength = (wrapX - x) / (scale * aspect); if (wrapX <= x || wrapX <= -1 || str.length() < maxLength) { drawStringLine(str, font, x, y, scale, color); return y - scale; } str = Util.wrapString(str, maxLength); String[] strs = str.split("\n"); for (int i = 0; i < strs.length; i++) { String[] wrappedStrings = strs[i].split("(?<=\\G.{" + ((int) maxLength) + "})"); for (int j = 0; j < wrappedStrings.length; j++, y -= scale) { drawStringLine(wrappedStrings[j], font, x, y, scale, color); } } return y; }
5
public NameGenerator(){ Scanner scanner; random = new Random(); try{ scanner = new Scanner(this.getClass().getResourceAsStream("/res/vowels.txt")); }catch(Exception e){ e.printStackTrace(); return; } if(!scanner.nextLine().equals("vowels:")){ System.out.println("wrong file!"); return; } ArrayList<String> vowelList = new ArrayList<String>(); ArrayList<String> consonantList = new ArrayList<String>(); boolean addToVowelList = true; while(scanner.hasNext()){ String line = scanner.next(); if(line.equals("consonants:")){ addToVowelList = false; continue; } if(addToVowelList) vowelList.add(line); else consonantList.add(line); } consonants = toArray(consonantList); vowels = toArray(vowelList); }
5
private void handleKeyboardInput() { while(Keyboard.next()) { if (Keyboard.getEventKeyState()) { if(Keyboard.getEventKey() == Keyboard.KEY_ESCAPE) { System.exit(0); } if(Keyboard.getEventKey() == Keyboard.KEY_RETURN) { mouseActive = !mouseActive; } } } moveDir.set(0.0f,0.0f,0.0f); float MOVE_SPEED = 0.2f; if(Keyboard.isKeyDown(Keyboard.KEY_LEFT)) { moveDir.setX(-MOVE_SPEED); } if(Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) { moveDir.setX(MOVE_SPEED); } if(Keyboard.isKeyDown(Keyboard.KEY_UP)) { moveDir.setZ(-MOVE_SPEED); } if(Keyboard.isKeyDown(Keyboard.KEY_DOWN)) { moveDir.setZ(MOVE_SPEED); } lb.move(moveDir); }
8
private final void method2525(int[] is, Node_Sub10 node_sub10, int i, int i_7_, int i_8_, int i_9_) { if (i_9_ != 12073) { DECODE_MASKS_PLAYERS_COUNT = 44; } if ((0x4 & aNode_Sub9_Sub1_9734.anIntArray9680[node_sub10.anInt7080] ^ 0xffffffff) != -1 && node_sub10.anInt7100 < 0) { int i_10_ = aNode_Sub9_Sub1_9734.anIntArray9685[node_sub10.anInt7080] / Class365.anInt4523; for (;;) { int i_11_ = (-node_sub10.anInt7076 + (1048575 + i_10_)) / i_10_; if (i_11_ > i_7_) { break; } node_sub10.aNode_Sub9_Sub2_7095.method2427(is, i_8_, i_11_); node_sub10.anInt7076 += -1048576 + i_10_ * i_11_; i_7_ -= i_11_; i_8_ += i_11_; int i_12_ = Class365.anInt4523 / 100; int i_13_ = 262144 / i_10_; if ((i_13_ ^ 0xffffffff) > (i_12_ ^ 0xffffffff)) { i_12_ = i_13_; } Node_Sub9_Sub2 node_sub9_sub2 = node_sub10.aNode_Sub9_Sub2_7095; if ((aNode_Sub9_Sub1_9734.anIntArray9659[node_sub10.anInt7080] ^ 0xffffffff) != -1) { node_sub10.aNode_Sub9_Sub2_7095 = Node_Sub9_Sub2.method2509(node_sub10.aNode_Sub45_Sub1_7087, node_sub9_sub2.method2503(), 0, node_sub9_sub2.method2511()); aNode_Sub9_Sub1_9734.method2466(node_sub10.aNode_Sub6_7098.aShortArray7044[node_sub10.anInt7091] < 0, node_sub10, -26045); node_sub10.aNode_Sub9_Sub2_7095.method2478(i_12_, node_sub9_sub2.method2504()); } else { node_sub10.aNode_Sub9_Sub2_7095 = Node_Sub9_Sub2.method2509(node_sub10.aNode_Sub45_Sub1_7087, node_sub9_sub2.method2503(), node_sub9_sub2.method2504(), node_sub9_sub2.method2511()); } if (node_sub10.aNode_Sub6_7098.aShortArray7044[node_sub10.anInt7091] < 0) { node_sub10.aNode_Sub9_Sub2_7095.method2481(-1); } node_sub9_sub2.method2483(i_12_); node_sub9_sub2.method2427(is, i_8_, -i_8_ + i); if (node_sub9_sub2.method2499()) { aNode_Sub9_Sub3_9740.method2513(node_sub9_sub2); } } node_sub10.anInt7076 += i_7_ * i_10_; } anInt9735++; node_sub10.aNode_Sub9_Sub2_7095.method2427(is, i_8_, i_7_); }
9
private boolean isDragOk( final java.io.PrintStream out, final java.awt.dnd.DropTargetDragEvent evt ) { boolean ok = false; // Get data flavors being dragged java.awt.datatransfer.DataFlavor[] flavors = evt.getCurrentDataFlavors(); // See if any of the flavors are a file list int i = 0; while( !ok && i < flavors.length ) { // BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added. // Is the flavor a file list? final DataFlavor curFlavor = flavors[i]; if( curFlavor.equals( java.awt.datatransfer.DataFlavor.javaFileListFlavor ) || curFlavor.isRepresentationClassReader()){ ok = true; } // END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added. i++; } // end while: through flavors // If logging is enabled, show data flavors if( out != null ) { if( flavors.length == 0 ) log( out, "FileDrop: no data flavors." ); for( i = 0; i < flavors.length; i++ ) log( out, flavors[i].toString() ); } // end if: logging enabled return ok; }
7
@Override public void close() { if (this.connection != null) try { this.connection.close(); } catch (SQLException ex) { this.writeError("Error on Connection close: " + ex, true); } }
2
public void storePerson(Person person) throws NameClashException, UpdatingNonexistantPersonException { Person foundDbPerson = null; int personId = person.getId(); if (personId != -1) { foundDbPerson = findPersonWithId(personId); if (foundDbPerson == null) { throw new UpdatingNonexistantPersonException( "A person with id " + personId + " was being updated but the ID doesn't exist."); } } else { for (Person dbPerson : persons) { if (person.getFirstName().equals(dbPerson.getFirstName()) && person.getLastName().equals(dbPerson.getLastName())) { if (person.getId() != dbPerson.getId()) { throw new NameClashException( "Two persons with the same name is not allowed"); } else { foundDbPerson = dbPerson; break; } } } } if (foundDbPerson != null) { persons.remove(foundDbPerson); } if (person.getId() == -1) { person.setId(idCount++); } try { Person clonedPerson = person.clone(); persons.add(clonedPerson); } catch (CloneNotSupportedException e) { // Person doesn't throw a CloneNotSupportedException } }
9
public static String askPath(String msg) { String res = null; while (res == null || !Draft.isPath(res) ) { res = ask(msg); if ( !Draft.isPath(res) ) System.out.println("\n!!! No such file !!!"); } return res; }
3
public static int calculeHyperperiode(List<Tache> taches) { int nb = 0; List<Integer> Pi = new ArrayList<Integer>(); for(Tache tache : taches) { if (tache instanceof TachePeriodique) { Pi.add(((TachePeriodique) tache).getPi()); nb++; } } Integer[] periodes = new Integer[nb]; Pi.toArray(periodes); int hyperperiode = Utils.ppcm(periodes); if (Simulation.getInstance().getTypeSimulation().equals(OrdonnanceurRM.mode)) { int chargeP = 0; int chargeA = 0; for (Tache tache : taches) { if (tache instanceof TachePeriodique) { int coeff = hyperperiode / ((TachePeriodique)tache).getPi(); chargeP += coeff * tache.getCi(); } else { chargeA += tache.getCi(); } } int chargesLibres = hyperperiode - chargeP; return (chargeA > 0) ? (hyperperiode * new Double(Math.ceil(new Double(chargeA)/new Double(chargesLibres))).intValue()) : hyperperiode; } else { return hyperperiode; } }
6
private int insert0(int pos, byte[] code, boolean exclusive) throws BadBytecode { int len = code.length; if (len <= 0) return pos; // currentPos will change. pos = insertGapAt(pos, len, exclusive).position; int p = pos; for (int j = 0; j < len; ++j) bytecode[p++] = code[j]; return pos; }
2
public static void main(String args[]) { String url = "jdbc:oracle:thin:@192.168.1.105:1521:timran11g"; // HOST:192.168.1.105;PORT:1521;SID_NAME:timran11g String strSql = "SELECT * FROM t1"; // 将sql中将;去掉 String strSql1 = "SELECT * FROM MYTEST"; String createTable1 = "Create table MYTEST (ID INT,NAME VARCHAR(20))"; String sql1 = "insert into MYTEST (ID,NAME) VALUES(1,'JOE')"; String sql3 = "insert into MYTEST (ID,NAME) VALUES(2,'JOHN')"; String sql2 = "delete MYTEST WHERE ID = 1"; String sql4 = "drop table MYTEST PURGE"; try { Class.forName("oracle.jdbc.driver.OracleDriver"); // 建表后先commit才能在其它端中调用 Connection conn = DriverManager.getConnection(url, "scott", "scott"); Statement stmt = conn.createStatement(); stmt.execute("insert into t1 (id) values(3)"); // 表已建立,插入记录 ResultSet rs = stmt.executeQuery(strSql); // 查询语句的使用 while (rs.next()) { System.out.println("ID:" + rs.getString(1)); } stmt.executeUpdate(createTable1); // CREATE TABLE DDL stmt.executeUpdate(sql1); // INSERT TABLE DATA stmt.executeUpdate(sql3); // INSERT TABLE DATA stmt.executeUpdate(sql2); //DELETE TABLE DATA ResultSet rs1 = stmt.executeQuery(strSql1); // 查询语句的使用 while (rs1.next()) { System.out.println("MYID:" + rs1.getString(1)); System.out.println("MYNAME:" + rs1.getString(2)); } stmt.executeUpdate(sql4); //dorp table DDL rs.close(); rs1.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } System.exit(0); }
3
static public int get(int itemLevel) { /*if (itemLevel < 1) { throw new IllegalArgumentException("Invalid Item Level: " + itemLevel); } else*/if (itemLevel < 18) { return 0; } else if (itemLevel < 30) { return 1; } else if (itemLevel < 42) { return 2; } else if (itemLevel < 54) { return 3; } else if (itemLevel < 88) { return 4; } else if (itemLevel < 99) { return 5; } else if (itemLevel < 177) { return 6; } else { return 8; } }
6
public BinaryDataType createBinaryDataType() { return new BinaryDataType(); }
0
public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException { //System.out.println(request.getHeader("data")); //System.out.println(System.currentTimeMillis()); baseRequest.setHandled(true); //response.getWriter().println("Message From Server"); String command = request.getHeader("command"); String key = request.getHeader("key"); String value = request.getHeader("value"); String responseBody = "0"; if (command.equals("add")){ //int res = shardManager.addValue(key, value); //responseBody = String.valueOf(res); System.out.println("add(" + key + ", " + value + ")"); } else if (command.equals("del")){ //int res = shardManager.deleteValue(key); //responseBody = String.valueOf(res); System.out.println("del(" + key + ")"); } else if (command.equals("edit")){ //int res = shardManager.editValue(key, value); //responseBody = String.valueOf(res); System.out.println("edit(" + key + ", " + value + ")"); } else if (command.equals("get")){ //responseBody = shardManager.getValue(key); System.out.println("get(" + key + ")"); } else if (command.equals("getKeys")){ //responseBody = shardManager.getKeys(); System.out.println("getKeys"); } else if (command.equals("clear")){ //int res = shardManager.clearDataStorage(); //responseBody = String.valueOf(res); System.out.println("clear"); } else { responseBody = "4"; } response.getWriter().println(responseBody); }
6
TimeMarker[] getTimeMarkers( long start, long stop ) { start *= 1000; // Discard milliseconds stop *= 1000; Calendar cMaj = Calendar.getInstance(); Calendar cMin = Calendar.getInstance(); // Set the start calculation point for the grids setStartPoint(cMaj, majGridTimeUnit, start); setStartPoint(cMin, minGridTimeUnit, start); // Find first visible grid point long minPoint = cMin.getTimeInMillis(); long majPoint = cMaj.getTimeInMillis(); while ( majPoint < start ) majPoint = getNextPoint(cMaj, majGridTimeUnit, majGridUnitSteps); while ( minPoint < start ) minPoint = getNextPoint(cMin, minGridTimeUnit, minGridUnitSteps); ArrayList markerList = new ArrayList(); // Marker list does not care in what order the markers are returned, we could // get minor and major grid sequentially, but, if we did that, we might draw the marker // more than once if the major and minor overlap, which is most likely slower than // this way of calculating the markers. // // In short: the first while() loop is not *necessary* to get correct results while ( minPoint <= stop && majPoint <= stop ) { if ( minPoint < majPoint ) { markerList.add( new TimeMarker( minPoint, "", false ) ); minPoint = getNextPoint( cMin, minGridTimeUnit, minGridUnitSteps ); } else if ( minPoint == majPoint ) // Special case, but will happen most of the time { markerList.add( new TimeMarker( majPoint, dateFormat.format(cMaj.getTime()), true ) ); majPoint = getNextPoint( cMaj, majGridTimeUnit, majGridUnitSteps ); minPoint = getNextPoint( cMin, minGridTimeUnit, minGridUnitSteps ); } else { markerList.add( new TimeMarker( majPoint, dateFormat.format(cMaj.getTime()), true ) ); majPoint = getNextPoint( cMaj, majGridTimeUnit, majGridUnitSteps ); } } while ( minPoint <= stop ) { markerList.add( new TimeMarker( minPoint, "", false ) ); minPoint = getNextPoint( cMin, minGridTimeUnit, minGridUnitSteps ); } while ( majPoint <= stop ) { markerList.add( new TimeMarker( majPoint, dateFormat.format(cMaj.getTime()), true ) ); majPoint = getNextPoint( cMaj, majGridTimeUnit, majGridUnitSteps ); } return (TimeMarker[]) markerList.toArray( new TimeMarker[0] ); }
8
@Override public void actionPerformed(ActionEvent arg0) { Iterator<JRadioButton> it = buttonlist.iterator(); while ( it.hasNext() ) { JRadioButton thisButton = it.next(); if ( thisButton.isSelected() ) { if ( callbackHandler != null ) { callbackHandler.selectInterface(thisButton.getText()); setVisible(false); dispose(); } } } }
3
public void setParent(View parent) { super.setParent(parent); fContainer = parent!=null ?getContainer() :null; if( parent==null && fComponent!=null ) { fComponent.getParent().remove(fComponent); fComponent = null; } }
3
public void visit_lreturn(final Instruction inst) { stackHeight -= 2; if (stackHeight < minStackHeight) { minStackHeight = stackHeight; } }
1
private boolean guardarFichero (String salida) { boolean guardado = false; JFileChooser chooser = new JFileChooser(); int retrival = chooser.showSaveDialog(MainVentana.this); if (retrival == JFileChooser.APPROVE_OPTION) { try (FileWriter fw = new FileWriter(chooser.getSelectedFile()+".txt")) { String [] parciales = salida.split("\n"); for (String linea : parciales) { fw.write(linea); fw.append(System.lineSeparator()); } guardado = true; } catch (Exception e) { System.out.println("Error al tratar de guardar el archivo:\n"+e.getMessage()); guardado = false; } } return guardado; } // FIN guardarFichero
3
protected void checkMovement() { if(figUp && !figDown) figY -= speed; if(figDown && !figUp) figY += speed; if(figRight && !figLeft) figX += speed; if(figLeft && !figRight) figX -= speed; l.setFigureCoordinates(figX, figY); g.setFigureCoordinates(figX, figY); }
8
public void setCoordinates(List<T> coordinates) { this.coordinates = coordinates; }
0
public void start(BundleContext context) throws Exception { super.start(context); IWorkspace workspace = ResourcesPlugin.getWorkspace(); IResourceChangeListener listener = new IResourceChangeListener() { @Override public void resourceChanged(IResourceChangeEvent event) { // blocking double check after replacing if (!listenerLocked) { IResourceDeltaVisitor visitor = new IResourceDeltaVisitor() { public boolean visit(IResourceDelta delta) { //only interested in changed resources (not added or removed) if (delta.getKind() != IResourceDelta.CHANGED) return true; //only interested in content changes if ((delta.getFlags() & IResourceDelta.CONTENT) == 0) return true; IResource resource = delta.getResource(); //only interested in files if (resource.getType() == IResource.FILE) { ApexCheckstyleOnFilesJob job = new ApexCheckstyleOnFilesJob((IFile)resource, false); job.setRule(ResourcesPlugin.getWorkspace().getRoot()); job.schedule(); } return true; } }; try { event.getDelta().accept(visitor); } catch (CoreException e) { e.printStackTrace(); } } listenerLocked = false; } }; workspace.addResourceChangeListener(listener, IResourceChangeEvent.POST_CHANGE); }
5
@Override public List<Integer> sort(List<Integer> list) { // checking input parameter for null if (list == null) { throw new IllegalArgumentException("ArrayList not specified!"); } // building heap for (int child = 1; child < list.size(); child++) { int parent = (child - 1) / 2; // swap child & parent if parent < child while (parent >= 0 && list.get(parent).compareTo(list.get(child)) < 0) { appUtil.swap(list, parent, child); child = parent; parent = (child - 1) / 2; } } return shrinkHeap(list); }
4
public Lid getLid() { return lid; }
0
public void startNewGame() { // Create Deck createTime = new Date(); int count = 0; for (ItalianDeckSuit suit : ItalianDeckCard.ItalianDeckSuit.values()) { for (ItalianDeckRank rank : ItalianDeckCard.ItalianDeckRank .values()) { deck[count++] = new ItalianDeckCard(suit, rank); } } // Shuffle for (int i = 0; i < deck.length; i++) { ItalianDeckCard card = deck[i]; int random = (int) (Math.random() * 40); deck[i] = deck[random]; deck[random] = card; } this.life = drawCard(); hasStarted = true; for (int i = 0; i < playerHands.length; i++) { ItalianDeckCard[] temp = new ItalianDeckCard[3]; for (int j = 0; j < temp.length; j++) { temp[j] = drawCard(); } playerHands[i] = temp; } }
5
int[] ContaTudo() { FileWriter wr; PrintWriter pw; wr = null; pw = null; try{ wr = new FileWriter("resultado.csv", true); pw = new PrintWriter(wr, true); } catch(Exception e) { } if(!h) { pw.printf("Tempo, Presa, Predador, Reciclador, Defunto, Vazio\n"); h = true; tmp = 0; } int presa, predador, reciclador, defunto, nada, ret[]; ret = new int[5]; presa = predador = reciclador = defunto = 0; for(int i = 0; i < l; i++) for(int j = 0; j < c; j++) { if(mapa_atual[i][j].tipo == PRESA) presa++; else if(mapa_atual[i][j].tipo == PREDADOR) predador++; else if(mapa_atual[i][j].tipo == RECICLADOR) reciclador++; else if(mapa_atual[i][j].tipo == DEFUNTO) defunto++; } nada = l * c - presa - predador - reciclador; ret[0] = presa; ret[1] = predador; ret[2] = reciclador; ret[3] = defunto; ret[4] = nada; pw.printf("%d,%d,%d,%d,%d, %d\n", tmp++, ret[0], ret[1], ret[2], ret[3], ret[4]); pw.close(); return ret; }
8
private IFn findAndCacheBestMethod(Object dispatchVal) throws Exception{ Map.Entry bestEntry = null; for(Object o : getMethodTable()) { Map.Entry e = (Map.Entry) o; if(isA(dispatchVal, e.getKey())) { if(bestEntry == null || dominates(e.getKey(), bestEntry.getKey())) bestEntry = e; if(!dominates(bestEntry.getKey(), e.getKey())) throw new IllegalArgumentException( String.format( "Multiple methods in multimethod '%s' match dispatch value: %s -> %s and %s, and neither is preferred", name, dispatchVal, e.getKey(), bestEntry.getKey())); } } if(bestEntry == null) return null; //ensure basis has stayed stable throughout, else redo if(cachedHierarchy == hierarchy.deref()) { //place in cache methodCache = methodCache.assoc(dispatchVal, bestEntry.getValue()); return (IFn) bestEntry.getValue(); } else { resetCache(); return findAndCacheBestMethod(dispatchVal); } }
7
public void update() throws MaltChainedException { final AddressValue a = addressFunction.getAddressValue(); if (a.getAddress() == null) { if (getSymbolTable() != null) { featureValue.setIndexCode(getSymbolTable().getNullValueCode(NullValueId.NO_NODE)); featureValue.setSymbol(getSymbolTable().getNullValueSymbol(NullValueId.NO_NODE)); } else { featureValue.setIndexCode(0); featureValue.setSymbol("#null"); } // featureValue.setKnown(true); featureValue.setNullValue(true); } else { final DependencyNode node = (DependencyNode)a.getAddress(); if (!node.isRoot()) { if (getSymbolTable() != null && node.hasLabel(getSymbolTable())) { featureValue.setIndexCode(node.getLabelCode(getSymbolTable())); featureValue.setSymbol(getSymbolTable().getSymbolCodeToString(node.getLabelCode(getSymbolTable()))); // featureValue.setKnown(getSymbolTable().getKnown(node.getLabelCode(getSymbolTable()))); featureValue.setNullValue(false); } else { // featureValue.setCode(0); // featureValue.setSymbol("#null"); if (getSymbolTable() != null) { featureValue.setIndexCode(getSymbolTable().getNullValueCode(NullValueId.NO_VALUE)); featureValue.setSymbol(getSymbolTable().getNullValueSymbol(NullValueId.NO_VALUE)); } // else { // featureValue.setCode(0); // featureValue.setSymbol("#null"); // } // featureValue.setKnown(true); featureValue.setNullValue(true); } } else { if (getSymbolTable() != null) { featureValue.setIndexCode(getSymbolTable().getNullValueCode(NullValueId.ROOT_NODE)); featureValue.setSymbol(getSymbolTable().getNullValueSymbol(NullValueId.ROOT_NODE)); } // else { // featureValue.setCode(0); // featureValue.setSymbol("#null"); // } // featureValue.setCode(0); // featureValue.setSymbol("#null"); // featureValue.setKnown(true); featureValue.setNullValue(true); } } featureValue.setValue(1); }
7
public SimpleStringProperty countryProperty() { return country; }
0