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

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

Introduction

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

Prototype

public static String leftPad(final String str, final int size, String padStr) 

Source Link

Document

Left pad a String with a specified String.

Pad to a size of size .

 StringUtils.leftPad(null, *, *)      = null StringUtils.leftPad("", 3, "z")      = "zzz" StringUtils.leftPad("bat", 3, "yz")  = "bat" StringUtils.leftPad("bat", 5, "yz")  = "yzbat" StringUtils.leftPad("bat", 8, "yz")  = "yzyzybat" StringUtils.leftPad("bat", 1, "yz")  = "bat" StringUtils.leftPad("bat", -1, "yz") = "bat" StringUtils.leftPad("bat", 5, null)  = "  bat" StringUtils.leftPad("bat", 5, "")    = "  bat" 

Usage

From source file:com.netsteadfast.greenstep.bsc.util.PerformanceScoreChainUtils.java

private static void setScore(MonitorItemScoreVO itemScoreObj, float score) {
    String scoreStr = BscReportSupportUtils.parse2(score);
    if (scoreStr.length() > MAX_SCORE_FIELD_SIZE) {
        String tmp[] = scoreStr.split("[.]");
        if (tmp.length != 2) { // 123123123123123
            scoreStr = StringUtils.leftPad("", MAX_SCORE_FIELD_SIZE, "9");
        } else { // 1234567891234.23
            if (tmp[0].length() > MAX_SCORE_FIELD_SIZE) {
                scoreStr = StringUtils.leftPad("", MAX_SCORE_FIELD_SIZE, "9");
            } else {
                scoreStr = scoreStr.substring(0, MAX_SCORE_FIELD_SIZE);
            }//from  w  ww.j  ava2s.c o  m
        }
    }
    itemScoreObj.setScore(scoreStr);
}

From source file:com.tcay.slalom.timingDevices.MicrogateREI2.MicrogateAgent.java

private String toTimeOfDay(String time) {
    String timeOfDay = null;//from   ww  w . j  ava  2s .  c  om
    Long seconds = getSecondsOnly(time);
    Long hundreths = getHundreths(time);
    Long hours = toHours(time);//seconds);//(seconds/(60*60));
    Long minutes = toMinutes(time);//(seconds, hours);//(seconds - hours*60*60) / 60l;
    seconds %= 60; /// discard portion > 59, we will indicate that in minutes here/// needed ???

    //Long tenThousanths = Long.valueOf(time)%10000;

    String sMinutes = StringUtils.leftPad(minutes.toString(), 2, "0");
    String sSeconds = StringUtils.leftPad(seconds.toString(), 2, "0");
    String sHundreths = StringUtils.leftPad(hundreths.toString(), 2, "0");

    //logRaw.info("TIME IN SECONDS " + minutesAndSecondsTotSeconds(time));
    timeOfDay = hours + ":" + sMinutes + ":" + sSeconds + "." + sHundreths;
    return (timeOfDay);

}

From source file:net.ontopia.topicmaps.nav2.portlets.pojos.MenuUtils.java

/**
 * Create a child (Heading or Item) of the parent represented by a given topic
 * @param topic The topic of the parent.
 * @param title The title of the new child.
 * @param isHeading true to create a Heading, false to create an Item.
 * @return//from w  w w  .ja v  a 2 s.  c o  m
 */
private static Menu.ChildIF createChild(TopicIF topic, String title, boolean isHeading) {
    TopicMapIF tm = topic.getTopicMap();
    TopicMapBuilderIF builder = tm.getBuilder();
    QueryProcessorIF qp = QueryUtils.getQueryProcessor(tm);
    DeclarationContextIF dc = optimisticParse(tm, "using menu for i\"http://psi.ontopia.net/portal/menu/\"");

    TopicIF itemIFTopicType = getTopic(isHeading ? "menu:heading" : "menu:item", tm);
    TopicIF parentChildAssociation = getTopic("menu:parent-child", tm);
    TopicIF parentRoleType = getTopic("menu:parent", tm);
    TopicIF childRoleType = getTopic("menu:child", tm);
    TopicIF sortOccurrenceType = getTopic("menu:sort", tm);

    ParsedQueryIF sortKeysQuery = optimisticParse(qp, dc,
            "select $SORT from " + "menu:parent-child(%topic% : menu:parent, $CHILD : menu:child), "
                    + "{ menu:sort($CHILD, $SORT) } order by $SORT?");

    // Create the heading topic.
    TopicIF itemIFTopic = builder.makeTopic(itemIFTopicType);

    // Make the heading child of the menu.
    AssociationIF assoc = builder.makeAssociation(parentChildAssociation);
    builder.makeAssociationRole(assoc, parentRoleType, topic);
    builder.makeAssociationRole(assoc, childRoleType, itemIFTopic);

    // Get the highest sort key of children of this menu.
    String lastSortKey = getLastValue(topic, sortKeysQuery);
    int lastSortKeyInt = Integer.parseInt(lastSortKey);
    lastSortKeyInt++;
    String newSortKey = StringUtils.leftPad(Integer.toString(lastSortKeyInt), 3, '0');
    builder.makeOccurrence(itemIFTopic, sortOccurrenceType, newSortKey);

    Menu.ChildIF itemIF;
    if (isHeading)
        itemIF = new Heading(itemIFTopic);
    else
        itemIF = new Item(itemIFTopic);
    itemIF.setTitle(title);
    return itemIF;
}

