Example usage for java.io PrintStream PrintStream

List of usage examples for java.io PrintStream PrintStream

Introduction

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

Prototype

public PrintStream(File file) throws FileNotFoundException 

Source Link

Document

Creates a new print stream, without automatic line flushing, with the specified file.

Usage

From source file:io.anserini.search.SearchWebCollection.java

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

    SearchArgs searchArgs = new SearchArgs();
    CmdLineParser parser = new CmdLineParser(searchArgs, ParserProperties.defaults().withUsageWidth(90));

    try {//from   ww  w  . j av a2  s .c om
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        parser.printUsage(System.err);
        System.err.println("Example: SearchWebCollection" + parser.printExample(OptionHandlerFilter.REQUIRED));
        return;
    }

    LOG.info("Reading index at " + searchArgs.index);
    Directory dir;
    if (searchArgs.inmem) {
        LOG.info("Using MMapDirectory with preload");
        dir = new MMapDirectory(Paths.get(searchArgs.index));
        ((MMapDirectory) dir).setPreload(true);
    } else {
        LOG.info("Using default FSDirectory");
        dir = FSDirectory.open(Paths.get(searchArgs.index));
    }

    Similarity similarity = null;

    if (searchArgs.ql) {
        LOG.info("Using QL scoring model");
        similarity = new LMDirichletSimilarity(searchArgs.mu);
    } else if (searchArgs.bm25) {
        LOG.info("Using BM25 scoring model");
        similarity = new BM25Similarity(searchArgs.k1, searchArgs.b);
    } else {
        LOG.error("Error: Must specify scoring model!");
        System.exit(-1);
    }

    RerankerCascade cascade = new RerankerCascade();
    boolean useQueryParser = false;
    if (searchArgs.rm3) {
        cascade.add(new Rm3Reranker(new EnglishAnalyzer(), FIELD_BODY,
                "src/main/resources/io/anserini/rerank/rm3/rm3-stoplist.gov2.txt"));
        useQueryParser = true;
    } else {
        cascade.add(new IdentityReranker());
    }
    FeatureExtractors extractors = null;
    if (searchArgs.extractors != null) {
        extractors = FeatureExtractors.loadExtractor(searchArgs.extractors);
    }

    if (searchArgs.dumpFeatures) {
        PrintStream out = new PrintStream(searchArgs.featureFile);
        Qrels qrels = new Qrels(searchArgs.qrels);
        cascade.add(new WebCollectionLtrDataGenerator(out, qrels, extractors));
    }

    Path topicsFile = Paths.get(searchArgs.topics);

    if (!Files.exists(topicsFile) || !Files.isRegularFile(topicsFile) || !Files.isReadable(topicsFile)) {
        throw new IllegalArgumentException(
                "Topics file : " + topicsFile + " does not exist or is not a (readable) file.");
    }

    TopicReader tr = (TopicReader) Class
            .forName("io.anserini.search.query." + searchArgs.topicReader + "TopicReader")
            .getConstructor(Path.class).newInstance(topicsFile);
    SortedMap<Integer, String> topics = tr.read();

    final long start = System.nanoTime();
    SearchWebCollection searcher = new SearchWebCollection(searchArgs.index);
    searcher.search(topics, searchArgs.output, similarity, searchArgs.hits, cascade, useQueryParser,
            searchArgs.keepstop);
    searcher.close();
    final long durationMillis = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS);
    LOG.info("Total " + topics.size() + " topics searched in "
            + DurationFormatUtils.formatDuration(durationMillis, "HH:mm:ss"));
}

From source file:edu.msu.cme.rdp.classifier.train.validation.distance.PairwiseSeqDistance.java

/**
* This program does the pairwise alignment between each pair of sequences, 
* reports a summary of the average distances and the stdev at each rank.
* @param args/*from   www .ja  v a2 s .  c o  m*/
* @throws Exception 
*/
public static void main(String[] args) throws Exception {

    String trainseqFile = null;
    String taxFile = null;
    PrintStream outStream = null;
    AlignmentMode mode = AlignmentMode.overlap;
    boolean show_alignment = false;

    try {
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption("show_alignment")) {
            show_alignment = true;
        }
        if (line.hasOption("alignment-mode")) {
            String m = line.getOptionValue("alignment-mode").toLowerCase();
            mode = AlignmentMode.valueOf(m);

        }

        if (args.length != 3) {
            throw new Exception("wrong arguments");
        }
        args = line.getArgs();
        trainseqFile = args[0];
        taxFile = args[1];
        outStream = new PrintStream(new File(args[2]));
    } catch (Exception e) {
        System.err.println("Command Error: " + e.getMessage());
        new HelpFormatter().printHelp(80, " [options] trainseqFile taxonFile outFile", "", options, "");
        return;
    }

    PairwiseSeqDistance theObj = new PairwiseSeqDistance(trainseqFile, taxFile, mode, show_alignment);

    theObj.printSummary(outStream);
}

