Example usage for org.apache.commons.lang3 StringUtils rightPad

List of usage examples for org.apache.commons.lang3 StringUtils rightPad

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils rightPad.

Prototype

public static String rightPad(final String str, final int size) 

Source Link

Document

Right pad a String with spaces (' ').

The String is padded to the size of size .

 StringUtils.rightPad(null, *)   = null StringUtils.rightPad("", 3)     = "   " StringUtils.rightPad("bat", 3)  = "bat" StringUtils.rightPad("bat", 5)  = "bat  " StringUtils.rightPad("bat", 1)  = "bat" StringUtils.rightPad("bat", -1) = "bat" 

Usage

From source file:info.financialecology.finance.utilities.datastruct.VersatileTimeSeries.java

/**
 * Prints the formatted values of the time series plus a left-hand and 
 * right-hand row label. See {@link #printValues()} for more details 
 * and for parameter dependencies.//from   www.j  av a2 s .co  m
 * <p>
 * @param width the width of the column containing the left-hand row label
 * @param label the row label used in the output (rather than the time 
 * series key
 * @return the sequence of formatted time series values plus the left-hand
 * and right-hand row labels
 * @see #printValues()
 * @see VersatileTimeSeriesCollection#printDecoratedSeries(String, int)
 */
public String printDecoratedValues(String label, int width) {
    String ts = "";
    ts += StringUtils.rightPad(label, width);
    ts += printValues();
    ts += " - " + label;

    return ts;
}

From source file:info.financialecology.finance.utilities.datastruct.VersatileTimeSeriesCollection.java

/**
 * Prints all time series of this collection in a formatted table.
 * <p>//from   w w  w . j a va 2  s .c  o  m
 * Uses the print methods from {@link VersatileTimeSeries}, but
 * adds the index map functionality (see {@link #newIndexMap(
 * String, String, String...)}) and the run and experiment 
 * indices. Rather than just printing one time series, it 
 * prints all time series in a formatted table form, with
 * ticks, times, or dates and an optional row separator.
 * <p>
 * <b>Note:</b> Currently this method uses a single label 
 * (<code>baseName</code>) as the variable name and hence cannot
 * be used to print out a collection that contains time series
 * of different variables. For such a collection, you first need
 * to obtain subsets of time series belonging to the same variable
 * using {@link #getSubset(String)} before printing. You can chain
 * the operations.
 * <p>
 * <b>Example:</b> Operations that return a collection can be chained. 
 * If <code>tscResults</code> is for instance a collection of time 
 * series that include prices, you can print these out by invoking
 * <code>tscResults.getSubset("price").printDecoratedSeries("PRICE", 
 * FIRST_COLUMN_WIDTH)</code> 
 * @param baseName the label used to indicate the variable name
 * @param width the width of the columns that hold the time series values
 * @param ticks true, if ticks, times, or dates are to be shown in a header
 * separated by a row separator. 
 * @return the string containing the formatted time series table
 */
public String printDecoratedSeries(String baseName, int width, Boolean ticks) {
    List<VersatileTimeSeries> atsList = getSeries();
    String atsString = "";
    Boolean isHeaderPrinted = false;

    for (VersatileTimeSeries ats : atsList) { // loops through all time series in this collection
        String label = "";
        String key = (String) ats.getKey();
        //            ArrayList<String> indices = ats.extractVariableIndices(key);
        //            String varName = ats.extractVariableName(key);
        //            HashMap<String, String> map = indexMap.get(varName);
        String exp = ats.extractExperimentIndex(key);
        String run = ats.extractRunIndex(key);

        if (ticks && !isHeaderPrinted) { // print the header only if requested and only once for this table
            atsString = ats.printDecoratedTicks(width) + "\n";
            atsString += ats.printDecoratedRowSeparator(width) + "--------------------\n";
            isHeaderPrinted = true;
        }

        // Generate the variable name and dimension indices (which might be mapped)
        label += StringUtils.rightPad(baseName, width);
        label += mapIndices(ats) + " | ";

        // Generate the run and experiment labels
        if ((exp != null) && (run != null))
            label += "{";

        if (exp != null) {
            label += StringUtils.capitalize(exp);
            if (run != null)
                label += ", ";
        }

        if (run != null)
            label += StringUtils.capitalize(run);

        if ((exp != null) && (run != null))
            label += "}";

        atsString += label + " " + ats.printValues() + "   | " + label + "  " + "\n"; // assemble the output line 
    }

    return atsString; // output string; typically consists of several lines 
}

