Example usage for java.io PrintWriter println

List of usage examples for java.io PrintWriter println

Introduction

In this page you can find the example usage for java.io PrintWriter println.

Prototype

public void println(Object x) 

Source Link

Document

Prints an Object and then terminates the line.

Usage

From source file:BufferedSocketClient.java

public static void main(String args[]) throws Exception {
        int cTosPortNumber = 1777;
        String str;//w  w w.  ja  v  a  2s  .c  o  m

        ServerSocket servSocket = new ServerSocket(cTosPortNumber);
        System.out.println("Waiting for a connection on " + cTosPortNumber);

        Socket fromClientSocket = servSocket.accept();
        PrintWriter pw = new PrintWriter(fromClientSocket.getOutputStream(), true);

        BufferedReader br = new BufferedReader(new InputStreamReader(fromClientSocket.getInputStream()));

        while ((str = br.readLine()) != null) {
            System.out.println("The message: " + str);

            if (str.equals("bye")) {
                pw.println("bye");
                break;
            } else {
                str = "Server returns " + str;
                pw.println(str);
            }
        }
        pw.close();
        br.close();

        fromClientSocket.close();
    }

From source file:com.kappaware.logtrawler.Main.java

@SuppressWarnings("static-access")
static public void main(String[] argv) throws Throwable {

    Config config;/*from  w w w.  j a  v a2s  . c om*/

    Options options = new Options();

    options.addOption(OptionBuilder.hasArg().withArgName("configFile").withLongOpt("config-file")
            .withDescription("JSON configuration file").create("c"));
    options.addOption(OptionBuilder.hasArg().withArgName("folder").withLongOpt("folder")
            .withDescription("Folder to monitor").create("f"));
    options.addOption(OptionBuilder.hasArg().withArgName("exclusion").withLongOpt("exclusion")
            .withDescription("Exclusion regex").create("x"));
    options.addOption(OptionBuilder.hasArg().withArgName("adminEndpoint").withLongOpt("admin-endpoint")
            .withDescription("Endpoint for admin REST").create("e"));
    options.addOption(OptionBuilder.hasArg().withArgName("outputFlow").withLongOpt("output-flow")
            .withDescription("Target to post result on").create("o"));
    options.addOption(OptionBuilder.hasArg().withArgName("hostname").withLongOpt("hostname")
            .withDescription("This hostname").create("h"));
    options.addOption(OptionBuilder.withLongOpt("displayDot").withDescription("Display Dot").create("d"));
    options.addOption(OptionBuilder.hasArg().withArgName("mimeType").withLongOpt("mime-type")
            .withDescription("Valid MIME type").create("m"));
    options.addOption(OptionBuilder.hasArg().withArgName("allowedAdmin").withLongOpt("allowedAdmin")
            .withDescription("Allowed admin network").create("a"));
    options.addOption(OptionBuilder.hasArg().withArgName("configFile").withLongOpt("gen-config-file")
            .withDescription("Generate JSON configuration file").create("g"));
    options.addOption(OptionBuilder.hasArg().withArgName("maxBatchSize").withLongOpt("max-batch-size")
            .withDescription("Max JSON batch (array) size").create("b"));

    CommandLineParser clParser = new BasicParser();
    CommandLine line;
    String configFile = null;
    try {
        // parse the command line argument
        line = clParser.parse(options, argv);
        if (line.hasOption("c")) {
            configFile = line.getOptionValue("c");
            config = Json.fromJson(Config.class,
                    new BufferedReader(new InputStreamReader(new FileInputStream(configFile))));
        } else {
            config = new Config();
        }
        if (line.hasOption("f")) {
            String[] fs = line.getOptionValues("f");
            // Get the first agent (Create it if needed)
            if (config.getAgents() == null || config.getAgents().size() == 0) {
                Config.Agent agent = new Config.Agent("default");
                config.addAgent(agent);
            }
            Config.Agent agent = config.getAgents().iterator().next();
            for (String f : fs) {
                agent.addFolder(new Config.Agent.Folder(f, false));
            }
        }
        if (line.hasOption("e")) {
            String e = line.getOptionValue("e");
            config.setAdminEndpoint(e);
        }
        if (line.hasOption("o")) {
            String[] es = line.getOptionValues("o");
            if (config.getAgents() != null) {
                for (Agent agent : config.getAgents()) {
                    for (String s : es) {
                        agent.addOuputFlow(s);
                    }
                }
            }
        }
        if (line.hasOption("h")) {
            String e = line.getOptionValue("h");
            config.setHostname(e);
        }
        if (line.hasOption("x")) {
            if (config.getAgents() != null) {
                for (Agent agent : config.getAgents()) {
                    if (agent.getFolders() != null) {
                        for (Folder folder : agent.getFolders()) {
                            String[] exs = line.getOptionValues("x");
                            for (String ex : exs) {
                                folder.addExcludedPath(ex);
                            }
                        }
                    }
                }
            }
        }
        if (line.hasOption("m")) {
            if (config.getAgents() != null) {
                for (Agent agent : config.getAgents()) {
                    String[] exs = line.getOptionValues("m");
                    for (String ex : exs) {
                        agent.addLogMimeType(ex);
                    }
                }
            }
        }
        if (line.hasOption("a")) {
            String[] exs = line.getOptionValues("a");
            for (String ex : exs) {
                config.addAdminAllowedNetwork(ex);
            }
        }
        if (line.hasOption("d")) {
            config.setDisplayDot(true);
        }
        if (line.hasOption("b")) {
            Integer i = getIntegerParameter(line, "b");
            if (config.getAgents() != null) {
                for (Agent agent : config.getAgents()) {
                    agent.setOutputMaxBatchSize(i);
                }
            }
        }
        config.setDefault();
        if (line.hasOption("g")) {
            String fileName = line.getOptionValue("g");
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName, false)));
            out.println(Json.toJson(config, true));
            out.flush();
            out.close();
            System.exit(0);
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        usage(options, exp.getMessage());
        return;
    }

    try {
        // Check config
        if (config.getAgents() == null || config.getAgents().size() < 1) {
            throw new ConfigurationException("At least one folder to monitor must be provided!");
        }
        Map<String, AgentHandler> agentHandlerByName = new HashMap<String, AgentHandler>();
        for (Config.Agent agent : config.getAgents()) {
            agentHandlerByName.put(agent.getName(), new AgentHandler(agent));
        }
        if (!Utils.isNullOrEmpty(config.getAdminEndpoint())) {
            new AdminServer(config, agentHandlerByName);
        }
    } catch (ConfigurationException e) {
        log.error(e.toString());
        System.exit(1);
    } catch (Throwable t) {
        log.error("Error in main", t);
        System.exit(2);
    }
}

