Example usage for java.util ArrayList add

List of usage examples for java.util ArrayList add

Introduction

In this page you can find the example usage for java.util ArrayList add.

Prototype

public boolean add(E e) 

Source Link

Document

Appends the specified element to the end of this list.

Usage

From source file:Main.java

public final static void main(String[] args) throws Exception {
    final ArrayList<String> list = new ArrayList<String>();

    ParserDelegator parserDelegator = new ParserDelegator();
    ParserCallback parserCallback = new ParserCallback() {
        public void handleText(final char[] data, final int pos) {
        }//from   ww w .j ava  2s  .  co m

        public void handleStartTag(Tag tag, MutableAttributeSet attribute, int pos) {
            if (tag == Tag.A) {
                String address = (String) attribute.getAttribute(Attribute.HREF);
                list.add(address);
            }
        }

        public void handleEndTag(Tag t, final int pos) {
        }

        public void handleSimpleTag(Tag t, MutableAttributeSet a, final int pos) {
        }

        public void handleComment(final char[] data, final int pos) {
        }

        public void handleError(final java.lang.String errMsg, final int pos) {
        }
    };
    parserDelegator.parse(new FileReader("a.html"), parserCallback, false);
    System.out.println(list);
}

From source file:unalcol.termites.boxplots.RoundNumber1.java

/**
 * For testing from the command line./* w  w w. j  a  v  a  2 s. c  om*/
 *
 * @param args ignored.
 */
public static void main(final String[] args) {
    //        double pf = Double.valueOf(args[0]);
    //       System.out.println("pf:" + args[0]);
    /* SASO Paper */
    /*
     double pf = 0;
     ArrayList<Double> pf0 = new ArrayList<>();
     ArrayList<Double> pfg1 = new ArrayList<>();
     ArrayList<Double> pfg2 = new ArrayList<>();
     ArrayList<Double> pfg3 = new ArrayList<>();
            
     pf0.add(0.0);
     pfg1.add(1.0E-4);
     pfg1.add(3.0E-4);
            
     pfg2.add(5.0E-4);
     pfg2.add(7.0E-4);
            
     pfg3.add(9.0E-4);
     //pfg3.add(1.0E-3);
            
     //Log.getInstance().addTarget(new PrintStreamLogTarget(System.out));
     final RoundNumber1 demo = new RoundNumber1("Round Number", pf0);
     final RoundNumber1 demo1 = new RoundNumber1("Round Number", pfg1);
     final RoundNumber1 demo2 = new RoundNumber1("Round Number", pfg2);
     final RoundNumber1 demo3 = new RoundNumber1("Round Number", pfg3);
     //demo.pack();
     //RefineryUtilities.centerFrameOnScreen(demo);
     //demo.setVisible(true);
     */
    if (args.length > 0) {
        experimentsDir = args[0];
    }

    if (args.length > 1) {
        mazeMode = args[1];
    }

    aMode = new String[args.length - 2];

    for (int i = 2; i < args.length; i++) {
        aMode[i - 2] = args[i];
    }

    ArrayList<Double> failureProbs = getFailureProbs();

    for (Double pf : failureProbs) {
        ArrayList<Double> pfi = new ArrayList<>();
        pfi.add(pf);
        final RoundNumber1 demo = new RoundNumber1("Round Number", pfi);
    }

    /*
     double pf = 0;
     ArrayList<Double> pf0 = new ArrayList<>();
     ArrayList<Double> pf1 = new ArrayList<>();
     ArrayList<Double> pf3 = new ArrayList<>();
     ArrayList<Double> pf5 = new ArrayList<>();
     ArrayList<Double> pf7 = new ArrayList<>();
     ArrayList<Double> pf9 = new ArrayList<>();
     ArrayList<Double> pf01 = new ArrayList<>();
            
     pf0.add(0.0);
     pf1.add(1.0E-4);
     pf3.add(3.0E-4);
     pf5.add(5.0E-4);
     pf7.add(7.0E-4);
     pf9.add(9.0E-4);
     pf01.add(1.0E-3);
            
     //pfg3.add(1.0E-3);
     //Log.getInstance().addTarget(new PrintStreamLogTarget(System.out));
     final RoundNumber1 demo = new RoundNumber1("Round Number", pf0);
     final RoundNumber1 demo1 = new RoundNumber1("Round Number", pf1);
     final RoundNumber1 demo2 = new RoundNumber1("Round Number", pf3);
     final RoundNumber1 demo3 = new RoundNumber1("Round Number", pf5);
     final RoundNumber1 demo4 = new RoundNumber1("Round Number", pf7);
     final RoundNumber1 demo5 = new RoundNumber1("Round Number", pf9);
     final RoundNumber1 demo6 = new RoundNumber1("Round Number", pf01);
     //demo.pack();
     //RefineryUtilities.centerFrameOnScreen(demo);
     //demo.setVisible(true);
     */
}

From source file:ch.epfl.lsir.xin.test.MFTest.java

/**
 * @param args//from   w w  w  .j a v a2 s  .  c  o m
 */