From source file:edu.oregonstate.eecs.mcplan.ml.LinearDiscriminantAnalysis.java

public static void main(final String[] args) throws FileNotFoundException {
    final File root = new File("test/LinearDiscriminantAnalysis");
    root.mkdirs();/*from  ww w.  j  a  v  a 2 s . c om*/
    final int seed = 42;
    final int N = 30;
    final double shrinkage = 1e-6;

    final RandomGenerator rng = new MersenneTwister(seed);
    final Pair<ArrayList<double[]>, int[]> dataset = Datasets.twoVerticalGaussian2D(rng, N);
    final ArrayList<double[]> data = dataset.first;
    final int[] label = dataset.second;
    final int Nlabels = 2;
    final int[] shuffle_idx = Fn.linspace(0, Nlabels * N);
    Fn.shuffle(rng, shuffle_idx);
    final ArrayList<double[]> shuffled = new ArrayList<double[]>();
    final int[] shuffled_label = new int[label.length];
    for (int i = 0; i < data.size(); ++i) {
        shuffled.add(Fn.copy(data.get(shuffle_idx[i])));
        shuffled_label[i] = label[shuffle_idx[i]];
    }

    final Csv.Writer data_writer = new Csv.Writer(new PrintStream(new File(root, "data.csv")));
    for (final double[] v : data) {
        for (int i = 0; i < v.length; ++i) {
            data_writer.cell(v[i]);
        }
        data_writer.newline();
    }
    data_writer.close();

    System.out.println("[Training]");
    //      final KernelPrincipalComponentsAnalysis<RealVector> kpca
    //         = new KernelPrincipalComponentsAnalysis<RealVector>( shuffled, new RadialBasisFunctionKernel( 0.5 ), 1e-6 );
    final LinearDiscriminantAnalysis lda = new LinearDiscriminantAnalysis(shuffled, shuffled_label, Nlabels,
            shrinkage);
    System.out.println("[Finished]");
    for (final RealVector ev : lda.eigenvectors) {
        System.out.println(ev);
    }

    System.out.println("Transformed data:");
    final LinearDiscriminantAnalysis.Transformer transformer = lda.makeTransformer();
    final Csv.Writer transformed_writer = new Csv.Writer(new PrintStream(new File(root, "transformed.csv")));
    for (final double[] u : data) {
        final RealVector uvec = new ArrayRealVector(u);
        System.out.println(uvec);
        final RealVector v = transformer.transform(uvec);
        System.out.println("-> " + v);
        for (int i = 0; i < v.getDimension(); ++i) {
            transformed_writer.cell(v.getEntry(i));
        }
        transformed_writer.newline();
    }
    transformed_writer.close();
}

From source file:com.act.lcms.AnimateNetCDFAroundMass.java