From source file:csv.parser.CSVParser.java

@SuppressWarnings("resource")
public static void main(String[] args) throws Exception {
    String file_to_parse;//ww  w . j  av a 2s . com
    String[] val_array;
    file_to_parse = "./input/E-library-data-3.csv";
    //Build reader instance
    //Read CSV file
    CSVReader reader = new CSVReader(new FileReader(file_to_parse), ';', '"', 1);

    //Read all rows at once
    List<String[]> allRows = reader.readAll();

    //        Read CSV line by line and use the string array as you want
    for (String[] row : allRows) {
        for (int i = 0; i < row.length; i++) {
            //Removing all newlines, tabs and '&' characters(invalid XML character)
            row[i] = row[i].replaceAll("(\\r|\\n|\\r\\n)+", " ");
            row[i] = row[i].replaceAll(System.getProperty("line.separator"), "; ");
            row[i] = row[i].replaceAll("&", "and");
        }

        System.out.println(Arrays.toString(row));
    }
    //Get the input fields
    List<String[]> map = getMap();
    String[] field;
    //Numbering for folders, folderNum is incremented for each new file
    long folderNum;
    folderNum = 0;
    for (String[] row : allRows) {
        //Creating new folder
        File file1 = new File("./output//newdir//folder" + folderNum + "");
        file1.mkdirs();
        //Creating content file
        PrintWriter writer_content = new PrintWriter("./output//newdir//folder" + folderNum + "//contents",
                "UTF-16");
        //Creating metadata_lrmi.xml
        PrintWriter writer_lrmi = new PrintWriter(
                "./output//newdir//folder" + folderNum + "//metadata_lrmi.xml", "UTF-16");
        //Creating content.xml
        PrintWriter writer = new PrintWriter("./output//newdir//folder" + folderNum + "//content.xml",
                "UTF-16");
        writer.println("<?xml version=\"1.0\" encoding=\"utf-16\" standalone=\"no\"?>");
        writer.println("<dublin_core schema=\"dc\">");
        writer_lrmi.println("<?xml version=\"1.0\" encoding=\"utf-16\" standalone=\"no\"?>");
        writer_lrmi.println("<dublin_core shema=\"lrmi\">");
        for (int i = 0; i < row.length; i++) {
            //After snooping data, we have to change these setting for each new csv file, as the data fileds are many times mismatched
            //These if-else statements take care of mismatched steps.
            if (i == 43) {
                continue;
            } else if (i == 43) {
                field = map.get(42);
            } else if (i == 44) {
                field = map.get(43);
            } else if (i == 45 || i == 46) {
                continue;
            } else {
                field = map.get(i);
            }
            //Separate multiple values
            val_array = parseVal(row[i]);
            //                if (val_array.length == 0) {
            //                    continue;
            //                }
            PrintWriter useWriter = writer;
            if (field[0].equals("lrmi")) {
                useWriter = writer_lrmi;
            }
            switch (field.length) {
            case 2:
                writeXML(useWriter, field[1], "", val_array);
                break;
            case 3:
                writeXML(useWriter, field[1], field[2], val_array);
                break;
            default:

            }
        }
        folderNum++;
        writer.println("</dublin_core>");
        writer_lrmi.println("</dublin_core>");
        writer.close();
        writer_lrmi.close();
        writer_content.close();
    }
}