public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub

    PrintWriter logger = new PrintWriter(".//results//MF");

    PropertiesConfiguration config = new PropertiesConfiguration();
    config.setFile(new File("conf//MF.properties"));
    try {
        config.load();
    } catch (ConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Read rating data...");
    logger.flush();
    DataLoaderFile loader = new DataLoaderFile(".//data//MoveLens100k.txt");
    loader.readSimple();
    DataSetNumeric dataset = loader.getDataset();
    System.out.println("Number of ratings: " + dataset.getRatings().size() + " Number of users: "
            + dataset.getUserIDs().size() + " Number of items: " + dataset.getItemIDs().size());
    logger.println("Number of ratings: " + dataset.getRatings().size() + ", Number of users: "
            + dataset.getUserIDs().size() + ", Number of items: " + dataset.getItemIDs().size());
    logger.flush();

    double totalMAE = 0;
    double totalRMSE = 0;
    double totalPrecision = 0;
    double totalRecall = 0;
    double totalMAP = 0;
    double totalNDCG = 0;
    double totalMRR = 0;
    double totalAUC = 0;
    int F = 5;
    logger.println(F + "- folder cross validation.");
    logger.flush();
    ArrayList<ArrayList<NumericRating>> folders = new ArrayList<ArrayList<NumericRating>>();
    for (int i = 0; i < F; i++) {
        folders.add(new ArrayList<NumericRating>());
    }
    while (dataset.getRatings().size() > 0) {
        int index = new Random().nextInt(dataset.getRatings().size());
        int r = new Random().nextInt(F);
        folders.get(r).add(dataset.getRatings().get(index));
        dataset.getRatings().remove(index);
    }

    for (int folder = 1; folder <= F; folder++) {
        System.out.println("Folder: " + folder);
        logger.println("Folder: " + folder);
        logger.flush();
        ArrayList<NumericRating> trainRatings = new ArrayList<NumericRating>();
        ArrayList<NumericRating> testRatings = new ArrayList<NumericRating>();
        for (int i = 0; i < folders.size(); i++) {
            if (i == folder - 1)//test data
            {
                testRatings.addAll(folders.get(i));
            } else {//training data
                trainRatings.addAll(folders.get(i));
            }
        }

        //create rating matrix
        HashMap<String, Integer> userIDIndexMapping = new HashMap<String, Integer>();
        HashMap<String, Integer> itemIDIndexMapping = new HashMap<String, Integer>();
        for (int i = 0; i < dataset.getUserIDs().size(); i++) {
            userIDIndexMapping.put(dataset.getUserIDs().get(i), i);
        }
        for (int i = 0; i < dataset.getItemIDs().size(); i++) {
            itemIDIndexMapping.put(dataset.getItemIDs().get(i), i);
        }
        RatingMatrix trainRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(),
                dataset.getItemIDs().size());
        for (int i = 0; i < trainRatings.size(); i++) {
            trainRatingMatrix.set(userIDIndexMapping.get(trainRatings.get(i).getUserID()),
                    itemIDIndexMapping.get(trainRatings.get(i).getItemID()), trainRatings.get(i).getValue());
        }
        RatingMatrix testRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(),
                dataset.getItemIDs().size());
        for (int i = 0; i < testRatings.size(); i++) {
            //            if( testRatings.get(i).getValue() < 5 )
            //               continue;
            testRatingMatrix.set(userIDIndexMapping.get(testRatings.get(i).getUserID()),
                    itemIDIndexMapping.get(testRatings.get(i).getItemID()), testRatings.get(i).getValue());
        }
        System.out.println("Training: " + trainRatingMatrix.getTotalRatingNumber() + " vs Test: "
                + testRatingMatrix.getTotalRatingNumber());

        logger.println("Initialize a matrix factorization based recommendation model.");
        logger.flush();
        MatrixFactorization algo = new MatrixFactorization(trainRatingMatrix, false,
                ".//localModels//" + config.getString("NAME"));
        algo.setLogger(logger);
        algo.build();
        algo.saveModel(".//localModels//" + config.getString("NAME"));
        logger.println("Save the model.");
        logger.flush();

        //rating prediction accuracy
        double RMSE = 0;
        double MAE = 0;
        double precision = 0;
        double recall = 0;
        double map = 0;
        double ndcg = 0;
        double mrr = 0;
        double auc = 0;
        int count = 0;
        for (int i = 0; i < testRatings.size(); i++) {
            NumericRating rating = testRatings.get(i);
            double prediction = algo.predict(userIDIndexMapping.get(rating.getUserID()),
                    itemIDIndexMapping.get(rating.getItemID()), false);
            if (prediction > algo.getMaxRating())
                prediction = algo.getMaxRating();
            if (prediction < algo.getMinRating())
                prediction = algo.getMinRating();
            if (Double.isNaN(prediction)) {
                System.out.println("no prediction");
                continue;
            }
            MAE = MAE + Math.abs(rating.getValue() - prediction);
            RMSE = RMSE + Math.pow((rating.getValue() - prediction), 2);
            count++;
        }
        MAE = MAE / count;
        RMSE = Math.sqrt(RMSE / count);
        totalMAE = totalMAE + MAE;
        totalRMSE = totalRMSE + RMSE;
        System.out.println("Folder --- MAE: " + MAE + " RMSE: " + RMSE);
        logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Folder --- MAE: "
                + MAE + " RMSE: " + RMSE);
        //ranking accuracy
        if (algo.getTopN() > 0) {
            HashMap<Integer, ArrayList<ResultUnit>> results = new HashMap<Integer, ArrayList<ResultUnit>>();
            for (int i = 0; i < trainRatingMatrix.getRow(); i++) {
                ArrayList<ResultUnit> rec = algo.getRecommendationList(i);
                if (rec == null)
                    continue;
                int total = testRatingMatrix.getUserRatingNumber(i);
                if (total == 0)//this user is ignored
                    continue;
                results.put(i, rec);
                //               for( Map.Entry<Integer, Double> entry : testRatingMatrix.getRatingMatrix().get(i).entrySet() )
                //               {
                //                  System.out.print( entry.getKey() + "(" + entry.getValue() + ") , ");
                //               }
                //               System.out.println();
                //               for( int j = 0 ; j < rec.size() ; j++ )
                //               {
                //                  System.out.print(rec.get(j).getItemIndex() + "(" + rec.get(j).getPrediciton() +
                //                        ") , ");
                //               }
                //               System.out.println("**********");
            }
            RankResultGenerator generator = new RankResultGenerator(results, algo.getTopN(), testRatingMatrix,
                    trainRatingMatrix);
            precision = generator.getPrecisionN();
            totalPrecision = totalPrecision + precision;
            recall = generator.getRecallN();
            totalRecall = totalRecall + recall;
            map = generator.getMAPN();
            totalMAP = totalMAP + map;
            ndcg = generator.getNDCGN();
            totalNDCG = totalNDCG + ndcg;
            mrr = generator.getMRRN();
            totalMRR = totalMRR + mrr;
            auc = generator.getAUC();
            totalAUC = totalAUC + auc;
            System.out.println("Folder --- precision: " + precision + " recall: " + recall + " map: " + map
                    + " ndcg: " + ndcg + " mrr: " + mrr + " auc: " + auc);
            logger.println("Folder --- precision: " + precision + " recall: " + recall + " map: " + map
                    + " ndcg: " + ndcg + " mrr: " + mrr + " auc: " + auc);
        }

        logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " MAE: " + MAE
                + " RMSE: " + RMSE);
        logger.flush();
    }

    System.out.println("MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F);
    System.out.println("Precision@N: " + totalPrecision / F);
    System.out.println("Recall@N: " + totalRecall / F);
    System.out.println("MAP@N: " + totalMAP / F);
    System.out.println("MRR@N: " + totalMRR / F);
    System.out.println("NDCG@N: " + totalNDCG / F);
    System.out.println("AUC@N: " + totalAUC / F);

    logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\n" + "MAE: "
            + totalMAE / F + " RMSE: " + totalRMSE / F + "\n" + "Precision@N: " + totalPrecision / F + "\n"
            + "Recall@N: " + totalRecall / F + "\n" + "MAP@N: " + totalMAP / F + "\n" + "MRR@N: " + totalMRR / F
            + "\n" + "NDCG@N: " + totalNDCG / F + "\n" + "AUC@N: " + totalAUC / F);
    logger.flush();
    logger.close();

}

