List of usage examples for java.util ArrayList size
int size
To view the source code for java.util ArrayList size.
Click Source Link
From source file:com.xandrev.altafitcalendargenerator.Main.java
public static void main(String[] args) { CalendarPrinter printer = new CalendarPrinter(); XLSExtractor extractor = new XLSExtractor(); if (args != null && args.length > 0) { try {//from w w w .j a v a 2 s. c o m Options opt = new Options(); opt.addOption("f", true, "Filepath of the XLS file"); opt.addOption("t", true, "Type name of activities"); opt.addOption("m", true, "Month index"); opt.addOption("o", true, "Output filename of the generated ICS"); BasicParser parser = new BasicParser(); CommandLine cliParser = parser.parse(opt, args); if (cliParser.hasOption("f")) { String fileName = cliParser.getOptionValue("f"); LOG.debug("File name to be imported: " + fileName); String activityNames = cliParser.getOptionValue("t"); LOG.debug("Activity type names: " + activityNames); ArrayList<String> nameList = new ArrayList<>(); String[] actNames = activityNames.split(","); if (actNames != null) { nameList.addAll(Arrays.asList(actNames)); } LOG.debug("Sucessfully activities parsed: " + nameList.size()); if (cliParser.hasOption("m")) { String monthIdx = cliParser.getOptionValue("m"); LOG.debug("Month index: " + monthIdx); int month = Integer.parseInt(monthIdx) - 1; if (cliParser.hasOption("o")) { String outputfilePath = cliParser.getOptionValue("o"); LOG.debug("Output file to be generated: " + monthIdx); LOG.debug("Starting to extract the spreadsheet"); HashMap<Integer, ArrayList<TimeTrack>> result = extractor.importExcelSheet(fileName); LOG.debug("Extracted the spreadsheet done"); LOG.debug("Starting the filter of the data"); HashMap<Date, String> cal = printer.getCalendaryByItem(result, nameList, month); LOG.debug("Finished the filter of the data"); LOG.debug("Creating the ics Calendar"); net.fortuna.ical4j.model.Calendar calendar = printer.createICSCalendar(cal); LOG.debug("Finished the ics Calendar"); LOG.debug("Printing the ICS file to: " + outputfilePath); printer.saveCalendar(calendar, outputfilePath); LOG.debug("Finished the ICS file to: " + outputfilePath); } } } } catch (ParseException ex) { LOG.error("Error parsing the argument list: ", ex); } } }
From source file:com.tamingtext.classifier.bayes.ClassifyDocument.java
public static void main(String[] args) { log.info("Command-line arguments: " + Arrays.toString(args)); DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); ArgumentBuilder abuilder = new ArgumentBuilder(); GroupBuilder gbuilder = new GroupBuilder(); Option inputOpt = obuilder.withLongName("input").withRequired(true) .withArgument(abuilder.withName("input").withMinimum(1).withMaximum(1).create()) .withDescription("Input file").withShortName("i").create(); Option modelOpt = obuilder.withLongName("model").withRequired(true) .withArgument(abuilder.withName("model").withMinimum(1).withMaximum(1).create()) .withDescription("Model to use when classifying data").withShortName("m").create(); Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h") .create();//from w ww.ja v a 2s. c o m Group group = gbuilder.withName("Options").withOption(inputOpt).withOption(modelOpt).withOption(helpOpt) .create(); try { Parser parser = new Parser(); parser.setGroup(group); CommandLine cmdLine = parser.parse(args); if (cmdLine.hasOption(helpOpt)) { CommandLineUtil.printHelp(group); return; } File inputFile = new File(cmdLine.getValue(inputOpt).toString()); if (!inputFile.isFile()) { throw new IllegalArgumentException(inputFile + " does not exist or is not a file"); } File modelDir = new File(cmdLine.getValue(modelOpt).toString()); if (!modelDir.isDirectory()) { throw new IllegalArgumentException(modelDir + " does not exist or is not a directory"); } BayesParameters p = new BayesParameters(); p.set("basePath", modelDir.getCanonicalPath()); Datastore ds = new InMemoryBayesDatastore(p); Algorithm a = new BayesAlgorithm(); ClassifierContext ctx = new ClassifierContext(a, ds); ctx.initialize(); //TODO: make the analyzer configurable StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_36); TokenStream ts = analyzer.tokenStream(null, new InputStreamReader(new FileInputStream(inputFile), "UTF-8")); ArrayList<String> tokens = new ArrayList<String>(1000); while (ts.incrementToken()) { tokens.add(ts.getAttribute(CharTermAttribute.class).toString()); } String[] document = tokens.toArray(new String[tokens.size()]); ClassifierResult[] cr = ctx.classifyDocument(document, "unknown", 5); for (ClassifierResult r : cr) { System.err.println(r.getLabel() + "\t" + r.getScore()); } } catch (OptionException e) { log.error("Exception", e); CommandLineUtil.printHelp(group); } catch (IOException e) { log.error("IOException", e); } catch (InvalidDatastoreException e) { log.error("InvalidDataStoreException", e); } finally { } }
From source file:ArrayListDemo.java
public static void main(String[] argv) { ArrayList al = new ArrayList(); // Create a source of Objects StructureDemo source = new StructureDemo(15); // Add lots of elements to the ArrayList... al.add(source.getDate());//from w w w . ja v a 2 s.c om al.add(source.getDate()); al.add(source.getDate()); // First print them out using a for loop. System.out.println("Retrieving by index:"); for (int i = 0; i < al.size(); i++) { System.out.println("Element " + i + " = " + al.get(i)); } }
From source file:interpolation.Polyfit.java
public static void main(String[] args) { final ArrayList<Pair<Integer, Double>> mts = loadsimple( new File("/Users/varunkapoor/Documents/Ines_Fourier/Cell39.txt")); final ArrayList<Pair<Integer, Double>> mtspoly = new ArrayList<Pair<Integer, Double>>(); double[] x = new double[mts.size()]; double[] y = new double[mts.size()]; int i = 0;/*w ww .ja v a 2s .c o m*/ for (Pair<Integer, Double> point : mts) { x[i] = point.getA(); y[i] = point.getB(); i++; } int degree = 20; Polyfit regression = new Polyfit(x, y, degree); for (double t = x[0]; t <= x[x.length - 1]; ++t) { double poly = regression.predict(t); mtspoly.add(new ValuePair<Integer, Double>((int) t, poly)); } XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(Tracking.drawPoints(mtspoly, new double[] { 1, 1, 1 }, "Function fit")); dataset.addSeries(Tracking.drawPoints(mts, new double[] { 1, 1, 1 }, "Original Data")); JFreeChart chart = Tracking.makeChart(dataset); Tracking.display(chart, new Dimension(500, 400)); Tracking.setColor(chart, i, new Color(255, 0, 0)); Tracking.setStroke(chart, i, 0.5f); for (int j = degree; j >= 0; --j) System.out.println(regression.GetCoefficients(j) + " *x power " + j); }
From source file:iac.cnr.it.TestSearcher.java
public static void main(String[] args) throws IOException, ParseException { /** Command line parser and options */ CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption(OPT_INDEX, true, "Index path"); options.addOption(OPT_QUERY, true, "The query"); CommandLine cmd = null;//from w w w . j ava2s. c om try { cmd = parser.parse(options, args); } catch (org.apache.commons.cli.ParseException e) { logger.fatal("Error while parsing command line arguments"); System.exit(1); } /** Check for mandatory options */ if (!cmd.hasOption(OPT_INDEX) || !cmd.hasOption(OPT_QUERY)) { usage(); System.exit(0); } /** Read options */ File casePath = new File(cmd.getOptionValue(OPT_INDEX)); String query = cmd.getOptionValue(OPT_QUERY); /** Check correctness of the path containing an ISODAC case */ if (!casePath.exists() || !casePath.isDirectory()) { logger.fatal("The case directory \"" + casePath.getAbsolutePath() + "\" is not valid"); System.exit(1); } /** Check existance of the info.dat file */ File infoFile = new File(casePath, INFO_FILENAME); if (!infoFile.exists()) { logger.fatal("Can't find " + INFO_FILENAME + " within the case directory (" + casePath + ")"); System.exit(1); } /** Load the mapping image_uuid --> image_filename */ imagesMap = new HashMap<Integer, String>(); BufferedReader reader = new BufferedReader(new FileReader(infoFile)); while (reader.ready()) { String line = reader.readLine(); logger.info("Read the line: " + line); String currentID = line.split("\t")[0]; String currentImgFile = line.split("\t")[1]; imagesMap.put(Integer.parseInt(currentID), currentImgFile); logger.info("ID: " + currentID + " - IMG: " + currentImgFile + " added to the map"); } reader.close(); /** Load all the directories containing an index */ ArrayList<String> indexesDirs = new ArrayList<String>(); for (File f : casePath.listFiles()) { logger.info("Analyzing: " + f); if (f.isDirectory()) indexesDirs.add(f.getAbsolutePath()); } logger.info(indexesDirs.size() + " directories found!"); /** Set-up the searcher */ Searcher searcher = null; try { String[] array = indexesDirs.toArray(new String[indexesDirs.size()]); searcher = new Searcher(array); TopDocs results = searcher.search(query, Integer.MAX_VALUE); ScoreDoc[] hits = results.scoreDocs; int numTotalHits = results.totalHits; System.out.println(numTotalHits + " total matching documents"); for (int i = 0; i < numTotalHits; i++) { Document doc = searcher.doc(hits[i].doc); String path = doc.get(FIELD_PATH); String filename = doc.get(FIELD_FILENAME); String image_uuid = doc.get(FIELD_IMAGE_ID); if (path != null) { //System.out.println((i + 1) + ". " + path + File.separator + filename + " - score: " + hits[i].score); // System.out.println((i + 1) + ". " + path + File.separator + filename + " - image_file: " + image_uuid); System.out.println((i + 1) + ". " + path + File.separator + filename + " - image_file: " + imagesMap.get(Integer.parseInt(image_uuid))); } else { System.out.println((i + 1) + ". " + "No path for this document"); } } } catch (Exception e) { System.err.println("An error occurred: " + e.getMessage()); e.printStackTrace(); } finally { if (searcher != null) searcher.close(); } }
From source file:ekb.elastic.ingest.TaxiQuery.java
public static void main(String... args) { Options options = new Options(); HelpFormatter help = new HelpFormatter(); try {/* ww w.j a v a 2 s. c o m*/ Option hostOpt = new Option("h", "host", true, "ElasticSearch URL"); hostOpt.setArgs(1); hostOpt.setRequired(true); Option portOpt = new Option("p", "port", true, "ElasticSearch URL"); portOpt.setArgs(1); portOpt.setRequired(true); Option clusterOpt = new Option("c", "cluster", true, "Cluster"); clusterOpt.setArgs(1); clusterOpt.setRequired(true); Option indexOpt = new Option("i", "index", true, "The index"); indexOpt.setArgs(1); indexOpt.setRequired(true); Option pickupTimeOpt = new Option("u", "pickup", true, "The pickup time"); pickupTimeOpt.setArgs(1); pickupTimeOpt.setRequired(true); Option dropTimeOpt = new Option("d", "dropoff", true, "The dropoff time"); dropTimeOpt.setArgs(1); dropTimeOpt.setRequired(true); options.addOption(hostOpt); options.addOption(portOpt); options.addOption(clusterOpt); options.addOption(indexOpt); options.addOption(pickupTimeOpt); options.addOption(dropTimeOpt); GnuParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", cmd.getOptionValue('c')) .build(); Client client = new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress( cmd.getOptionValue('h'), Integer.parseInt(cmd.getOptionValue('p')))); TaxiQuery tq = new TaxiQuery(); TaxiStats stats = tq.getTaxiStats(client, cmd.getOptionValues("i")); log.info("Results:\n" + stats.toDateString()); sdf.parse(cmd.getOptionValue("u")); sdf.parse(cmd.getOptionValue("d")); // 2013-01-01T10:10:00 ArrayList<TaxiBucket> list = tq.getInterval(client, cmd.getOptionValues("index"), cmd.getOptionValue("u"), cmd.getOptionValue("d"), 60); log.info("List size is: " + list.size()); client.close(); } catch (ParseException pe) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); help.printUsage(pw, 80, TaxiQuery.class.getName(), options); log.error(sw.toString()); } catch (TaxiQueryException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); log.error(sw.toString()); } catch (java.text.ParseException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); log.error(sw.toString()); } }
From source file:au.org.ala.layers.grid.GridCacheBuilder.java
public static void main(String[] args) throws IOException { logger.info("args[0]=diva grid input dir\nargs[1]=cached diva grid output dir\n\n"); //load up all diva grids in a directory ArrayList<Grid> grids = loadGridHeaders(args[0]); //identify groups ArrayList<ArrayList<Grid>> groups = identifyGroups(grids); //write large enough groups for (int i = 0; i < groups.size(); i++) { writeGroup(args[1], groups.get(i)); }/*ww w. j a v a 2 s.c om*/ }
From source file:fitmon.Client.java
public static void main(String[] args) throws IOException, ClientProtocolException, NoSuchAlgorithmException, InvalidKeyException, SAXException, ParserConfigurationException { Food food = null;/*from w w w. j a va2s. co m*/ DietAPI dApi = new DietAPI(); JDBCConnection jdbcCon = new JDBCConnection(); ArrayList<Food> foodItems = dApi.getFood(); Scanner scan = new Scanner(System.in); Calendar currentDate = Calendar.getInstance(); //Get the current date SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); //format it as per your requirement String dateNow = formatter.format(currentDate.getTime()); System.out.println("Now the date is :=> " + dateNow); for (int i = 0; i < foodItems.size(); i++) { food = foodItems.get(i); System.out.println("ID : " + food.getFoodID()); System.out.println("servingID : " + food.getServingID()); System.out.println("Name : " + food.getItemName()); System.out.println("category : " + food.getCategory()); System.out.println("Quantity : " + food.getQuantity()); System.out.println("calories : " + food.getCalories()); System.out.println("fat : " + food.getFat()); System.out.println("carbs : " + food.getCarbs()); System.out.println("protein : " + food.getProtein()); System.out.println("fiber : " + food.getFiber()); System.out.println("sodium : " + food.getSodium()); System.out.println("sugar : " + food.getSugar()); System.out.println("cholesterol : " + food.getCholesterol()); System.out.println( "------------------------------------------------------------------------------------------------"); } System.out.println("Choose a meal......"); String mealType = scan.next(); System.out.println("Choose an item......"); String servingID = scan.next(); for (int j = 0; j < foodItems.size(); j++) { if (foodItems.get(j).getServingID() == null ? servingID == null : foodItems.get(j).getServingID().equals(servingID)) { food = foodItems.get(j); break; } } Diet diet = new CustomizedDiet(); diet.createDiet(food, mealType, dateNow); }
From source file:edu.oregonstate.eecs.mcplan.domains.toy.WeinsteinLittman.java
public static void main(final String[] argv) throws NumberFormatException, IOException { final RandomGenerator rng = new MersenneTwister(42); final int nirrelevant = 2; while (true) { final Parameters params = new Parameters(nirrelevant); final Actions actions = new Actions(params); final FsssModel model = new FsssModel(rng, params); State s = model.initialState(); while (!s.isTerminal()) { System.out.println(s); System.out.println("R(s): " + model.reward(s)); actions.setState(s, 0);/*from ww w . j a v a 2 s.c om*/ final ArrayList<Action> action_list = Fn.takeAll(actions); for (int i = 0; i < action_list.size(); ++i) { System.out.println(i + ": " + action_list.get(i)); } System.out.print(">>> "); final BufferedReader cin = new BufferedReader(new InputStreamReader(System.in)); final int choice = Integer.parseInt(cin.readLine()); final Action a = action_list.get(choice); System.out.println("R(s, a): " + model.reward(s, a)); s = model.sampleTransition(s, a); } System.out.println("Terminal: " + s); System.out.println("R(s): " + model.reward(s)); System.out.println("********************"); } }
From source file:edu.ucla.cs.scai.swim.qa.ontology.dbpedia.tipicality.Test.java
public static void main(String[] args) throws IOException, ClassNotFoundException { String path = DBpediaOntology.DBPEDIA_CSV_FOLDER; if (args != null && args.length > 0) { path = args[0];/* www .j a v a2s . c om*/ if (!path.endsWith("/")) { path = path + "/"; } } stopAttributes.add("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"); stopAttributes.add("http://www.w3.org/2002/07/owl#sameAs"); stopAttributes.add("http://dbpedia.org/ontology/wikiPageRevisionID"); stopAttributes.add("http://dbpedia.org/ontology/wikiPageID"); stopAttributes.add("http://purl.org/dc/elements/1.1/description"); stopAttributes.add("http://dbpedia.org/ontology/thumbnail"); stopAttributes.add("http://dbpedia.org/ontology/type"); try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path + "counts.bin"))) { categories = (HashSet<String>) ois.readObject(); attributes = (HashSet<String>) ois.readObject(); categoryCount = (HashMap<String, Integer>) ois.readObject(); attributeCount = (HashMap<String, Integer>) ois.readObject(); categoryAttributeCount = (HashMap<String, HashMap<String, Integer>>) ois.readObject(); attributeCategoryCount = (HashMap<String, HashMap<String, Integer>>) ois.readObject(); } System.out.println(categories.size() + " categories found"); System.out.println(attributes.size() + " attributes found"); n = 0; for (Map.Entry<String, Integer> e : categoryCount.entrySet()) { n += e.getValue(); } System.out.println(n); HashMap<String, ArrayList<Pair>> sortedCategoryAttributes = new HashMap<>(); for (String category : categories) { //System.out.println(category); //System.out.println("-----------"); ArrayList<Pair> attributesRank = new ArrayList<Pair>(); Integer c = categoryCount.get(category); if (c == null || c == 0) { continue; } HashMap<String, Integer> thisCategoryAttributeCount = categoryAttributeCount.get(category); for (Map.Entry<String, Integer> e : thisCategoryAttributeCount.entrySet()) { attributesRank.add(new Pair(e.getKey(), 1.0 * e.getValue() / c)); } Collections.sort(attributesRank); for (Pair p : attributesRank) { //System.out.println("A:" + p.getS() + "\t" + p.getP()); } //System.out.println("==============================="); sortedCategoryAttributes.put(category, attributesRank); } for (String attribute : attributes) { //System.out.println(attribute); //System.out.println("-----------"); ArrayList<Pair> categoriesRank = new ArrayList<>(); Integer a = attributeCount.get(attribute); if (a == null || a == 0) { continue; } HashMap<String, Integer> thisAttributeCategoryCount = attributeCategoryCount.get(attribute); for (Map.Entry<String, Integer> e : thisAttributeCategoryCount.entrySet()) { categoriesRank.add(new Pair(e.getKey(), 1.0 * e.getValue() / a)); } Collections.sort(categoriesRank); for (Pair p : categoriesRank) { //System.out.println("C:" + p.getS() + "\t" + p.getP()); } //System.out.println("==============================="); } HashMap<Integer, Integer> histogram = new HashMap<>(); histogram.put(0, 0); histogram.put(1, 0); histogram.put(2, 0); histogram.put(Integer.MAX_VALUE, 0); int nTest = 0; if (args != null && args.length > 0) { path = args[0]; if (!path.endsWith("/")) { path = path + "/"; } } for (File f : new File(path).listFiles()) { if (f.isFile() && f.getName().endsWith(".csv")) { String category = f.getName().replaceFirst("\\.csv", ""); System.out.println("Category: " + category); ArrayList<HashSet<String>> entities = extractEntities(f, 2); for (HashSet<String> attributesOfThisEntity : entities) { nTest++; ArrayList<String> rankedCategories = rankedCategories(attributesOfThisEntity); boolean found = false; for (int i = 0; i < rankedCategories.size() && !found; i++) { if (rankedCategories.get(i).equals(category)) { Integer count = histogram.get(i); if (count == null) { histogram.put(i, 1); } else { histogram.put(i, count + 1); } found = true; } } if (!found) { histogram.put(Integer.MAX_VALUE, histogram.get(Integer.MAX_VALUE) + 1); } } System.out.println("Tested entities: " + nTest); System.out.println("1: " + histogram.get(0)); System.out.println("2: " + histogram.get(1)); System.out.println("3: " + histogram.get(2)); System.out.println("+3: " + (nTest - histogram.get(2) - histogram.get(1) - histogram.get(0) - histogram.get(Integer.MAX_VALUE))); System.out.println("NF: " + histogram.get(Integer.MAX_VALUE)); } } }