From source file:at.tuwien.ifs.feature.evaluation.SimilarityRetrievalWriter.java

public static void main(String[] args) throws SOMToolboxException, IOException {
    // register and parse all options
    JSAPResult config = OptionFactory.parseResults(args, OPTIONS);
    File inputVectorFile = config.getFile("inputVectorFile");
    String outputDirStr = AbstractOptionFactory.getFilePath(config, "outputDirectory");
    File outputDirBase = new File(outputDirStr);
    outputDirBase.mkdirs();/*from  ww  w  .j  a v a2 s.  c  o m*/
    String metricName = config.getString("metric");
    DistanceMetric metric = AbstractMetric.instantiateNice(metricName);

    int neighbours = config.getInt("numberNeighbours");
    int startIndex = config.getInt("startIndex");
    int numberItems = config.getInt("numberItems", -1);

    try {
        SOMLibSparseInputData data = new SOMLibSparseInputData(inputVectorFile.getAbsolutePath());
        int endIndex = data.numVectors();
        if (numberItems != -1) {
            if (startIndex + numberItems > endIndex) {
                System.out.println("Specified number of items (" + numberItems + ") exceeds maximum ("
                        + data.numVectors() + "), limiting to " + (endIndex - startIndex) + ".");
            } else {
                endIndex = startIndex + numberItems;
            }
        }
        StdErrProgressWriter progress = new StdErrProgressWriter(endIndex - startIndex, "processing vector ");
        // SortedSet<InputDistance> distances;
        for (int inputDatumIndex = startIndex; inputDatumIndex < endIndex; inputDatumIndex++) {

            InputDatum inputDatum = data.getInputDatum(inputDatumIndex);
            String inputLabel = inputDatum.getLabel();
            if (inputDatumIndex == -1) {
                throw new IllegalArgumentException(
                        "Input with label '" + inputLabel + "' not found in vector file '" + inputVectorFile
                                + "'; possible labels are: " + StringUtils.toString(data.getLabels(), 15));
            }

            File outputDir = new File(outputDirBase,
                    inputLabel.charAt(2) + "/" + inputLabel.charAt(3) + "/" + inputLabel.charAt(4));
            outputDir.mkdirs();
            File outputFile = new File(outputDir, inputLabel + ".txt");

            boolean fileExistsAndValid = false;
            if (outputFile.exists()) {
                // check if it the valid data
                String linesInvalid = "";
                int validLineCount = 0;
                ArrayList<String> lines = FileUtils.readLinesAsList(outputFile.getAbsolutePath());
                for (String string : lines) {
                    if (string.trim().length() == 0) {
                        continue;
                    }
                    String[] parts = string.split("\t");
                    if (parts.length != 2) {
                        linesInvalid += "Line '" + string + "' invalid - contains " + parts.length
                                + " elements.\n";
                    } else if (!NumberUtils.isNumber(parts[1])) {
                        linesInvalid = "Line '" + string + "' invalid - 2nd part is not a number.\n";
                    } else {
                        validLineCount++;
                    }
                }
                if (validLineCount != neighbours) {
                    linesInvalid = "Not enough valid lines; expected " + neighbours + ", found "
                            + validLineCount + ".\n";
                }
                fileExistsAndValid = true;
                if (org.apache.commons.lang.StringUtils.isNotBlank(linesInvalid)) {
                    System.out.println("File " + outputFile.getAbsolutePath() + " exists, but is not valid:\n"
                            + linesInvalid);
                }
            }

            if (fileExistsAndValid) {
                Logger.getLogger("at.tuwien.ifs.feature.evaluation").finer(
                        "File " + outputFile.getAbsolutePath() + " exists and is valid; not recomputing");
            } else {
                PrintWriter p = new PrintWriter(outputFile);
                SmallestElementSet<InputDistance> distances = data.getNearestDistances(inputDatumIndex,
                        neighbours, metric);
                for (InputDistance inputDistance : distances) {
                    p.println(inputDistance.getInput().getLabel() + "\t" + inputDistance.getDistance());
                }
                p.close();
            }
            progress.progress();
        }

    } catch (IllegalArgumentException e) {
        System.out.println(e.getMessage() + ". Aborting.");
        System.exit(-1);
    }
}

