Example usage for java.io PrintWriter print

List of usage examples for java.io PrintWriter print

Introduction

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

Prototype

public void print(Object obj) 

Source Link

Document

Prints an object.

Usage

From source file:eval.dataset.ParseWikiLog.java

public static void main(String[] ss) throws FileNotFoundException, ParserConfigurationException, IOException {
    FileInputStream fin = new FileInputStream("data/enwiki-20151201-pages-logging.xml.gz");
    GzipCompressorInputStream gzIn = new GzipCompressorInputStream(fin);
    InputStreamReader reader = new InputStreamReader(gzIn);
    BufferedReader br = new BufferedReader(reader);
    PrintWriter pw = new PrintWriter(new FileWriter("data/user_page.txt"));
    pw.println(//from w ww  . j  a  v  a 2  s  .com
            "#list of user names and pages that they have edited, deleted or created. These info are mined from logitems of enwiki-20150304-pages-logging.xml.gz");
    TreeMap<String, Set<String>> userPageList = new TreeMap();
    TreeSet<String> pageList = new TreeSet();
    int counterEntry = 0;
    String currentUser = null;
    String currentPage = null;
    try {
        for (String line = br.readLine(); line != null; line = br.readLine()) {

            if (line.trim().equals("</logitem>")) {
                counterEntry++;
                if (currentUser != null && currentPage != null) {
                    updateMap(userPageList, currentUser, currentPage);
                    pw.println(currentUser + "\t" + currentPage);
                    pageList.add(currentPage);
                }
                currentUser = null;
                currentPage = null;
            } else if (line.trim().startsWith("<username>")) {
                currentUser = line.trim().split(">")[1].split("<")[0].replace(" ", "_");

            } else if (line.trim().startsWith("<logtitle>")) {
                String content = line.trim().split(">")[1].split("<")[0];
                if (content.split(":").length == 1) {
                    currentPage = content.replace(" ", "_");
                }
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(ParseWikiLog.class.getName()).log(Level.SEVERE, null, ex);
    }
    pw.println("#analysed " + counterEntry + " entries of wikipesia log file");
    pw.println("#gathered a list of unique user of size " + userPageList.size());
    pw.println("#gathered a list of pages of size " + pageList.size());
    pw.close();
    gzIn.close();

    PrintWriter pwUser = new PrintWriter(new FileWriter("data/user_list_page_edited.txt"));
    pwUser.println(
            "#list of unique users and pages that they have edited, extracted from logitems of enwiki-20150304-pages-logging.xml.gz");
    for (String user : userPageList.keySet()) {
        pwUser.print(user);
        Set<String> getList = userPageList.get(user);
        for (String page : getList) {
            pwUser.print("\t" + page);
        }
        pwUser.println();
    }
    pwUser.close();

    PrintWriter pwPage = new PrintWriter(new FileWriter("data/all_pages.txt"));
    pwPage.println("#list of the unique pages that are extracted from enwiki-20150304-pages-logging.xml.gz");
    for (String page : pageList) {
        pwPage.println(page);
    }
    pwPage.close();
    System.out.println("#analysed " + counterEntry + " entries of wikipesia log file");
    System.out.println("#gathered a list of unique user of size " + userPageList.size());
    System.out.println("#gathered a list of pages of size " + pageList.size());
}

From source file:ModifyModelSample.java

public static void main(String args[]) {
    JFrame frame = new JFrame("Modifying Model");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();

    // Fill model
    final DefaultListModel model = new DefaultListModel();
    for (int i = 0, n = labels.length; i < n; i++) {
        model.addElement(labels[i]);/* w  w  w  . j  a  va 2 s .co m*/
    }
    JList jlist = new JList(model);
    JScrollPane scrollPane1 = new JScrollPane(jlist);
    contentPane.add(scrollPane1, BorderLayout.WEST);

    final JTextArea textArea = new JTextArea();
    textArea.setEditable(false);
    JScrollPane scrollPane2 = new JScrollPane(textArea);
    contentPane.add(scrollPane2, BorderLayout.CENTER);

    ListDataListener listDataListener = new ListDataListener() {
        public void contentsChanged(ListDataEvent listDataEvent) {
            appendEvent(listDataEvent);
        }

        public void intervalAdded(ListDataEvent listDataEvent) {
            appendEvent(listDataEvent);
        }

        public void intervalRemoved(ListDataEvent listDataEvent) {
            appendEvent(listDataEvent);
        }

        private void appendEvent(ListDataEvent listDataEvent) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            switch (listDataEvent.getType()) {
            case ListDataEvent.CONTENTS_CHANGED:
                pw.print("Type: Contents Changed");
                break;
            case ListDataEvent.INTERVAL_ADDED:
                pw.print("Type: Interval Added");
                break;
            case ListDataEvent.INTERVAL_REMOVED:
                pw.print("Type: Interval Removed");
                break;
            }
            pw.print(", Index0: " + listDataEvent.getIndex0());
            pw.print(", Index1: " + listDataEvent.getIndex1());
            DefaultListModel theModel = (DefaultListModel) listDataEvent.getSource();
            Enumeration elements = theModel.elements();
            pw.print(", Elements: ");
            while (elements.hasMoreElements()) {
                pw.print(elements.nextElement());
                pw.print(",");
            }
            pw.println();
            textArea.append(sw.toString());
        }
    };

    model.addListDataListener(listDataListener);

    // Setup buttons
    JPanel jp = new JPanel(new GridLayout(2, 1));
    JPanel jp1 = new JPanel(new FlowLayout(FlowLayout.CENTER, 1, 1));
    JPanel jp2 = new JPanel(new FlowLayout(FlowLayout.CENTER, 1, 1));
    jp.add(jp1);
    jp.add(jp2);
    JButton jb = new JButton("add F");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.add(0, "First");
        }
    });
    jb = new JButton("addElement L");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.addElement("Last");
        }
    });
    jb = new JButton("insertElementAt M");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            model.insertElementAt("Middle", size / 2);
        }
    });
    jb = new JButton("set F");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.set(0, "New First");
        }
    });
    jb = new JButton("setElementAt L");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.setElementAt("New Last", size - 1);
        }
    });
    jb = new JButton("load 10");
    jp1.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            for (int i = 0, n = labels.length; i < n; i++) {
                model.addElement(labels[i]);
            }
        }
    });
    jb = new JButton("clear");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.clear();
        }
    });
    jb = new JButton("remove F");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.remove(0);
        }
    });
    jb = new JButton("removeAllElements");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.removeAllElements();
        }
    });
    jb = new JButton("removeElement 'Last'");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.removeElement("Last");
        }
    });
    jb = new JButton("removeElementAt M");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.removeElementAt(size / 2);
        }
    });
    jb = new JButton("removeRange FM");
    jp2.add(jb);
    jb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            int size = model.getSize();
            if (size != 0)
                model.removeRange(0, size / 2);
        }
    });
    contentPane.add(jp, BorderLayout.SOUTH);
    frame.setSize(640, 300);
    frame.setVisible(true);
}