From source file:net.sourceforge.pmd.benchmark.TextTimingReportRenderer.java

@Override
public void render(final TimingReport report, final Writer writer) throws IOException {
    for (final TimedOperationCategory category : TimedOperationCategory.values()) {
        final Map<String, TimedResult> labeledMeasurements = report.getLabeledMeasurements(category);
        if (!labeledMeasurements.isEmpty()) {
            renderCategoryMeasurements(category, labeledMeasurements, writer);
        }/*from   w w w . j av  a 2 s  .  com*/
    }

    renderHeader("Summary", writer);

    for (final TimedOperationCategory category : TimedOperationCategory.values()) {
        final TimedResult timedResult = report.getUnlabeledMeasurements(category);
        if (timedResult != null) {
            renderMeasurement(category.displayName(), timedResult, writer);
        }
    }

    writer.write(PMD.EOL);
    renderHeader("Total", writer);

    writer.write(StringUtils.rightPad("Wall Clock Time", LABEL_COLUMN_WIDTH));
    final String wallClockTime = MessageFormat.format(TIME_FORMAT, report.getWallClockMillis() / 1000.0);
    writer.write(StringUtils.leftPad(wallClockTime, TIME_COLUMN_WIDTH));
    writer.write(PMD.EOL);

    writer.flush();
}

From source file:net.sourceforge.pmd.benchmark.TextTimingReportRenderer.java

private void renderMeasurement(final String label, final TimedResult timedResult, final Writer writer)
        throws IOException {
    writer.write(StringUtils.rightPad(label, LABEL_COLUMN_WIDTH));

    final String time = MessageFormat.format(TIME_FORMAT, timedResult.totalTimeNanos.get() / 1000000000.0);
    writer.write(StringUtils.leftPad(time, TIME_COLUMN_WIDTH));

    final String selfTime = MessageFormat.format(TIME_FORMAT, timedResult.selfTimeNanos.get() / 1000000000.0);
    writer.write(StringUtils.leftPad(selfTime, SELF_TIME_COLUMN_WIDTH));

    if (timedResult.callCount.get() > 0) {
        final String callCount = MessageFormat.format(CUSTOM_COUNTER_FORMAT, timedResult.callCount.get());
        writer.write(StringUtils.leftPad(callCount, CALL_COLUMN_WIDTH));

        if (timedResult.extraDataCounter.get() > 0) {
            final String counter = MessageFormat.format(CUSTOM_COUNTER_FORMAT,
                    timedResult.extraDataCounter.get());
            writer.write(StringUtils.leftPad(counter, COUNTER_COLUMN_WIDTH));
        }//from   w  w w  .  j av  a  2  s .  c  o m
    }

    writer.write(PMD.EOL);
}

From source file:net.sourceforge.pmd.benchmark.TextTimingReportRenderer.java

