Example usage for java.io BufferedWriter newLine

List of usage examples for java.io BufferedWriter newLine

Introduction

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

Prototype

public void newLine() throws IOException 

Source Link

Document

Writes a line separator.

Usage

From source file:dsfixgui.view.DSFGraphicsPane.java

public void setFPSFixKey(String newFPSFixKey) {
    try {//from  w  w  w  .  jav a  2 s .  co m
        String fpsFixCfg = readTextFile(ui.getDataFolder() + "\\" + FPS_FIX_FILES[1]);

        ui.printConsole(WRITING_FILE[0] + FPS_FIX_FILES[1] + "...");
        //The file to be written
        File writeFile = new File(ui.getDataFolder() + "\\" + FPS_FIX_FILES[1]);
        if (writeFile.exists()) {
            //If file exists, try to delete it
            if (!writeFile.delete()) {
                //If file cannot be deleted, throw OIOException
                throw new IIOException("Could not delete pre-existing file: " + FPS_FIX_FILES[1]);
            }
        }

        //Format each linebreak to be displayed correctly in a text file
        String formattedText = fpsFixCfg.replaceAll("\n", String.format("%n"));
        //Initialize BufferedWriter to write string to file
        BufferedWriter fileWriter = new BufferedWriter(new FileWriter(writeFile));
        //Write the file
        Scanner scanner = new Scanner(formattedText);
        int i = 0;
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.startsWith("Key=")) {
                fileWriter.write("Key=" + newFPSFixKey);
                fileWriter.newLine();
                i++;
            } else if (line.length() > 1) {
                fileWriter.write(line);
                fileWriter.newLine();
                i++;
            } else if (i == 2 || i == 4) {
                fileWriter.newLine();
                i++;
            }
        }
        fileWriter.close();
        scanner.close();

        ui.printConsole(WRITING_FILE[1]);
    } catch (IOException ex) {
        ui.printConsole(FILES_EDITED_ERR[0] + FPS_FIX_FILES[1]);
        fpsFixKeyPicker.setDisable(true);
    }
}

From source file:org.matsim.contrib.drt.analysis.DynModeTripsAnalyser.java

public static void analyseWaitTimes(String fileName, List<DynModeTrip> trips, int binsize_s) {
    Collections.sort(trips);//from   w w  w  .  ja  va 2  s  .co m
    if (trips.size() == 0)
        return;
    int startTime = ((int) (trips.get(0).getDepartureTime() / binsize_s)) * binsize_s;
    int endTime = ((int) (trips.get(trips.size() - 1).getDepartureTime() / binsize_s) + binsize_s) * binsize_s;
    Map<Double, List<DynModeTrip>> splitTrips = splitTripsIntoBins(trips, startTime, endTime, binsize_s);

    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    format.setMinimumIntegerDigits(1);
    format.setMaximumFractionDigits(2);
    format.setGroupingUsed(false);

    SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");

    BufferedWriter bw = IOUtils.getBufferedWriter(fileName + ".csv");
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    TimeSeriesCollection datasetrequ = new TimeSeriesCollection();
    TimeSeries averageWaitC = new TimeSeries("average");
    TimeSeries medianWait = new TimeSeries("median");
    TimeSeries p_5Wait = new TimeSeries("5th percentile");
    TimeSeries p_95Wait = new TimeSeries("95th percentile");
    TimeSeries requests = new TimeSeries("Ride requests");

    try {
        bw.write("timebin;trips;average_wait;min;p_5;p_25;median;p_75;p_95;max");
        for (Entry<Double, List<DynModeTrip>> e : splitTrips.entrySet()) {
            long rides = 0;
            double averageWait = 0;
            double min = 0;
            double p_5 = 0;
            double p_25 = 0;
            double median = 0;
            double p_75 = 0;
            double p_95 = 0;
            double max = 0;
            if (!e.getValue().isEmpty()) {
                DescriptiveStatistics stats = new DescriptiveStatistics();
                for (DynModeTrip t : e.getValue()) {
                    stats.addValue(t.getWaitTime());
                }
                rides = stats.getN();
                averageWait = stats.getMean();
                min = stats.getMin();
                p_5 = stats.getPercentile(5);
                p_25 = stats.getPercentile(25);
                median = stats.getPercentile(50);
                p_75 = stats.getPercentile(75);
                p_95 = stats.getPercentile(95);
                max = stats.getMax();

            }
            Minute h = new Minute(sdf2.parse(Time.writeTime(e.getKey())));

            medianWait.addOrUpdate(h, Double.valueOf(median));
            averageWaitC.addOrUpdate(h, Double.valueOf(averageWait));
            p_5Wait.addOrUpdate(h, Double.valueOf(p_5));
            p_95Wait.addOrUpdate(h, Double.valueOf(p_95));
            requests.addOrUpdate(h, rides * 3600. / binsize_s);// normalised [req/h]
            bw.newLine();
            bw.write(Time.writeTime(e.getKey()) + ";" + rides + ";" + format.format(averageWait) + ";"
                    + format.format(min) + ";" + format.format(p_5) + ";" + format.format(p_25) + ";"
                    + format.format(median) + ";" + format.format(p_75) + ";" + format.format(p_95) + ";"
                    + format.format(max));

        }
        bw.flush();
        bw.close();
        dataset.addSeries(averageWaitC);
        dataset.addSeries(medianWait);
        dataset.addSeries(p_5Wait);
        dataset.addSeries(p_95Wait);
        datasetrequ.addSeries(requests);
        JFreeChart chart = chartProfile(splitTrips.size(), dataset, "Waiting times", "Wait time (s)");
        JFreeChart chart2 = chartProfile(splitTrips.size(), datasetrequ, "Ride requests per hour",
                "Requests per hour (req/h)");
        ChartSaveUtils.saveAsPNG(chart, fileName, 1500, 1000);
        ChartSaveUtils.saveAsPNG(chart2, fileName + "_requests", 1500, 1000);

    } catch (IOException | ParseException e) {

        e.printStackTrace();
    }

}