From source file:gr.demokritos.iit.demos.Demo.java

public static void main(String[] args) {
    try {//from   w w  w  . j a  va  2 s.  c  o  m
        Options options = new Options();
        options.addOption("h", HELP, false, "show help.");
        options.addOption("i", INPUT, true,
                "The file containing JSON " + " representations of tweets or SAG posts - 1 per line"
                        + " default file looked for is " + DEFAULT_INFILE);
        options.addOption("o", OUTPUT, true,
                "Where to write the output " + " default file looked for is " + DEFAULT_OUTFILE);
        options.addOption("p", PROCESS, true, "Type of processing to do "
                + " ner for Named Entity Recognition re for Relation Extraction" + " default is NER");
        options.addOption("s", SAG, false,
                "Whether to process as SAG posts" + " default is off - if passed means process as SAG posts");

        CommandLineParser parser = new BasicParser();
        CommandLine cmd = parser.parse(options, args);
        // DEFAULTS
        String filename = DEFAULT_INFILE;
        String outfilename = DEFAULT_OUTFILE;
        String process = NER;
        boolean isSAG = false;

        if (cmd.hasOption(HELP)) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("NER + RE extraction module", options);
            System.exit(0);
        }
        if (cmd.hasOption(INPUT)) {
            filename = cmd.getOptionValue(INPUT);
        }
        if (cmd.hasOption(OUTPUT)) {
            outfilename = cmd.getOptionValue(OUTPUT);
        }
        if (cmd.hasOption(SAG)) {
            isSAG = true;
        }
        if (cmd.hasOption(PROCESS)) {
            process = cmd.getOptionValue(PROCESS);
        }
        System.out.println();
        System.out.println("Reading from file: " + filename);
        System.out.println("Process type: " + process);
        System.out.println("Processing SAG: " + isSAG);
        System.out.println("Writing to file: " + outfilename);
        System.out.println();

        List<String> jsoni = new ArrayList();
        Scanner in = new Scanner(new FileReader(filename));
        while (in.hasNextLine()) {
            String json = in.nextLine();
            jsoni.add(json);
        }
        PrintWriter writer = new PrintWriter(outfilename, "UTF-8");
        System.out.println("Read " + jsoni.size() + " lines from " + filename);
        if (process.equalsIgnoreCase(RE)) {
            System.out.println("Running Relation Extraction");
            System.out.println();
            String json = API.RE(jsoni, isSAG);
            System.out.println(json);
            writer.print(json);
        } else {
            System.out.println("Running Named Entity Recognition");
            System.out.println();
            jsoni = API.NER(jsoni, isSAG);
            /*
            for(String json: jsoni){
               NamedEntityList nel = NamedEntityList.fromJSON(json);
               nel.prettyPrint();
            }
            */
            for (String json : jsoni) {
                System.out.println(json);
                writer.print(json);
            }
        }
        writer.close();
    } catch (ParseException | UnsupportedEncodingException | FileNotFoundException ex) {
        Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:medcheck.Medcheck.java

/**
 * @param args the command line arguments
 *//*from  ww w  . j a v  a2  s  .  c  om*/
public static void main(String[] args) {
    String jsonFileLocation = "meddata.json";
    File jsonTxt = new File(jsonFileLocation);

    String xmlFileLocation = "XML Files";
    File xmlDirectory = new File(xmlFileLocation);

    String jsonString = getJSONString(jsonTxt);

    PrintWriter csvWriter;
    try {
        csvWriter = new PrintWriter("meddata.csv", "UTF-8");
    } catch (Exception e) {
        System.out.println("ERROR: " + e.getMessage());
        e.printStackTrace();
        return;
    }

    Drug[] csvArray = convertToDrugArrayFromJSON(jsonString);
    Drug[] xmlArray = convertToDrugArrayFromXML(xmlDirectory);
    String csvString = convertToCsvString(csvArray, xmlArray);
    csvWriter.print(csvString);
    csvWriter.close();
}

From source file:com.aestel.chemistry.openEye.fp.DistMatrix.java

public static void main(String... args) throws IOException {
    long start = System.currentTimeMillis();

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("i", true, "input file [.tsv from FingerPrinter]");
    opt.setRequired(true);//from  ww  w .  j  a va  2  s. com
    options.addOption(opt);

    opt = new Option("o", true, "outpur file [.tsv ");
    opt.setRequired(true);
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    if (args.length != 0)
        exitWithHelp(options);

    String file = cmd.getOptionValue("i");
    BufferedReader in = new BufferedReader(new FileReader(file));

    file = cmd.getOptionValue("o");
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));

    ArrayList<Fingerprint> fps = new ArrayList<Fingerprint>();
    ArrayList<String> ids = new ArrayList<String>();
    String line;
    while ((line = in.readLine()) != null) {
        String[] parts = line.split("\t");
        if (parts.length == 3) {
            ids.add(parts[0]);
            fps.add(new ByteFingerprint(parts[2]));
        }
    }
    in.close();

    out.print("ID");
    for (int i = 0; i < ids.size(); i++) {
        out.print('\t');
        out.print(ids.get(i));
    }
    out.println();

    for (int i = 0; i < ids.size(); i++) {
        out.print(ids.get(i));
        Fingerprint fp1 = fps.get(i);

        for (int j = 0; j <= i; j++) {
            out.printf("\t%.4g", fp1.tanimoto(fps.get(j)));
        }
        out.println();
    }
    out.close();

    System.err.printf("Done %d fingerprints in %.2gsec\n", fps.size(),
            (System.currentTimeMillis() - start) / 1000D);
}