From source file:ca.uhn.fhir.model.primitive.BaseDateTimeDt.java

/**
 * Sets the value for this type using the given Java Date object as the time, and using the specified precision, as
 * well as the local timezone as determined by the local operating system. Both of
 * these properties may be modified in subsequent calls if neccesary.
 * /*  w  w  w .j a  va 2  s.co  m*/
 * @param theValue
 *           The date value
 * @param thePrecision
 *           The precision
 * @throws DataFormatException
 */
public void setValue(Date theValue, TemporalPrecisionEnum thePrecision) throws DataFormatException {
    if (getTimeZone() == null) {
        setTimeZone(TimeZone.getDefault());
    }
    myPrecision = thePrecision;
    myFractionalSeconds = "";
    if (theValue != null) {
        long millis = theValue.getTime() % 1000;
        if (millis < 0) {
            // This is for times before 1970 (see bug #444)
            millis = 1000 + millis;
        }
        String fractionalSeconds = Integer.toString((int) millis);
        myFractionalSeconds = StringUtils.leftPad(fractionalSeconds, 3, '0');
    }
    super.setValue(theValue);
}

From source file:integration.MigrationTest.java

private CharSequence asJavaString(String rawString) {
    StringBuilder b = new StringBuilder();
    for (char c : rawString.toCharArray()) {
        if (c >= 32 && c < 128) {
            b.append(c);//  w ww  .j a v  a2  s  .  c o  m
        } else {
            b.append("\\u").append(StringUtils.leftPad(Integer.toHexString(c & 0xffff), 4, '0'));
        }
    }
    return b;
}

From source file:com.jkoolcloud.jesl.simulator.TNT4JSimulator.java

private static int printProgress(String text, long iteration, int trcWidth) {
    if (numIterations == 1)
        return 0;

    int itPct = (int) ((double) iteration / numIterations * 100.0);
    int maxItWidth = (int) (Math.log10(numIterations) + 1);
    String bkSpStr = StringUtils.leftPad("", trcWidth, '\b');
    String trcMsg = String.format(bkSpStr + "%" + maxItWidth + "d (%02d%%)", iteration, itPct);
    trcWidth = trcMsg.length() - bkSpStr.length();
    System.out.print(trcMsg);/*from  ww  w .  jav a2  s  .c o m*/
    return trcWidth;
}

From source file:ca.uhn.fhir.model.primitive.BaseDateTimeDt.java

/**
 * Sets the nanoseconds within the current second
 * <p>// w  w w  . j  ava2 s .c  om
 * Note that this method sets the
 * same value as {@link #setMillis(int)} but with more precision.
 * </p>
 */
public BaseDateTimeDt setNanos(long theNanos) {
    validateValueInRange(theNanos, 0, NANOS_PER_SECOND - 1);
    String fractionalSeconds = StringUtils.leftPad(Long.toString(theNanos), 9, '0');

    // Strip trailing 0s
    for (int i = fractionalSeconds.length(); i > 0; i--) {
        if (fractionalSeconds.charAt(i - 1) != '0') {
            fractionalSeconds = fractionalSeconds.substring(0, i);
            break;
        }
    }
    int millis = (int) (theNanos / NANOS_PER_MILLIS);
    setFieldValue(Calendar.MILLISECOND, millis, fractionalSeconds, 0, 999);
    return this;
}

From source file:ca.uhn.fhir.model.primitive.BaseDateTimeDt.java

private void setFieldValue(int theField, int theValue, String theFractionalSeconds, int theMinimum,
        int theMaximum) {
    validateValueInRange(theValue, theMinimum, theMaximum);
    Calendar cal;// ww w  .  j a  v a  2  s.  com
    if (getValue() == null) {
        cal = new GregorianCalendar(0, 0, 0);
    } else {
        cal = getValueAsCalendar();
    }
    if (theField != -1) {
        cal.set(theField, theValue);
    }
    if (theFractionalSeconds != null) {
        myFractionalSeconds = theFractionalSeconds;
    } else if (theField == Calendar.MILLISECOND) {
        myFractionalSeconds = StringUtils.leftPad(Integer.toString(theValue), 3, '0');
    }
    super.setValue(cal.getTime());
}