From source file:GIST.IzbirkomExtractor.IzbirkomExtractor.java

/**
 * @param args/*from ww  w.j a v  a 2 s .  c  o m*/
 */
public static void main(String[] args) {

    // process command-line options
    Options options = new Options();
    options.addOption("n", "noaddr", false, "do not do any address matching (for testing)");
    options.addOption("i", "info", false, "create and populate address information table");
    options.addOption("h", "help", false, "this message");

    // database connection
    options.addOption("s", "server", true, "database server to connect to");
    options.addOption("d", "database", true, "OSM database name");
    options.addOption("u", "user", true, "OSM database user name");
    options.addOption("p", "pass", true, "OSM database password");

    // logging options
    options.addOption("l", "logdir", true, "log file directory (default './logs')");
    options.addOption("e", "loglevel", true, "log level (default 'FINEST')");

    // automatically generate the help statement
    HelpFormatter help_formatter = new HelpFormatter();

    // database URI for connection
    String dburi = null;

    // Information message for help screen
    String info_msg = "IzbirkomExtractor [options] <html_directory>";

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption('h') || cmd.getArgs().length != 1) {
            help_formatter.printHelp(info_msg, options);
            System.exit(1);
        }

        /* prohibit n and i together */
        if (cmd.hasOption('n') && cmd.hasOption('i')) {
            System.err.println("Options 'n' and 'i' cannot be used together.");
            System.exit(1);
        }

        /* require database arguments without -n */
        if (cmd.hasOption('n')
                && (cmd.hasOption('s') || cmd.hasOption('d') || cmd.hasOption('u') || cmd.hasOption('p'))) {
            System.err.println("Options 'n' and does not need any databse parameters.");
            System.exit(1);
        }

        /* require all 4 database options to be used together */
        if (!cmd.hasOption('n')
                && !(cmd.hasOption('s') && cmd.hasOption('d') && cmd.hasOption('u') && cmd.hasOption('p'))) {
            System.err.println(
                    "For database access all of the following arguments have to be specified: server, database, user, pass");
            System.exit(1);
        }

        /* useful variables */
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm");
        String dateString = formatter.format(new Date());

        /* setup logging */
        File logdir = new File(cmd.hasOption('l') ? cmd.getOptionValue('l') : "logs");
        FileUtils.forceMkdir(logdir);
        File log_file_name = new File(
                logdir + "/" + IzbirkomExtractor.class.getName() + "-" + formatter.format(new Date()) + ".log");
        FileHandler log_file = new FileHandler(log_file_name.getPath());

        /* create "latest" link to currently created log file */
        Path latest_log_link = Paths.get(logdir + "/latest");
        Files.deleteIfExists(latest_log_link);
        Files.createSymbolicLink(latest_log_link, Paths.get(log_file_name.getName()));

        log_file.setFormatter(new SimpleFormatter());
        LogManager.getLogManager().reset(); // prevents logging to console
        logger.addHandler(log_file);
        logger.setLevel(cmd.hasOption('e') ? Level.parse(cmd.getOptionValue('e')) : Level.FINEST);

        // open directory with HTML files and create file list
        File dir = new File(cmd.getArgs()[0]);
        if (!dir.isDirectory()) {
            System.err.println("Unable to find directory '" + cmd.getArgs()[0] + "', exiting");
            System.exit(1);
        }
        PathMatcher pmatcher = FileSystems.getDefault()
                .getPathMatcher("glob:?  * ?*.html");
        ArrayList<File> html_files = new ArrayList<>();
        for (Path file : Files.newDirectoryStream(dir.toPath()))
            if (pmatcher.matches(file.getFileName()))
                html_files.add(file.toFile());
        if (html_files.size() == 0) {
            System.err.println("No matching HTML files found in '" + dir.getAbsolutePath() + "', exiting");
            System.exit(1);
        }

        // create csvResultSink
        FileOutputStream csvout_file = new FileOutputStream("parsed_addresses-" + dateString + ".csv");
        OutputStreamWriter csvout = new OutputStreamWriter(csvout_file, "UTF-8");
        ResultSink csvResultSink = new CSVResultSink(csvout, new CSVStrategy('|', '"', '#'));

        // Connect to DB and osmAddressMatcher
        AddressMatcher osmAddressMatcher;
        DBSink dbSink = null;
        DBInfoSink dbInfoSink = null;
        if (cmd.hasOption('n')) {
            osmAddressMatcher = new DummyAddressMatcher();
        } else {
            dburi = "jdbc:postgresql://" + cmd.getOptionValue('s') + "/" + cmd.getOptionValue('d');
            Connection con = DriverManager.getConnection(dburi, cmd.getOptionValue('u'),
                    cmd.getOptionValue('p'));
            osmAddressMatcher = new OsmAddressMatcher(con);
            dbSink = new DBSink(con);
            if (cmd.hasOption('i'))
                dbInfoSink = new DBInfoSink(con);
        }

        /* create resultsinks */
        SinkMultiplexor sm = SinkMultiplexor.newSinkMultiplexor();
        sm.addResultSink(csvResultSink);
        if (dbSink != null) {
            sm.addResultSink(dbSink);
            if (dbInfoSink != null)
                sm.addResultSink(dbInfoSink);
        }

        // create tableExtractor
        TableExtractor te = new TableExtractor(osmAddressMatcher, sm);

        // TODO: printout summary of options: processing date/time, host, directory of HTML files, jdbc uri, command line with parameters

        // iterate through files
        logger.info("Start processing " + html_files.size() + " files in " + dir);
        for (int i = 0; i < html_files.size(); i++) {
            System.err.println("Parsing #" + i + ": " + html_files.get(i));
            te.processHTMLfile(html_files.get(i));
        }

        System.err.println("Processed " + html_files.size() + " HTML files");
        logger.info("Finished processing " + html_files.size() + " files in " + dir);

    } catch (ParseException e1) {
        System.err.println("Failed to parse CLI: " + e1.getMessage());
        help_formatter.printHelp(info_msg, options);
        System.exit(1);
    } catch (IOException e) {
        System.err.println("I/O Exception: " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    } catch (SQLException e) {
        System.err.println("Database '" + dburi + "': " + e.getMessage());
        System.exit(1);
    } catch (ResultSinkException e) {
        System.err.println("Failed to initialize ResultSink: " + e.getMessage());
        System.exit(1);
    } catch (TableExtractorException e) {
        System.err.println("Failed to initialize Table Extractor: " + e.getMessage());
        System.exit(1);
    } catch (CloneNotSupportedException | IllegalAccessException | InstantiationException e) {
        System.err.println("Something really odd happened: " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:de.prozesskraft.pkraft.Perlcode.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    //      try//from   w ww.  ja v a 2  s  . co m
    //      {
    //         if (args.length != 3)
    //         {
    //            System.out.println("Please specify processdefinition file (xml) and an outputfilename");
    //         }
    //         
    //      }
    //      catch (ArrayIndexOutOfBoundsException e)
    //      {
    //         System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString());
    //      }

    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Perlcode.class) + "/" + "../etc/pkraft-perlcode.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option ostep = OptionBuilder.withArgName("STEPNAME").hasArg().withDescription(
            "[optional] stepname of step to generate a script for. if this parameter is omitted, a script for the process will be generated.")
            //            .isRequired()
            .create("step");

    Option ooutput = OptionBuilder.withArgName("DIR").hasArg()
            .withDescription("[mandatory] directory for generated files. must not exist when calling.")
            //            .isRequired()
            .create("output");

    Option odefinition = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory] process definition file.")
            //            .isRequired()
            .create("definition");

    Option onolist = OptionBuilder.withArgName("")
            //            .hasArg()
            .withDescription(
                    "[optional] with this parameter the multiple use of multi-optionis is forced. otherwise it is possible to use an integrated comma-separeated list.")
            //            .isRequired()
            .create("nolist");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(ostep);
    options.addOption(ooutput);
    options.addOption(odefinition);
    options.addOption(onolist);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        commandline = parser.parse(options, args);
    } catch (Exception exp) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        exiter();
    }

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("perlcode", options);
        System.exit(0);
    }

    else if (commandline.hasOption("v")) {
        System.out.println("web:     www.prozesskraft.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }

    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    if (!(commandline.hasOption("definition"))) {
        System.err.println("option -definition is mandatory.");
        exiter();
    }

    if (!(commandline.hasOption("output"))) {
        System.err.println("option -output is mandatory.");
        exiter();
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/
    Process p1 = new Process();
    java.io.File outputDir = new java.io.File(commandline.getOptionValue("output"));
    java.io.File outputDirProcessScript = new java.io.File(commandline.getOptionValue("output"));
    java.io.File outputDirBin = new java.io.File(commandline.getOptionValue("output") + "/bin");
    java.io.File outputDirLib = new java.io.File(commandline.getOptionValue("output") + "/lib");
    boolean nolist = false;
    if (commandline.hasOption("nolist")) {
        nolist = true;
    }

    if (outputDir.exists()) {
        System.err.println("fatal: directory already exists: " + outputDir.getCanonicalPath());
        exiter();
    } else {
        outputDir.mkdir();
    }

    p1.setInfilexml(commandline.getOptionValue("definition"));
    System.err.println("info: reading process definition " + commandline.getOptionValue("definition"));
    Process p2 = null;
    try {
        p2 = p1.readXml();
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.err.println("error");
        exiter();
    }

    // perlcode generieren fuer einen bestimmten step
    if (commandline.hasOption("step")) {
        outputDirBin.mkdir();
        String stepname = commandline.getOptionValue("step");
        writeStepAsPerlcode(p2, stepname, outputDirBin, nolist);
    }

    // perlcode generieren fuer den gesamten process
    else {
        outputDirBin.mkdir();
        writeProcessAsPerlcode(p2, outputDirProcessScript, outputDirBin, nolist);

        // copy all perllibs from the lib directory
        outputDirLib.mkdir();
        final Path source = Paths.get(WhereAmI.getInstallDirectoryAbsolutePath(Perlcode.class) + "/../perllib");
        final Path target = Paths.get(outputDirLib.toURI());

        copyDirectoryTree.copyDirectoryTree(source, target);
    }
}

From source file:isc_415_practica_1.ISC_415_Practica_1.java

/**
 * @param args the command line arguments
 *//*from w  w w  .ja  v  a 2s . c o m*/
public static void main(String[] args) {
    String urlString;
    Scanner input = new Scanner(System.in);
    Document doc;

    try {
        urlString = input.next();
        if (urlString.equals("servlet")) {
            urlString = "http://localhost:8084/ISC_415_Practica1_Servlet/client";
        }
        urlString = urlString.contains("http://") || urlString.contains("https://") ? urlString
                : "http://" + urlString;
        doc = Jsoup.connect(urlString).get();
    } catch (Exception ex) {
        System.out.println("El URL ingresado no es valido.");
        return;
    }

    ArrayList<NameValuePair> formInputParams;
    formInputParams = new ArrayList<>();
    String[] plainTextDoc = new TextNode(doc.html(), "").getWholeText().split("\n");
    System.out.println(String.format("Nmero de lineas del documento: %d", plainTextDoc.length));
    System.out.println(String.format("Nmero de p tags: %d", doc.select("p").size()));
    System.out.println(String.format("Nmero de img tags: %d", doc.select("img").size()));
    System.out.println(String.format("Nmero de form tags: %d", doc.select("form").size()));

    Integer index = 1;

    ArrayList<NameValuePair> urlParameters = new ArrayList<>();
    for (Element e : doc.select("form")) {
        System.out.println(String.format("Form %d: Nmero de Input tags %d", index, e.select("input").size()));
        System.out.println(e.select("input"));

        for (Element formInput : e.select("input")) {
            if (formInput.attr("id") != null && formInput.attr("id") != "") {
                urlParameters.add(new BasicNameValuePair(formInput.attr("id"), "PRACTICA1"));
            } else if (formInput.attr("name") != null && formInput.attr("name") != "") {
                urlParameters.add(new BasicNameValuePair(formInput.attr("name"), "PRACTICA1"));
            }
        }

        index++;
    }

    if (!urlParameters.isEmpty()) {
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(urlParameters, Consts.UTF_8);
            HttpPost httpPost = new HttpPost(urlString);
            httpPost.setHeader("User-Agent", USER_AGENT);
            httpPost.setEntity(entity);
            HttpResponse response = httpclient.execute(httpPost);
            System.out.println(response.getStatusLine());
        } catch (IOException ex) {
            Logger.getLogger(ISC_415_Practica_1.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}

From source file:jsdp.app.inventory.univariate.StochasticLotSizing.java

public static void main(String args[]) {

    boolean simulate = true;

    /*******************************************************************
     * Problem parameters//  ww  w .  j av a  2 s  . c o  m
     */
    double fixedOrderingCost = 300;
    double proportionalOrderingCost = 0;
    double holdingCost = 1;
    double penaltyCost = 10;

    double[] meanDemand = { 10, 20, 15, 20, 15, 10 };
    double coefficientOfVariation = 0.2;
    double truncationQuantile = 0.999;

    // Random variables

    Distribution[] distributions = IntStream.iterate(0, i -> i + 1).limit(meanDemand.length)
            //.mapToObj(i -> new NormalDist(meanDemand[i],meanDemand[i]*coefficientOfVariation))
            .mapToObj(i -> new PoissonDist(meanDemand[i])).toArray(Distribution[]::new);
    double[] supportLB = IntStream.iterate(0, i -> i + 1).limit(meanDemand.length)
            .mapToDouble(i -> distributions[i].inverseF(1 - truncationQuantile)).toArray();
    double[] supportUB = IntStream.iterate(0, i -> i + 1).limit(meanDemand.length)
            .mapToDouble(i -> distributions[i].inverseF(truncationQuantile)).toArray();

    double initialInventory = 0;

    /*******************************************************************
     * Model definition
     */

    // State space

    double stepSize = 1; //Stepsize must be 1 for discrete distributions
    double minState = -50; //Inventory level lower bound in each period
    double maxState = 150; //Inventory level upper bound in each period
    StateImpl.setStateBoundaries(stepSize, minState, maxState);

    // Actions

    Function<State, ArrayList<Action>> buildActionList = s -> {
        StateImpl state = (StateImpl) s;
        ArrayList<Action> feasibleActions = new ArrayList<Action>();
        for (double i = state.getInitialState(); i <= StateImpl.getMaxState(); i += StateImpl.getStepSize()) {
            feasibleActions.add(new ActionImpl(state, i - state.getInitialState()));
        }
        return feasibleActions;
    };

    Function<State, Action> idempotentAction = s -> new ActionImpl(s, 0.0);

    // Immediate Value Function

    ImmediateValueFunction<State, Action, Double> immediateValueFunction = (initialState, action,
            finalState) -> {
        ActionImpl a = (ActionImpl) action;
        StateImpl fs = (StateImpl) finalState;
        double orderingCost = a.getAction() > 0 ? (fixedOrderingCost + a.getAction() * proportionalOrderingCost)
                : 0;
        double holdingAndPenaltyCost = holdingCost * Math.max(fs.getInitialState(), 0)
                + penaltyCost * Math.max(-fs.getInitialState(), 0);
        return orderingCost + holdingAndPenaltyCost;
    };

    // Random Outcome Function

    RandomOutcomeFunction<State, Action, Double> randomOutcomeFunction = (initialState, action, finalState) -> {
        double realizedDemand = ((StateImpl) initialState).getInitialState() + ((ActionImpl) action).getAction()
                - ((StateImpl) finalState).getInitialState();
        return realizedDemand;
    };

    /*******************************************************************
     * Solve
     */

    // Sampling scheme

    SamplingScheme samplingScheme = SamplingScheme.NONE;
    int maxSampleSize = 100;
    double reductionFactorPerStage = 1;

    // Value Function Processing Method: backward recursion
    double discountFactor = 1.0;
    int stateSpaceLowerBound = 10000000;
    float loadFactor = 0.8F;
    BackwardRecursionImpl recursion = new BackwardRecursionImpl(OptimisationDirection.MIN, distributions,
            supportLB, supportUB, immediateValueFunction, randomOutcomeFunction, buildActionList,
            idempotentAction, discountFactor, samplingScheme, maxSampleSize, reductionFactorPerStage,
            stateSpaceLowerBound, loadFactor, HashType.THASHMAP);

    System.out.println("--------------Backward recursion--------------");
    recursion.runBackwardRecursionMonitoring();
    System.out.println();
    double ETC = recursion.getExpectedCost(initialInventory);
    StateDescriptorImpl initialState = new StateDescriptorImpl(0, initialInventory);
    double action = recursion.getOptimalAction(initialState).getAction();
    long percent = recursion.getMonitoringInterfaceBackward().getPercentCPU();
    System.out.println(
            "Expected total cost (assuming an initial inventory level " + initialInventory + "): " + ETC);
    System.out.println("Optimal initial action: " + action);
    System.out.println("Time elapsed: " + recursion.getMonitoringInterfaceBackward().getTime());
    System.out
            .println("Cpu usage: " + percent + "% (" + Runtime.getRuntime().availableProcessors() + " cores)");
    System.out.println();

    /*******************************************************************
     * Charting
     */
    System.out.println("--------------Charting--------------");
    int targetPeriod = 0;
    plotOptimalPolicyAction(targetPeriod, recursion); //Plot optimal policy action
    BackwardRecursionImpl recursionPlot = new BackwardRecursionImpl(OptimisationDirection.MIN, distributions,
            supportLB, supportUB, immediateValueFunction, randomOutcomeFunction, buildActionList,
            idempotentAction, discountFactor, targetPeriod > 0 ? SamplingScheme.NONE : samplingScheme,
            maxSampleSize, reductionFactorPerStage, HashType.THASHMAP);
    plotOptimalPolicyCost(targetPeriod, recursionPlot); //Plot optimal policy cost 
    System.out.println();

    /*******************************************************************
     * Simulation
     */
    System.out.println("--------------Simulation--------------");
    double confidence = 0.95; //Simulation confidence level 
    double errorTolerance = 0.0001; //Simulation error threshold

    if (simulate && samplingScheme == SamplingScheme.NONE)
        simulate(distributions, fixedOrderingCost, holdingCost, penaltyCost, proportionalOrderingCost,
                initialInventory, recursion, confidence, errorTolerance);
    else {
        if (!simulate)
            System.out.println("Simulation disabled.");
        if (samplingScheme != SamplingScheme.NONE)
            System.out.println(
                    "Cannot simulate a sampled solution, please disable sampling: set samplingScheme == SamplingScheme.NONE.");
    }
}

From source file:unalcol.termites.boxplots.ECALMessages.java

/**
 * For testing from the command line.//from w  ww  .  j a va2  s.c o m
 *
 * @param args ignored.
 */
public static void main(final String[] args) {
    //        double pf = Double.valueOf(args[0]);
    //       System.out.println("pf:" + args[0]);
    double pf = 0;
    ArrayList<Double> pf0 = new ArrayList<>();
    ArrayList<Double> pfg1 = new ArrayList<>();
    ArrayList<Double> pfg2 = new ArrayList<>();
    ArrayList<Double> pfg3 = new ArrayList<>();

    pf0.add(0.0);
    //pfg1.add(1.0E-4);
    pfg1.add(3.0E-4);
    //pfg2.add(5.0E-4);
    pfg2.add(7.0E-4);
    pfg3.add(9.0E-4);
    //pfg3.add(1.0E-3);

    //Log.getInstance().addTarget(new PrintStreamLogTarget(System.out));
    final ECALMessages demo = new ECALMessages("Messages Number", pf0);
    final ECALMessages demo1 = new ECALMessages("Messages Number", pfg1);
    final ECALMessages demo2 = new ECALMessages("Messages Number", pfg2);
    final ECALMessages demo3 = new ECALMessages("Messages Number", pfg3);
    //demo.pack();
    //RefineryUtilities.centerFrameOnScreen(demo);
    //demo.setVisible(true);

}

From source file:unalcol.termites.boxplots.MessagesSent2.java

/**
 * For testing from the command line.//from w w  w. j  av a 2 s. co m
 *
 * @param args ignored.
 */
public static void main(final String[] args) {
    //        double pf = Double.valueOf(args[0]);
    //       System.out.println("pf:" + args[0]);
    double pf = 0;
    ArrayList<Double> pf0 = new ArrayList<>();
    ArrayList<Double> pfg1 = new ArrayList<>();
    ArrayList<Double> pfg2 = new ArrayList<>();
    ArrayList<Double> pfg3 = new ArrayList<>();

    pf0.add(0.0);
    //pfg1.add(1.0E-4);
    pfg1.add(3.0E-4);
    //pfg2.add(5.0E-4);
    pfg2.add(7.0E-4);
    pfg3.add(9.0E-4);
    //pfg3.add(1.0E-3);

    //Log.getInstance().addTarget(new PrintStreamLogTarget(System.out));
    final MessagesSent2 demo = new MessagesSent2("Messages Number", pf0);
    final MessagesSent2 demo1 = new MessagesSent2("Messages Number", pfg1);
    final MessagesSent2 demo2 = new MessagesSent2("Messages Number", pfg2);
    final MessagesSent2 demo3 = new MessagesSent2("Messages Number", pfg3);
    //demo.pack();
    //RefineryUtilities.centerFrameOnScreen(demo);
    //demo.setVisible(true);

}

From source file:OpenDataExtractor.java

public static void main(String[] args) {

    System.out.println("\nSeleziona in che campo fare la ricerca: ");
    System.out.println("Elenco completo delle gare in formato (1)"); // cc16106a-1a65-4c34-af13-cc045d181452
    System.out.println("Composizione delle commissioni giudicatrici (2)"); // c90f1ffb-c315-4f59-b0e3-b0f2f8709127
    System.out.println("Registro delle imprese escluse dalle gare (3)"); // 2ea798cc-1f52-4fc8-a28e-f92a6f409cb8
    System.out.println("Registro delle imprese invitate alle gare (4)"); // a124b6af-ae31-428a-8ac5-bb341feb3c46
    System.out.println("Registro delle imprese che hanno partecipato alle gare (5)");// e58396cf-1145-4cb1-84a4-34311238a0c6
    System.out.println("Anagrafica completa dei contratti per l'acquisizione di beni e servizi (6)"); // aa6a8664-5ef5-43eb-a563-910e25161798
    System.out.println("Fornitori (7)"); // 253c8ac9-8335-4425-84c5-4a90be863c00
    System.out.println("Autorizzazioni subappalti per i lavori  (8)"); // 4f9ba542-5768-4b39-a92a-450c45eabd5d
    System.out.println("Aggiudicazioni delle gare per i lavori (9)"); // 34e298ad-3a99-4feb-9614-b9c4071b9d8e
    System.out.println("Dati cruscotto lavori per area (10)"); // 1ee3ea1b-58e3-48bf-8eeb-36ac313eeaf8
    System.out.println("Dati cruscotto lavori per lotto (11)"); // cbededce-269f-48d2-8c25-2359bf246f42
    int count = 0;
    int scelta;/*  w  w w .ja  va  2 s. c om*/
    String id_ref = "";
    Scanner scanner;

    try {

        do {
            scanner = new Scanner(System.in);
            scelta = scanner.nextInt();
            switch (scelta) {

            case 1:
                id_ref = "cc16106a-1a65-4c34-af13-cc045d181452&q=";
                break;
            case 2:
                id_ref = "c90f1ffb-c315-4f59-b0e3-b0f2f8709127&q=";
                break;
            case 3:
                id_ref = "2ea798cc-1f52-4fc8-a28e-f92a6f409cb8&q=";
                break;
            case 4:
                id_ref = "a124b6af-ae31-428a-8ac5-bb341feb3c46&q=";
                break;
            case 5:
                id_ref = "e58396cf-1145-4cb1-84a4-34311238a0c6&q=";
                break;
            case 6:
                id_ref = "aa6a8664-5ef5-43eb-a563-910e25161798&q=";
                break;
            case 7:
                id_ref = "253c8ac9-8335-4425-84c5-4a90be863c00&q=";
                break;
            case 8:
                id_ref = "4f9ba542-5768-4b39-a92a-450c45eabd5d&q=";
                break;
            case 9:
                id_ref = "34e298ad-3a99-4feb-9614-b9c4071b9d8e&q=";
                break;
            case 10:
                id_ref = "1ee3ea1b-58e3-48bf-8eeb-36ac313eeaf8&q=";
                break;
            case 11:
                id_ref = "cbededce-269f-48d2-8c25-2359bf246f42&q=";
                break;
            default:
                System.out.println("Numero non selezionabile");
                System.out.println("Reinserisci");
                break;

            }
        } while (scelta <= 0 || scelta > 11);

        scanner = new Scanner(System.in);

        System.out.println("Inserisci un parametro di ricerca: ");
        String record = scanner.nextLine();
        String limit = "&limit=10000";
        System.out.println("id di riferimento: " + id_ref);
        System.out.println("___________________________");
        String requestString = "http://dati.openexpo2015.it/catalog/api/action/datastore_search?resource_id="
                + id_ref + record + limit;
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(requestString);
        HttpResponse response = client.execute(request);

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String result = "";
        String resline = "";
        while ((resline = rd.readLine()) != null) {
            result += resline;
        }
        if (result != null) {
            JSONObject jsonObject = new JSONObject(result);
            JSONObject resultJson = (JSONObject) jsonObject.get("result");
            JSONArray resultJsonFields = (JSONArray) resultJson.get("fields");
            ArrayList<TypeFields> type = new ArrayList<TypeFields>();
            TypeFields type1;
            JSONObject temp;

            while (count < resultJsonFields.length()) {

                temp = (JSONObject) resultJsonFields.get(count);
                type1 = new TypeFields(temp.getString("id"), temp.getString("type"));
                type.add(type1);
                count++;
            }

            JSONArray arr = (JSONArray) resultJson.get("records");
            count = 0;

            while (count < arr.length()) {
                System.out.println("Entry numero: " + count);
                temp = (JSONObject) arr.get(count);
                for (TypeFields temp2 : type) {
                    System.out.println(temp2.nameType + ": " + temp.get(temp2.nameType));
                }
                count++;
                System.out.println("--------------------------");

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}