From source file:BookRank.java

/** Grab the sales rank off the web page and log it. */
public static void main(String[] args) throws Exception {

    Properties p = new Properties();
    String title = p.getProperty("title", "NO TITLE IN PROPERTIES");
    // The url must have the "isbn=" at the very end, or otherwise
    // be amenable to being string-catted to, like the default.
    String url = p.getProperty("url", "http://test.ing/test.cgi?isbn=");
    // The 10-digit ISBN for the book.
    String isbn = p.getProperty("isbn", "0000000000");
    // The RE pattern (MUST have ONE capture group for the number)
    String pattern = p.getProperty("pattern", "Rank: (\\d+)");

    // Looking for something like this in the input:
    //    <b>QuickBookShop.web Sales Rank: </b>
    //    26,252/* w ww  .  java2  s  .  c o m*/
    //    </font><br>

    Pattern r = Pattern.compile(pattern);

    // Open the URL and get a Reader from it.
    BufferedReader is = new BufferedReader(new InputStreamReader(new URL(url + isbn).openStream()));
    // Read the URL looking for the rank information, as
    // a single long string, so can match RE across multi-lines.
    String input = "input from console";
    // System.out.println(input);

    // If found, append to sales data file.
    Matcher m = r.matcher(input);
    if (m.find()) {
        PrintWriter pw = new PrintWriter(new FileWriter(DATA_FILE, true));
        String date = // `date +'%m %d %H %M %S %Y'`;
                new SimpleDateFormat("MM dd hh mm ss yyyy ").format(new Date());
        // Paren 1 is the digits (and maybe ','s) that matched; remove comma
        Matcher noComma = Pattern.compile(",").matcher(m.group(1));
        pw.println(date + noComma.replaceAll(""));
        pw.close();
    } else {
        System.err.println("WARNING: pattern `" + pattern + "' did not match in `" + url + isbn + "'!");
    }

    // Whether current data found or not, draw the graph, using
    // external plotting program against all historical data.
    // Could use gnuplot, R, any other math/graph program.
    // Better yet: use one of the Java plotting APIs.

    String gnuplot_cmd = "set term png\n" + "set output \"" + GRAPH_FILE + "\"\n" + "set xdata time\n"
            + "set ylabel \"Book sales rank\"\n" + "set bmargin 3\n" + "set logscale y\n"
            + "set yrange [1:60000] reverse\n" + "set timefmt \"%m %d %H %M %S %Y\"\n" + "plot \"" + DATA_FILE
            + "\" using 1:7 title \"" + title + "\" with lines\n";

    Process proc = Runtime.getRuntime().exec("/usr/local/bin/gnuplot");
    PrintWriter gp = new PrintWriter(proc.getOutputStream());
    gp.print(gnuplot_cmd);
    gp.close();
}

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

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

    PrintWriter logger = new PrintWriter(".//results//MostPopular");
    PropertiesConfiguration config = new PropertiesConfiguration();
    config.setFile(new File(".//conf//MostPopular.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...");
    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();

    TrainTestSplitter splitter = new TrainTestSplitter(dataset);
    splitter.splitFraction(config.getDouble("TRAIN_FRACTION"));
    ArrayList<NumericRating> trainRatings = splitter.getTrain();
    ArrayList<NumericRating> testRatings = splitter.getTest();

    HashMap<String, Integer> userIDIndexMapping = new HashMap<String, Integer>();
    HashMap<String, Integer> itemIDIndexMapping = new HashMap<String, Integer>();
    //create rating matrix
    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++) {
        //only consider 5-star rating in the test set
        //         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 most popular based recommendation model.");
    MostPopular algo = new MostPopular(trainRatingMatrix);
    algo.setLogger(logger);
    algo.build();
    algo.saveModel(".//localModels//" + config.getString("NAME"));
    logger.println("Save the model.");
    logger.flush();

    HashMap<Integer, ArrayList<ResultUnit>> results = new HashMap<Integer, ArrayList<ResultUnit>>();
    for (int i = 0; i < testRatingMatrix.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);
    }

    RankResultGenerator generator = new RankResultGenerator(results, algo.getTopN(), testRatingMatrix,
            trainRatingMatrix);
    System.out.println("Precision@N: " + generator.getPrecisionN());
    System.out.println("Recall@N: " + generator.getRecallN());
    System.out.println("MAP@N: " + generator.getMAPN());
    System.out.println("MRR@N: " + generator.getMRRN());
    System.out.println("NDCG@N: " + generator.getNDCGN());
    System.out.println("AUC@N: " + generator.getAUC());
    logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\n" + "Precision@N: "
            + generator.getPrecisionN() + "\n" + "Recall@N: " + generator.getRecallN() + "\n" + "MAP@N: "
            + generator.getMAPN() + "\n" + "MRR@N: " + generator.getMRRN() + "\n" + "NDCG@N: "
            + generator.getNDCGN() + "\n" + "AUC@N: " + generator.getAUC());
    logger.flush();
    logger.close();
}