From source file:client.QueryLastFm.java

License:asdf

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

    // isAlreadyInserted("asdfs","jas,jnjkah");

    // FileWriter fw = new FileWriter(".\\tracks.csv");
    OutputStream track_os = new FileOutputStream(".\\tracks.csv");
    PrintWriter out = new PrintWriter(new OutputStreamWriter(track_os, "UTF-8"));

    OutputStream track_id_os = new FileOutputStream(".\\track_id_sim_track_id.csv");
    PrintWriter track_id_out = new PrintWriter(new OutputStreamWriter(track_id_os, "UTF-8"));

    track_id_out.print("");

    ByteArrayInputStream input;/*from w ww  . jav  a2s  .  c  o m*/
    Document doc = null;
    CloseableHttpClient httpclient = HttpClients.createDefault();

    String trackName = "";
    String artistName = "";
    String sourceMbid = "";
    out.print("ID");// first row first column
    out.print(",");
    out.print("TrackName");// first row second column
    out.print(",");
    out.println("Artist");// first row third column

    track_id_out.print("source");// first row second column
    track_id_out.print(",");
    track_id_out.println("target");// first row third column
    // track_id_out.print(",");
    // track_id_out.println("type");// first row third column

    // out.flush();

    // out.close();

    // fw.close();

    // os.close();

    try {
        URI uri = new URIBuilder().setScheme("http").setHost("ws.audioscrobbler.com").setPath("/2.0/")
                .setParameter("method", "track.getsimilar").setParameter("artist", "cher")
                .setParameter("track", "believe").setParameter("limit", "100")
                .setParameter("api_key", "88858618961414f8bec919bddd057044").build();

        // new URIBuilder().
        HttpGet request = new HttpGet(uri);

        // request.
        // This is useful for last.fm logging and preventing them from blocking this client
        request.setHeader(HttpHeaders.USER_AGENT,
                "nileshmore@gatech.edu - ClassAssignment at GeorgiaTech Non-commercial use");

        HttpGet httpGet = new HttpGet(
                "http://ws.audioscrobbler.com/2.0/?method=track.getsimilar&artist=cher&track=believe&limit=4&api_key=88858618961414f8bec919bddd057044");
        CloseableHttpResponse response = httpclient.execute(request);

        int statusCode = response.getStatusLine().getStatusCode();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        // The underlying HTTP connection is still held by the response object
        // to allow the response content to be streamed directly from the network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally clause.
        // Please note that if response content is not fully consumed the underlying
        // connection cannot be safely re-used and will be shut down and discarded
        // by the connection manager.
        try {
            if (statusCode == 200) {
                HttpEntity entity1 = response.getEntity();
                BufferedReader br = new BufferedReader(
                        new InputStreamReader((response.getEntity().getContent())));
                Document document = builder.parse((response.getEntity().getContent()));
                Element root = document.getDocumentElement();
                root.normalize();
                // Need to focus and resolve this part
                NodeList nodes;
                nodes = root.getChildNodes();

                nodes = root.getElementsByTagName("track");
                if (nodes.getLength() == 0) {
                    // System.out.println("empty");
                    return;
                }
                Node trackNode;
                for (int k = 0; k < nodes.getLength(); k++) // can access all tracks now
                {
                    trackNode = nodes.item(k);
                    NodeList trackAttributes = trackNode.getChildNodes();

                    // check if mbid is present in track attributes
                    // System.out.println("Length  " + (trackAttributes.item(5).getNodeName().compareToIgnoreCase("mbid") == 0));

                    if ((trackAttributes.item(5).getNodeName().compareToIgnoreCase("mbid") == 0)) {
                        if (((Element) trackAttributes.item(5)).hasChildNodes())
                            ;// System.out.println("Go aHead");
                        else
                            continue;
                    } else
                        continue;

                    for (int n = 0; n < trackAttributes.getLength(); n++) {
                        Node attribute = trackAttributes.item(n);
                        if ((attribute.getNodeName().compareToIgnoreCase("name")) == 0) {
                            // System.out.println(((Element)attribute).getFirstChild().getNodeValue());
                            trackName = ((Element) attribute).getFirstChild().getNodeValue(); // make string encoding as UTF-8 ************ 

                        }

                        if ((attribute.getNodeName().compareToIgnoreCase("mbid")) == 0) {
                            // System.out.println(n +  "   " +  ((Element)attribute).getFirstChild().getNodeValue());
                            sourceMbid = attribute.getFirstChild().getNodeValue();

                        }

                        if ((attribute.getNodeName().compareToIgnoreCase("artist")) == 0) {
                            NodeList ArtistNodeList = attribute.getChildNodes();
                            for (int j = 0; j < ArtistNodeList.getLength(); j++) {
                                Node Artistnode = ArtistNodeList.item(j);
                                if ((Artistnode.getNodeName().compareToIgnoreCase("name")) == 0) {
                                    // System.out.println(((Element)Artistnode).getFirstChild().getNodeValue());
                                    artistName = ((Element) Artistnode).getFirstChild().getNodeValue();
                                }
                            }
                        }
                    }
                    out.print(sourceMbid);
                    out.print(",");
                    out.print(trackName);
                    out.print(",");
                    out.println(artistName);
                    // out.print(",");
                    findSimilarTracks(track_id_out, sourceMbid, trackName, artistName);

                }
                track_id_out.flush();

                out.flush();
                out.close();
                track_id_out.close();
                track_os.close();

                // fw.close();
                Element trac = (Element) nodes.item(0);
                // trac.normalize();
                nodes = trac.getChildNodes();
                // System.out.println(nodes.getLength());

                for (int i = 0; i < nodes.getLength(); i++) {
                    Node node = nodes.item(i);
                    // System.out.println(node.getNodeName());
                    if ((node.getNodeName().compareToIgnoreCase("name")) == 0) {
                        // System.out.println(((Element)node).getFirstChild().getNodeValue());
                    }

                    if ((node.getNodeName().compareToIgnoreCase("mbid")) == 0) {
                        // System.out.println(((Element)node).getFirstChild().getNodeValue());
                    }

                    if ((node.getNodeName().compareToIgnoreCase("artist")) == 0) {

                        // System.out.println("Well");
                        NodeList ArtistNodeList = node.getChildNodes();
                        for (int j = 0; j < ArtistNodeList.getLength(); j++) {
                            Node Artistnode = ArtistNodeList.item(j);
                            if ((Artistnode.getNodeName().compareToIgnoreCase("name")) == 0) {
                                /* System.out.println(((Element)Artistnode).getFirstChild().getNodeValue());*/
                            }
                            /*System.out.println(Artistnode.getNodeName());*/
                        }
                    }

                }
                /*if(node instanceof Element){
                  //a child element to process
                  Element child = (Element) node;
                  String attribute = child.getAttribute("width");
                }*/

                // System.out.println(root.getAttribute("status"));
                NodeList tracks = root.getElementsByTagName("track");
                Element track = (Element) tracks.item(0);
                // System.out.println(track.getTagName());
                track.getChildNodes();

            } else {
                System.out.println("failed with status" + response.getStatusLine());
            }
            // input = (ByteArrayInputStream)entity1.getContent();
            // do something useful with the response body
            // and ensure it is fully consumed
        } finally {
            response.close();
        }
    }

    finally {
        System.out.println("Exited succesfully.");
        httpclient.close();

    }
}