From source file:Main.Interface_Main.java

private void logData() {

    File f = new File(logTmpFile);
    boolean header = false;

    if (!f.exists()) {
        header = true;/*from  w  w w .  j  a va  2  s. com*/
    }

    //int csvDataSize = csvData.size();

    try {
        BufferedWriter writer = null;
        writer = new BufferedWriter(new FileWriter(f.getAbsolutePath(), true));
        if (header) {
            writer.write("time, amp, max, min, volt, max, min, wattage, mah, mwh, dp, dm");
            writer.newLine();
        }

        for (int i = lastCSVPos; i < csvData.size(); i++) {
            writer.write(csvData.get(i).toString());
            writer.newLine();
        }

        writer.close();
        System.out.println("Data Logged");
        csvData.clear();
        //csvData.trimToSize();
        //lastCSVPos = csvDataSize;

    } catch (java.io.IOException e) {

        JOptionPane.showMessageDialog(this, e);

    }

}

From source file:com.roquahacks.semafor4j.FrameNetService.java

public void writeOptionsToConfig() {
    try {//from  w w  w  .j  av a2 s.  c  om
        this.configFile = FileUtils.readLines(new File(FrameNetOptions.ABS_PATH_FILE_CONFIG));
        BufferedWriter bw = new BufferedWriter(new FileWriter(new File(FrameNetOptions.ABS_PATH_FILE_CONFIG)));
        for (String s : configFile) {
            if (s.startsWith(SEMAFOR_HOME)) {
                s = SEMAFOR_HOME + FrameNetOptions.ABS_PATH_SEMAFOR;
            } else if (s.startsWith(MST_MODE)) {
                if (this.fnOpt.isServerModeOn()) {
                    s = MST_MODE + "server";
                } else {
                    s = MST_MODE + "noserver";
                }
            } else if (s.startsWith(JAVA_HOME)) {
                s = JAVA_HOME + this.fnOpt.getJavaHomePath();
            } else if (s.startsWith(GOLD_TARGET_FILE)) {
                s = GOLD_TARGET_FILE + this.fnOpt.getGoldTargetsPath();
            } else if (s.startsWith(AUTO_TARGET_ID_MODE)) {
                if (this.fnOpt.isAutoTargetIDStrictModeOn()) {
                    s = AUTO_TARGET_ID_MODE + "strict";
                } else {
                    s = AUTO_TARGET_ID_MODE + "relaxed";
                }
            } else if (s.startsWith(USE_GRAPH_FILES)) {
                if (this.fnOpt.isGraphFilesOn()) {
                    s = USE_GRAPH_FILES + "yes";
                } else {
                    s = USE_GRAPH_FILES + "no";
                }
            } else if (s.startsWith(DECODING_TYPE)) {
                s = DECODING_TYPE + this.fnOpt.getDecodingType();
            }
            bw.write(s);
            bw.newLine();
        }
        bw.flush();
        bw.close();
        this.configFile.clear();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:ffx.algorithms.OSRW.java

@Override
public double energyAndGradient(double[] x, double[] gradient) {

    double e = potential.energyAndGradient(x, gradient);

    /**/*from   w ww .  j  a  v  a 2 s.  c o m*/
     * OSRW is propagated with the slowly varying terms.
     */
    if (state == STATE.FAST) {
        return e;
    }

    if (osrwOptimization && lambda > osrwOptimizationLambdaCutoff) {
        if (energyCount % osrwOptimizationFrequency == 0) {
            logger.info(String.format(" OSRW Minimization (Step %d)", energyCount));

            // Set Lambda value to 1.0.
            lambdaInterface.setLambda(1.0);

            potential.setEnergyTermState(Potential.STATE.BOTH);

            // Optimize the system.
            Minimize minimize = new Minimize(null, potential, null);
            minimize.minimize(osrwOptimizationEps);

            // Collect the minimum energy.
            double minEnergy = potential.getTotalEnergy();
            // If a new minimum has been found, save its coordinates.
            if (minEnergy < osrwOptimum) {
                osrwOptimum = minEnergy;
                logger.info(String.format(" New minimum energy found: %16.8f (Step %d).", osrwOptimum,
                        energyCount));
                int n = potential.getNumberOfVariables();
                osrwOptimumCoords = new double[n];
                osrwOptimumCoords = potential.getCoordinates(osrwOptimumCoords);
                if (pdbFilter.writeFile(pdbFile, false)) {
                    logger.info(String.format(" Wrote PDB file to " + pdbFile.getName()));
                }
            }

            // Reset lambda value.
            lambdaInterface.setLambda(lambda);

            // Remove the scaling of coordinates & gradient set by the minimizer.
            potential.setScaling(null);

            // Reset the Potential State
            potential.setEnergyTermState(state);

            // Revert to the coordinates and gradient prior to optimization.
            double eCheck = potential.energyAndGradient(x, gradient);

            if (abs(eCheck - e) > osrwOptimizationTolerance) {
                logger.warning(String.format(
                        " OSRW optimization could not revert coordinates %16.8f vs. %16.8f.", e, eCheck));
            }
        }
    }

    double biasEnergy = 0.0;
    dEdLambda = lambdaInterface.getdEdL();
    d2EdLambda2 = lambdaInterface.getd2EdL2();
    int lambdaBin = binForLambda(lambda);
    int FLambdaBin = binForFLambda(dEdLambda);
    double dEdU = dEdLambda;

    if (propagateLambda) {
        energyCount++;
    }

    /**
     * Calculate recursion kernel G(L, F_L) and its derivatives with respect
     * to L and F_L.
     */
    double dGdLambda = 0.0;
    double dGdFLambda = 0.0;
    double ls2 = (2.0 * dL) * (2.0 * dL);
    double FLs2 = (2.0 * dFL) * (2.0 * dFL);
    for (int iL = -biasCutoff; iL <= biasCutoff; iL++) {
        int lcenter = lambdaBin + iL;
        double deltaL = lambda - (lcenter * dL);
        double deltaL2 = deltaL * deltaL;
        // Mirror conditions for recursion kernel counts.
        int lcount = lcenter;
        double mirrorFactor = 1.0;
        if (lcount == 0 || lcount == lambdaBins - 1) {
            mirrorFactor = 2.0;
        } else if (lcount < 0) {
            lcount = -lcount;
        } else if (lcount > lambdaBins - 1) {
            // Number of bins past the last bin
            lcount -= (lambdaBins - 1);
            // Mirror bin
            lcount = lambdaBins - 1 - lcount;
        }
        for (int iFL = -biasCutoff; iFL <= biasCutoff; iFL++) {
            int FLcenter = FLambdaBin + iFL;
            /**
             * If either of the following FL edge conditions are true, then
             * there are no counts and we continue.
             */
            if (FLcenter < 0 || FLcenter >= FLambdaBins) {
                continue;
            }
            double deltaFL = dEdLambda - (minFLambda + FLcenter * dFL + dFL_2);
            double deltaFL2 = deltaFL * deltaFL;
            double weight = mirrorFactor * recursionKernel[lcount][FLcenter];
            double bias = weight * biasMag * exp(-deltaL2 / (2.0 * ls2)) * exp(-deltaFL2 / (2.0 * FLs2));
            biasEnergy += bias;
            dGdLambda -= deltaL / ls2 * bias;
            dGdFLambda -= deltaFL / FLs2 * bias;
        }
    }

    /**
     * Lambda gradient due to recursion kernel G(L, F_L).
     */
    dEdLambda += dGdLambda + dGdFLambda * d2EdLambda2;

    /**
     * Cartesian coordinate gradient due to recursion kernel G(L, F_L).
     */
    fill(dUdXdL, 0.0);
    lambdaInterface.getdEdXdL(dUdXdL);
    for (int i = 0; i < nVariables; i++) {
        gradient[i] += dGdFLambda * dUdXdL[i];
    }

    if (propagateLambda && energyCount > 0) {
        /**
         * Update free energy F(L) every ~10 steps.
         */
        if (energyCount % 10 == 0) {
            fLambdaUpdates++;
            boolean printFLambda = fLambdaUpdates % fLambdaPrintInterval == 0;
            totalFreeEnergy = updateFLambda(printFLambda);
            /**
             * Calculating Moving Average & Standard Deviation
             */
            totalAverage += totalFreeEnergy;
            totalSquare += Math.pow(totalFreeEnergy, 2);
            periodCount++;
            if (periodCount == window - 1) {
                lastAverage = totalAverage / window;
                //lastStdDev = Math.sqrt((totalSquare - Math.pow(totalAverage, 2) / window) / window);
                lastStdDev = Math.sqrt((totalSquare - (totalAverage * totalAverage)) / (window * window));
                logger.info(String.format(
                        " The running average is %12.4f kcal/mol and the stdev is %8.4f kcal/mol.", lastAverage,
                        lastStdDev));
                totalAverage = 0;
                totalSquare = 0;
                periodCount = 0;
            }
        }
        if (energyCount % saveFrequency == 0) {
            if (algorithmListener != null) {
                algorithmListener.algorithmUpdate(lambdaOneAssembly);
            }
            /**
             * Only the rank 0 process writes the histogram restart file.
             */
            if (rank == 0) {
                try {
                    OSRWHistogramWriter osrwHistogramRestart = new OSRWHistogramWriter(
                            new BufferedWriter(new FileWriter(histogramFile)));
                    osrwHistogramRestart.writeHistogramFile();
                    osrwHistogramRestart.flush();
                    osrwHistogramRestart.close();
                    logger.info(String.format(" Wrote OSRW histogram restart file to %s.",
                            histogramFile.getName()));
                } catch (IOException ex) {
                    String message = " Exception writing OSRW histogram restart file.";
                    logger.log(Level.INFO, message, ex);
                }
            }
            /**
             * All ranks write a lambda restart file.
             */
            try {
                OSRWLambdaWriter osrwLambdaRestart = new OSRWLambdaWriter(
                        new BufferedWriter(new FileWriter(lambdaFile)));
                osrwLambdaRestart.writeLambdaFile();
                osrwLambdaRestart.flush();
                osrwLambdaRestart.close();
                logger.info(String.format(" Wrote OSRW lambda restart file to %s.", lambdaFile.getName()));
            } catch (IOException ex) {
                String message = " Exception writing OSRW lambda restart file.";
                logger.log(Level.INFO, message, ex);
            }
        }
        /**
         * Write out snapshot upon each full lambda traversal.
         */
        if (writeTraversalSnapshots) {
            double heldTraversalLambda = 0.5;
            if (!traversalInHand.isEmpty()) {
                heldTraversalLambda = Double.parseDouble(traversalInHand.get(0).split(",")[0]);
                if ((lambda > 0.2 && traversalSnapshotTarget == 0)
                        || (lambda < 0.8 && traversalSnapshotTarget == 1)) {
                    int snapshotCounts = Integer.parseInt(traversalInHand.get(0).split(",")[1]);
                    traversalInHand.remove(0);
                    File fileToWrite;
                    int numStructures;
                    if (traversalSnapshotTarget == 0) {
                        fileToWrite = lambdaZeroFile;
                        numStructures = ++lambdaZeroStructures;
                    } else {
                        fileToWrite = lambdaOneFile;
                        numStructures = ++lambdaOneStructures;
                    }
                    try {
                        FileWriter fw = new FileWriter(fileToWrite, true);
                        BufferedWriter bw = new BufferedWriter(fw);
                        bw.write(String.format("MODEL        %d          L=%.4f  counts=%d", numStructures,
                                heldTraversalLambda, snapshotCounts));
                        for (int i = 0; i < 50; i++) {
                            bw.write(" ");
                        }
                        bw.newLine();
                        for (int i = 0; i < traversalInHand.size(); i++) {
                            bw.write(traversalInHand.get(i));
                            bw.newLine();
                        }
                        bw.write(String.format("ENDMDL"));
                        for (int i = 0; i < 75; i++) {
                            bw.write(" ");
                        }
                        bw.newLine();
                        bw.close();
                        logger.info(String.format(" Wrote traversal structure L=%.4f", heldTraversalLambda));
                    } catch (Exception exception) {
                        logger.warning(String.format("Exception writing to file: %s", fileToWrite.getName()));
                    }
                    heldTraversalLambda = 0.5;
                    traversalInHand.clear();
                    traversalSnapshotTarget = 1 - traversalSnapshotTarget;
                }
            }
            if (((lambda < 0.1 && traversalInHand.isEmpty())
                    || (lambda < heldTraversalLambda - 0.025 && !traversalInHand.isEmpty()))
                    && (traversalSnapshotTarget == 0 || traversalSnapshotTarget == -1)) {
                if (lambdaZeroFilter == null) {
                    lambdaZeroFilter = new PDBFilter(lambdaZeroFile, lambdaZeroAssembly, null, null);
                    lambdaZeroFilter.setListMode(true);
                }
                lambdaZeroFilter.clearListOutput();
                lambdaZeroFilter.writeFileWithHeader(lambdaFile,
                        new StringBuilder(String.format("%.4f,%d,", lambda, totalCounts)));
                traversalInHand = lambdaZeroFilter.getListOutput();
                traversalSnapshotTarget = 0;
            } else if (((lambda > 0.9 && traversalInHand.isEmpty())
                    || (lambda > heldTraversalLambda + 0.025 && !traversalInHand.isEmpty()))
                    && (traversalSnapshotTarget == 1 || traversalSnapshotTarget == -1)) {
                if (lambdaOneFilter == null) {
                    lambdaOneFilter = new PDBFilter(lambdaOneFile, lambdaOneAssembly, null, null);
                    lambdaOneFilter.setListMode(true);
                }
                lambdaOneFilter.clearListOutput();
                lambdaOneFilter.writeFileWithHeader(lambdaFile,
                        new StringBuilder(String.format("%.4f,%d,", lambda, totalCounts)));
                traversalInHand = lambdaOneFilter.getListOutput();
                traversalSnapshotTarget = 1;
            }
        }
    }

    /**
     * Compute the energy and gradient for the recursion slave at F(L) using
     * interpolation.
     */
    double freeEnergy = currentFreeEnergy();
    biasEnergy += freeEnergy;

    if (print) {
        logger.info(String.format(" %s %16.8f", "Bias Energy       ", biasEnergy));
        logger.info(String.format(" %s %16.8f  %s", "OSRW Potential    ", e + biasEnergy, "(Kcal/mole)"));
    }

    if (propagateLambda && energyCount > 0) {
        /**
         * Log the current Lambda state.
         */
        if (energyCount % printFrequency == 0) {
            if (lambdaBins < 1000) {
                logger.info(String.format(" L=%6.4f (%3d) F_LU=%10.4f F_LB=%10.4f F_L=%10.4f", lambda,
                        lambdaBin, dEdU, dEdLambda - dEdU, dEdLambda));
            } else {
                logger.info(String.format(" L=%6.4f (%4d) F_LU=%10.4f F_LB=%10.4f F_L=%10.4f", lambda,
                        lambdaBin, dEdU, dEdLambda - dEdU, dEdLambda));
            }
        }

        /**
         * Metadynamics grid counts (every 'countInterval' steps).
         */
        if (energyCount % countInterval == 0) {
            if (jobBackend != null) {
                if (world.size() > 1) {
                    jobBackend.setComment(String.format(
                            "Overall dG=%10.4f at %7.3e psec, Current: [L=%6.4f, F_L=%10.4f, dG=%10.4f] at %7.3e psec",
                            totalFreeEnergy, totalCounts * dt * countInterval, lambda, dEdU, -freeEnergy,
                            energyCount * dt));
                } else {
                    jobBackend.setComment(String.format(
                            "Overall dG=%10.4f at %7.3e psec, Current: [L=%6.4f, F_L=%10.4f, dG=%10.4f]",
                            totalFreeEnergy, totalCounts * dt * countInterval, lambda, dEdU, -freeEnergy));
                }
            }
            if (asynchronous) {
                asynchronousSend(lambda, dEdU);
            } else {
                synchronousSend(lambda, dEdU);
            }
        }
    }

    /**
     * Propagate the Lambda particle.
     */
    if (propagateLambda) {
        langevin();
    } else {
        equilibrationCounts++;
        if (jobBackend != null) {
            jobBackend.setComment(String.format("Equilibration [L=%6.4f, F_L=%10.4f]", lambda, dEdU));
        }
        if (equilibrationCounts % 10 == 0) {
            logger.info(String.format(" L=%6.4f, F_L=%10.4f", lambda, dEdU));
        }
    }

    totalEnergy = e + biasEnergy;

    return totalEnergy;
}

From source file:chibi.gemmaanalysis.OutlierDetectionTestCli.java

/*** Write results to the output file; file name must be given as argument ***/
private void writeResultsToFileCombined(BufferedWriter bw, ExpressionExperiment ee,
        OutlierDetectionTestDetails testDetails) {
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(4);//from w w w  . j a  va2  s  . c o  m
    try {
        // Get information about the experiment:
        ee = this.eeService.thawLite(ee);
        System.out.println("Writing results to file for " + ee.getShortName());
        bw.write(ee.getShortName());
        bw.write("\t" + getPlatforms(ee));
        bw.write("\t" + testDetails.getNumExpFactors());
        if (useRegression) {
            bw.write("\t" + testDetails.getNumSigFactors());
        }
        bw.write("\t" + ee.getBioAssays().size());
        bw.write("\t" + testDetails.getNumRemoved());
        bw.write("\t" + testDetails.getNumOutliersBasicAlgorithm());
        bw.write("\t" + testDetails.getNumOutliersByMedian());
        bw.write("\t" + testDetails.getNumOutliers());
        // Get information about each of the outliers
        for (OutlierDetails outlier : testDetails.getOutliers()) {
            bw.write("\t" + outlier.getBioAssay().getName());
        }
        if (useRegression) {
            for (ExperimentalFactor factor : testDetails.getSignificantFactors()) {
                bw.write("\t" + factor.getName());
            }
        }
        bw.newLine();

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.asterix.extension.grammar.GrammarExtensionMojo.java

private void merge(BufferedWriter writer, Pair<String, String> baseBlocks, String[] extensions)
        throws IOException, MojoExecutionException {
    String errorMessage = "Merged base node doesn't conform to expected mergable node structure";
    int block1Open = baseBlocks.first.indexOf(OPEN_BRACE);
    int block1Close = baseBlocks.first.lastIndexOf(CLOSE_BRACE);
    // first block
    writer.write(OPEN_BRACE);/*  ww w.j a va 2s  .c  om*/
    if (extensions[0] != null) {
        writer.write(extensions[0]);
    }
    writer.write(baseBlocks.first.substring(block1Open + 1, block1Close));
    if (extensions[1] != null) {
        writer.write(extensions[1]);
    }
    writer.write(CLOSE_BRACE);
    writer.newLine();
    // second block
    writer.write(OPEN_BRACE);
    writer.newLine();
    if (extensions[2] != null) {
        writer.write(extensions[2]);
    }
    String innerBlock2String = null;
    if (baseBlocks.second != null) {
        BufferedReader blockReader = stringToReader(baseBlocks.second);
        Position blockPosition = new Position();
        blockPosition.index = 0;
        blockPosition.line = blockReader.readLine();
        while (blockPosition.line != null
                && (blockPosition.line.trim().length() == 0 || blockPosition.line.indexOf(OPEN_BRACE) < 0)) {
            if (blockPosition.line.trim().length() > 0) {
                writer.write(blockPosition.line);
                writer.newLine();
            }
            blockPosition.line = blockReader.readLine();
        }
        if (blockPosition.line == null) {
            throw new MojoExecutionException(errorMessage);
        }
        int block2Open = blockPosition.line.indexOf(OPEN_BRACE);
        blockPosition.line = blockPosition.line.substring(block2Open + 1);
        while (blockPosition.line != null
                && (blockPosition.line.trim().length() == 0 || blockPosition.line.indexOf(OPEN_PAREN) < 0)) {
            if (blockPosition.line.trim().length() > 0) {
                writer.write(blockPosition.line);
                writer.newLine();
            }
            blockPosition.line = blockReader.readLine();
        }
        if (blockPosition.line == null) {
            throw new MojoExecutionException(errorMessage);
        }
        int innerBlock1Open = blockPosition.line.indexOf(OPEN_PAREN);
        writer.write("  ");
        writer.write(OPEN_PAREN);
        blockPosition.index = innerBlock1Open;
        readBlock(blockReader, OPEN_PAREN, CLOSE_PAREN, blockPosition);
        String innerBlock1String = record.toString();
        writer.newLine();
        writer.write("    ");
        writer.write(innerBlock1String.substring(innerBlock1String.indexOf(OPEN_PAREN) + 1,
                innerBlock1String.lastIndexOf(CLOSE_PAREN)).trim());
        writer.newLine();
        record.reset();
        // read second inner block
        blockPosition.line = blockReader.readLine();
        while (blockPosition.line != null && blockPosition.line.trim().length() == 0) {
            blockPosition.line = blockReader.readLine();
        }
        int innerBlock2Open = blockPosition.line.indexOf(OPEN_BRACE);
        if (innerBlock2Open < 0) {
            throw new MojoExecutionException(errorMessage);
        }
        blockPosition.index = innerBlock2Open;
        readBlock(blockReader, OPEN_BRACE, CLOSE_BRACE, blockPosition);
        innerBlock2String = record.toString();
        record.reset();
    }
    if (extensions[3] != null) {
        writer.write(extensions[3]);
    }
    writer.newLine();
    writer.write("  ");
    writer.write(CLOSE_PAREN);
    writer.newLine();
    writer.write("  ");
    writer.write(OPEN_BRACE);
    if (extensions[4] != null) {
        writer.write(extensions[4]);
    }
    if (innerBlock2String != null) {
        writer.newLine();
        writer.write("  ");
        writer.write(innerBlock2String.substring(innerBlock2String.indexOf(OPEN_BRACE) + 1,
                innerBlock2String.lastIndexOf(CLOSE_BRACE)).trim());
        writer.newLine();
    }
    if (extensions[5] != null) {
        writer.write(extensions[5]);
    }
    // Close inner second block
    writer.write("  ");
    writer.write(CLOSE_BRACE);
    writer.newLine();
    // Close second block
    writer.write(CLOSE_BRACE);
    writer.newLine();
}

From source file:net.minecraftforge.common.config.Configuration.java

private void save(BufferedWriter out) throws IOException {
    for (ConfigCategory cat : categories.values()) {
        if (!cat.isChild()) {
            cat.write(out, 0);//  ww w  .  j  a  va2  s  .c  o  m
            out.newLine();
        }
    }
}

From source file:ffx.utilities.BlockAverager.java

/**
 * Constructor grabs all histograms from the file and loads them into data
 * structures. TODO: figure out how to disregard histogram-bin combos that
 * aren't (currently) changing per time.
 * @param filename/*from  ww w  .  j a v a  2  s  .  c om*/
 * @param testMode
 * @param grepCmd
 * @param psPerHisto
 * @param blockSizeStep
 * @param maxBlockSize
 * @throws java.io.IOException
 */
public BlockAverager(String filename, boolean testMode, Optional<String> grepCmd, Optional<Double> psPerHisto,
        Optional<Integer> blockSizeStep, Optional<Integer> maxBlockSize) throws IOException {
    this.TEST = testMode;
    this.psPerHisto = (psPerHisto.isPresent()) ? psPerHisto.get() : 1.0;
    this.blockSizeStep = (blockSizeStep.isPresent()) ? blockSizeStep.get() : 100;
    int linesPerHistogram = (System.getProperty("ba-lph") == null) ? 201
            : Integer.parseInt(System.getProperty("ba-lph"));

    if (TEST) {
        logger.info(" Testing Mode ");
        linesPerHistogram = 1;
    }

    File parallelInFile = new File(filename);
    int nThreads = ParallelTeam.getDefaultThreadCount();
    parallelTeam = new ParallelTeam(nThreads);
    numThreads = parallelTeam.getThreadCount();
    BlockRegion parallelBlock = new BlockRegion(parallelInFile);
    try {
        parallelTeam.execute(parallelBlock);
    } catch (Exception ex) {
        Logger.getLogger(BlockAverager.class.getName()).log(Level.SEVERE, null, ex);
    }

    // Step 1: Find histograms and create a stream.
    Scanner scan = null;
    File outFile = null;
    if (preGrep != null) {
        File file = new File(preGrep);
        BufferedReader br = new BufferedReader(new FileReader(file));
        scan = new Scanner(br);
    } else {
        outFile = new File(filename + "-ba.tmp");
        if (outFile.exists()) {
            logger.info(format(" Previous temp file exists: %s", outFile.getName()));
            if (!outFile.canWrite()) {
                logger.severe(format("Lacked write permissions to temp file."));
            }
            System.out.print(format("   Delete it? (Y/N) "));
            Scanner kb = new Scanner(System.in);
            if (kb.nextLine().toUpperCase().startsWith("Y")) {
                outFile.delete();
                logger.info("");
            } else {
                logger.severe("Aborted by user.");
            }
        }

        // Manually accomplish a 'grep -A 201 Bins filename'.
        File inFile = new File(filename);
        BufferedReader br = new BufferedReader(new FileReader(inFile));
        scan = new Scanner(br);
        BufferedWriter bw = new BufferedWriter(new FileWriter(outFile));

        logger.info(" Parsing logfile... ");
        int numFound = 0;
        while (scan.hasNextLine()) {
            String line = scan.nextLine();
            if (TEST) { // No headers in test data.
                if (++numFound % 100 == 0) {
                    logger.info(format("    Parsed %d histograms.", numFound));
                }
                bw.write(line);
                bw.newLine();
                continue;
            }
            if (line.contains("Lambda Bins")) {
                if (++numFound % 100 == 0) {
                    logger.info(format("    Parsed %d histograms.", numFound));
                }
                bw.write(line);
                bw.newLine();
                for (int i = 0; i < linesPerHistogram; i++) {
                    if (!scan.hasNextLine() && i < linesPerHistogram) {
                        logger.warning(format("Found incomplete histogram: %d, %s", numFound, line));
                    }
                    bw.write(scan.nextLine());
                    bw.newLine();
                }
            }
        }
        bw.flush();
        scan = new Scanner(outFile);
    }

    // Parse stream into data structures.
    List<Bin> binList = new ArrayList<>();
    Histogram histo = null;
    while (scan.hasNextLine()) {
        String line = scan.nextLine();
        String[] tokens = line.split("\\s+");
        // Catch grep flotsam.
        if (tokens[0].startsWith("--")) {
            continue;
        }
        // Header line signals time for a new histogram.
        if (line.contains("Lambda Bins") || TEST) {
            if (histo != null) {
                histoList.add(histo);
            }
            histo = new Histogram(++histoIndexer);
            if (histoIndexer % 100 == 0) {
                if (psPerHisto.isPresent()) {
                    logger.info(format(" BlockAverager loaded %d histograms (simTime %.2f ps).", histoIndexer,
                            histoIndexer * this.psPerHisto));
                } else {
                    logger.info(format(" BlockAverager loaded %d histograms.", histoIndexer));
                }
            }
            if (TEST) { // No headers in test data.
                histo.bins.add(new Bin(tokens));
            }
            continue;
        }
        histo.bins.add(new Bin(tokens));
    }
    histoList.add(histo);
    Collections.sort(histoList);
    logger.info(format(""));

    numObs = histoList.size();
    this.maxBlockSize = (maxBlockSize.isPresent()) ? maxBlockSize.get() : numObs;

    // Validate
    for (int i = 1; i < histoList.size(); i++) {
        if (histoList.get(i).index != histoList.get(i - 1).index + 1
                || histoList.get(i).bins.size() != histoList.get(i - 1).bins.size()) {
            logger.warning(format("Improper indexing or bin size mismatch. i,i-1,binsi,binsi-1: %d %d %d %d",
                    histoList.get(i).index, histoList.get(i - 1).index, histoList.get(i).bins.size(),
                    histoList.get(i - 1).bins.size()));
            throw new ArithmeticException();
        }
    }

    if (outFile != null && outFile.exists()) {
        outFile.delete();
    }
    numBins = histoList.get(0).bins.size();
    this.describe();
}

From source file:chibi.gemmaanalysis.OutlierDetectionTestCli.java

/*** Write results to the output file; file name must be given as argument ***/
private void writeResultsToFileBasic(BufferedWriter bw, ExpressionExperiment ee,
        OutlierDetectionTestDetails testDetails) {
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(4);//from www .  j a  v  a  2 s .  c  om
    try {
        // Get information about the experiment:
        ee = this.eeService.thawLite(ee);
        System.out.println("Writing results to file for " + ee.getShortName());
        bw.write(ee.getShortName());
        bw.write("\t" + getPlatforms(ee));
        bw.write("\t" + testDetails.getNumExpFactors());
        if (useRegression) {
            bw.write("\t" + testDetails.getNumSigFactors());
        }
        bw.write("\t" + ee.getBioAssays().size());
        bw.write("\t" + testDetails.getNumOutliers());
        // Get information about each of the outliers:
        for (OutlierDetails outlier : testDetails.getOutliers()) {
            bw.write("\t" + outlier.getBioAssay().getName());
            bw.write("\t" + nf.format(outlier.getThresholdCorrelation()));
            bw.write("\t" + nf.format(outlier.getScore()));
        }
        bw.write("\tlast threshold: " + nf.format(testDetails.getLastThreshold()));
        if (useRegression) {
            for (ExperimentalFactor factor : testDetails.getSignificantFactors()) {
                bw.write("\t" + factor.getName());
            }
        }
        bw.newLine();

    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}