From source file:ArrayFile.java

public static void main(String[] args) throws Exception {

    PrintWriter out = new PrintWriter(new FileWriter("arrayfile.txt"));

    CaBioApplicationService appService = (CaBioApplicationService) ApplicationServiceProvider
            .getApplicationServiceFromUrl("http://cabioapi-qa.nci.nih.gov/cabio42");

    ArrayAnnotationService am = new ArrayAnnotationServiceImpl(appService);

    String arrayName = "HG-U133_Plus_2";

    Collection<ArrayReporter> reps = am.getReportersForPlatform(arrayName);

    out.println("Name\tSymbol\tHUGO Symbol\tUnigene Id\t" + "Sequence Type\tSequence Source\tTarget Id\t"
            + "Target Description\tCytoband\tChromosome\tStart\tEnd");

    int c = 0;/*w w  w .  j a v  a  2s.  c om*/
    for (ArrayReporter rep : reps) {

        ExpressionArrayReporter er = (ExpressionArrayReporter) rep;

        out.println(resolve(er, "name") + "\t" + resolve(er, "gene.symbol") + "\t"
                + resolve(er, "gene.hugoSymbol") + "\t" + resolve(er, "gene.clusterId") + "\t"
                + resolve(er, "sequenceType") + "\t" + resolve(er, "sequenceSource") + "\t"
                + resolve(er, "targetId") + "\t" + resolve(er, "targetDescription") + "\t"
                + resolve(er, "cytogeneticLocationCollection[0].startCytoband.name") + "\t"
                + resolve(er, "physicalLocationCollection[0].chromosome.number") + "\t"
                + resolve(er, "physicalLocationCollection[0].chromosomalStartPosition") + "\t"
                + resolve(er, "physicalLocationCollection[0].chromosomalEndPosition"));

        if (c++ > 500)
            break;
    }

    out.close();
}

From source file:fr.tpt.s3.mcdag.bench.MainBench.java