private void renderHeader(final String displayName, final Writer writer) throws IOException {
    final StringBuilder sb = new StringBuilder(COLUMNS).append(displayName);

    // Make sure we have an even-length string
    if (displayName.length() % 2 == 1) {
        sb.append(' ');
    }//  w w  w  . j  a v a 2s .  com

    // Surround with <<< and >>>
    sb.insert(0, "<<< ").append(" >>>");

    // Create the ruler
    while (sb.length() < COLUMNS) {
        sb.insert(0, '-').append('-');
    }

    writer.write(sb.toString());
    writer.write(PMD.EOL);

    // Write table titles
    writer.write(StringUtils.rightPad("Label", LABEL_COLUMN_WIDTH));
    writer.write(StringUtils.leftPad("Time (secs)", TIME_COLUMN_WIDTH));
    writer.write(StringUtils.leftPad("Self Time (secs)", SELF_TIME_COLUMN_WIDTH));
    writer.write(StringUtils.leftPad("# Calls", CALL_COLUMN_WIDTH));
    writer.write(StringUtils.leftPad("Counter", COUNTER_COLUMN_WIDTH));
    writer.write(PMD.EOL);
    writer.write(PMD.EOL);
}

From source file:nz.co.testamation.common.util.StringUtil.java

public static String truncateAndRightPad(String value, int size) {
    return StringUtils.rightPad(StringUtil.truncate(value, size), size);
}

From source file:org.apache.mahout.benchmark.VectorBenchmarks.java

@Override
public String toString() {
    int pad = 24;
    StringBuilder sb = new StringBuilder(1000);
    sb.append(StringUtils.rightPad("BenchMarks", pad));
    for (int i = 0; i < implType.size(); i++) {
        for (Entry<String, Integer> e : implType.entrySet()) {
            if (e.getValue() == i) {
                sb.append(StringUtils.rightPad(e.getKey(), pad).substring(0, pad));
                break;
            }// ww  w  .  j a v a2 s.  co  m
        }
    }
    sb.append('\n');
    List<String> keys = Lists.newArrayList(statsMap.keySet());
    Collections.sort(keys);
    for (String benchmarkName : keys) {
        List<String[]> implTokenizedStats = statsMap.get(benchmarkName);
        int maxStats = 0;
        for (String[] stat : implTokenizedStats) {
            maxStats = Math.max(maxStats, stat.length);
        }

        for (int i = 0; i < maxStats; i++) {
            boolean printedName = false;
            for (String[] stats : implTokenizedStats) {
                if (i == 0 && !printedName) {
                    sb.append(StringUtils.rightPad(benchmarkName, pad));
                    printedName = true;
                } else if (!printedName) {
                    printedName = true;
                    sb.append(StringUtils.rightPad("", pad));
                }
                if (stats.length > i) {
                    sb.append(StringUtils.rightPad(stats[i], pad));
                } else {
                    sb.append(StringUtils.rightPad("", pad));
                }

            }
            sb.append('\n');
        }
        sb.append('\n');
    }
    return sb.toString();
}

From source file:org.apache.mahout.classifier.ConfusionMatrix.java

/**
 * This is overloaded. toString() is not a formatted report you print for a manager :)
 * Assume that if there are no default assignments, the default feature was not used
 *///from  w ww  .j a va2s.  c o m
@Override
public String toString() {
    StringBuilder returnString = new StringBuilder(200);
    returnString.append("=======================================================").append('\n');
    returnString.append("Confusion Matrix\n");
    returnString.append("-------------------------------------------------------").append('\n');

    int unclassified = getTotal(defaultLabel);
    for (Map.Entry<String, Integer> entry : this.labelMap.entrySet()) {
        if (entry.getKey().equals(defaultLabel) && unclassified == 0) {
            continue;
        }

        returnString.append(StringUtils.rightPad(getSmallLabel(entry.getValue()), 5)).append('\t');
    }

    returnString.append("<--Classified as").append('\n');
    for (Map.Entry<String, Integer> entry : this.labelMap.entrySet()) {
        if (entry.getKey().equals(defaultLabel) && unclassified == 0) {
            continue;
        }
        String correctLabel = entry.getKey();
        int labelTotal = 0;
        for (String classifiedLabel : this.labelMap.keySet()) {
            if (classifiedLabel.equals(defaultLabel) && unclassified == 0) {
                continue;
            }
            returnString
                    .append(StringUtils.rightPad(Integer.toString(getCount(correctLabel, classifiedLabel)), 5))
                    .append('\t');
            labelTotal += getCount(correctLabel, classifiedLabel);
        }
        returnString.append(" |  ").append(StringUtils.rightPad(String.valueOf(labelTotal), 6)).append('\t')
                .append(StringUtils.rightPad(getSmallLabel(entry.getValue()), 5)).append(" = ")
                .append(correctLabel).append('\n');
    }
    if (unclassified > 0) {
        returnString.append("Default Category: ").append(defaultLabel).append(": ").append(unclassified)
                .append('\n');
    }
    returnString.append('\n');
    return returnString.toString();
}