From source file:Who.java

public static void main(String[] v) {
    Socket s = null;/*from  w  w w .  j a v a2s  .co  m*/
    PrintWriter out = null;
    BufferedReader in = null;
    try {
        // Connect to port 79 (the standard finger port) on the host.
        String hostname = "www.java2s.com";
        s = new Socket(hostname, 79);
        // Set up the streams
        out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
        in = new BufferedReader(new InputStreamReader(s.getInputStream()));

        // Send a blank line to the finger server, telling it that we want
        // a listing of everyone logged on instead of information about an
        // individual user.
        out.print("\n");
        out.flush(); // Send it out

        // Now read the server's response
        // The server should send lines terminated with \n or \r.
        String line;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
        System.out.println("Who's Logged On: " + hostname);
    } catch (IOException e) {
        System.out.println("Who's Logged On: Error");
    }
    // Close the streams!
    finally {
        try {
            in.close();
            out.close();
            s.close();
        } catch (Exception e) {
        }
    }
}

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 .  ja v 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:edu.cornell.med.icb.goby.reads.ColorSpaceConverter.java

public static void main(final String[] args) throws JSAPException, IOException {
    final JSAP jsap = new JSAP();

    final FlaggedOption sequenceOption = new FlaggedOption("input");
    sequenceOption.setRequired(true);//from   ww  w. ja  va2s . co  m
    sequenceOption.setLongFlag("input");
    sequenceOption.setShortFlag('i');
    sequenceOption.setStringParser(FileStringParser.getParser().setMustBeFile(true).setMustExist(true));
    sequenceOption.setHelp("The input file (in Fasta format) to convert");
    jsap.registerParameter(sequenceOption);

    final FlaggedOption outputOption = new FlaggedOption("output");
    outputOption.setRequired(false);
    outputOption.setLongFlag("output");
    outputOption.setShortFlag('o');
    outputOption.setStringParser(FileStringParser.getParser().setMustBeFile(true));
    outputOption.setHelp("The output file to write to (default = stdout)");
    jsap.registerParameter(outputOption);

    final FlaggedOption titleOption = new FlaggedOption("title");
    titleOption.setRequired(false);
    titleOption.setLongFlag("title");
    titleOption.setShortFlag('t');
    titleOption.setHelp("Title for this conversion");
    jsap.registerParameter(titleOption);

    final Switch verboseOption = new Switch("verbose");
    verboseOption.setLongFlag("verbose");
    verboseOption.setShortFlag('v');
    verboseOption.setHelp("Verbose output");
    jsap.registerParameter(verboseOption);

    final Switch helpOption = new Switch("help");
    helpOption.setLongFlag("help");
    helpOption.setShortFlag('h');
    helpOption.setHelp("Print this message");
    jsap.registerParameter(helpOption);

    jsap.setUsage("Usage: " + ColorSpaceConverter.class.getName() + " " + jsap.getUsage());

    final JSAPResult result = jsap.parse(args);

    if (result.getBoolean("help")) {
        System.out.println(jsap.getHelp());
        System.exit(0);
    }

    if (!result.success()) {
        final Iterator<String> errors = result.getErrorMessageIterator();
        while (errors.hasNext()) {
            System.err.println(errors.next());
        }
        System.err.println(jsap.getUsage());
        System.exit(1);
    }

    final boolean verbose = result.getBoolean("verbose");

    final File sequenceFile = result.getFile("input");
    if (verbose) {
        System.out.println("Reading sequence from: " + sequenceFile);
    }

    // extract the title to use for the output header
    final String title;
    if (result.contains("title")) {
        title = result.getString("title");
    } else {
        title = sequenceFile.getName();
    }

    Reader inputReader = null;
    PrintWriter outputWriter = null;

    try {
        if ("gz".equals(FilenameUtils.getExtension(sequenceFile.getName()))) {
            inputReader = new InputStreamReader(new GZIPInputStream(FileUtils.openInputStream(sequenceFile)));
        } else {
            inputReader = new FileReader(sequenceFile);
        }
        final FastaParser fastaParser = new FastaParser(inputReader);

        final File outputFile = result.getFile("output");
        final OutputStream outputStream;
        if (outputFile != null) {
            outputStream = FileUtils.openOutputStream(outputFile);
            if (verbose) {
                System.out.println("Writing sequence : " + outputFile);
            }
        } else {
            outputStream = System.out;
        }
        outputWriter = new PrintWriter(outputStream);

        // write the header portion of the output
        outputWriter.print("# ");
        outputWriter.print(new Date());
        outputWriter.print(' ');
        outputWriter.print(ColorSpaceConverter.class.getName());
        for (final String arg : args) {
            outputWriter.print(' ');
            outputWriter.print(arg);
        }
        outputWriter.println();
        outputWriter.print("# Cwd: ");
        outputWriter.println(new File(".").getCanonicalPath());
        outputWriter.print("# Title: ");
        outputWriter.println(title);

        // now parse the input sequence
        long sequenceCount = 0;
        final MutableString descriptionLine = new MutableString();
        final MutableString sequence = new MutableString();
        final MutableString colorSpaceSequence = new MutableString();

        while (fastaParser.hasNext()) {
            fastaParser.next(descriptionLine, sequence);
            outputWriter.print('>');
            outputWriter.println(descriptionLine);

            convert(sequence, colorSpaceSequence);
            CompactToFastaMode.writeSequence(outputWriter, colorSpaceSequence);

            sequenceCount++;
            if (verbose && sequenceCount % 10000 == 0) {
                System.out.println("Converted " + sequenceCount + " entries");
            }
        }

        if (verbose) {
            System.out.println("Conversion complete!");
        }
    } finally {
        IOUtils.closeQuietly(inputReader);
        IOUtils.closeQuietly(outputWriter);
    }
}