public static void main(String[] args) throws IOException, InterruptedException {

    // Command line options
    Options options = new Options();

    Option input = new Option("i", "input", true, "MC-DAG XML models");
    input.setRequired(true);//from w  ww. j ava 2 s.  c om
    input.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(input);

    Option output = new Option("o", "output", true, "Folder where results have to be written.");
    output.setRequired(true);
    options.addOption(output);

    Option uUti = new Option("u", "utilization", true, "Utilization.");
    uUti.setRequired(true);
    options.addOption(uUti);

    Option output2 = new Option("ot", "output-total", true, "File where total results are being written");
    output2.setRequired(true);
    options.addOption(output2);

    Option oCores = new Option("c", "cores", true, "Cores given to the test");
    oCores.setRequired(true);
    options.addOption(oCores);

    Option oLvls = new Option("l", "levels", true, "Levels tested for the system");
    oLvls.setRequired(true);
    options.addOption(oLvls);

    Option jobs = new Option("j", "jobs", true, "Number of threads to be launched.");
    jobs.setRequired(false);
    options.addOption(jobs);

    Option debug = new Option("d", "debug", false, "Debug logs.");
    debug.setRequired(false);
    options.addOption(debug);

    /*
     * Parsing of the command line
     */
    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        formatter.printHelp("Benchmarks MultiDAG", options);
        System.exit(1);
        return;
    }

    String inputFilePath[] = cmd.getOptionValues("input");
    String outputFilePath = cmd.getOptionValue("output");
    String outputFilePathTotal = cmd.getOptionValue("output-total");
    double utilization = Double.parseDouble(cmd.getOptionValue("utilization"));
    boolean boolDebug = cmd.hasOption("debug");
    int nbLvls = Integer.parseInt(cmd.getOptionValue("levels"));
    int nbJobs = 1;
    int nbFiles = inputFilePath.length;

    if (cmd.hasOption("jobs"))
        nbJobs = Integer.parseInt(cmd.getOptionValue("jobs"));

    int nbCores = Integer.parseInt(cmd.getOptionValue("cores"));

    /*
     *  While files need to be allocated
     *  run the tests in the pool of threads
     */

    // For dual-criticality systems we call a specific thread
    if (nbLvls == 2) {

        System.out.println(">>>>>>>>>>>>>>>>>>>>> NB levels " + nbLvls);

        int i_files2 = 0;
        String outFile = outputFilePath.substring(0, outputFilePath.lastIndexOf('.'))
                .concat("-schedulability.csv");
        PrintWriter writer = new PrintWriter(outFile, "UTF-8");
        writer.println(
                "Thread; File; FSched (%); FPreempts; FAct; LSched (%); LPreempts; LAct; ESched (%); EPreempts; EAct; HSched(%); HPreempts; HAct; Utilization");
        writer.close();

        ExecutorService executor2 = Executors.newFixedThreadPool(nbJobs);
        while (i_files2 != nbFiles) {
            BenchThreadDualCriticality bt2 = new BenchThreadDualCriticality(inputFilePath[i_files2], outFile,
                    nbCores, boolDebug);

            executor2.execute(bt2);
            i_files2++;
        }

        executor2.shutdown();
        executor2.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

        int fedTotal = 0;
        int laxTotal = 0;
        int edfTotal = 0;
        int hybridTotal = 0;
        int fedPreempts = 0;
        int laxPreempts = 0;
        int edfPreempts = 0;
        int hybridPreempts = 0;
        int fedActiv = 0;
        int laxActiv = 0;
        int edfActiv = 0;
        int hybridActiv = 0;
        // Read lines in file and do average
        int i = 0;
        File f = new File(outFile);
        @SuppressWarnings("resource")
        Scanner line = new Scanner(f);
        while (line.hasNextLine()) {
            String s = line.nextLine();
            if (i > 0) { // To skip the first line
                try (Scanner inLine = new Scanner(s).useDelimiter("; ")) {
                    int j = 0;

                    while (inLine.hasNext()) {
                        String val = inLine.next();
                        if (j == 2) {
                            fedTotal += Integer.parseInt(val);
                        } else if (j == 3) {
                            fedPreempts += Integer.parseInt(val);
                        } else if (j == 4) {
                            fedActiv += Integer.parseInt(val);
                        } else if (j == 5) {
                            laxTotal += Integer.parseInt(val);
                        } else if (j == 6) {
                            laxPreempts += Integer.parseInt(val);
                        } else if (j == 7) {
                            laxActiv += Integer.parseInt(val);
                        } else if (j == 8) {
                            edfTotal += Integer.parseInt(val);
                        } else if (j == 9) {
                            edfPreempts += Integer.parseInt(val);
                        } else if (j == 10) {
                            edfActiv += Integer.parseInt(val);
                        } else if (j == 11) {
                            hybridTotal += Integer.parseInt(val);
                        } else if (j == 12) {
                            hybridPreempts += Integer.parseInt(val);
                        } else if (j == 13) {
                            hybridActiv += Integer.parseInt(val);
                        }
                        j++;
                    }
                }
            }
            i++;
        }

        // Write percentage
        double fedPerc = (double) fedTotal / nbFiles;
        double laxPerc = (double) laxTotal / nbFiles;
        double edfPerc = (double) edfTotal / nbFiles;
        double hybridPerc = (double) hybridTotal / nbFiles;

        double fedPercPreempts = (double) fedPreempts / fedActiv;
        double laxPercPreempts = (double) laxPreempts / laxActiv;
        double edfPercPreempts = (double) edfPreempts / edfActiv;
        double hybridPercPreempts = (double) hybridPreempts / hybridActiv;

        Writer wOutput = new BufferedWriter(new FileWriter(outputFilePathTotal, true));
        wOutput.write(Thread.currentThread().getName() + "; " + utilization + "; " + fedPerc + "; "
                + fedPreempts + "; " + fedActiv + "; " + fedPercPreempts + "; " + laxPerc + "; " + laxPreempts
                + "; " + laxActiv + "; " + laxPercPreempts + "; " + edfPerc + "; " + edfPreempts + "; "
                + edfActiv + "; " + edfPercPreempts + "; " + hybridPerc + "; " + hybridPreempts + "; "
                + hybridActiv + "; " + hybridPercPreempts + "\n");
        wOutput.close();

    } else if (nbLvls > 2) {
        int i_files2 = 0;
        String outFile = outputFilePath.substring(0, outputFilePath.lastIndexOf('.'))
                .concat("-schedulability.csv");
        PrintWriter writer = new PrintWriter(outFile, "UTF-8");
        writer.println(
                "Thread; File; LSched (%); LPreempts; LAct; ESched (%); EPreempts; EAct; HSched(%); HPreempts; HAct; Utilization");
        writer.close();

        ExecutorService executor2 = Executors.newFixedThreadPool(nbJobs);
        while (i_files2 != nbFiles) {
            BenchThreadNLevels bt2 = new BenchThreadNLevels(inputFilePath[i_files2], outFile, nbCores,
                    boolDebug);

            executor2.execute(bt2);
            i_files2++;
        }

        executor2.shutdown();
        executor2.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

        int laxTotal = 0;
        int edfTotal = 0;
        int hybridTotal = 0;
        int laxPreempts = 0;
        int edfPreempts = 0;
        int hybridPreempts = 0;
        int laxActiv = 0;
        int edfActiv = 0;
        int hybridActiv = 0;
        // Read lines in file and do average
        int i = 0;
        File f = new File(outFile);
        @SuppressWarnings("resource")
        Scanner line = new Scanner(f);
        while (line.hasNextLine()) {
            String s = line.nextLine();
            if (i > 0) { // To skip the first line
                try (Scanner inLine = new Scanner(s).useDelimiter("; ")) {
                    int j = 0;

                    while (inLine.hasNext()) {
                        String val = inLine.next();
                        if (j == 2) {
                            laxTotal += Integer.parseInt(val);
                        } else if (j == 3) {
                            laxPreempts += Integer.parseInt(val);
                        } else if (j == 4) {
                            laxActiv += Integer.parseInt(val);
                        } else if (j == 5) {
                            edfTotal += Integer.parseInt(val);
                        } else if (j == 6) {
                            edfPreempts += Integer.parseInt(val);
                        } else if (j == 7) {
                            edfActiv += Integer.parseInt(val);
                        } else if (j == 8) {
                            hybridTotal += Integer.parseInt(val);
                        } else if (j == 9) {
                            hybridPreempts += Integer.parseInt(val);
                        } else if (j == 10) {
                            hybridActiv += Integer.parseInt(val);
                        }
                        j++;
                    }
                }
            }
            i++;
        }

        // Write percentage
        double laxPerc = (double) laxTotal / nbFiles;
        double edfPerc = (double) edfTotal / nbFiles;
        double hybridPerc = (double) hybridTotal / nbFiles;

        double laxPercPreempts = (double) laxPreempts / laxActiv;
        double edfPercPreempts = (double) edfPreempts / edfActiv;
        double hybridPercPreempts = (double) hybridPreempts / hybridActiv;

        Writer wOutput = new BufferedWriter(new FileWriter(outputFilePathTotal, true));
        wOutput.write(Thread.currentThread().getName() + "; " + utilization + "; " + laxPerc + "; "
                + laxPreempts + "; " + laxActiv + "; " + laxPercPreempts + "; " + edfPerc + "; " + edfPreempts
                + "; " + edfActiv + "; " + edfPercPreempts + "; " + hybridPerc + "; " + hybridPreempts + "; "
                + hybridActiv + "; " + hybridPercPreempts + "\n");
        wOutput.close();

    } else {
        System.err.println("Wrong number of levels");
        System.exit(-1);
    }

    System.out.println("[BENCH Main] Done benchmarking U = " + utilization + " Levels " + nbLvls);
}