From source file:org.apache.mahout.classifier.RegressionResultAnalyzer.java

@Override
public String toString() {
    double sumActual = 0.0;
    double sumActualSquared = 0.0;
    double sumResult = 0.0;
    double sumResultSquared = 0.0;
    double sumActualResult = 0.0;
    double sumAbsolute = 0.0;
    double sumAbsoluteSquared = 0.0;
    int predictable = 0;
    int unpredictable = 0;

    for (Result res : results) {
        double actual = res.getActual();
        double result = res.getResult();
        if (Double.isNaN(result)) {
            unpredictable++;/*from ww w.  ja v a2 s  . c om*/
        } else {
            sumActual += actual;
            sumActualSquared += actual * actual;
            sumResult += result;
            sumResultSquared += result * result;
            sumActualResult += actual * result;
            double absolute = Math.abs(actual - result);
            sumAbsolute += absolute;
            sumAbsoluteSquared += absolute * absolute;
            predictable++;
        }
    }

    StringBuilder returnString = new StringBuilder();

    returnString.append("=======================================================\n");
    returnString.append("Summary\n");
    returnString.append("-------------------------------------------------------\n");

    if (predictable > 0) {
        double varActual = sumActualSquared - sumActual * sumActual / predictable;
        double varResult = sumResultSquared - sumResult * sumResult / predictable;
        double varCo = sumActualResult - sumActual * sumResult / predictable;

        double correlation;
        if (varActual * varResult <= 0) {
            correlation = 0.0;
        } else {
            correlation = varCo / Math.sqrt(varActual * varResult);
        }

        Locale.setDefault(Locale.US);
        NumberFormat decimalFormatter = new DecimalFormat("0.####");

        returnString.append(StringUtils.rightPad("Correlation coefficient", 40)).append(": ")
                .append(StringUtils.leftPad(decimalFormatter.format(correlation), 10)).append('\n');
        returnString.append(StringUtils.rightPad("Mean absolute error", 40)).append(": ")
                .append(StringUtils.leftPad(decimalFormatter.format(sumAbsolute / predictable), 10))
                .append('\n');
        returnString.append(StringUtils.rightPad("Root mean squared error", 40)).append(": ")
                .append(StringUtils
                        .leftPad(decimalFormatter.format(Math.sqrt(sumAbsoluteSquared / predictable)), 10))
                .append('\n');
    }
    returnString.append(StringUtils.rightPad("Predictable Instances", 40)).append(": ")
            .append(StringUtils.leftPad(Integer.toString(predictable), 10)).append('\n');
    returnString.append(StringUtils.rightPad("Unpredictable Instances", 40)).append(": ")
            .append(StringUtils.leftPad(Integer.toString(unpredictable), 10)).append('\n');
    returnString.append(StringUtils.rightPad("Total Regressed Instances", 40)).append(": ")
            .append(StringUtils.leftPad(Integer.toString(results.size()), 10)).append('\n');
    returnString.append('\n');

    return returnString.toString();
}

From source file:org.apache.mahout.classifier.ResultAnalyzer.java