public static void main(String[] args) throws Exception {
    if (args.length < 7 || !areNCFiles(Arrays.copyOfRange(args, 5, args.length))) {
        throw new RuntimeException(
                "Needs: \n" + "(1) mass value, e.g., 132.0772 \n" + "(2) time value, e.g., 39.2, (seconds), \n"
                        + "(3) minimum Mz Precision, 0.04 \n" + "(4) max z axis, e.g., 20000 \n"
                        + "(5) prefix for .data and rendered .pdf \n" + "(6..) 2 or more NetCDF .nc files");
    }/*from w w w  . ja va  2 s .  c o  m*/

    Double mz = Double.parseDouble(args[0]);
    Double time = Double.parseDouble(args[1]);
    Double minMzPrecision = Double.parseDouble(args[2]);
    Double maxZAxis = Double.parseDouble(args[3]);
    String outPrefix = args[4];

    // the mz values go from 50-950, we start with a big window and exponentially narrow down
    double mzWin = 100;
    // time values go from 0-450, we start with a big window and exponentially narrow down
    double timeWin = 50;

    // the factor by which to zoom in every step (has to be >1, a value of 2 is good)
    double factor = 1.2;

    // the animation frame count
    int frame = 1;

    AnimateNetCDFAroundMass c = new AnimateNetCDFAroundMass();
    String[] netCDFFnames = Arrays.copyOfRange(args, 5, args.length);
    List<List<XYZ>> spectra = c.getSpectra(netCDFFnames, time, timeWin, mz, mzWin);

    for (List<XYZ> s : spectra) {
        System.out.format("%d xyz datapoints in (initial narrowed) spectra\n", s.size());
    }

    String[] labels = new String[netCDFFnames.length];
    for (int i = 0; i < labels.length; i++)
        labels[i] = "Dataset: " + i;
    // you could set labels to netCDFFnames to get precise labels on the graphs

    Gnuplotter plotter = new Gnuplotter();
    String fmt = "png";

    List<String> outImgFiles = new ArrayList<>(), outDataFiles = new ArrayList<>();
    while (mzWin > minMzPrecision) {

        // exponentially narrow windows down
        mzWin /= factor;
        timeWin /= factor;

        List<List<XYZ>> windowedSpectra = c.getSpectraInWindowAll(spectra, time, timeWin, mz, mzWin);

        String frameid = String.format("%03d", frame);
        String outPDF = outPrefix + frameid + "." + fmt;
        String outDATA = outPrefix + frameid + ".data";
        outImgFiles.add(outPDF);
        outDataFiles.add(outDATA);
        frame++;

        // Write data output to outfile
        PrintStream out = new PrintStream(new FileOutputStream(outDATA));

        // print out the spectra to outDATA
        for (List<XYZ> windowOfSpectra : windowedSpectra) {
            for (XYZ xyz : windowOfSpectra) {
                out.format("%.4f\t%.4f\t%.4f\n", xyz.time, xyz.mz, xyz.intensity);
                out.flush();
            }
            // delimit this dataset from the rest
            out.print("\n\n");
        }

        // close the .data
        out.close();

        // render outDATA to outPDF using gnuplot
        plotter.plotMulti3D(outDATA, outPDF, fmt, labels, maxZAxis);
    }

    String outImgs = outPrefix + "*." + fmt;
    plotter.makeAnimatedGIF(outImgs, outPrefix + ".gif");
    // all the frames are now in the animated gif, remove the intermediate files
    for (String f : outDataFiles)
        new File(f).delete();
    for (String f : outImgFiles)
        new File(f).delete();
}

From source file:master.utilities.PopulationFunctionFromJSON.java

/**
 * Main method for debugging./*from   ww w. j  av  a 2s . c  o  m*/
 * 
 * @param args 
 * @throws java.lang.Exception 
 */
public static void main(String[] args) throws Exception {

    PopulationFunctionFromJSON instance = new PopulationFunctionFromJSON();
    instance.initByName("fileName", "/home/tim/work/articles/volzpaper/SimulatedData/SIR_1000sims.json",
            "popSizeExpression", "(I-1)/(2*0.00075*S)", "origin", new RealParameter("66.5499977474"), "trajNum",
            1, "popSizeStart", 0.0, "popSizeEnd", 0.0);

    // Write pop sizes and intensities out
    PrintStream outf = new PrintStream("test.txt");
    outf.println("t N intensity invIntensity");
    double dt = 66.5499977474 / 1000;
    for (int i = 0; i <= 1000; i++) {
        double t = dt * i;
        double N = instance.getPopSize(t);
        double intensity = instance.getIntensity(t);
        double invIntensity = instance.getInverseIntensity(intensity);

        outf.format("%g %g %g %g\n", t, N, intensity, invIntensity);
    }
    outf.println();

}

