List of usage examples for java.util Iterator hasNext
boolean hasNext();
From source file:edu.umd.cloud9.example.bigram.AnalyzeBigramCount.java
@SuppressWarnings({ "static-access" }) public static void main(String[] args) { Options options = new Options(); options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT)); CommandLine cmdline = null;//from w w w. j ava2 s .c o m CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(INPUT)) { System.out.println("args: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(AnalyzeBigramCount.class.getName(), options); ToolRunner.printGenericCommandUsage(System.out); System.exit(-1); } String inputPath = cmdline.getOptionValue(INPUT); System.out.println("input path: " + inputPath); List<PairOfWritables<Text, IntWritable>> bigrams = SequenceFileUtils.readDirectory(new Path(inputPath)); Collections.sort(bigrams, new Comparator<PairOfWritables<Text, IntWritable>>() { public int compare(PairOfWritables<Text, IntWritable> e1, PairOfWritables<Text, IntWritable> e2) { if (e2.getRightElement().compareTo(e1.getRightElement()) == 0) { return e1.getLeftElement().compareTo(e2.getLeftElement()); } return e2.getRightElement().compareTo(e1.getRightElement()); } }); int singletons = 0; int sum = 0; for (PairOfWritables<Text, IntWritable> bigram : bigrams) { sum += bigram.getRightElement().get(); if (bigram.getRightElement().get() == 1) { singletons++; } } System.out.println("total number of unique bigrams: " + bigrams.size()); System.out.println("total number of bigrams: " + sum); System.out.println("number of bigrams that appear only once: " + singletons); System.out.println("\nten most frequent bigrams: "); Iterator<PairOfWritables<Text, IntWritable>> iter = Iterators.limit(bigrams.iterator(), 10); while (iter.hasNext()) { PairOfWritables<Text, IntWritable> bigram = iter.next(); System.out.println(bigram.getLeftElement() + "\t" + bigram.getRightElement()); } }
From source file:graphene.dao.titan.BatchGraphTest.java
public static void main(String[] args) { Configuration conf = new BaseConfiguration(); conf.setProperty("storage.backend", "cassandrathrift"); conf.setProperty("storage.hostname", "127.0.0.1"); //conf.setProperty("storage.port", 9160); TitanGraph g = TitanFactory.open(conf); BatchGraph<TitanGraph> bgraph = new BatchGraph(g, VertexIDType.STRING, 1000); // for (String[] quad : quads) { // Vertex[] vertices = new Vertex[2]; // for (int i=0;i<2;i++) { // vertices[i] = bgraph.getVertex(quad[i]); // if (vertices[i]==null) vertices[i]=bgraph.addVertex(quad[i]); // }//from w w w . ja va 2s.c om // Edge edge = bgraph.addEdge(null,vertices[0],vertices[1],quad[2]); // edge.setProperty("annotation",quad[3]); // } for (int k = 0; k < MAXNODES; k++) { Vertex[] vertices = new Vertex[2]; for (int i = 0; i < 2; i++) { String id = "Vertex-" + rand.nextInt(MAXNODES); vertices[i] = bgraph.getVertex(id); if (vertices[i] == null) { vertices[i] = bgraph.addVertex(id); vertices[i].setProperty("label", id); } } String edgeId = "Edge-" + vertices[0].getId() + "--" + vertices[1].getId(); Edge e = bgraph.getEdge(edgeId); if (e == null) { e = bgraph.addEdge(null, vertices[0], vertices[1], edgeId); DateTime dt = new DateTime(); e.setProperty("edgeData", dt.getMillis()); } } bgraph.commit(); Iterator<Vertex> iter = bgraph.getVertices().iterator(); logger.debug("Start iterating over vertices"); while (iter.hasNext()) { Vertex v = iter.next(); Iterator<Edge> eIter = v.getEdges(Direction.BOTH).iterator(); while (eIter.hasNext()) { Edge currentEdge = eIter.next(); String data = currentEdge.getProperty("edgeData"); logger.debug("Observing edge " + currentEdge.getLabel()); logger.debug("has edge with data: " + data + " from " + currentEdge.getVertex(Direction.IN).getProperty("label") + " to " + currentEdge.getVertex(Direction.OUT).getProperty("label")); } } logger.debug("Done iterating over vertices"); }
From source file:MainClass.java
public static void main(String[] argv) { Map map = new MyMap(); map.put("Adobe", "Mountain View, CA"); map.put("Learning Tree", "Los Angeles, CA"); map.put("IBM", "White Plains, NY"); String queryString = "Google"; System.out.println("You asked about " + queryString + "."); String resultString = (String) map.get(queryString); System.out.println("They are located in: " + resultString); System.out.println();//w ww.ja va2s . co m Iterator k = map.keySet().iterator(); while (k.hasNext()) { String key = (String) k.next(); System.out.println("Key " + key + "; Value " + (String) map.get(key)); } Set es = map.entrySet(); System.out.println("entrySet() returns " + es.size() + " Map.Entry's"); }
From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step7aLearningDataProducer.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws IOException { String inputDir = args[0];/*from www. j ava 2s . com*/ File outputDir = new File(args[1]); if (!outputDir.exists()) { outputDir.mkdirs(); } Collection<File> files = IOHelper.listXmlFiles(new File(inputDir)); // for generating ConvArgStrict use this String prefix = "no-eq_DescendingScoreArgumentPairListSorter"; // for oversampling using graph transitivity properties use this // String prefix = "generated_no-eq_AscendingScoreArgumentPairListSorter"; Iterator<File> iterator = files.iterator(); while (iterator.hasNext()) { File file = iterator.next(); if (!file.getName().startsWith(prefix)) { iterator.remove(); } } int totalGoldPairsCounter = 0; Map<String, Integer> goldDataDistribution = new HashMap<>(); DescriptiveStatistics statsPerTopic = new DescriptiveStatistics(); int totalPairsWithReasonSameAsGold = 0; DescriptiveStatistics ds = new DescriptiveStatistics(); for (File file : files) { List<AnnotatedArgumentPair> argumentPairs = (List<AnnotatedArgumentPair>) XStreamTools.getXStream() .fromXML(file); int pairsPerTopicCounter = 0; String name = file.getName().replaceAll(prefix, "").replaceAll("\\.xml", ""); PrintWriter pw = new PrintWriter(new File(outputDir, name + ".csv"), "utf-8"); pw.println("#id\tlabel\ta1\ta2"); for (AnnotatedArgumentPair argumentPair : argumentPairs) { String goldLabel = argumentPair.getGoldLabel(); if (!goldDataDistribution.containsKey(goldLabel)) { goldDataDistribution.put(goldLabel, 0); } goldDataDistribution.put(goldLabel, goldDataDistribution.get(goldLabel) + 1); pw.printf(Locale.ENGLISH, "%s\t%s\t%s\t%s%n", argumentPair.getId(), goldLabel, multipleParagraphsToSingleLine(argumentPair.getArg1().getText()), multipleParagraphsToSingleLine(argumentPair.getArg2().getText())); pairsPerTopicCounter++; int sameInOnePair = 0; // get gold reason statistics for (AnnotatedArgumentPair.MTurkAssignment assignment : argumentPair.mTurkAssignments) { String label = assignment.getValue(); if (goldLabel.equals(label)) { sameInOnePair++; } } ds.addValue(sameInOnePair); totalPairsWithReasonSameAsGold += sameInOnePair; } totalGoldPairsCounter += pairsPerTopicCounter; statsPerTopic.addValue(pairsPerTopicCounter); pw.close(); } System.out.println("Total reasons matching gold " + totalPairsWithReasonSameAsGold); System.out.println(ds); System.out.println("Total gold pairs: " + totalGoldPairsCounter); System.out.println(statsPerTopic); int totalPairs = 0; for (Integer pairs : goldDataDistribution.values()) { totalPairs += pairs; } System.out.println("Total pairs: " + totalPairs); System.out.println(goldDataDistribution); }
From source file:Main.java
public static void main(String args[]) { List<String[]> left = new ArrayList<String[]>(); left.add(new String[] { "one", "two" }); List<String[]> right = new ArrayList<String[]>(); right.add(new String[] { "one", "two" }); java.util.Iterator<String[]> leftIterator = left.iterator(); java.util.Iterator<String[]> rightIterator = right.iterator(); if (left.size() != right.size()) { System.out.println("not equal"); }//from w w w . j av a2s. c o m while (leftIterator.hasNext()) { if (Arrays.equals(leftIterator.next(), rightIterator.next())) continue; else { System.out.print("not equal"); break; } } }
From source file:at.gv.egiz.pdfas.cli.test.SignaturProfileTest.java
public static void main(String[] args) { String user_home = System.getProperty("user.home"); String pdfas_dir = user_home + File.separator + ".pdfas"; PdfAs pdfas = PdfAsFactory.createPdfAs(new File(pdfas_dir)); try {/*from www . ja v a 2 s .c om*/ Configuration config = pdfas.getConfiguration(); ISettings settings = (ISettings) config; List<String> signatureProfiles = new ArrayList<String>(); List<String> signaturePDFAProfiles = new ArrayList<String>(); Iterator<String> itKeys = settings.getFirstLevelKeys("sig_obj.types.").iterator(); while (itKeys.hasNext()) { String key = itKeys.next(); String profile = key.substring("sig_obj.types.".length()); System.out.println("[" + profile + "]: " + settings.getValue(key)); if (settings.getValue(key).equals("on")) { signatureProfiles.add(profile); if (profile.contains("PDFA")) { signaturePDFAProfiles.add(profile); } } } byte[] input = IOUtils.toByteArray(new FileInputStream(sourcePDF)); IPlainSigner signer = new PAdESSignerKeystore(KS_FILE, KS_ALIAS, KS_PASS, KS_KEY_PASS, KS_TYPE); Iterator<String> itProfiles = signatureProfiles.iterator(); while (itProfiles.hasNext()) { String profile = itProfiles.next(); System.out.println("Testing " + profile); DataSource source = new ByteArrayDataSource(input); FileOutputStream fos = new FileOutputStream(targetFolder + profile + ".pdf"); SignParameter signParameter = PdfAsFactory.createSignParameter(config, source, fos); signParameter.setPlainSigner(signer); signParameter.setSignatureProfileId(profile); SignResult result = pdfas.sign(signParameter); fos.close(); } byte[] inputPDFA = IOUtils.toByteArray(new FileInputStream(sourcePDFA)); Iterator<String> itPDFAProfiles = signaturePDFAProfiles.iterator(); while (itPDFAProfiles.hasNext()) { String profile = itPDFAProfiles.next(); System.out.println("Testing " + profile); DataSource source = new ByteArrayDataSource(inputPDFA); FileOutputStream fos = new FileOutputStream(targetFolder + "PDFA_" + profile + ".pdf"); SignParameter signParameter = PdfAsFactory.createSignParameter(config, source, fos); signParameter.setPlainSigner(signer); signParameter.setSignatureProfileId(profile); SignResult result = pdfas.sign(signParameter); fos.close(); } } catch (Throwable e) { e.printStackTrace(); } }
From source file:dependencies.DependencyResolving.java
/** * @param args the command line arguments *///w w w. ja v a 2 s . co m public static void main(String[] args) { // TODO code application logic here JSONParser parser = new JSONParser(); //we use JSONParser in order to be able to read from JSON file try { //here we declare the file reader and define the path to the file dependencies.json Object obj = parser.parse(new FileReader( "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\dependencies.json")); JSONObject project = (JSONObject) obj; //a JSON object containing all the data in the .json file JSONArray dependencies = (JSONArray) project.get("dependencies"); //get array of objects with key "dependencies" System.out.print("We need to install the following dependencies: "); Iterator<String> iterator = dependencies.iterator(); //define an iterator over the array "dependencies" while (iterator.hasNext()) { System.out.println(iterator.next()); } //on the next line we declare another object, which parses a Parser object and reads from all_packages.json Object obj2 = parser.parse(new FileReader( "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\all_packages.json")); JSONObject tools = (JSONObject) obj2; //a JSON object containing all thr data in the file all_packages.json for (int i = 0; i < dependencies.size(); i++) { if (tools.containsKey(dependencies.get(i))) { System.out.println( "In order to install " + dependencies.get(i) + ", we need the following programs:"); JSONArray temporaryArray = (JSONArray) tools.get(dependencies.get(i)); //a temporary JSON array in which we store the keys and values of the dependencies for (i = 0; i < temporaryArray.size(); i++) { System.out.println(temporaryArray.get(i)); } ArrayList<Object> arraysOfJsonData = new ArrayList<Object>(); //an array in which we will store the keys of the objects, after we use the values and won't need them anymore for (i = 0; i < temporaryArray.size(); i++) { System.out.println("Installing " + temporaryArray.get(i)); } while (!temporaryArray.isEmpty()) { for (Object element : temporaryArray) { if (tools.containsKey(element)) { JSONArray secondaryArray = (JSONArray) tools.get(element); //a temporary array within the scope of the if-statement if (secondaryArray.size() != 0) { System.out.println("In order to install " + element + ", we need "); } for (i = 0; i < secondaryArray.size(); i++) { System.out.println(secondaryArray.get(i)); } for (Object o : secondaryArray) { arraysOfJsonData.add(o); //here we create a file with the installed dependency File file = new File( "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\installed_modules\\" + o); if (file.createNewFile()) { System.out.println(file.getName() + " is installed!"); } else { } } secondaryArray.clear(); } } temporaryArray.clear(); for (i = 0; i < arraysOfJsonData.size(); i++) { temporaryArray.add(arraysOfJsonData.get(i)); } arraysOfJsonData.clear(); } } } Set<String> keys = tools.keySet(); // here we define a set of keys of the objects in all_packages.json for (String s : keys) { File file = new File( "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\installed_modules\\" + s); if (file.createNewFile()) { System.out.println(file.getName() + " is installed."); } else { } } } catch (IOException ex) { Logger.getLogger(DependencyResolving.class.getName()).log(Level.SEVERE, null, ex); } catch (ParseException ex) { Logger.getLogger(DependencyResolving.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:jsonclient.JsonClient.java
public static void main(String args[]) { int EPS = 1;/*from www . j a v a 2s . c o m*/ List<Place> countries = new ArrayList<Place>(); List<Thread> threads = new ArrayList<Thread>(); Country country; countries = getCountries(); //CountrySearcher countrySearcher = null; Iterator<Place> itrCountry = countries.iterator(); ExecutorService exec = Executors.newFixedThreadPool(4); while (itrCountry.hasNext()) { country = new Country(itrCountry.next()); CountrySearcher cs = new CountrySearcher(country, EPS); threads.add(cs.thread); exec.execute(cs); } exec.shutdown(); for (Thread th : threads) try { th.join(); } catch (InterruptedException ex) { Logger.getLogger(JsonClient.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:edu.umd.cloud9.example.bigram.AnalyzeBigramRelativeFrequencyTuple.java
@SuppressWarnings({ "static-access" }) public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT)); CommandLine cmdline = null;/*w w w .jav a 2 s . c om*/ CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(INPUT)) { System.out.println("args: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(AnalyzeBigramRelativeFrequencyJson.class.getName(), options); ToolRunner.printGenericCommandUsage(System.out); System.exit(-1); } String inputPath = cmdline.getOptionValue(INPUT); System.out.println("input path: " + inputPath); List<PairOfWritables<Tuple, FloatWritable>> pairs = SequenceFileUtils.readDirectory(new Path(inputPath)); List<PairOfWritables<Tuple, FloatWritable>> list1 = Lists.newArrayList(); List<PairOfWritables<Tuple, FloatWritable>> list2 = Lists.newArrayList(); for (PairOfWritables<Tuple, FloatWritable> p : pairs) { Tuple bigram = p.getLeftElement(); if (bigram.get(0).equals("light")) { list1.add(p); } if (bigram.get(0).equals("contain")) { list2.add(p); } } Collections.sort(list1, new Comparator<PairOfWritables<Tuple, FloatWritable>>() { @SuppressWarnings("unchecked") public int compare(PairOfWritables<Tuple, FloatWritable> e1, PairOfWritables<Tuple, FloatWritable> e2) { if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) { return e1.getLeftElement().compareTo(e2.getLeftElement()); } return e2.getRightElement().compareTo(e1.getRightElement()); } }); Iterator<PairOfWritables<Tuple, FloatWritable>> iter1 = Iterators.limit(list1.iterator(), 10); while (iter1.hasNext()) { PairOfWritables<Tuple, FloatWritable> p = iter1.next(); Tuple bigram = p.getLeftElement(); System.out.println(bigram + "\t" + p.getRightElement()); } Collections.sort(list2, new Comparator<PairOfWritables<Tuple, FloatWritable>>() { @SuppressWarnings("unchecked") public int compare(PairOfWritables<Tuple, FloatWritable> e1, PairOfWritables<Tuple, FloatWritable> e2) { if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) { return e1.getLeftElement().compareTo(e2.getLeftElement()); } return e2.getRightElement().compareTo(e1.getRightElement()); } }); Iterator<PairOfWritables<Tuple, FloatWritable>> iter2 = Iterators.limit(list2.iterator(), 10); while (iter2.hasNext()) { PairOfWritables<Tuple, FloatWritable> p = iter2.next(); Tuple bigram = p.getLeftElement(); System.out.println(bigram + "\t" + p.getRightElement()); } }
From source file:net.wedjaa.elasticparser.tester.ESSearchTester.java
public static void main(String[] args) { System.out.println("ES Search Testing started."); System.out.println("Starting local node..."); Settings nodeSettings = ImmutableSettings.settingsBuilder().put("transport.tcp.port", "9600-9700") .put("http.port", "9500").put("http.max_content_length", "104857600").build(); Node node = NodeBuilder.nodeBuilder().settings(nodeSettings).clusterName("elasticparser.unittest").node(); node.start();/*w ww .j av a2 s. co m*/ // Populate our test index System.out.println("Preparing Unit Test Index - this may take a while..."); populateTest(); try { System.out.println("...OK - Executing query!"); // Try our searches ESSearch search = new ESSearch(null, null, ESSearch.ES_MODE_AGGS, "localhost", 9600, "elasticparser.unittest"); search.search(getQuery("test-aggs.json")); Map<String, Object> hit = null; while ((hit = search.next()) != null) { System.out.println("Hit: {"); for (String key : hit.keySet()) { System.out.println(" " + key + ": " + hit.get(key)); } System.out.println("};"); } search.close(); Map<String, Class<?>> fields = search.getFields(getQuery("test-aggs.json")); List<String> sortedKeys = new ArrayList<String>(fields.keySet()); Collections.sort(sortedKeys); Iterator<String> sortedKeyIter = sortedKeys.iterator(); while (sortedKeyIter.hasNext()) { String fieldname = sortedKeyIter.next(); System.out.println(" --> " + fieldname + "[" + fields.get(fieldname).getCanonicalName() + "]"); } } catch (Exception ex) { System.out.println("Exception: " + ex); } finally { System.out.println("Stopping Test Node"); node.stop(); } }