From source file:eu.amidst.dynamic.inference.DynamicMAPInference.java

/**
 * Runs the inference given an input search algorithm.
 * @param searchAlgorithm a valid {@link SearchAlgorithm} value.
 *///w  w  w  .jav  a2 s .  c om
public void runInference(SearchAlgorithm searchAlgorithm) {

    if (MAPvariable == null || MAPvarName == null) {
        System.out.println("Error: The MAP variable has not been set");
        System.exit(-30);
    }

    if (this.mergedClassVarModels == null) {
        this.computeMergedClassVarModels();
    }

    if (this.unfoldedStaticModel == null) {
        unfoldedStaticModel = DynamicToStaticBNConverter.convertDBNtoBN(model, nTimeSteps);
    }

    //
    //        if (evidence!=null && staticEvidence==null) {
    //
    //            staticEvidence = new HashMapAssignment(staticEvenModel.getNumberOfVars());
    //
    //            evidence.stream().forEach(dynamicAssignment -> {
    //                int time = (int) dynamicAssignment.getTimeID();
    //                Set<Variable> dynAssigVariables = dynamicAssignment.getVariables();
    //                for (Variable dynVariable : dynAssigVariables) {
    //                    Variable staticVariable = staticEvenModel.getVariables().getVariableByName(dynVariable.getName() + "_t" + Integer.toString(time));
    //                    double varValue = dynamicAssignment.getValue(dynVariable);
    //                    staticEvidence.setValue(staticVariable, varValue);
    //                }
    //
    //            });
    //        }
    //

    if (evidence != null && staticEvidence == null) {

        staticEvidence = new HashMapAssignment(unfoldedStaticModel.getNumberOfVars());

        evidence.stream().forEach(dynamicAssignment -> {
            int time = (int) dynamicAssignment.getTimeID();
            Set<Variable> dynAssigVariables = dynamicAssignment.getVariables();
            for (Variable dynVariable : dynAssigVariables) {
                Variable staticVariable = unfoldedStaticModel.getVariables()
                        .getVariableByName(dynVariable.getName() + "_t" + Integer.toString(time));
                double varValue = dynamicAssignment.getValue(dynVariable);
                staticEvidence.setValue(staticVariable, varValue);
            }
        });
    }

    List<InferenceAlgorithm> staticModelsInference = new ArrayList<>(nMergedClassVars);
    IntStream.range(0, nMergedClassVars).forEachOrdered(i -> {
        InferenceAlgorithm currentModelInference;
        switch (searchAlgorithm) {
        case VMP:
            currentModelInference = new VMP();
            //((VMP)currentModelInference).setTestELBO(true);
            ((VMP) currentModelInference).setThreshold(0.0001);
            ((VMP) currentModelInference).setMaxIter(3000);
            break;

        case IS:
        default:

            currentModelInference = new ImportanceSamplingRobust();

            Random random = new Random((this.seed));
            currentModelInference.setSeed(random.nextInt());

            this.seed = random.nextInt();

            ((ImportanceSamplingRobust) currentModelInference).setSampleSize(sampleSize);

            break;
        }
        currentModelInference.setParallelMode(this.parallelMode);
        currentModelInference.setModel(mergedClassVarModels.get(i));

        if (searchAlgorithm == SearchAlgorithm.IS) {
            ((ImportanceSamplingRobust) currentModelInference)
                    .setVariablesAPosteriori(mergedClassVarModels.get(i).getVariables().getListOfVariables()
                            .stream().filter(variable -> variable.getName().contains(groupedClassName))
                            .collect(Collectors.toList()));
        }

        BayesianNetwork thisModel = mergedClassVarModels.get(i);

        if (staticEvidence != null) {
            Assignment thisEvidence = new HashMapAssignment();
            for (Variable varEvidence : staticEvidence.getVariables()) {
                thisEvidence.setValue(thisModel.getVariables().getVariableByName(varEvidence.getName()),
                        staticEvidence.getValue(varEvidence));
            }
            currentModelInference.setEvidence(thisEvidence);
        }
        currentModelInference.runInference();

        //System.out.println(currentModelInference.getLogProbabilityOfEvidence());

        staticModelsInference.add(currentModelInference);
    });
    //
    //        IntStream.range(0, 2).parallel().forEach(i -> {
    //            if (i == 0) {
    //                evenModelInference.setParallelMode(this.parallelMode);
    //                evenModelInference.setModel(staticEvenModel);
    //                if (evidence != null) {
    //                    evenModelInference.setEvidence(staticEvidence);
    //                }
    //                evenModelInference.runInference();
    //            }
    //            else {
    //                oddModelInference.setParallelMode(this.parallelMode);
    //                oddModelInference.setModel(staticOddModel);
    //                if (evidence != null) {
    //                    oddModelInference.setEvidence(staticEvidence);
    //                }
    //                oddModelInference.runInference();
    //            }
    //        });

    List<List<UnivariateDistribution>> posteriorMAPDistributions = new ArrayList<>();
    IntStream.range(0, nMergedClassVars).forEachOrdered(modelNumber -> {

        List<UnivariateDistribution> currentModelPosteriorMAPDistributions = new ArrayList<>();
        int nReplicationsMAPVariable = (modelNumber == 0 ? 0 : 1)
                + (nTimeSteps - modelNumber) / nMergedClassVars
                + ((nTimeSteps - modelNumber) % nMergedClassVars == 0 ? 0 : 1);

        IntStream.range(0, nReplicationsMAPVariable).forEachOrdered(i -> {
            currentModelPosteriorMAPDistributions.add(staticModelsInference.get(modelNumber).getPosterior(i));
            //System.out.println(staticModelsInference.get(modelNumber).getPosterior(i).toString());
        });

        posteriorMAPDistributions.add(currentModelPosteriorMAPDistributions);
    });

    //        int replicationsMAPVariableEvenModel = nTimeSteps/2 + nTimeSteps%2;
    //        IntStream.range(0,replicationsMAPVariableEvenModel).forEachOrdered(i -> posteriorMAPDistributionsEvenModel.add(evenModelInference.getPosterior(i)));
    //
    //        int replicationsMAPVariableOddModel = 1 + (nTimeSteps-1)/2 + (nTimeSteps-1)%2;
    //        IntStream.range(0,replicationsMAPVariableOddModel).forEachOrdered(i -> posteriorMAPDistributionsOddModel.add(oddModelInference.getPosterior(i)));

    posteriorMAPDistributions.forEach(list -> {

        StringBuilder stringBuilder = new StringBuilder();

        list.forEach(uniDist -> {
            stringBuilder.append(Arrays.toString(uniDist.getParameters()));
            stringBuilder.append(" ,  ");
        });
        //System.out.println("Model number " + posteriorMAPDistributions.indexOf(list) + ": " + stringBuilder.toString());
    });

    allGroupedPosteriorDistributions = posteriorMAPDistributions;

    bestSequenceEachModel = new ArrayList<>();
    IntStream.range(0, nMergedClassVars).forEachOrdered(modelNumber -> {
        int[] thisModelBestSequence = new int[nTimeSteps];
        int indexSequence = 0;

        List<UnivariateDistribution> thisModelPosteriors = posteriorMAPDistributions.get(modelNumber);

        for (int k = 0; k < thisModelPosteriors.size(); k++) {
            UnivariateDistribution thisDistribution = thisModelPosteriors.get(k);

            int indexMaxProbability = (int) argMax(thisDistribution.getParameters())[1];
            int thisDistribNumberOfMergedVars = (int) Math
                    .round(Math.log(thisDistribution.getVariable().getNumberOfStates())
                            / Math.log(MAPvariable.getNumberOfStates()));

            String m_base_nStates = Integer.toString(
                    Integer.parseInt(Integer.toString(indexMaxProbability), 10),
                    MAPvariable.getNumberOfStates());
            m_base_nStates = StringUtils.leftPad(m_base_nStates, thisDistribNumberOfMergedVars, '0');

            for (int j = 0; j < m_base_nStates.length(); j++) {
                thisModelBestSequence[indexSequence] = Integer.parseInt(m_base_nStates.substring(j, j + 1));
                indexSequence++;
            }
        }

        //System.out.println("Best sequence model " + modelNumber + ": " + Arrays.toString(thisModelBestSequence));
        bestSequenceEachModel.add(thisModelBestSequence);
    });

    List<double[]> conditionalDistributionsMAPvariable = obtainMAPVariableConditionalDistributions(
            posteriorMAPDistributions);
    //System.out.println("Cond Distributions: " + Arrays.toString(conditionalDistributionsMAPvariable));

    StringBuilder stringBuilder = new StringBuilder();
    conditionalDistributionsMAPvariable.forEach(conDistr -> {

        stringBuilder.append(Arrays.toString(conDistr));
        stringBuilder.append(" ,  ");
    });
    //System.out.println("Combined Conditional Distributions: \n" + stringBuilder.toString());

    computeMostProbableSequence(conditionalDistributionsMAPvariable);

}

From source file:org.osgp.adapter.protocol.dlms.domain.commands.DlmsHelperService.java

private String byteArrayToString(final byte[] bitStringValue) {
    if (bitStringValue == null || bitStringValue.length == 0) {
        return null;
    }// w ww  . j a va 2 s. co m
    final StringBuilder sb = new StringBuilder();
    for (final byte element : bitStringValue) {
        sb.append(StringUtils.leftPad(Integer.toBinaryString(element & 0xFF), 8, "0"));
        sb.append(" ");
    }
    return sb.toString();
}