From source file:AwsConsoleApp.java

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

    System.out.println("===========================================");
    System.out.println("Welcome to the AWS VPN connection creator");
    System.out.println("===========================================");

    init();//from w  ww .  j  a v  a  2  s .  c  o  m
    List<String> CIDRblocks = new ArrayList<String>();
    String vpnType = null;
    String vpnGatewayId = null;
    String customerGatewayId = null;
    String customerGatewayInfoPath = null;
    String routes = null;

    options.addOption("h", "help", false, "show help.");
    options.addOption("vt", "vpntype", true, "Set vpn tunnel type e.g. (ipec.1)");
    options.addOption("vgw", "vpnGatewayId", true, "Set AWS VPN Gateway ID e.g. (vgw-eca54d85)");
    options.addOption("cgw", "customerGatewayId", true, "Set AWS Customer Gateway ID e.g. (cgw-c16e87a8)");
    options.addOption("r", "staticroutes", true, "Set static routes e.g. cutomer subnet 10.77.77.0/24");
    options.addOption("vi", "vpninfo", true, "path to vpn info file c:\\temp\\customerGatewayInfo.xml");

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    // Parse command line options
    try {
        cmd = parser.parse(options, args);

        if (cmd.hasOption("h"))
            help();

        if (cmd.hasOption("vt")) {
            log.log(Level.INFO, "Using cli argument -vt=" + cmd.getOptionValue("vt"));

            vpnType = cmd.getOptionValue("vt");

            // Whatever you want to do with the setting goes here
        } else {
            log.log(Level.SEVERE, "Missing vt option");
            help();
        }

        if (cmd.hasOption("vgw")) {
            log.log(Level.INFO, "Using cli argument -vgw=" + cmd.getOptionValue("vgw"));
            vpnGatewayId = cmd.getOptionValue("vgw");
        } else {
            log.log(Level.SEVERE, "Missing vgw option");
            help();
        }

        if (cmd.hasOption("cgw")) {
            log.log(Level.INFO, "Using cli argument -cgw=" + cmd.getOptionValue("cgw"));
            customerGatewayId = cmd.getOptionValue("cgw");

        } else {
            log.log(Level.SEVERE, "Missing cgw option");
            help();
        }

        if (cmd.hasOption("r")) {
            log.log(Level.INFO, "Using cli argument -r=" + cmd.getOptionValue("r"));
            routes = cmd.getOptionValue("r");

            String[] routeItems = routes.split(",");
            CIDRblocks = Arrays.asList(routeItems);

        } else {
            log.log(Level.SEVERE, "Missing r option");
            help();
        }

        if (cmd.hasOption("vi")) {
            log.log(Level.INFO, "Using cli argument -vi=" + cmd.getOptionValue("vi"));
            customerGatewayInfoPath = cmd.getOptionValue("vi");

        } else {
            log.log(Level.SEVERE, "Missing vi option");
            help();
        }

    } catch (ParseException e) {
        log.log(Level.SEVERE, "Failed to parse comand line properties", e);
        help();
    }

    /*
     * Amazon VPC
     * Create and delete VPN tunnel to customer VPN hardware
     */
    try {

        //String vpnType = "ipsec.1";
        //String vpnGatewayId = "vgw-eca54d85";
        //String customerGatewayId = "cgw-c16e87a8";
        //List<String> CIDRblocks = new ArrayList<String>();
        //CIDRblocks.add("10.77.77.0/24");
        //CIDRblocks.add("172.16.1.0/24");
        //CIDRblocks.add("172.18.1.0/24");
        //CIDRblocks.add("10.66.66.0/24");
        //CIDRblocks.add("10.8.1.0/24");

        //String customerGatewayInfoPath = "c:\\temp\\customerGatewayInfo.xml";

        Boolean staticRoutesOnly = true;

        List<String> connectionIds = new ArrayList<String>();
        List<String> connectionIdList = new ArrayList<String>();

        connectionIdList = vpnExists(connectionIds);

        if (connectionIdList.size() == 0) {
            CreateVpnConnectionRequest vpnReq = new CreateVpnConnectionRequest(vpnType, customerGatewayId,
                    vpnGatewayId);
            CreateVpnConnectionResult vpnRes = new CreateVpnConnectionResult();

            VpnConnectionOptionsSpecification vpnspec = new VpnConnectionOptionsSpecification();
            vpnspec.setStaticRoutesOnly(staticRoutesOnly);
            vpnReq.setOptions(vpnspec);

            System.out.println("Creating VPN connection");
            vpnRes = ec2.createVpnConnection(vpnReq);
            String vpnConnId = vpnRes.getVpnConnection().getVpnConnectionId();
            String customerGatewayInfo = vpnRes.getVpnConnection().getCustomerGatewayConfiguration();

            //System.out.println("Customer Gateway Info:" + customerGatewayInfo);

            // Write Customer Gateway Info to file
            System.out.println("Writing Customer Gateway Info to file:" + customerGatewayInfoPath);
            try (PrintStream out = new PrintStream(new FileOutputStream(customerGatewayInfoPath))) {
                out.print(customerGatewayInfo);
            }

            System.out.println("Creating VPN routes");
            for (String destCIDR : CIDRblocks) {
                CreateVpnConnectionRouteRequest routeReq = new CreateVpnConnectionRouteRequest();
                CreateVpnConnectionRouteResult routeRes = new CreateVpnConnectionRouteResult();

                routeReq.setDestinationCidrBlock(destCIDR);
                routeReq.setVpnConnectionId(vpnConnId);

                routeRes = ec2.createVpnConnectionRoute(routeReq);
            }

            // Parse XML file
            File file = new File(customerGatewayInfoPath);
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse(customerGatewayInfoPath);

            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            XPathExpression exprGetipAddress = xpath
                    .compile("/vpn_connection/ipsec_tunnel/vpn_gateway/tunnel_outside_address/ip_address");
            NodeList vpnGateway = (NodeList) exprGetipAddress.evaluate(document, XPathConstants.NODESET);
            if (vpnGateway != null) {
                for (int i = 0; i < vpnGateway.getLength(); i++) {
                    String vpnGatewayIP = vpnGateway.item(i).getTextContent();
                    System.out
                            .println("AWS vpnGatewayIP for tunnel " + Integer.toString(i) + " " + vpnGatewayIP);
                }
            }

            System.out.println("==============================================");

            XPathExpression exprGetKey = xpath.compile("/vpn_connection/ipsec_tunnel/ike/pre_shared_key");
            NodeList presharedKeyList = (NodeList) exprGetKey.evaluate(document, XPathConstants.NODESET);
            if (presharedKeyList != null) {
                for (int i = 0; i < presharedKeyList.getLength(); i++) {
                    String pre_shared_key = presharedKeyList.item(i).getTextContent();
                    System.out.println(
                            "AWS pre_shared_key for tunnel " + Integer.toString(i) + " " + pre_shared_key);
                }
            }

            System.out.println("Creating VPN creation completed!");

        } else {
            boolean yn;
            Scanner scan = new Scanner(System.in);
            System.out.println("Enter yes or no to delete VPN connection: ");
            String input = scan.next();
            String answer = input.trim().toLowerCase();
            while (true) {
                if (answer.equals("yes")) {
                    yn = true;
                    break;
                } else if (answer.equals("no")) {
                    yn = false;
                    System.exit(0);
                } else {
                    System.out.println("Sorry, I didn't catch that. Please answer yes/no");
                }
            }

            // Delete all existing VPN connections
            System.out.println("Deleting AWS VPN connection(s)");

            for (String vpnConID : connectionIdList) {
                DeleteVpnConnectionResult delVPNres = new DeleteVpnConnectionResult();
                DeleteVpnConnectionRequest delVPNreq = new DeleteVpnConnectionRequest();
                delVPNreq.setVpnConnectionId(vpnConID);

                delVPNres = ec2.deleteVpnConnection(delVPNreq);
                System.out.println("Successfully deleted AWS VPN conntion: " + vpnConID);

            }

        }

    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
    }

}

From source file:Main.java

/**
 * Creates a no-op print stream./*from  w  w  w.  j a v a2s.  c o  m*/
 */
public static PrintStream nopPrintStream() {
    return new PrintStream(nopOuputStream());
}

From source file:Main.java

public static void append(File aFile, String content) {
    try {//from   w  ww .j  a  v  a  2  s. c o m
        PrintStream p = new PrintStream(new BufferedOutputStream(new FileOutputStream(aFile, true)));
        p.println(content);
        p.close();

    } catch (Exception e) {
        e.printStackTrace();
        System.err.println(aFile);
    }
}

From source file:Main.java

public static void resultToFile(String path) throws FileNotFoundException {
    File file = new File(path);
    PrintStream printStream = new PrintStream(new FileOutputStream(file));
    PrintStream out = printStream;
    System.setOut(out);/*from w  ww  .ja v  a2 s .  c o m*/
}

From source file:Main.java

private static String getStringFromException(Throwable e) {
    String result = "";
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(bos);
    e.printStackTrace(ps);//w ww. j a  v  a 2  s  .  c  o m
    try {
        result = bos.toString("utf-8");
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    return result;
}