@Override
public String toString() {
    StringBuilder returnString = new StringBuilder();

    returnString.append('\n');
    returnString.append("=======================================================\n");
    returnString.append("Summary\n");
    returnString.append("-------------------------------------------------------\n");
    int totalClassified = correctlyClassified + incorrectlyClassified;
    double percentageCorrect = (double) 100 * correctlyClassified / totalClassified;
    double percentageIncorrect = (double) 100 * incorrectlyClassified / totalClassified;
    NumberFormat decimalFormatter = new DecimalFormat("0.####");

    returnString.append(StringUtils.rightPad("Correctly Classified Instances", 40)).append(": ")
            .append(StringUtils.leftPad(Integer.toString(correctlyClassified), 10)).append('\t')
            .append(StringUtils.leftPad(decimalFormatter.format(percentageCorrect), 10)).append("%\n");
    returnString.append(StringUtils.rightPad("Incorrectly Classified Instances", 40)).append(": ")
            .append(StringUtils.leftPad(Integer.toString(incorrectlyClassified), 10)).append('\t')
            .append(StringUtils.leftPad(decimalFormatter.format(percentageIncorrect), 10)).append("%\n");
    returnString.append(StringUtils.rightPad("Total Classified Instances", 40)).append(": ")
            .append(StringUtils.leftPad(Integer.toString(totalClassified), 10)).append('\n');
    returnString.append('\n');

    returnString.append(confusionMatrix);
    returnString.append("=======================================================\n");
    returnString.append("Statistics\n");
    returnString.append("-------------------------------------------------------\n");

    RunningAverageAndStdDev normStats = confusionMatrix.getNormalizedStats();
    returnString.append(StringUtils.rightPad("Kappa", 40))
            .append(StringUtils.leftPad(decimalFormatter.format(confusionMatrix.getKappa()), 10)).append('\n');
    returnString.append(StringUtils.rightPad("Accuracy", 40))
            .append(StringUtils.leftPad(decimalFormatter.format(confusionMatrix.getAccuracy()), 10))
            .append("%\n");
    returnString.append(StringUtils.rightPad("Reliability", 40))
            .append(StringUtils.leftPad(decimalFormatter.format(normStats.getAverage() * 100.00000001), 10))
            .append("%\n");
    returnString.append(StringUtils.rightPad("Reliability (standard deviation)", 40))
            .append(StringUtils.leftPad(decimalFormatter.format(normStats.getStandardDeviation()), 10))
            .append('\n');
    returnString.append(StringUtils.rightPad("Weighted precision", 40))
            .append(StringUtils.leftPad(decimalFormatter.format(confusionMatrix.getWeightedPrecision()), 10))
            .append('\n');
    returnString.append(StringUtils.rightPad("Weighted recall", 40))
            .append(StringUtils.leftPad(decimalFormatter.format(confusionMatrix.getWeightedRecall()), 10))
            .append('\n');
    returnString.append(StringUtils.rightPad("Weighted F1 score", 40))
            .append(StringUtils.leftPad(decimalFormatter.format(confusionMatrix.getWeightedF1score()), 10))
            .append('\n');

    if (hasLL) {/*from w w  w  . ja va  2s  .  c  o  m*/
        returnString.append(StringUtils.rightPad("Log-likelihood", 30)).append("mean      : ")
                .append(StringUtils.leftPad(decimalFormatter.format(summarizer.getMean()), 10)).append('\n');
        returnString.append(StringUtils.rightPad("", 30)).append(StringUtils.rightPad("25%-ile   : ", 10))
                .append(StringUtils.leftPad(decimalFormatter.format(summarizer.getQuartile(1)), 10))
                .append('\n');
        returnString.append(StringUtils.rightPad("", 30)).append(StringUtils.rightPad("75%-ile   : ", 10))
                .append(StringUtils.leftPad(decimalFormatter.format(summarizer.getQuartile(3)), 10))
                .append('\n');
    }

    return returnString.toString();
}