From source file:at.tuwien.ifs.somtoolbox.apps.helper.VectorSimilarityWriter.java

public static void main(String[] args) throws ClassNotFoundException, InstantiationException,
        IllegalAccessException, IOException, SOMToolboxException {
    JSAPResult config = OptionFactory.parseResults(args, OptionFactory.OPTIONS_INPUT_SIMILARITY_COMPUTER);
    String inputVectorDistanceMatrix = config.getString("inputVectorDistanceMatrix");
    String inputVectorFileName = config.getString("inputVectorFile");
    int numNeighbours = config.getInt("numberNeighbours");
    String outputFormat = config.getString("outputFormat");

    InputVectorDistanceMatrix matrix = null;
    InputData data = new SOMLibSparseInputData(inputVectorFileName);

    if (StringUtils.isNotBlank(inputVectorDistanceMatrix)) {
        matrix = InputVectorDistanceMatrix.initFromFile(inputVectorDistanceMatrix);
    } else {/*from   w w  w .  j  av  a  2 s .c  om*/
        String metricName = config.getString("metric");
        DistanceMetric metric = AbstractMetric.instantiate(metricName);
        matrix = new LeightWeightMemoryInputVectorDistanceMatrix(data, metric);
    }

    String outputFileName = config.getString("output");
    PrintWriter w = FileUtils.openFileForWriting("Similarity File", outputFileName);

    if (outputFormat.equals("SAT-DB")) {
        // find feature type
        String type = "";
        if (inputVectorFileName.endsWith(".rh") || inputVectorFileName.endsWith(".rp")
                || inputVectorFileName.endsWith(".ssd")) {
            type = "_" + inputVectorFileName.substring(inputVectorFileName.lastIndexOf(".") + 1);
        }
        w.println("INSERT INTO `sat_track_similarity_ifs" + type
                + "` (`TRACKID`, `SIMILARITYCOUNT`, `SIMILARITYIDS`) VALUES ");
    }

    int numVectors = matrix.numVectors();
    // numVectors = 10; // for testing
    StdErrProgressWriter progress = new StdErrProgressWriter(numVectors, "Writing similarities for vector ", 1);
    for (int i = 0; i < numVectors; i++) {
        int[] nearest = matrix.getNNearest(i, numNeighbours);
        if (outputFormat.equals("SAT-DB")) {
            w.print("  (" + i + " , NULL, '");
            for (int j = 0; j < nearest.length; j++) {
                String label = data.getLabel(nearest[j]);
                w.print(label.replace(".mp3", "")); // strip ending
                if (j + 1 < nearest.length) {
                    w.print(",");
                } else {
                    w.print("')");
                }
            }
            if (i + 1 < numVectors) {
                w.print(",");
            }
        } else {
            w.print(data.getLabel(i) + ",");
            for (int j = 0; j < nearest.length; j++) {
                w.print(data.getLabel(nearest[j]));
                if (j + 1 < nearest.length) {
                    w.print(",");
                }
            }
        }
        w.println();
        w.flush();
        progress.progress();
    }
    if (outputFormat.equals("SAT-DB")) {
        w.print(";");
    }
    w.flush();
    w.close();
}

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