From source file:microbiosima.Microbiosima.java

/**
 * @param args//from   w  ww  . j  av  a2s . co m
 *            the command line arguments
 * @throws java.io.FileNotFoundException
 * @throws java.io.UnsupportedEncodingException
 */
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
    //Init with default values
    int populationSize = 500;
    int microSize = 1000;
    int numberOfSpecies = 150;
    int numberOfGeneration = 10000;
    int numberOfObservation = 100;
    int numberOfReplication = 1;
    double pctEnv = 0;
    double pctPool = 0;

    Options options = new Options();

    Option help = new Option("h", "help", false, "print this message");
    Option version = new Option("v", "version", false, "print the version information and exit");
    options.addOption(help);
    options.addOption(version);

    options.addOption(Option.builder("o").longOpt("obs").hasArg().argName("OBS")
            .desc("Number generation for observation [default: 100]").build());
    options.addOption(Option.builder("r").longOpt("rep").hasArg().argName("REP")
            .desc("Number of replication [default: 1]").build());

    Builder C = Option.builder("c").longOpt("config").numberOfArgs(4).argName("Pop Micro Spec Gen")
            .desc("Four Parameters in the following orders: "
                    + "(1) population size, (2) microbe size, (3) number of species, (4) number of generation"
                    + " [default: 500 1000 150 10000]");
    options.addOption(C.build());

    HelpFormatter formatter = new HelpFormatter();
    String syntax = "microbiosima pctEnv pctPool";
    String header = "\nSimulates the evolutionary and ecological dynamics of microbiomes within a population of hosts.\n\n"
            + "required arguments:\n" + "  pctEnv             Percentage of environmental acquisition\n"
            + "  pctPool            Percentage of pooled environmental component\n" + "\noptional arguments:\n";
    String footer = "\n";

    formatter.setWidth(80);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
        String[] pct_config = cmd.getArgs();

        if (cmd.hasOption("h") || args.length == 0) {
            formatter.printHelp(syntax, header, options, footer, true);
            System.exit(0);
        }
        if (cmd.hasOption("v")) {
            System.out.println("Microbiosima " + VERSION);
            System.exit(0);
        }
        if (pct_config.length != 2) {
            System.out.println("ERROR! Required exactly two argumennts for pct_env and pct_pool. It got "
                    + pct_config.length + ": " + Arrays.toString(pct_config));
            formatter.printHelp(syntax, header, options, footer, true);
            System.exit(3);
        } else {
            pctEnv = Double.parseDouble(pct_config[0]);
            pctPool = Double.parseDouble(pct_config[1]);
            if (pctEnv < 0 || pctEnv > 1) {
                System.out.println(
                        "ERROR: pctEnv (Percentage of environmental acquisition) must be between 0 and 1 (pctEnv="
                                + pctEnv + ")! EXIT");
                System.exit(3);
            }
            if (pctPool < 0 || pctPool > 1) {
                System.out.println(
                        "ERROR: pctPool (Percentage of pooled environmental component must) must be between 0 and 1 (pctPool="
                                + pctPool + ")! EXIT");
                System.exit(3);
            }

        }
        if (cmd.hasOption("config")) {
            String[] configs = cmd.getOptionValues("config");
            populationSize = Integer.parseInt(configs[0]);
            microSize = Integer.parseInt(configs[1]);
            numberOfSpecies = Integer.parseInt(configs[2]);
            numberOfGeneration = Integer.parseInt(configs[3]);
        }
        if (cmd.hasOption("obs")) {
            numberOfObservation = Integer.parseInt(cmd.getOptionValue("obs"));
        }
        if (cmd.hasOption("rep")) {
            numberOfReplication = Integer.parseInt(cmd.getOptionValue("rep"));
        }

    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(3);
    }

    StringBuilder sb = new StringBuilder();
    sb.append("Configuration Summary:").append("\n\tPopulation size: ").append(populationSize)
            .append("\n\tMicrobe size: ").append(microSize).append("\n\tNumber of species: ")
            .append(numberOfSpecies).append("\n\tNumber of generation: ").append(numberOfGeneration)
            .append("\n\tNumber generation for observation: ").append(numberOfObservation)
            .append("\n\tNumber of replication: ").append(numberOfReplication).append("\n");
    System.out.println(sb.toString());

    //      System.exit(3);
    // LogNormalDistribution lgd=new LogNormalDistribution(0,1);
    // environment=lgd.sample(150);
    // double environment_sum=0;
    // for (int i=0;i<No;i++){
    // environment_sum+=environment[i];
    // }
    // for (int i=0;i<No;i++){
    // environment[i]/=environment_sum;
    // }

    double[] environment = new double[numberOfSpecies];
    for (int i = 0; i < numberOfSpecies; i++) {
        environment[i] = 1 / (double) numberOfSpecies;
    }

    for (int rep = 0; rep < numberOfReplication; rep++) {
        String prefix = "" + (rep + 1) + "_";
        String sufix = "_E" + pctEnv + "_P" + pctPool + ".txt";

        System.out.println("Output 5 result files in the format of: " + prefix + "[****]" + sufix);
        try {

            PrintWriter file1 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "gamma_diversity" + sufix)));
            PrintWriter file2 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "alpha_diversity" + sufix)));
            PrintWriter file3 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "beta_diversity" + sufix)));
            PrintWriter file4 = new PrintWriter(new BufferedWriter(new FileWriter(prefix + "sum" + sufix)));
            PrintWriter file5 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "inter_generation_distance" + sufix)));
            PrintWriter file6 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "environment_population_distance" + sufix)));

            Population population = new Population(microSize, environment, populationSize, pctEnv, pctPool, 0,
                    0);

            while (population.getNumberOfGeneration() < numberOfGeneration) {
                population.sumSpecies();
                if (population.getNumberOfGeneration() % numberOfObservation == 0) {
                    file1.println(population.gammaDiversity(true));
                    file2.println(population.alphaDiversity(true));
                    file3.print(population.betaDiversity(true));
                    file3.print("\t");
                    file3.println(population.BrayCurtis(true));
                    file4.println(population.printOut());
                    file5.println(population.interGenerationDistance());
                    file6.println(population.environmentPopulationDistance());
                }
                population.getNextGen();
            }
            file1.close();
            file2.close();
            file3.close();
            file4.close();
            file5.close();
            file6.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}