List of usage examples for java.util Collection add
boolean add(E e);
From source file:example.Example.java
public static void main(String[] args) { if (args.length == 0) { System.err.println("Usage: Example username:password ... [-f twitter_id ...] [-t keyword]"); System.exit(1);//w ww. j a va2 s . com } Collection<String> credentials = new ArrayList<String>(); Collection<String> followIds = null; Collection<String> trackKeywords = null; Collection<String> list = credentials; for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.equals("-f")) { followIds = new ArrayList<String>(); list = followIds; } else if (arg.equals("-t")) { trackKeywords = new ArrayList<String>(); list = trackKeywords; } else { list.add(arg); } } final Collection<String> finalFollowIds = followIds; final Collection<String> finalTrackKeywords = trackKeywords; FilterParameterFetcher filterParameterFetcher = new FilterParameterFetcher() { public Collection<String> getFollowIds() { return finalFollowIds; } public Collection<String> getTrackKeywords() { return finalTrackKeywords; } }; new TwitterClient(filterParameterFetcher, new ExampleTwitterStreamProcessor(), "http://stream.twitter.com/1/statuses/filter.json", 200, 10, credentials, 60 * 1000L).execute(); }
From source file:com.ipeirotis.gal.core.CategoryPair.java
public static void main(String[] args) { Category a = new Category("A"); Category b = new Category("B"); a.setPrior(0.5);/*from w ww . j a v a2 s.co m*/ b.setPrior(0.5); a.setCost("A", 0.0); a.setCost("B", 1.0); b.setCost("A", 1.0); b.setCost("B", 0.0); Collection<Category> categories = new HashSet<Category>(); categories.add(a); categories.add(b); Map<String, Category> map = new HashMap<String, Category>(); map.put("A", a); map.put("B", b); ConfusionMatrix cm = new ConfusionMatrix(categories); // FOR TESTS: // q=1 should return 0 cost // q=1 should not be affected by m /* cm.setErrorRate("A", "A", 0.9); cm.setErrorRate("A", "B", 0.1); cm.setErrorRate("B", "B", 0.0); cm.setErrorRate("B", "A", 1.0); double tau=0.01; double w = cm.getWorkerWage(1.0, tau, map); double pwage = Double.valueOf(new DecimalFormat("#.####").format(w)); double pworkers = Double.valueOf(new DecimalFormat("#.####").format(1.0/w)); System.out.print("\t"+pwage+"\t"+pworkers); */ //double q=0.9; for (int Q = 95; Q >= 55; Q -= 5) { double q = Q / 100.0; cm.setErrorRate("A", "A", q); cm.setErrorRate("A", "B", 1 - q); cm.setErrorRate("B", "B", q); cm.setErrorRate("B", "A", 1 - q); // Classification cost of a set of m workers with the confusion matrix given above /* for (int m = 1; m<=40; m+=2) { System.out.print(q+"\t"+m); Double c = cm.getWorkerCost(m, map, 100*m*m); System.out.println("\t"+Math.round(100000*c)/100000.0); } */ for (double tau = 0.1; tau > 0.0001; tau /= 1.5) { double pq = Double.valueOf(new DecimalFormat("#.##").format(q)); double ptau = Double.valueOf(new DecimalFormat("#.####").format((1 - tau))); System.out.print(pq + "\t" + ptau); double w = cm.getWorkerWage(1.0, tau, map); double pwage = Double.valueOf(new DecimalFormat("#.####").format(w)); double pworkers = Double.valueOf(new DecimalFormat("#.####").format(1.0 / w)); System.out.print("\t" + pwage + "\t" + pworkers); double wr = cm.getWorkerWageRegr(1.0, tau, map); double pwager = Double.valueOf(new DecimalFormat("#.####").format(wr)); double pworkersr = Double.valueOf(new DecimalFormat("#.####").format(1.0 / wr)); System.out.print("\t" + pwager + "\t" + pworkersr); System.out.println(); } } }
From source file:com.willwinder.universalgcodesender.ExperimentalWindow.java
/** * @param args the command line arguments *//*from w ww.j a v a2 s . c om*/ 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(ExperimentalWindow.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ExperimentalWindow.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ExperimentalWindow.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ExperimentalWindow.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> // Fix look and feel to use CMD+C/X/V/A instead of CTRL if (SystemUtils.IS_OS_MAC) { Collection<InputMap> ims = new ArrayList<>(); ims.add((InputMap) UIManager.get("TextField.focusInputMap")); ims.add((InputMap) UIManager.get("TextArea.focusInputMap")); ims.add((InputMap) UIManager.get("EditorPane.focusInputMap")); ims.add((InputMap) UIManager.get("FormattedTextField.focusInputMap")); ims.add((InputMap) UIManager.get("PasswordField.focusInputMap")); ims.add((InputMap) UIManager.get("TextPane.focusInputMap")); int c = KeyEvent.VK_C; int v = KeyEvent.VK_V; int x = KeyEvent.VK_X; int a = KeyEvent.VK_A; int meta = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); for (InputMap im : ims) { im.put(KeyStroke.getKeyStroke(c, meta), DefaultEditorKit.copyAction); im.put(KeyStroke.getKeyStroke(v, meta), DefaultEditorKit.pasteAction); im.put(KeyStroke.getKeyStroke(x, meta), DefaultEditorKit.cutAction); im.put(KeyStroke.getKeyStroke(a, meta), DefaultEditorKit.selectAllAction); } } /* Create the form */ // GUIBackend backend = new GUIBackend(); final ExperimentalWindow mw = new ExperimentalWindow(); /* Apply the settings to the ExperimentalWindow bofore showing it */ mw.setSize(mw.backend.getSettings().getMainWindowSettings().width, mw.backend.getSettings().getMainWindowSettings().height); mw.setLocation(mw.backend.getSettings().getMainWindowSettings().xLocation, mw.backend.getSettings().getMainWindowSettings().yLocation); mw.addComponentListener(new ComponentListener() { @Override public void componentResized(ComponentEvent ce) { mw.backend.getSettings().getMainWindowSettings().height = ce.getComponent().getSize().height; mw.backend.getSettings().getMainWindowSettings().width = ce.getComponent().getSize().width; } @Override public void componentMoved(ComponentEvent ce) { mw.backend.getSettings().getMainWindowSettings().xLocation = ce.getComponent().getLocation().x; mw.backend.getSettings().getMainWindowSettings().yLocation = ce.getComponent().getLocation().y; } @Override public void componentShown(ComponentEvent ce) { } @Override public void componentHidden(ComponentEvent ce) { } }); /* Display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { mw.setVisible(true); } }); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { mw.connectionPanel.saveSettings(); mw.commandPanel.saveSettings(); if (mw.pendantUI != null) { mw.pendantUI.stop(); } } }); }
From source file:com.netscape.cmstools.CMCResponse.java
public static void main(String args[]) throws Exception { Option option = new Option("d", true, "NSS database location"); option.setArgName("path"); options.addOption(option);// www . j a v a 2 s . c o m option = new Option("i", true, "Input file containing CMC response in binary format"); option.setArgName("path"); options.addOption(option); option = new Option("o", true, "Output file to store certificate chain in PKCS #7 PEM format; also prints out cert base 64 encoding individually"); option.setArgName("path"); options.addOption(option); options.addOption("v", "verbose", false, "Run in verbose mode. Base64 encoding of certs in response will be printed individually"); options.addOption(null, "help", false, "Show help message."); CommandLine cmd = parser.parse(options, args, true); @SuppressWarnings("unused") String database = cmd.getOptionValue("d"); String input = cmd.getOptionValue("i"); String output = cmd.getOptionValue("o"); boolean printCerts = cmd.hasOption("v"); if (cmd.hasOption("help")) { printUsage(); System.exit(1); } if (input == null) { System.err.println("ERROR: Missing input CMC response"); System.err.println("Try 'CMCResponse --help' for more information."); System.exit(1); } // load CMC response byte[] data = Files.readAllBytes(Paths.get(input)); // display CMC response CMCResponse response = new CMCResponse(data); response.printContent(printCerts); // terminate if any of the statuses is not a SUCCESS Collection<CMCStatusInfoV2> statusInfos = response.getStatusInfos(); if (statusInfos != null) { // full response for (CMCStatusInfoV2 statusInfo : statusInfos) { int status = statusInfo.getStatus(); if (status == CMCStatusInfoV2.SUCCESS) { continue; } SEQUENCE bodyList = statusInfo.getBodyList(); Collection<INTEGER> list = new ArrayList<>(); for (int i = 0; i < bodyList.size(); i++) { INTEGER n = (INTEGER) bodyList.elementAt(i); list.add(n); } System.err.println("ERROR: CMC status for " + list + ": " + CMCStatusInfoV2.STATUS[status]); System.exit(1); } } // export PKCS #7 if requested if (output != null) { PKCS7 pkcs7 = new PKCS7(data); try (FileWriter fw = new FileWriter(output)) { fw.write(pkcs7.toPEMString()); } System.out.println("\nPKCS#7 now stored in file: " + output); } }
From source file:org.biopax.validator.BiopaxValidatorClient.java
/** * Checks BioPAX files using the online BioPAX Validator. * /* w w w .j a v a2s . co m*/ * @see <a href="http://www.biopax.org/validator">BioPAX Validator Webservice</a> * * @param argv * @throws IOException */ public static void main(String[] argv) throws IOException { if (argv.length == 0) { System.err.println("Available parameters: \n" + "<path> <output> [xml|html|biopax] [auto-fix] [only-errors] [maxerrors=n] [notstrict]\n" + "\t- validate a BioPAX file/directory (up to ~25MB in total size, -\n" + "\totherwise, please use the biopax-validator.jar instead)\n" + "\tin the directory using the online BioPAX Validator service\n" + "\t(generates html or xml report, or gets the processed biopax\n" + "\t(cannot fix all errros though) see http://www.biopax.org/validator)"); System.exit(-1); } final String input = argv[0]; final String output = argv[1]; File fileOrDir = new File(input); if (!fileOrDir.canRead()) { System.err.println("Cannot read from " + input); System.exit(-1); } if (output == null || output.isEmpty()) { System.err.println("No output file specified (for the validation report)."); System.exit(-1); } // default options RetFormat outf = RetFormat.HTML; boolean fix = false; Integer maxErrs = null; Behavior level = null; //will report both errors and warnings String profile = null; // match optional arguments for (int i = 2; i < argv.length; i++) { if ("html".equalsIgnoreCase(argv[i])) { outf = RetFormat.HTML; } else if ("xml".equalsIgnoreCase(argv[i])) { outf = RetFormat.XML; } else if ("biopax".equalsIgnoreCase(argv[i])) { outf = RetFormat.OWL; } else if ("auto-fix".equalsIgnoreCase(argv[i])) { fix = true; } else if ("only-errors".equalsIgnoreCase(argv[i])) { level = Behavior.ERROR; } else if ((argv[i]).toLowerCase().startsWith("maxerrors=")) { String num = argv[i].substring(10); maxErrs = Integer.valueOf(num); } else if ("notstrict".equalsIgnoreCase(argv[i])) { profile = "notstrict"; } } // collect files Collection<File> files = new HashSet<File>(); if (fileOrDir.isDirectory()) { // validate all the OWL files in the folder FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { return (name.endsWith(".owl")); } }; for (String s : fileOrDir.list(filter)) { files.add(new File(fileOrDir.getCanonicalPath() + File.separator + s)); } } else { files.add(fileOrDir); } // upload and validate using the default URL: http://www.biopax.org/biopax-validator/check.html if (!files.isEmpty()) { BiopaxValidatorClient val = new BiopaxValidatorClient(); val.validate(fix, profile, outf, level, maxErrs, null, files.toArray(new File[] {}), new FileOutputStream(output)); } }
From source file:facade.examples.Collections.java
/** * Run the examples// w ww .ja v a2 s .c o m * @param args <i>ignored</i> */ public static void main(String[] args) { /* RESISTORS IN PARALLEL WITH FACADE */ System.out.println("-> With facade: "); /* Empty collection of resistors */ Collection<Double> resistors = new ArrayList<Double>(); /* adding values. on() modifies the collection in place */ on(resistors).add(1.5, 3.0, 15.0, 30.0, 150.0); /* computing resistance. with() works on a collection copy. */ double r = 1.0 / with(resistors).map(inverse).reduce(sum); /* pretty printing the resistors */ System.out.println("[ " + with(resistors).join(", ") + " ]"); /* printing the equivalent resistor */ System.out.println(r); /* --------------------------------------------------------------- */ System.out.println(); /* --------------------------------------------------------------- */ /* RESISTORS IN PARALLEL WITH CLASSIC JAVA */ System.out.println("-> Without facade: "); /* Empty collection of resistors */ resistors = new ArrayList<Double>(); /* adding values */ resistors.add(1.5); resistors.add(3.0); resistors.add(15.0); resistors.add(30.0); resistors.add(150.0); /* computing resistance */ double sum = 0.0; for (Double resistor : resistors) { sum += 1.0 / resistor; } r = 1.0 / sum; /* pretty printing the resistors */ StringBuilder sb = new StringBuilder(); sb.append("[ "); Iterator<Double> it = resistors.iterator(); if (it.hasNext()) { sb.append(it.next()); } while (it.hasNext()) { sb.append(", ").append(it.next()); } sb.append(" ]"); System.out.println(sb.toString()); /* printing the equivalent resistor */ System.out.println(r); }
From source file:com.willwinder.universalgcodesender.MainWindow.java
/** * @param args the command line arguments *///from w ww . j a v a 2 s . com 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(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> // Fix look and feel to use CMD+C/X/V/A instead of CTRL if (SystemUtils.IS_OS_MAC) { Collection<InputMap> ims = new ArrayList<>(); ims.add((InputMap) UIManager.get("TextField.focusInputMap")); ims.add((InputMap) UIManager.get("TextArea.focusInputMap")); ims.add((InputMap) UIManager.get("EditorPane.focusInputMap")); ims.add((InputMap) UIManager.get("FormattedTextField.focusInputMap")); ims.add((InputMap) UIManager.get("PasswordField.focusInputMap")); ims.add((InputMap) UIManager.get("TextPane.focusInputMap")); int c = KeyEvent.VK_C; int v = KeyEvent.VK_V; int x = KeyEvent.VK_X; int a = KeyEvent.VK_A; int meta = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); for (InputMap im : ims) { im.put(KeyStroke.getKeyStroke(c, meta), DefaultEditorKit.copyAction); im.put(KeyStroke.getKeyStroke(v, meta), DefaultEditorKit.pasteAction); im.put(KeyStroke.getKeyStroke(x, meta), DefaultEditorKit.cutAction); im.put(KeyStroke.getKeyStroke(a, meta), DefaultEditorKit.selectAllAction); } } /* Create the form */ GUIBackend backend = new GUIBackend(); final MainWindow mw = new MainWindow(backend); /* Apply the settings to the MainWindow bofore showing it */ mw.arrowMovementEnabled.setSelected(mw.settings.isManualModeEnabled()); mw.stepSizeSpinner.setValue(mw.settings.getManualModeStepSize()); boolean unitsAreMM = mw.settings.getDefaultUnits().equals("mm"); mw.mmRadioButton.setSelected(unitsAreMM); mw.inchRadioButton.setSelected(!unitsAreMM); mw.fileChooser = new JFileChooser(mw.settings.getLastOpenedFilename()); mw.commPortComboBox.setSelectedItem(mw.settings.getPort()); mw.baudrateSelectionComboBox.setSelectedItem(mw.settings.getPortRate()); mw.scrollWindowCheckBox.setSelected(mw.settings.isScrollWindowEnabled()); mw.showVerboseOutputCheckBox.setSelected(mw.settings.isVerboseOutputEnabled()); mw.showCommandTableCheckBox.setSelected(mw.settings.isCommandTableEnabled()); mw.showCommandTableCheckBoxActionPerformed(null); mw.firmwareComboBox.setSelectedItem(mw.settings.getFirmwareVersion()); mw.setSize(mw.settings.getMainWindowSettings().width, mw.settings.getMainWindowSettings().height); mw.setLocation(mw.settings.getMainWindowSettings().xLocation, mw.settings.getMainWindowSettings().yLocation); mw.addComponentListener(new ComponentListener() { @Override public void componentResized(ComponentEvent ce) { mw.settings.getMainWindowSettings().height = ce.getComponent().getSize().height; mw.settings.getMainWindowSettings().width = ce.getComponent().getSize().width; } @Override public void componentMoved(ComponentEvent ce) { mw.settings.getMainWindowSettings().xLocation = ce.getComponent().getLocation().x; mw.settings.getMainWindowSettings().yLocation = ce.getComponent().getLocation().y; } @Override public void componentShown(ComponentEvent ce) { } @Override public void componentHidden(ComponentEvent ce) { } }); /* Display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { mw.setVisible(true); } }); mw.initFileChooser(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { if (mw.fileChooser.getSelectedFile() != null) { mw.settings.setLastOpenedFilename(mw.fileChooser.getSelectedFile().getAbsolutePath()); } mw.settings.setDefaultUnits(mw.inchRadioButton.isSelected() ? "inch" : "mm"); mw.settings.setManualModeStepSize(mw.getStepSize()); mw.settings.setManualModeEnabled(mw.arrowMovementEnabled.isSelected()); mw.settings.setPort(mw.commPortComboBox.getSelectedItem().toString()); mw.settings.setPortRate(mw.baudrateSelectionComboBox.getSelectedItem().toString()); mw.settings.setScrollWindowEnabled(mw.scrollWindowCheckBox.isSelected()); mw.settings.setVerboseOutputEnabled(mw.showVerboseOutputCheckBox.isSelected()); mw.settings.setCommandTableEnabled(mw.showCommandTableCheckBox.isSelected()); mw.settings.setFirmwareVersion(mw.firmwareComboBox.getSelectedItem().toString()); SettingsFactory.saveSettings(mw.settings); if (mw.pendantUI != null) { mw.pendantUI.stop(); } } }); // Check command line for a file to open. boolean open = false; for (String arg : args) { if (open) { try { backend.setGcodeFile(new File(arg)); } catch (Exception ex) { Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex); System.exit(1); } } if (arg.equals("--open") || arg.equals("-o")) { open = true; } } }
From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step6HITPreparator.java
public static void main(String[] args) throws Exception { // input dir - list of xml query containers // step5-linguistic-annotation/ System.err.println("Starting step 6 HIT Preparation"); File inputDir = new File(args[0]); // output dir File outputDir = new File(args[1]); if (outputDir.exists()) { outputDir.delete();//from w w w . j a va2 s . com } outputDir.mkdir(); List<String> queries = new ArrayList<>(); // iterate over query containers int countClueWeb = 0; int countSentence = 0; for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) { QueryResultContainer queryResultContainer = QueryResultContainer .fromXML(FileUtils.readFileToString(f, "utf-8")); if (queries.contains(f.getName()) || queries.size() == 0) { // groups contain only non-empty documents Map<Integer, List<QueryResultContainer.SingleRankedResult>> groups = new HashMap<>(); // split to groups according to number of sentences for (QueryResultContainer.SingleRankedResult rankedResult : queryResultContainer.rankedResults) { if (rankedResult.originalXmi != null) { byte[] bytes = new BASE64Decoder() .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes())); JCas jCas = JCasFactory.createJCas(); XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas()); Collection<Sentence> sentences = JCasUtil.select(jCas, Sentence.class); int groupId = sentences.size() / 40; if (rankedResult.originalXmi == null) { System.err.println("Empty document: " + rankedResult.clueWebID); } else { if (!groups.containsKey(groupId)) { groups.put(groupId, new ArrayList<>()); } } //handle it groups.get(groupId).add(rankedResult); countClueWeb++; } } for (Map.Entry<Integer, List<QueryResultContainer.SingleRankedResult>> entry : groups.entrySet()) { Integer groupId = entry.getKey(); List<QueryResultContainer.SingleRankedResult> rankedResults = entry.getValue(); // make sure the results are sorted // DEBUG // for (QueryResultContainer.SingleRankedResult r : rankedResults) { // System.out.print(r.rank + "\t"); // } Collections.sort(rankedResults, (o1, o2) -> o1.rank.compareTo(o2.rank)); // iterate over results for one query and group for (int i = 0; i < rankedResults.size() && i < TOP_RESULTS_PER_GROUP; i++) { QueryResultContainer.SingleRankedResult rankedResult = rankedResults.get(i); QueryResultContainer.SingleRankedResult r = rankedResults.get(i); int rank = r.rank; MustacheFactory mf = new DefaultMustacheFactory(); Mustache mustache = mf.compile("template/template.html"); String queryId = queryResultContainer.qID; String query = queryResultContainer.query; // make the first letter uppercase query = query.substring(0, 1).toUpperCase() + query.substring(1); List<String> relevantInformationExamples = queryResultContainer.relevantInformationExamples; List<String> irrelevantInformationExamples = queryResultContainer.irrelevantInformationExamples; byte[] bytes = new BASE64Decoder() .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes())); JCas jCas = JCasFactory.createJCas(); XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas()); List<generators.Sentence> sentences = new ArrayList<>(); List<Integer> paragraphs = new ArrayList<>(); paragraphs.add(0); for (WebParagraph webParagraph : JCasUtil.select(jCas, WebParagraph.class)) { for (Sentence s : JCasUtil.selectCovered(Sentence.class, webParagraph)) { String sentenceBegin = String.valueOf(s.getBegin()); generators.Sentence sentence = new generators.Sentence(s.getCoveredText(), sentenceBegin); sentences.add(sentence); countSentence++; } int SentenceID = paragraphs.get(paragraphs.size() - 1); if (sentences.size() > 120) while (SentenceID < sentences.size()) { if (!paragraphs.contains(SentenceID)) paragraphs.add(SentenceID); SentenceID = SentenceID + 120; } paragraphs.add(sentences.size()); } System.err.println("Output dir: " + outputDir); int startID = 0; int endID; for (int j = 0; j < paragraphs.size(); j++) { endID = paragraphs.get(j); int sentLength = endID - startID; if (sentLength > 120 || j == paragraphs.size() - 1) { if (sentLength > 120) { endID = paragraphs.get(j - 1); j--; } sentLength = endID - startID; if (sentLength <= 40) groupId = 40; else if (sentLength <= 80 && sentLength > 40) groupId = 80; else if (sentLength > 80) groupId = 120; File folder = new File(outputDir + "/" + groupId); if (!folder.exists()) { System.err.println("creating directory: " + outputDir + "/" + groupId); boolean result = false; try { folder.mkdir(); result = true; } catch (SecurityException se) { //handle it } if (result) { System.out.println("DIR created"); } } String newHtmlFile = folder.getAbsolutePath() + "/" + f.getName() + "_" + rankedResult.clueWebID + "_" + sentLength + ".html"; System.err.println("Printing a file: " + newHtmlFile); File newHTML = new File(newHtmlFile); int t = 0; while (newHTML.exists()) { newHTML = new File(folder.getAbsolutePath() + "/" + f.getName() + "_" + rankedResult.clueWebID + "_" + sentLength + "." + t + ".html"); t++; } mustache.execute(new PrintWriter(new FileWriter(newHTML)), new generators(query, relevantInformationExamples, irrelevantInformationExamples, sentences.subList(startID, endID), queryId, rank)) .flush(); startID = endID; } } } } } } System.out.println("Printed " + countClueWeb + " documents with " + countSentence + " sentences"); }
From source file:Main.java
public static void add(Collection c, Object o) { c.add(o); }
From source file:Main.java
public static <O> boolean safeAdd(Collection<O> c, O item) { try {/* w w w. jav a 2 s .c o m*/ return c.add(item); } catch (Throwable ex) { return false; } }