/**
 * @param args//ww  w.j ava  2 s.c  om
 */
public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub

    PrintWriter logger = new PrintWriter(".//results//UserAverage");
    PropertiesConfiguration config = new PropertiesConfiguration();
    config.setFile(new File(".//conf//UserAverage.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...");
    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;
    int F = 5;
    logger.println(F + "- folder cross validation.");
    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++) {
        logger.println("Folder: " + folder);
        System.out.println("Folder: " + folder);
        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());
        }
        trainRatingMatrix.calculateGlobalAverage();
        RatingMatrix testRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(),
                dataset.getItemIDs().size());
        for (int i = 0; i < testRatings.size(); i++) {
            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 recommendation model based on user average method.");
        UserAverage algo = new UserAverage(trainRatingMatrix);
        algo.setLogger(logger);
        algo.build();
        algo.saveModel(".//localModels//" + config.getString("NAME"));
        logger.println("Save the model.");
        System.out.println(trainRatings.size() + " vs. " + testRatings.size());

        double RMSE = 0;
        double MAE = 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()));
            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);

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

    System.out.println("MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F);
    logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Final results: MAE: "
            + totalMAE / F + " RMSE: " + totalRMSE / F);
    logger.flush();
    logger.close();
    //MAE: 0.8353035962363073 RMSE: 1.0422971886952053 (MovieLens 100k)
}