text
stringlengths
14
410k
label
int32
0
9
private static String escapeJSON(String text) { StringBuilder builder = new StringBuilder(); builder.append('"'); for (int index = 0; index < text.length(); index++) { char chr = text.charAt(index); switch (chr) { case '"': case '\\': builder.append('\\'); builder.append(chr); break; case '\b': builder.append("\\b"); break; case '\t': builder.append("\\t"); break; case '\n': builder.append("\\n"); break; case '\r': builder.append("\\r"); break; default: if (chr < ' ') { String t = "000" + Integer.toHexString(chr); builder.append("\\u" + t.substring(t.length() - 4)); } else { builder.append(chr); } break; } } builder.append('"'); return builder.toString(); }
8
private void addCardElementsToList(NodeList nList, String type) { for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; if ( type == "CommunityChest" ) { cardElements.add(createCommunityChestElement(eElement)); } else if ( type == "Chance" ) { cardElements.add(createChanceElement(eElement)); } else if ( type == "Property" ) { cardElements.add(createPropertyElement(eElement)); } //endif } } }
5
public void checkProjectileCollisions() { for (Projectile p : projectiles) { //projectile to wall collisions boolean tmp[] = check.checkWallCollisions(p); for (int i = 0; i < 4; i++) { //mahdollista muuta käyttöä myöhemmin if(tmp[i]==true) p.destroy(); } //projectile to ship collisions for (Ship ship : ships) { if (check.checkProjectileToShipCollisions(p, ship)) { if(p.getTeam()!=ship.getTeam()){ p.destroy(); ship.changeHp(-p.getPower()); } } } } }
6
public Tex rendered() { if(rnm == null) { boolean hv = (type & 2) != 0; BufferedImage nm = null; if(name.length() > 0) nm = Utils.outline2(nfnd.render(name, BuddyWnd.gc[group]).img, Utils.contrast(BuddyWnd.gc[group])); int w = 0, h = 0; if(nm != null) { w += nm.getWidth(); if(nm.getHeight() > h) h = nm.getHeight(); } if(hv) { w += vlg.getWidth() + 1; if(vlg.getHeight() > h) h = vlg.getHeight(); } if(w == 0) { rnm = new TexIM(new Coord(1, 1)); } else { BufferedImage buf = TexI.mkbuf(new Coord(w, h)); Graphics g = buf.getGraphics(); int x = 0; if(hv) { g.drawImage(vlg, x, (h / 2) - (vlg.getHeight() / 2), null); x += vlg.getWidth() + 1; } if(nm != null) { g.drawImage(nm, x, (h / 2) - (nm.getHeight() / 2), null); x += nm.getWidth(); } g.dispose(); rnm = new TexI(buf); } } return(rnm); }
9
private double parseLevel1() throws ParsingException { if (tipoTokenActual == TOKEN_TYPE.VARIABLE) { TOKEN_TYPE tokenTemp = tipoTokenActual; String tokenNow = token;/*new String(token);*/ int temp_index = i; getToken(); if (token.equals("=")) { if (isFunction(tokenNow)) { throw new ParsingException("reserved word used as identifier '" + token + "'", i, ErrorType.IDENTIFICADOR_COMO_PALABRA_RESERVADA); } else if (userVar.isConstant(tokenNow)) { throw new ParsingException("cannot assign a value to const variable '" + tokenNow + "'", i, ErrorType.ASIGNACION_DE_CONSTANTE); } else if (tokenNow.equals("e")) { throw new ParsingException("cannot assign a value to const variable '" + tokenNow + "'", i, ErrorType.ASIGNACION_DE_CONSTANTE); } else if (tokenNow.equals("pi")) { throw new ParsingException("cannot assign a value to const variable '" + tokenNow + "'", i, ErrorType.ASIGNACION_DE_CONSTANTE); } else if (tokenNow.equals("g")) { throw new ParsingException("cannot assign a value to const variable '" + tokenNow + "'", i, ErrorType.ASIGNACION_DE_CONSTANTE); } else if (tokenNow.equals("random")) { throw new ParsingException("cannot assign a value to const variable '" + tokenNow + "'", i, ErrorType.ASIGNACION_DE_CONSTANTE); } getToken(); double r_temp = parseLevel2(); if (userVar.addVar(tokenNow, r_temp) == false) { throw new ParsingException("Defining variable failed", i, ErrorType.DEFINICION_DE_VARIABLE_FALLIDA); } else { return r_temp; } } else { // No era una asignación, hay que recuperar el índex: i = temp_index; token = tokenNow; tipoTokenActual = tokenTemp; } } return parseLevel2(); }
9
public void updateCustomer(Customer customer) { this.em.merge(customer); }
0
static int calculate(int x, int y) { if (y == 0) throw new ArithmeticException(); return x / y; }
1
private void writeHeader() throws IOException { byte FileLangId = dbfConfig.getLanguageID(); int HeaderSize = 0; int RecordHeaderSize = 0; byte[] header = null; if (dbfConfig.getDbfVersion() == ru.nyrk.util.jdbf.DBFConfig.DbfVersion.xBaseVII) { HeaderSize = 68; RecordHeaderSize = 48; header = new byte[HeaderSize]; header[VerDBFindex] = 0x03; header[4] = 0x01; } else { HeaderSize = 32; RecordHeaderSize = 32; header = new byte[HeaderSize]; if (dbfConfig.getDbfVersion() == ru.nyrk.util.jdbf.DBFConfig.DbfVersion.xFoxPro) { header[VerDBFindex] = 0x03; header[FileLangIdindex] = (byte)0xc9; HeaderSize += 263; } else header[VerDBFindex] = 0x03; // standard language WE, dBase III no language support if (dbfConfig.getDbfVersion() == ru.nyrk.util.jdbf.DBFConfig.DbfVersion.xBaseIII) header[FileLangIdindex] = 0; } Calendar clnd = Calendar.getInstance(); header[1] = (byte)(clnd.get(1) - 2000); header[2] = (byte)(clnd.get(2)+1); header[3] = (byte)clnd.get(5); if(dbfConfig.getRecCount() > 0){ copyTo(header, intToByteArray(dbfConfig.getRecCount()), 4 ); } int fieldsize = HeaderSize + RecordHeaderSize* fields.length+1; header[8] = (byte)(fieldsize % 256); header[9] = (byte)(fieldsize / 256); int recsize = 1; for (int i = 0; i < fields.length; i++) recsize += fields[i].getLength(); header[10] = (byte)(recsize % 256); header[11] = (byte)(recsize / 256); stream.write(header, 0, header.length); }
5
@Override public void run() { while (true) { if (!pause) { Log.i("TaskClearing!!!"); try { Set<String> keys = runningTasks.keySet(); Iterator<String> iterator = keys.iterator(); while (iterator.hasNext()) { String key = iterator.next(); ServerTask task = runningTasks.get(key); if (System.currentTimeMillis() - task.getLastActiveTime() > MAX_TASK_FREE_TIME) { runningTasks.remove(key); if (task instanceof FriendServerTask) { freeFriendServerTasks.add((FriendServerTask) task); }else if(task instanceof GroupServerTask){ freeGroupServerTasks.add((GroupServerTask) task); } Log.i("TaskClearing!!!--clear "+task.getServeUni()); } } sleep(CLEAR_PERIOD); } catch (InterruptedException e) { //Log.e(e.getMessage()); } catch (Exception e) { // TODO: handle exception } } } }
8
public boolean isCellEditable(int row, int col) { if (col == ID || col == USE || col == ENTITY) return false; return true; }
3
public static void main(String ... a) throws Exception { Options options = new Options(); options.addOption("i", "input", true, "input path. Required"); options.addOption("o", "output", true, "output path. Required"); options.addOption("b", "block-size", true, "size in bytes of i/o block"); options.addOption("m", "memory-size", true, "size in bytes of memory buffer"); options.addOption("c", "split-count", true, "number of parts file should be splitted"); options.addOption("t", "tmp", true, "directory for temporary files"); options.addOption("dt", "generate-test-data", true, "Generates test data"); options.addOption("ts", "text-sort", false, "Sorts text file with a number per line"); options.addOption("t2b", "text-to-binary", false, "converts text to binary file"); options.addOption("b2t", "binary-to-text", false, "converts binary to text file"); options.addOption("h", "help", false, "shows this table"); CommandLineParser parser = new PosixParser(); CommandLine arguments = parser.parse(options, a); if ((!arguments.hasOption("o") && !(arguments.hasOption("dt") || arguments.hasOption("i"))) || arguments.hasOption("h")) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("java -jar sort-jar-with-dependencies.jar", options); return; } Path outputPath = Paths.get(arguments.getOptionValue("o")); if (arguments.hasOption("dt")) { long size = Long.parseLong(arguments.getOptionValue("dt")); FileTransformer.generateTestData(outputPath, size); return; } int bufferSize = Integer.parseInt(arguments.getOptionValue("b", "1048576")); int bigBufferSize = Integer.parseInt(arguments.getOptionValue("m", "536870912")); Preconditions.checkArgument(bufferSize % 8 == 0); Preconditions.checkArgument(bigBufferSize % 16 == 0); Preconditions.checkArgument(bigBufferSize > 2 * bufferSize); int maxBufferCount = bigBufferSize / bufferSize - 1; int bufferCount = Integer.parseInt(arguments.getOptionValue("c", maxBufferCount + "")); bufferCount = Math.max(2, bufferCount); bufferCount = Math.min(maxBufferCount, bufferCount); Path inputPath = Paths.get(arguments.getOptionValue("i")); Path tmpDir = Paths.get(arguments.getOptionValue("t", "./sort-tmp")); Preconditions.checkArgument(Files.exists(inputPath)); FileUtils.deleteDirectory(tmpDir.toFile()); Files.createDirectories(tmpDir); List<ByteBuffer> bigBuffer = Utils.buildBuffersPool(bigBufferSize); ByteBuffer readBuffer = ByteBuffer.allocateDirect(bufferSize); LongSerializer serializer = new LongSerializer(); ChannelIterable.Builder<Long> channelIterator = new Builder<>(readBuffer, serializer); ByteBuffersList<Long> list = new ByteBuffersList<>(bigBuffer, serializer); Files.deleteIfExists(outputPath); if (arguments.hasOption("t2b")) { FileTransformer.textToBinaryNumbers(inputPath, outputPath, readBuffer); return; } if (arguments.hasOption("b2t")) { FileTransformer.binaryNumbersToText(inputPath, outputPath, readBuffer); return; } System.out.println("Parameters: " + Files.size(inputPath) + " " + bigBufferSize + " " + bufferSize + " " + bufferCount); if (arguments.hasOption("ts")) { Path binInputPath = Paths.get(inputPath.toString() + ".bin"); Files.deleteIfExists(binInputPath); Path binOutputPath = Paths.get(outputPath.toString() + ".bin"); Files.deleteIfExists(binOutputPath); FileTransformer.textToBinaryNumbers(inputPath, binInputPath, readBuffer); ExternalMemorySort<Long> sortByDustribution = new ExternalMemorySort<>(channelIterator, list, bufferCount, tmpDir); sortByDustribution.sort(binInputPath, binOutputPath, Ordering.<Long>natural()); FileTransformer.binaryNumbersToText(binOutputPath, outputPath, readBuffer); return; } ExternalMemorySort<Long> sort = new ExternalMemorySort<>(channelIterator, list, bufferCount, tmpDir); sort.sort(inputPath, outputPath, Ordering.<Long>natural()); }
8
private void waterFlow() { float flowRate = Globals.getSetting("Flow rate", "Water");//0.04f; float flowThreshold = Globals.getSetting("Flow threshold", "Water");//0.1f; for(int x = 1; x < Globals.width-1; x++){ for(int y = 1; y < Globals.height-1; y++){ if(groundWaterLevel[x][y] >= flowRate){ float height = Globals.heightmap[x][y]; for(int[] neighbor : HexagonUtils.neighborTiles(x, y, false)){ if(Globals.heightmap[neighbor[0]][neighbor[1]] < height && groundWaterLevel[neighbor[0]][neighbor[1]] < 1.0f-flowThreshold){ groundWaterLevel[x][y] -= flowRate; groundWaterLevel[neighbor[0]][neighbor[1]] += flowRate; } } } } } }
6
void gotoNextLiftSource() { if (!demoMode) return; Hill hill = null; Cloud cloud = null; if (app.landscape != null) { hill = app.landscape.nextHill(new Vector3d(p.x, p.y + 2, p.z)); } if (app.sky != null) { cloud = app.sky.nextCloud(new Vector3d(p.x, p.y + 2, p.z)); } cutPending = false; if (hill != null) { this.moveManager.setCircuit(hill.getCircuit()); cutPending = true; cutWhen = whenArrive(hill.x0, hill.y0) - app.cameraMan.CUT_LEN * 2; //??2 cutSubject = hill; cutCount = 0; //System.out.println("Cut when: " + cutWhen); return; } //no hill - look at clouds if (cloud == null) { //backtrack upwind if (app.sky != null) cloud = app.sky.prevCloud(new Vector3d(p.x, p.y - 2, p.z)); if (cloud == null) { //try again later, fly downwind for now this.moveManager.setTargetPoint(new Vector3d(p.x, p.y + 8, p.z)); tryLater = 25; return; } } //glide to cloud this.moveManager.setCloud(cloud); cutPending = true; cutWhen = whenArrive(cloud.p.x, cloud.p.y) - app.cameraMan.CUT_LEN * 2; cutSubject = cloud; cutCount = 0; //System.out.println("Cut when: " + cutWhen); //app.cameraMan.cutSetup(cloud, isUser); }
7
public static String composeWhereForNum(String sql, String fieldName, String fieldValue, int action) { // String sTmp = String.valueOf(fieldValue); if (fieldValue == null || fieldValue.trim().compareTo("") == 0) return sql; String sTmp = fieldName + " = " + fieldValue; switch (action) { case EQUAL: break; case LIKE: break; case GE: sTmp = fieldName + " >= " + fieldValue; break; case LE: sTmp = fieldName + " <= " + fieldValue; break; case IN: sTmp = fieldName + " in (" + fieldValue + ")"; break; } if (sql == null || sql.trim().compareTo("") == 0) return " WHERE " + sTmp; else return sql + " AND " + sTmp; }
9
private void btnEkleMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnEkleMousePressed if(!btnEkle.isEnabled()) return ; HashMap<String, String> values = new HashMap<>(); values.put("ad", txtAd.getText().trim()); values.put("soyad", txtSoyad.getText().trim()); values.put("telefon", txtTelefon.getText().trim()); values.put("resimURL", "C:\\"); values.put("kullaniciAdi", txtKullaniciAdi.getText().trim()); values.put("sifre1", txtSifre.getText().trim()); values.put("sifre2", txtSifreTekrar.getText().trim()); values.put("maas", txtMaas.getText().trim()); values.put("adres", txtAdres.getText().trim()); if(radioAdmin.isSelected()) values.put("tip", KisiI.ADMIN+""); else values.put("tip", KisiI.KASIYER+""); Calisan c = mutlakkafe.MutlakKafe.mainCont.getCalisanCont().getCalisan(values); if(c != null){ mutlakkafe.MutlakKafe.mainCont.getCalisanCont().kisiEkle(c); kilitle(); lstKasiyerListesi.setModel(mutlakkafe.MutlakKafe.mainCont.getCalisanCont().kullaniciAdiList()); lblToplamKayit.setText("Toplam Kayıt : " + lstKasiyerListesi.getModel().getSize()); } }//GEN-LAST:event_btnEkleMousePressed
3
public void setScale(double scale){ scaleBy = scale; // drawer.setScale(scale); }
0
public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Please enter number of rows for a matrix operation"); int rows = Integer.parseInt(reader.readLine()); System.out.println("Please enter number of columns for a matrix operation"); int columns = Integer.parseInt(reader.readLine()); int[][] matrix = new int[rows][columns]; System.out.println("Please enter row elements the matrix"); for (int i = 0; i < rows; i++) { System.out.println("Please enter row " + i + " elements"); for (int j = 0; j < columns; j++) { matrix[i][j] = Integer.parseInt(reader.readLine()); } } System.out.println("Your Matrix is : "); for (int rowIndex = 0; rowIndex < matrix.length; rowIndex++) { int[] row = matrix[rowIndex]; if (row != null) { for (int columnIndex = 0; columnIndex < row.length; columnIndex++) { System.out.print(matrix[rowIndex][columnIndex] + "\t"); } } System.out.println(); } int[][] updatedMatrix = rotateMaxtrix(matrix, rows); System.out.println("Updatedf Matrix is : "); for (int rowIndex = 0; rowIndex < updatedMatrix.length; rowIndex++) { int[] row = updatedMatrix[rowIndex]; if (row != null) { for (int columnIndex = 0; columnIndex < row.length; columnIndex++) { System.out.print(updatedMatrix[rowIndex][columnIndex] + "\t"); } } System.out.println(); } }
8
public static void download(final String from, final String to) { try { final URL url = new URL(from); out = new BufferedOutputStream(new FileOutputStream(to)); in = url.openConnection().getInputStream(); while ((read = in.read(buffer)) != -1) out.write(buffer, 0, read); System.out.println("The file at <" + from + "> was downloaded to the path <" + to + ">."); } catch (MalformedURLException e) { System.err.println("The URL given <" + from + "> was not found!"); } catch (FileNotFoundException e) { System.err.println("The file path given <" + to + "> was not found!"); } catch (IOException e) { e.printStackTrace(); } finally { closeStreams(); } }
4
public void process(){ for(Entity e : getEntities()){ Velocity v = (Velocity) e.getComponent(velocityID); if(v.isEnabled()){ v.x += v.dx; //v.y += v.dy; if(v.x > 450 || v.x < 0) v.dx *= -1; //if(v.y > 450 || v.y < 0) v.dy *= -1; } } }
4
@Override public int getIndexOfChild(Object parent, Object child) { int count = 0; Class<?> type = parent.getClass(); if (type == Schema.class) { TreeMap<String, Table> tables = ((Schema)parent).getTables(); for (Map.Entry<String, Table> t : tables.entrySet()) { if (t.getKey().compareTo(child.toString()) == 0) { return count; } else { count++; } } return -1; } else if (type == Table.class) { TreeMap<String, Attribute> attrs = ((Table)parent).getAttrs(); for (Map.Entry<String, Attribute> a : attrs.entrySet()) { if (a.getKey().compareTo(child.toString()) == 0) { return count; } else { count++; } } } else if (type == Attribute.class) { return -1; } return -1; }
8
public static int kadaneAlgo (int[] seq) { int curr_max_sum = seq[0]; int max_sum = 0xFFFFFFFF; int temp_start = 0; for (int i = 1; i < seq.length; i++) { if (curr_max_sum < 0) { temp_start = i; curr_max_sum = seq[i]; } else { curr_max_sum += seq[i]; } if (curr_max_sum > max_sum) { start = temp_start; max_sum = curr_max_sum; end = i; } } return (max_sum); }
3
int getInfluencer(boolean[][] followingMatrix){ if(followingMatrix == null || followingMatrix.length != followingMatrix[0].length) return -1; Queue<Integer> queue = new LinkedList<Integer>(); boolean[] checked = new boolean[followingMatrix.length]; queue.offer(0); while(!queue.isEmpty()){ int currentUser = queue.poll(); boolean influencer = true; checked[currentUser] = true; for(int i=0; i<followingMatrix.length; i++){ if(i == currentUser) continue; if(!followingMatrix[i][currentUser]){ if(!checked[i]) queue.offer(i); influencer = false; } } if(influencer) return currentUser; } return -1; }
8
public static void mobSpawner() { // int mobSpawnGoal1; // int mobSpawnGoal2; // int mobSpawnGoal3; // mobSpawnGoal1 = 1; if(spawnFrameMob1 >= spawnTimeMob1){ // && mobSpawnCount1 < mobSpawnGoal1 for(int i = 0; i < Screen.mobs.length; i++){ if(!Screen.mobs[i].inGame){ Screen.mobs[i].spawnMob(Value.mobGreen); mobSpawnCount1 += 1; break; } } spawnFrameMob1 = 0; } else { spawnFrameMob1 += 1; // if(mobSpawnCount1 >= mobSpawnGoal1){ // Screen.hasWonWave(); // mobSpawnGoal1 = Screen.killsToWin + Screen.currentWave; // System.out.println(mobSpawnGoal1); // } } if(spawnFrameMob2 >= spawnTimeMob2){ for(int i = 0; i < Screen.mobs.length; i++){ if(!Screen.mobs[i].inGame){ Screen.mobs[i].spawnMob(Value.mobPink); mobSpawnCount2 += 1; break; } } spawnFrameMob2 = 0; } else { spawnFrameMob2 += 1; } if(spawnFrameMob3 >= spawnTimeMob3){ for(int i = 0; i < Screen.mobs.length; i++){ if(!Screen.mobs[i].inGame){ Screen.mobs[i].spawnMob(Value.mobYellow); mobSpawnCount3 += 1; break; } } spawnFrameMob3 = 0; } else { spawnFrameMob3 += 1; } }
9
@EventHandler(priority=EventPriority.LOW) public void getEnchantments(EnchantItemEvent event) { if(event.isCancelled()) return; Player play = event.getEnchanter(); Map<Enchantment, Integer> enchantments = event.getEnchantsToAdd(); if(MCListeners.isMultiWorld() && !play.hasPermission("mcjobs.world.all") && !play.hasPermission("mcjobs.world." + play.getWorld().getName())) { return; } for(Map.Entry<String, PlayerJobs> e : PlayerJobs.getJobsList().entrySet()) { if(PlayerCache.hasJob(play.getName(), e.getKey())) { CompCache comp = new CompCache(e.getKey(), play.getLocation(), play, enchantments, "enchant"); CompData.getCompCache().add(comp); } } }
6
static final boolean method989(int i, int i_92_, int i_93_) { anInt8401++; if (Class156.method1241(i_93_, i, i_92_ ^ 0x1fe) | (0x10000 & i) != 0 || BufferedPacket.method3325(i, i_93_, true)) return true; if (i_92_ != -385) return false; if ((i_93_ & 0x37) != 0 || !Class273.method2056(i, 120, i_93_)) return false; return true; }
5
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList1ValueChanged if (editor == jTextField1) { if (jList1.getSelectedValue() == null) jTextField1.setText(""); else jTextField1.setText(jList1.getSelectedValue().toString()); } else if (editor == jComboBox1) { if (jList1.getSelectedValue() == null) { jComboBox1.setSelectedIndex(jComboBox1.getItemCount()>0?0:-1); } else jComboBox1.setSelectedItem(jList1.getSelectedValue()); } else if (editor == pointPanel) { if (jList1.getSelectedValue() == null) { jSpinner1.setValue(0); jSpinner1.setValue(0); } else { jSpinner1.setValue(((Point)jList1.getSelectedValue()).x); jSpinner1.setValue(((Point)jList1.getSelectedValue()).y); } } else if (editor == CharStringMapPanel) { if (jList1.getSelectedValue() == null) { jTextField2.setText(""); jTextField3.setText(""); } else { jTextField2.setText(((Map.Entry)jList1.getSelectedValue()).getKey().toString()); jTextField3.setText(((Map.Entry)jList1.getSelectedValue()).getValue().toString()); } } }//GEN-LAST:event_jList1ValueChanged
9
@Override public void handleWindow(final Window window, int eventID) { if (!firstTradesWindowOpened) { showAllTrades = Settings.settings().getBoolean("ShowAllTrades", false); } if (!showAllTrades) { firstTradesWindowOpened = true; return; } if (eventID == WindowEvent.WINDOW_OPENED) { if (findCheckBox(window, "Sun") != null) { Utils.logToConsole("Setting trades log to show all trades"); // TWS versions before 955 SwingUtils.setCheckBoxSelected(window, "Sun", true); SwingUtils.setCheckBoxSelected(window, "Mon", true); SwingUtils.setCheckBoxSelected(window, "Tue", true); SwingUtils.setCheckBoxSelected(window, "Wed", true); SwingUtils.setCheckBoxSelected(window, "Thu", true); SwingUtils.setCheckBoxSelected(window, "Fri", true); SwingUtils.setCheckBoxSelected(window, "Sat", true); SwingUtils.setCheckBoxSelected(window, "All", true); monitorAllTradesCheckbox(window, "All"); if (! firstTradesWindowOpened) { if (Settings.settings().getBoolean("MinimizeMainWindow", false)) { ((JFrame) window).setExtendedState(java.awt.Frame.ICONIFIED); } } } else { Utils.logToConsole("Can't set trades log to show all trades with this TWS version: user must do this"); /* * For TWS 955 onwards, IB have replaced the row of daily * checkboxes with what appears visually to be a combo box: * it is indeed derived from a JComboBox, but setting the * selected item to 'Last 7 Days' doesn't have the desired * effect. * * At present I don't see a way of getting round this, but * the setting chosen by the user can now be persisted * between sessions, so there is really no longer a need for * 'ShowAllTrades'. * */ showAllTrades = false; ((JFrame) window).dispose(); } firstTradesWindowOpened = true; } else if (eventID == WindowEvent.WINDOW_CLOSING) { Utils.logToConsole("User closing trades log"); } else if (eventID == WindowEvent.WINDOW_CLOSED) { if (showAllTrades) { Utils.logToConsole("Trades log closed by user - recreating"); Utils.showTradesLogWindow(); } } }
9
public String getImie() { return imie; }
0
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(AltaPerfil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AltaPerfil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AltaPerfil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AltaPerfil.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 AltaPerfil().setVisible(true); } }); }
6
public Point2D getLocation() { return this; }
0
public int getUnsignedSmart() { // method421 int i = payload[offset] & 0xff; if (i < 0x80) { return getUnsignedByte() - 0x40; } else { return getUnsignedShort() - 0xC000; } }
1
@Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } Position other = (Position) obj; return this.x == other.x && this.y == other.y; }
4
private void setID(String num){ switch(num){ case "A": id = 1; break; case "J": id = 11; break; case "Q": id = 12; break; case "K": id = 13; break; default: id = Integer.parseInt(num); break; } }
4
public ResultPage<Book> getBooks(String search, String searchColumn, String orderColumn, int offset) throws SQLException { openBooksDatabase(); StringBuilder query = new StringBuilder("SELECT * FROM Titles WHERE "); if (searchColumn.equals("Title")) { query.append("Title"); } else { query.append("Author"); } query.append(" LIKE ? ORDER BY "); if (orderColumn.equals("Title")) { query.append("Title, Author"); } else { query.append("Author, Title"); } query.append(" LIMIT 11 OFFSET ?"); PreparedStatement statement = booksConnection.prepareStatement(query.toString()); statement.setString(1, '%' + search + '%'); statement.setInt(2, offset * 10); ResultSet resultSet = statement.executeQuery(); ArrayList<Book> results = new ArrayList<Book>(10); openPatronsDatabase(); for (int book = 0; book < 10 && resultSet.next(); book++) { PreparedStatement subStatement = patronsConnection.prepareStatement( "SELECT * FROM CheckedOut " + "WHERE BookNumber = ?"); subStatement.setInt(1, resultSet.getInt(1)); ResultSet subResultSet = subStatement.executeQuery(); results.add(new Book(resultSet.getInt(1), resultSet.getString(2), resultSet.getString(3), subResultSet.next())); subResultSet.close(); subStatement.close(); } closePatronsDatabase(); boolean isBeginning = false; boolean isEnd = false; if (offset == 0) { isBeginning = true; } if (!resultSet.next()) { isEnd = true; } resultSet.close(); statement.close(); closeBooksDatabase(); return new ResultPage<Book>(results, offset, isBeginning, isEnd); }
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(AlteraCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AlteraCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AlteraCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AlteraCliente.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 AlteraCliente().setVisible(true); } }); }
6
private static String getNumberEncoding(String characters) { if ("ABC".contains(characters)) { return "2"; } else if ("DEF".contains(characters)) { return "3"; } else if ("GHI".contains(characters)) { return "4"; } else if ("JKL".contains(characters)) { return "5"; } else if ("MNO".contains(characters)) { return "6"; } else if ("PQRS".contains(characters)) { return "7"; } else if ("TUV".contains(characters)) { return "8"; } else if ("WXYZ".contains(characters)) { return "9"; } else { return characters; } }
8
public static void removeVarObject(int objectType, int objectX, int objectY, int objectHeight) { for (int index = 0; index < varObjects.size(); index++) { VariableObject vo = varObjects.get(index); if(vo == null) continue; if(vo.getType() == objectType && vo.getX() == objectX && vo.getY() == objectY && vo.getHeight() == objectHeight) { varObjects.remove(index); break; } } }
6
public ArrayList<FrameSet> partition(String partitionType, int partitionOption){ //System.out.println("Partitioning."); // Generate set number of partitions. int itemsPerPartition = 0; int numberOfPartitions = 0; if (partitionType.equalsIgnoreCase("numberPartitions")){ itemsPerPartition = this.size / partitionOption; if(itemsPerPartition == 0) { numberOfPartitions = this.size; itemsPerPartition = 1; }else{ numberOfPartitions = partitionOption; } }else if(partitionType.equalsIgnoreCase("partitionSize")){ if (partitionOption > this.size){ itemsPerPartition = this.size; numberOfPartitions = 1; }else{ numberOfPartitions = (int) Math.ceil((double) this.size / partitionOption); itemsPerPartition = partitionOption; } }else{ throw new IllegalArgumentException("partitionType can only equal 'numberPartitions' or 'partitionSize'."); } //System.out.println(itemsPerPartition); //System.out.println(numberOfPartitions); ArrayList<FrameSet> partitions = new ArrayList<FrameSet>(numberOfPartitions); List<ArrayRealVector> source = permuteList(frameSet); for(int i = 0; i < numberOfPartitions; i++){ ArrayList<ArrayRealVector> subset = new ArrayList<ArrayRealVector>(); int addUntil = Math.min(i+itemsPerPartition, this.size); for(int j = i; j < addUntil; j++){ subset.add(source.get(j)); } partitions.add(new FrameSet(subset)); } return partitions; }
6
public ArrayList<Integer> cluster(){ int number_of_clusters = 3;//(int)Math.ceil(this.p.len/4); int its = 100; Dataset data = new DefaultDataset(); data.addAll(Arrays.asList(instances)); Dataset[] best_clusters = null; double best_score = 999999999999.0; for (int niter=0; niter<5; niter++) { Clusterer km = new KMeans(number_of_clusters, its); // new CosineSimilarity()); System.out.println("Clustering..."); Dataset[] clusters = km.cluster(data); System.out.println("End Clustering"); ClusterEvaluation sse = new SumOfSquaredErrors(); double score = sse.score(clusters); System.out.println("Score = "+score); System.out.println(""); if (score<best_score){ best_score = score; best_clusters = clusters; } } ArrayList<Integer> fpages = new ArrayList<Integer>(); ArrayList<Double> averages = new ArrayList<Double>(); System.out.println("Running Clustering with:"); System.out.println("Number of clusters = "+number_of_clusters); System.out.println("Iterations = "+its); System.out.println("Distance Measure = Cosine Similarity"); System.out.println("Best Score = "+best_score); System.out.println(""); System.out.println("Clusters found: " + best_clusters.length); for (int i=0;i<number_of_clusters;i++){ System.out.println(""); System.out.println(""); System.out.println(" ========== Cluster #"+(i+1)+" size: " +best_clusters[i].size()+" ========== "); System.out.println(""); double tot = 0; for (int j=0;j<best_clusters[i].size();j++) { Integer page = (Integer)best_clusters[i].get(j).classValue(); int key = p.pagenumbers.indexOf(page); tot += p.percent_color.get(key); System.out.print((page+1)+" "); } double aver = tot/best_clusters[i].size(); System.out.println("\nAverage = "+aver); averages.add(aver); } // Selecting the most suitabble pages from the clusters found int target = (int)(p.pagenumbers.size()*saving); int tot = 0; while (tot < target){ int select = max_douArrayList(averages); int projection = Math.abs(target - tot + best_clusters[select].size()); if (( projection > (target - tot)) && (tot > 0)) break; for (int i=0; i<best_clusters[select].size(); i++){ fpages.add((Integer)best_clusters[select].get(i).classValue()); tot += 1; } averages.set(select, -1.0); } return fpages; }
8
public void receivePose(SimplePose pose) { if (markerTransGroup == null){ return; } double[] trans = new double[3]; double[] rot = new double[4]; trans[0] = pose.getTx(); trans[1] = pose.getTy(); trans[2] = pose.getTz(); rot[0] = pose.getRx(); rot[1] = pose.getRy(); rot[2] = pose.getRz(); rot[3] = pose.getRw(); for (int i = positions.length - 1; i > 0; i--) { positions[i] = positions[i-1]; } positions[0] = new Vector3d(pose.getTx(), pose.getTy(), pose.getTz()); Quat4d quat = new Quat4d(pose.getRx(), pose.getRy(), pose.getRz(), pose.getRw()); int i = 1; Vector3d sum = positions[0]; for (i = 1; i < positions.length - 1 && positions[i] != null; i++) { sum.add(positions[i]); } sum.scale((double)1/i); Transform3D markerTransform = new Transform3D(); markerTransform.set(quat, sum, 1); markerTransGroup.setTransform(markerTransform); }
4
public int compareTo(InvalidOperation other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; InvalidOperation typedOther = (InvalidOperation)other; lastComparison = Boolean.valueOf(isSetWhat()).compareTo(typedOther.isSetWhat()); if (lastComparison != 0) { return lastComparison; } if (isSetWhat()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.what, typedOther.what); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetWhy()).compareTo(typedOther.isSetWhy()); if (lastComparison != 0) { return lastComparison; } if (isSetWhy()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.why, typedOther.why); if (lastComparison != 0) { return lastComparison; } } return 0; }
7
@Override public boolean hasNext() { while (count < vortexSpaces.length && vortexSpaces[count] == null) { count++; } if (count < vortexSpaces.length) { return true; } count = 0; return false; }
3
@Override public int compareTo(Oriented<S> o) { return orientation ? item.compareTo(o.item) : o.item.compareTo(item); }
1
public BufHashTbl() { // initializes all entries in the Page Table to null for (int i=0; i < HTSIZE; i++) ht[i] = null; } // end constructor
1
private void RightButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RightButtonActionPerformed if (FocusOwnerIndex == 1) { if (NumberField1.getCaretPosition() >= NumberField1.getText().length()) { // jump to next textfield FocusOwnerIndex += 1; NumberField2.requestFocus(); NumberField2.setCaretPosition(0); // before first character } else { NumberField1.setCaretPosition(NumberField1.getCaretPosition() + 1); NumberField1.getCaret().setVisible(true); } } else if (FocusOwnerIndex == 2) { if (NumberField2.getCaretPosition() >= NumberField2.getText().length()) { // jump to next textfield FocusOwnerIndex += 1; NumberField3.requestFocus(); NumberField3.setCaretPosition(0); // before first character } else { NumberField2.setCaretPosition(NumberField2.getCaretPosition() + 1); NumberField2.getCaret().setVisible(true); } } else if (FocusOwnerIndex == 3) { if (NumberField3.getCaretPosition() >= NumberField3.getText().length()) { // jump to next textfield FocusOwnerIndex += 1; NumberField4.requestFocus(); NumberField4.setCaretPosition(0); // before first character } else { NumberField3.setCaretPosition(NumberField3.getCaretPosition() + 1); NumberField3.getCaret().setVisible(true); } } else if (FocusOwnerIndex == 4) { if (NumberField4.getCaretPosition() >= NumberField4.getText().length()) { // do nothing } else { NumberField4.setCaretPosition(NumberField4.getCaretPosition() + 1); NumberField4.getCaret().setVisible(true); } } }//GEN-LAST:event_RightButtonActionPerformed
8
public List<T> DFS() { List<T> dfsTraversalElements = new ArrayList<T>(); Stack<BinaryTree<T>> nodes = new Stack<BinaryTree<T>>(); nodes.push(this); while (!nodes.isEmpty()) { BinaryTree<T> node = nodes.pop(); if(node != null) { nodes.push(node); BinaryTree<T> leftNode = node.left; while (leftNode != null) { nodes.push(leftNode); leftNode = leftNode.left; } BinaryTree<T> leftMostNode = nodes.pop(); if(leftMostNode != node.left || leftMostNode.right == null) { dfsTraversalElements.add(leftMostNode.value); } BinaryTree<T> rightNode = node.right; while (rightNode != null) { nodes.push(rightNode); rightNode = rightNode.right; } BinaryTree<T> rightMostNode = nodes.pop(); if(rightMostNode != node.right || rightMostNode.left == null) { dfsTraversalElements.add(rightMostNode.value); } } } dfsTraversalElements.add(nodes.pop().value); return dfsTraversalElements; }
8
public static void openURL(String url) { try { //attempt to use Desktop library from JDK 1.6+ Class<?> d = Class.forName("java.awt.Desktop"); d.getDeclaredMethod("browse", new Class[] {java.net.URI.class}).invoke( d.getDeclaredMethod("getDesktop").invoke(null), new Object[] {java.net.URI.create(url)}); //above code mimicks: java.awt.Desktop.getDesktop().browse() } catch (Exception ignore) { //library not available or failed String osName = System.getProperty("os.name"); try { if (osName.startsWith("Mac OS")) { Class.forName("com.apple.eio.FileManager").getDeclaredMethod( "openURL", new Class[] {String.class}).invoke(null, new Object[] {url}); } else if (osName.startsWith("Windows")) Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url); else { //assume Unix or Linux String browser = null; for (String b : browsers) if (browser == null && Runtime.getRuntime().exec(new String[] {"which", b}).getInputStream().read() != -1) Runtime.getRuntime().exec(new String[] {browser = b, url}); if (browser == null) throw new Exception(Arrays.toString(browsers)); } } catch (Exception e) { JOptionPane.showMessageDialog(null, errMsg + "\n" + e.toString()); } } }
9
public void execute() { try { while( !terminated ) { final List commandList = getCommandList(); final Map resultMap = getCommandResult( commandList ); List[] lists = getCommandResultAsLists( commandList, resultMap ); info( lists[ 0 ].size() + "/" + ipList.size() + " servers alive." ); info( lists[ 1 ].size() + "/" + ipList.size() + " servers dead." ); try { checkDNS( MDozensHA.getInstance().getRecordMap(), lists[ 0 ], lists[ 1 ] ); //dozensErrorCount = 0; //reset error count } catch( Exception e ) { //++dozensErrorCount; warn( e.getClass() ); warn( e ); } if( state == STATE_OK ) { MSystemUtil.sleep( failover_interval * 1000 ); } else { MSystemUtil.sleep( failback_interval * 1000 ); } } } catch( Exception e ) { warn( e ); } }
4
@Override public void start() { Logger l = plugin.getLogger(); try { if (socket == null) { socket = new ServerSocket(port); running = true; } if (running) { try { l.log(Level.INFO, "Waiting for connection.."); Socket client = socket.accept(); ClientHandler handler = new ClientHandler(client, plugin); l.log(Level.INFO, "New client submitted: " + client.getInetAddress()); service.submit(handler); } catch (IOException e) { e.printStackTrace(); l.log(Level.SEVERE, e.getMessage()); } } } catch (IOException e) { e.printStackTrace(); } }
4
private void synchronizeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_synchronizeButtonActionPerformed synchronizeButton.setEnabled(false); this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try { final String sourceDir = sourceDirectoyField.getText(); final String targetDir = targetDirectoryField.getText(); if (sourceDir != null && targetDir != null) { DirectorySyncer directorySyncer = new DirectorySyncer(sourceDir, targetDir, isSimulationMode); Map<String, Path> targetMap = directorySyncer.buildTargetFileMap(); report = directorySyncer.findAndHandleSourcesInTargetMap(targetMap); report = directorySyncer.cleanupDirs(report); this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); new ReportDialog(MainFrame.this, false).setVisible(true); //jDialog.setTitle("Syncing worked"); } //} catch (InterruptedException e) { // interrupt(); // System.out.println("Unterbrechung in sleep()"); } catch (IOException e1) { JDialog jDialog = new JDialog(MainFrame.this); jDialog.setTitle("Syncing failed"); this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); new ReportDialog(MainFrame.this, false).setVisible(true); } catch (Exception ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } }//GEN-LAST:event_synchronizeButtonActionPerformed
4
public static void main(String[] args) { FileMerger app = new FileMerger(); app.getFileName(); if (!app.createFileList()) { System.exit(0); } try { app.mergeFiles(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
2
private void ssInsertionSort (int PA, int first, int last, int depth) { final int[] SA = this.SA; int i, j; // pointer within SA int t; int r; for (i = last - 2; first <= i; --i) { for (t = SA[i], j = i + 1; 0 < (r = ssCompare (PA + t, PA + SA[j], depth));) { do { SA[j - 1] = SA[j]; } while ((++j < last) && (SA[j] < 0)); if (last <= j) { break; } } if (r == 0) { SA[j] = ~SA[j]; } SA[j - 1] = t; } }
6
public Processor(Privilege privilege, int numPhysPages) { System.out.print(" processor"); // Sets the pagesize if(Config.getString("Processor.pageSize")!= null) { pageSize = Config.getInteger("Processor.pageSize"); } else { // default pagesize pageSize = 0x400; } //System.out.println("PageSize = " + pageSize); maxPages = (int) (0x100000000L / pageSize); this.privilege = privilege; privilege.processor = new ProcessorPrivilege(); Class clsKernel = Lib.loadClass(Config.getString("Kernel.kernel")); Class clsVMKernel = Lib.tryLoadClass("nachos.vm.VMKernel"); usingTLB = (clsVMKernel != null && clsVMKernel.isAssignableFrom(clsKernel)); this.numPhysPages = numPhysPages; for (int i=0; i<numUserRegisters; i++) registers[i] = 0; mainMemory = new byte[pageSize * numPhysPages]; if (usingTLB) { translations = new TranslationEntry[tlbSize]; for (int i=0; i<tlbSize; i++) translations[i] = new TranslationEntry(); } else { translations = null; } }
5
public static int runToAddressLimit(int baseKeys, int startKeys, int stepLimit, int... addresses) { if (!curGb.onFrameBoundaries) { int add = curGb.step(0, addresses); if (add != 0) return add; } int steps = 0; while (steps < stepLimit) { int add = curGb.step(steps == 0 ? startKeys : baseKeys, addresses); if (add != 0) return add; steps++; } return 0; }
5
@Override public void run() { Thread.currentThread().setName("FileDeleter-" + getName()); Logger.log("Running FileDeleter on " + getAbsolutePath()); while (!done && isFile()) { if (System.currentTimeMillis() >= killTime) { Logger.log("Removing TemporaryFile " + getAbsolutePath()); try { remove(); } catch (IOException e) { Logger.logError(e); deleteOnExit(); } done = true; } else { try { Thread.sleep(100); } catch (InterruptedException e) {} } } }
5
public void map() { //points is start, controls, end double[][][] V = new double[points.length-1][intervals+1][2]; for (int c = 0; c < V.length; c++) { for (int i = 0; i < V[c].length; i++) { V[c][i][0] = (1 - (double)i/intervals)*points[c][0] + ((double)i/intervals)*points[c+1][0]; V[c][i][1] = (1 - (double)i/intervals)*points[c][1] + ((double)i/intervals)*points[c+1][1]; } } while (V.length > 1) { double[][][] VV = new double[V.length - 1][intervals+1][2]; for (int c = 0; c < VV.length; c++) { for (int i = 0; i < VV[c].length; i++) { VV[c][i][0] = (1 - (double)i/intervals)*V[c][i][0] + ((double)i/intervals)*V[c+1][i][0]; VV[c][i][1] = (1 - (double)i/intervals)*V[c][i][1] + ((double)i/intervals)*V[c+1][i][1]; } } V = VV; } XY = new int[2][V[0].length]; for(int i = 0; i < XY[0].length; i++) { XY[0][i] = (int) Math.round(V[0][i][0]); XY[1][i] = (int) Math.round(V[0][i][1]); } }
6
public String getColumnName(int columnIndex) { switch (columnIndex) { case 0: return "Name"; case 1: return "Level"; case 2: return "Teacher"; case 3: return "Quantity"; case 4: return "Schedule"; } return ""; }
5
private final void push(int ch) { if (ch != 0) { if (mTextPos == mTextBuffer.length) { char[] bigger = new char[mTextPos * 4 / 3 + 4]; System.arraycopy(mTextBuffer, 0, bigger, 0, mTextPos); mTextBuffer = bigger; } mTextBuffer[mTextPos++] = (char) ch; } }
2
public static boolean saveImage(Image img, String filename) { String extension = null; try { int index_of_extension = filename.lastIndexOf("."); extension = filename.substring(index_of_extension); if(extension.equalsIgnoreCase(".gif") ) { return saveGIF(img, filename); } else if(extension.equalsIgnoreCase(".jpg") || extension.equalsIgnoreCase(".jpeg") ) { return saveJPG(img, filename); } else if(extension.equalsIgnoreCase(".bmp") ) { return saveBMP(img, filename); } else if(extension.equalsIgnoreCase(".pgm") ) { return savePGM(img, filename); } else if(extension.equalsIgnoreCase(".ppm") ) { return savePPM(img, filename); } else { // System.out.println("Unsupported file type"); } } catch(Exception e) { // System.out.println("Error!!" + e.toString()); } // Put a message here return false; //error saving file }
7
public void executeCommand(CommandType userCommand) throws IOException, ParseException { CommandTypesEnum commandType = determineCommandType(userCommand); switch (commandType) { case ADD: AddCommandType addUserCommand = (AddCommandType) userCommand; add(addUserCommand.getDescription(), addUserCommand.getDateFrom(), addUserCommand.getDateTo(), addUserCommand.getProjectName()); break; case DISPLAY: DisplayCommandType displayUserCommand = (DisplayCommandType) userCommand; displayOverall(displayUserCommand.getModifiers()); break; case DELETE: DeleteCommandType deleteUserCommand = (DeleteCommandType) userCommand; delete(deleteUserCommand.getTaskDescription(), deleteUserCommand.getProjectName()); break; case SEARCH: SearchCommandType searchUserCommand = (SearchCommandType) userCommand; searchInProj(searchUserCommand.getTaskDescription(), searchUserCommand.getProjectName()); break; case EDIT: EditCommandType editUserCommand = (EditCommandType) userCommand; edit(editUserCommand.getTaskDescription(), editUserCommand.getProjectName()); break; case UNDO: undo(); break; case REDO: redo(); break; case RESET: reset(); break; case COMPLETE: CompleteCommandType completeUserCommand = (CompleteCommandType) userCommand; checkCompleteTask(completeUserCommand.getTaskDescription()); break; default: throw new Error(MESSAGE_ERROR_WRONG_CMDTYPE); } }
9
public static void main(String args[]) { 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(Invitado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Invitado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Invitado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Invitado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Invitado().setVisible(true); } }); }
6
public String getNotationSystemId(String nname) { Object notation[] = (Object[]) notationInfo.get(nname); if (notation == null) { return null; } else { return (String) notation[1]; } }
1
GameLoader(String[] classNames) throws Exception{ Arrays.sort(classNames); for(String s:classNames){ Class<?> c = classLoader.loadClass(s); if(Scene.class.isAssignableFrom(c)){ scenes.put(s, (Scene) c.newInstance()); System.out.println("Found scene " + s); continue; } if(Game.class.isAssignableFrom(c)){ game = (Game) c.newInstance(); System.out.println("Found game " + s); continue; } classes.put(s, (Class<?>) c.newInstance()); System.out.println("Found unspecified class " + s); } if(game == null || scenes.isEmpty()){ System.out.print("Lacking game or scene class.\nAborting."); System.exit(1); } game.startGame(); }
7
public void testSubtractDays() { // This is a test for a bug in version 1.0. The dayOfMonth range // duration field did not match the monthOfYear duration field. This // caused an exception to be thrown when subtracting days. DateTime dt = new DateTime (1112306400000L, GJChronology.getInstance(DateTimeZone.forID("Europe/Berlin"))); YearMonthDay ymd = dt.toYearMonthDay(); while (ymd.toDateTimeAtMidnight().getDayOfWeek() != DateTimeConstants.MONDAY) { ymd = ymd.minus(Period.days(1)); } }
1
public int getNonNullPropertyCount() { int res = 0; for (Object o : values) { if (o != null) { res++; } } return res; }
2
public void setPassiveActivities(PassiveActivities passiveActivities) { this.passiveActivity = passiveActivities; }
0
public int compare(Instance s1, Instance s2) { double d = s2.predict - s1.predict; if(d > 0) return 1; if(d < 0) return -1; return 0; }
2
@Override public void run() { // TODO Auto-generated method stub try{ while(run){ Socket socket = socketListen.accept(); ComingRequestChatHandler handleRequest = new ComingRequestChatHandler(socket, myUserName); handleRequest.start(); } } catch( IOException e){ } }
2
private Point findSpawnLocation(LayeredMap map) { for(int y=3; y<map.getHeight(); y++) { for(int x=3; x<map.getWidth(); x++) { boolean ok = true; for(int j=0; j<4; j++) { for(int i=0; i<4; i++) { int ground = map.get(0, x+i, y+j) & 0xFFFF; int feat = map.get(1, x+i, y+j) & 0xFFFF; if(ground != '.' || feat != 0) { ok = false; } } } if(ok) { return new Point(x, y); } } } // Hajo: Player most likely stuck ... return new Point(10, 10); }
7
private static void createAndShowGUI() { // http://docs.oracle.com/javase/tutorial/uiswing/examples/start/HelloWorldSwingProject/src/start/HelloWorldSwing.java //Create and set up the window. JFrame frame = new JFrame("VennMesh"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // capture global keyboard events, such as quit (ctrl-q) or save (ctrl-s). KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() { @Override // http://stackoverflow.com/questions/5344823/how-can-i-listen-for-key-presses-within-java-swing-accross-all-components public boolean dispatchKeyEvent(KeyEvent e) { // System.out.println("Got key event!"); System.out.println("getKeyChar[" + e.getKeyChar() + "] getKeyCode[" + e.getKeyCode() + "] getModifiers[" + e.getModifiers() + "]"); if (e.isControlDown()) {// cntrl-Q char ch = (char) e.getKeyCode();// always uppercase System.out.println("ch:" + ch + ":"); if (e.getKeyCode() == KeyEvent.VK_Q) { System.out.println("Quit!"); System.exit(0); } } else { if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {// just escape System.out.println("Quit!"); System.exit(0); } } return false;// false allows other key events to be triggered, too. } }); JPanel MainPanel = new JPanel(); frame.getContentPane().add(MainPanel); //Display the window. frame.pack(); frame.setVisible(true); MainPanel.setBackground(Color.CYAN); if (true) {// http://zetcode.com/tutorials/javaswingtutorial/basicswingcomponents/ JPanel panel = MainPanel;// new JPanel(); panel.setLayout(new BorderLayout(10, 10)); Drawing_Canvas dc = new Drawing_Canvas(); dc.setBackground(Color.red); dc.setSize(700, 700); panel.add(dc, BorderLayout.CENTER); //panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); } frame.setSize(700, 700); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }
4
private void simulate() { // Prepare the model for the iteration earthModel.begin(); // Submit the sim iteration to the thread pool. // Wait on the Future objects returned to block the current // thread until the iteration is complete across the whole surface. // Inspired by http://stackoverflow.com/questions/3929361/how-to-wait-for-all-tasks-in-an-threadpoolexecutor-to-finish-without-shutting-do Collection<Future<?>> futures = new LinkedList<Future<?>>(); for (ISimThread sim : this.parallelSims) { futures.add(threadPool.submit(sim)); } for (Future<?> future : futures) { try { future.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } // This will block if the buffer is full. If the Presenter has the // initiative, it must not call this method if the buffer is full. earthModel.commit(); }
7
public ListNode sort(ListNode p, int len) { if (len == 1) { return p; } ListNode a = p; ListNode b = p; ListNode atail = null; for (int i = 0; i < len / 2; i++) { atail = b; b = b.next; } atail.next = null; a = sort(a, len / 2); // don't forget renew a&b b = sort(b, len - len / 2); ListNode head = null; ListNode c = null; while (a != null && b != null) { ListNode chosen = null; if (a.val < b.val) { chosen = a; a = a.next; } else { chosen = b; b = b.next; } chosen.next = null; if (head == null) { head = c = chosen; } else { c.next = chosen; c = chosen; } } while (a != null) { c.next = a; c = a; a = a.next; } if (b != null) { c.next = b; } return head; }
8
@Override public Success<Type[]> parse(String s, int p) { // Parse the '['. if (s.charAt(p) != '[') return null; ++p; p = optWS(s, p); // Parse the first type. List<Type> genericArgs = new ArrayList<Type>(); Success<Type> resArg = TypeParser.singleton.parse(s, p); if (resArg == null) { if (s.charAt(p) == ']') throw new NiftyException("Empty parameter lists aren't accepted, just don't specify a list."); throw new NiftyException("Expecting a type after '[' in generic argument list."); } genericArgs.add(resArg.value); p = resArg.rem; p = optWS(s, p); // Parse any other types. for (;;) { // Parse the comma. if (s.charAt(p) != ',') break; p = optWS(s, p + 1); // Parse the next type. resArg = TypeParser.singleton.parse(s, p); if (resArg == null) throw new NiftyException("Expecting another type after ',' in generic argument list."); genericArgs.add(resArg.value); p = resArg.rem; p = optWS(s, p); } // Parse the ']'. if (s.charAt(p) != ']') throw new NiftyException("Expecting ']' after generic arguments."); ++p; Type[] result = genericArgs.toArray(new Type[genericArgs.size()]); return new Success<Type[]>(result, p); }
7
@Override public void run() { try { long startTime = System.currentTimeMillis(); long currentTime = startTime; Random r = new Random(); double amount = 1000.0; while(isRunning()){ switch(operations){ case deposit: myBank.deposit(Account.DEFAULT_ACCOUNT_ID, amount); break; case withdraw: myBank.withdraw(Account.DEFAULT_ACCOUNT_ID, amount); break; case transfer: int randomRemoteBankID = r.nextInt(BankUtilities.getNumberOfBanks()) + 1; myBank.transfer(Account.DEFAULT_ACCOUNT_ID, randomRemoteBankID, Account.DEFAULT_ACCOUNT_ID, amount); break; } Thread.sleep((r.nextInt(5)+1)*1000); currentTime = System.currentTimeMillis(); setRunning((currentTime - startTime) <= execTime); } } catch (InterruptedException e) { // TODO transaction is invoked. Set back all amounts. e.printStackTrace(); } catch (AccountException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (BankIDException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
7
public int addLeaf(Node root, Node leaf) { Node node = this.leafs.get(leaf.getInfo()); if (node!=null) { return -1; } if (root==null && this.head==null) { // no se el padre y no hay head -> head = leaf this.head = leaf; this.leafs.put(leaf.getInfo(), leaf); } else if (root==null && this.head != null) { // si no se el padre y hay head -> root = head leaf.setPadre(this.head); this.head.addHijo(leaf); this.leafs.put(leaf.getInfo(), leaf); } else if (root!=null && this.head==null) { // se el padre y no hay head -> head = root / root.addhijo(leaf) this.head = root; this.leafs.put(root.getInfo(), root); leaf.setPadre(root); this.head.addHijo(leaf); this.leafs.put(leaf.getInfo(), leaf); } else { // (root!=null && this.head!=null) hay padre y hay hijo root.addhijo(leaf) leaf.setPadre(root); this.leafs.get(root.getInfo()).addHijo(leaf); this.leafs.put(leaf.getInfo(), leaf); } return 0; }
7
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ObjectPropertyIdentifier other = (ObjectPropertyIdentifier) obj; if (objectType == null) { if (other.objectType != null) return false; } else if (!objectType.equals(other.objectType)) return false; if (propertyIdentifier == null) { if (other.propertyIdentifier != null) return false; } else if (!propertyIdentifier.equals(other.propertyIdentifier)) return false; return true; }
9
public void setRef2(String ref) { if (ref != null && ref.length() > 256) throw new IllegalArgumentException("Ref cannot be longer than 256 characters!"); this.ref2 = ref; }
2
public void removeLaser(Object player){ for(int i = 0; i < lasers.size(); i++){ if(lasers.get(i).getParent() == player){ lasers.remove(i); } } }
2
@Override public void paintComponent(Graphics g){ boolean[][] tiles = next.getTiles(); int count = 0; int width = next.getTiles()[0].length == 9 ? 3 : 4; // get width (3 or 4) of piece width = next.getTiles()[0].length == 4 ? 2 : width; for(int row = 0; row < width; ++row) { for(int col = 0; col < width; ++col){ if(tiles[orientation][count++]){ Screen.drawSquare(next.getColor(), offset+col*35, offset+row*35, g); } } } }
5
public static List<BoundaryBox> getBoundaries(ImageProcessor im, List<Point> maximPoints){ List<BoundaryBox> result = new ArrayList<BoundaryBox>(); for(int i = 0; i < maximPoints.size(); i++){ result.add(new BoundaryBox(maximPoints.get(i), im)); } return result; }
1
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); setHorizontalAlignment( JLabel.CENTER ); if (row == column) { cellComponent.setBackground(new java.awt.Color(60, 60, 60)); this.setText("N/A"); } else { if (row%2 == 0) cellComponent.setBackground(Color.white); else cellComponent.setBackground(new java.awt.Color(242, 242, 242)); } return cellComponent; }
2
public void move(Direction d) { this.lastInspected = ""; Direction up = boardState.getDirection(); d = Direction.values()[(d.ordinal() - up.ordinal() + 4) % 4]; if (!player.isFrozen() && System.currentTimeMillis() - lastMovedTime > player.getStepDelay()) { if (player.getDirection() == d) { Location newLoc = player.getLocationInFrontOf(); if (board.containsLocation(newLoc) && this.isFree(newLoc)) { if (board.canTraverse(newLoc)) { client.sendMove(newLoc); } else if (board.tileAt(newLoc).getOn() instanceof Door) { if (this.unlock((Lockable)board.tileAt(newLoc).getOn(), newLoc)) { client.sendMove(newLoc); } } } } else { client.sendTurn(d); } lastMovedTime = System.currentTimeMillis(); } }
8
public static Color contrastColor(Color color, Constrast type) { if (type == Constrast.invert) { return new Color(255 - color.getRed(), 255 - color.getGreen(), 255 - color.getBlue()); } if (type == Constrast.textbw) { // nasledovne konstanty nie su nahodne, neodporucam menit :) int value = color.getRed() * 299 + color.getGreen() * 587 + color.getBlue() * 114; if (value >= 128000) return Color.black; else return Color.white; } if (type == Constrast.borderbw) { // tu sa da s konstantami trochu pohrat int value = color.getRed() + color.getGreen() + color.getBlue() + 2; if (value > 200) return Color.black; else return Color.blue; } return Color.black; }
5
public void publish(ApplicationEvent event) { applicationEventPublisher.publishEvent(event); }
0
boolean siOuvert(int case1, int case2) { boolean ouvert = true; for (int i=0; i<aretes.size(); i++) { if (aretes.get(i).s1.num == case1) { if (aretes.get(i).s2.num == case2) ouvert = false; } else if (aretes.get(i).s1.num == case2) { if (aretes.get(i).s2.num == case1) ouvert = false; } } return ouvert; }
5
public boolean isOnPF(int marginx,int marginy) { if (!getTileBBox(temp_bbox_copy)) { temp_bbox_copy.x = (int)x; temp_bbox_copy.y = (int)y; temp_bbox_copy.width = 0; temp_bbox_copy.height = 0; } if (!pfwrapx) { if (temp_bbox_copy.x+temp_bbox_copy.width < -marginx) return false; if (temp_bbox_copy.x >pfwidth + marginx) return false; } if (!pfwrapy) { if (temp_bbox_copy.y+temp_bbox_copy.height < -marginy) return false; if (temp_bbox_copy.y > pfheight + marginy) return false; } return true; }
7
private void validateCustomerInfo(HttpServletRequest request, Customer customer) { if (!customer.isValid()) request.setAttribute("error", "true"); if (!customer.isValidGivenName()) request.setAttribute("invalidGivenName", "Given Name must not be empty and number"); if (!customer.isValidSurname()) request.setAttribute("invalidSurname", "Surname must not be empty and number"); if (!customer.isValidAddress()) request.setAttribute("invalidAddress", "Address must not be empty and special character"); if (!customer.isValidEmail()) request.setAttribute("invalidEmail", "Email has an invalid email format"); if (!customer.isValidCountry()) request.setAttribute("invalidCountry", "Country name must not be empty and number"); if (!customer.isValidState()) request.setAttribute("invalidState", "State must not be empty and number"); if (!customer.isValidPoscode()) request.setAttribute("invalidPostCode", "Postcode must not be empty and characters"); if (!customer.isValidCreditNo()) request.setAttribute("invalidCreditNo", "Credit Number must not be empty and characters"); }
9
public int moveUp(boolean findChange) { int total = 0; for (int y = 3; y > 0; y--) { for (int x = 0; x < 4; x++) { if (next.grid[x][y] != 0 && next.grid[x][y] == grid[x][y-1]) { next.grid[x][y] *= 2; next.grid[x][y-1] = 0; total += weightingMerge(next.grid[x][y]); } else if (next.grid[x][y] == 0 && next.grid[x][y-1] > 0) { next.grid[x][y-1] = next.grid[x][y]; next.grid[x][y-1] = 0; } } } if (findChange) return total + findChange(); return total; }
7
public String command(CommandSender sender, Command command, String[] args) { if (args.length < 1) return plugin.getString(Language.LOCKDOWN_ARGUMENTS); String admin = Ultrabans.DEFAULT_ADMIN; if (sender instanceof Player) admin = sender.getName(); boolean locked = config.getBoolean("Lockdown", false); String toggle = args[0]; if (toggle.equalsIgnoreCase("on")) { if (!locked) { plugin.getConfig().set("Lockdown", true); plugin.saveConfig(); plugin.log(admin + " initiated lockdown"); return plugin.getString(Language.LOCKDOWN_START); } return plugin.getString(Language.LOCKDOWN_LOGINMSG); } if (toggle.equalsIgnoreCase("off")) { if (locked) { plugin.getConfig().set("Lockdown", false); plugin.saveConfig(); plugin.log(admin + " disabled lockdown"); return plugin.getString(Language.LOCKDOWN_END); } return plugin.getString(Language.LOCKDOWN_STATUS); } return locked ? plugin.getString(Language.LOCKDOWN_LOGINMSG) : plugin.getString(Language.LOCKDOWN_STATUS); }
7
public static void parse_str(String string, Map<String, Object> results) { // parse a string that's URL encoded into an array if (results == null) return; if (string == null) return; String[] stuff; if (string.contains("&amp;")) { stuff = string.split("&amp;"); } else { stuff = string.split("&"); } String[] split; for (int i = 0; i < stuff.length; i++) { String part = stuff[i]; if (part.contains("=")) { split = part.split("="); try { results.put(URLDecoder.decode(split[0],"UTF-8"),URLDecoder.decode(split[1],"UTF-8")); } catch (Throwable e) { results.clear(); return; } } } }
6
protected void configFromAdjacent(boolean[] near, int numNear) { final Tile o = origin() ; type = TYPE_SOLAR ; if (numNear > 0 && numNear <= 2) { if (near[N] || near[S]) { facing = Y_AXIS ; if (o.y % 8 == 0) { type = TYPE_WIND ; attachModel(MODEL_TRAP_RIGHT) ; } else attachModel(MODEL_RIGHT) ; return ; } if (near[W] || near[E]) { facing = X_AXIS ; if (o.x % 8 == 0) { type = TYPE_WIND ; attachModel(MODEL_TRAP_LEFT) ; } else attachModel(MODEL_LEFT) ; return ; } } facing = CORNER ; attachModel(MODEL_LEFT) ; }
8
public static double binomialCoefficientLog(final int n, final int k) { ArithmeticUtils.checkBinomial(n, k); if ((n == k) || (k == 0)) { return 0; } if ((k == 1) || (k == n - 1)) { return FastMath.log(n); } /* * For values small enough to do exact integer computation, * return the log of the exact value */ if (n < 67) { return FastMath.log(binomialCoefficient(n,k)); } /* * Return the log of binomialCoefficientDouble for values that will not * overflow binomialCoefficientDouble */ if (n < 1030) { return FastMath.log(binomialCoefficientDouble(n, k)); } if (k > n / 2) { return binomialCoefficientLog(n, n - k); } /* * Sum logs for values that could overflow */ double logSum = 0; // n!/(n-k)! for (int i = n - k + 1; i <= n; i++) { logSum += FastMath.log(i); } // divide by k! for (int i = 2; i <= k; i++) { logSum -= FastMath.log(i); } return logSum; }
9
@Test public void testSpeicherVerwaltung() { Speicher speicher = new Speicher(); int anz = speicher.getAnzZellen(); //Kompletter Speicher erstellt? if (anz != Speicher.SPEICHERGROESSE) assertFalse(true); //Speicher richtig initialisiert? for (int i = 0; i < Speicher.SPEICHERGROESSE; i++) { if(speicher.getValueFromCell(i) != 0) { assertFalse(true); } } speicher.writeValueToCell(0, 15); speicher.writeValueToCell(1, 40); if(speicher.getValueFromCell(0) != 15){ assertFalse(true); } if(speicher.getValueFromCell(1) != 40){ assertFalse(true); } }
5
public void removeEventListener(IGameEventListener listener) { if (listener != null) { Iterator<Entry<GameEventType, Map<Integer, Set<IGameEventListener>>>> iterator = eventListeners.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<GameEventType, Map<Integer, Set<IGameEventListener>>> entry = iterator.next(); Iterator<Entry<Integer, Set<IGameEventListener>>> iterator2 = entry.getValue().entrySet().iterator(); while (iterator2.hasNext()) { Map.Entry<Integer, Set<IGameEventListener>> entry2 = iterator2.next(); Set<IGameEventListener> listeners = entry2.getValue(); if (listeners.contains(listener)) { listeners.remove(listener); if (listeners.size() <= 0) iterator2.remove(); if (LOGGER.isDebugEnabled()) LOGGER.debug("Successfully removed listener '" + listener + "' of priority '" + entry2.getKey() + "'for type '" + entry.getKey() + "'"); } } if (entry.getValue().size() <= 0) { iterator.remove(); if (LOGGER.isDebugEnabled()) LOGGER.debug("All listeners for type '" + entry.getKey() + "' were removed"); } } } }
8
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Segmento)) { return false; } Segmento other = (Segmento) object; if ((this.codsegmento == null && other.codsegmento != null) || (this.codsegmento != null && !this.codsegmento.equals(other.codsegmento))) { return false; } return true; }
5
public HostManifest(String file) throws Exception { Properties p=read(file); host=p.getProperty("host"); if(host==null) throw new RuntimeException("host name is required in "+file); for(Object x:p.keySet()) { String name=(String)x; if(!reservedName(name)) { // This is an rpm String version=p.getProperty(name); RPMRequest request=new RPMRequest(name,version); if(requests.get(name)!=null) throw new RuntimeException("Duplicate RPM name in "+file+":"+name); requests.put(name,request); } } HashSet<String> ctx=new HashSet<String>(); p=processImports(file,p.getProperty("import"),ctx); if(p!=null) { for(Object x:p.keySet()) { String name=(String)x; if(!reservedName(name)) if(!requests.containsKey(name)) requests.put(name,new RPMRequest(name,p.getProperty(name))); } } }
8
public static void updateAccountView() { Investor inv = (Investor) userList.get(userIndex); investorGUI.getBrokerNameText().setText(inv.getBroker().getFname() .concat(" ").concat(inv.getBroker().getLname())); investorGUI.getBalanceText().setText(Double.toString( inv.getAccount().getCashBalance())); investorGUI.getMarginText().setText(Double.toString( inv.getAccount().getMarginBorrowed())); investorGUI.getBuyLongText().setText(Double.toString( inv.getAccount().getAvailFundsToBuyLong())); investorGUI.getSellShortText().setText(Double.toString( inv.getAccount().getAvailFundsToSellShort())); investorGUI.getPercentEquityText().setText(Double.toString( inv.getAccount().getPercentEquity())); Account acct = inv.getAccount(); Portfolio folio = inv.getPortfolio(); double totalMarketValue = 0; ArrayList<Position> positions = folio.getPositions(); ArrayList<Trade> trades = folio.getTradeHistory(); ArrayList<CashTransaction> cashTrans = acct.getCashHistory(); ArrayList<MarginTransaction> margTrans = acct.getMarginHistory(); DefaultListModel positionModel = new DefaultListModel(); DefaultListModel pendingModel = new DefaultListModel(); DefaultListModel tradesModel = new DefaultListModel(); DefaultListModel cashHistModel = new DefaultListModel(); DefaultListModel margHistModel = new DefaultListModel(); investorGUI.getStockOwnedList().setModel(positionModel); investorGUI.getPendingList().setModel(pendingModel); investorGUI.getTradeHistoryList().setModel(tradesModel); investorGUI.getCashHistoryList().setModel(cashHistModel); investorGUI.getMarginHistoryList().setModel(margHistModel); // Build the list of positions if(!positions.isEmpty()) { for(int i = 0; i < positions.size(); i++) { positionModel.addElement(positions.get(i)); totalMarketValue += positions.get(i).getMarketValue(); } investorGUI.getMarketValueText().setText(Double.toString(totalMarketValue)); investorGUI.getStockOwnedList().setModel(positionModel); } // Build the list of trades if(!trades.isEmpty()) { for(int i = 0; i < trades.size(); i++) { tradesModel.addElement(trades.get(i)); if(trades.get(i).getPending()) { pendingModel.addElement(trades.get(i)); } } investorGUI.getTradeHistoryList().setModel(tradesModel); investorGUI.getPendingList().setModel(pendingModel); } // Build the list of cash transactions if(!cashTrans.isEmpty()) { for(int i = 0; i < cashTrans.size(); i++) { cashHistModel.addElement(cashTrans.get(i)); } investorGUI.getCashHistoryList().setModel(cashHistModel); } // Build the list of margin transactions if(!margTrans.isEmpty()) { for(int i = 0; i < margTrans.size(); i++) { margHistModel.addElement(margTrans.get(i)); } investorGUI.getMarginHistoryList().setModel(margHistModel); } }
9
public static void main(String[] args) { Scanner scanner=new Scanner(System.in); HDOJ1070 hdoj1070=new HDOJ1070(); int cases=scanner.nextInt(); while (cases-->0){ int milkCnt=scanner.nextInt(); List<Milk> milks=new ArrayList<>(); while (milkCnt-->0) { Milk milk = new Milk(scanner.next(), scanner.nextInt(), scanner.nextInt()); if(milk.days>0) milks.add(milk); } System.out.println(hdoj1070.entrance(milks)); } }
3
public static void main(String[] args) { Locale.setDefault(Locale.US); Scanner s = new Scanner(System.in); String op = s.nextLine(); double sum = 0; for(int i = 0; i < 5; i++){ int pad = i+1; for(int j = 0; j < pad; j++){ s.nextDouble(); } for(int j = pad; j < 12-pad; j++){ sum += s.nextDouble(); } for(int j = 0; j < pad; j++){ s.nextDouble(); } } System.out.printf("%.1f\n", "S".equals(op) ? sum : sum/30); }
5
protected void ensureOpen(String methodName) { if (isClosed) { throw new RuntimeException(methodName + "() called on a closed AbstractResultSet."); } }
1