Example usage for com.google.common.base Strings padStart

List of usage examples for com.google.common.base Strings padStart

Introduction

In this page you can find the example usage for com.google.common.base Strings padStart.

Prototype

public static String padStart(String string, int minLength, char padChar) 

Source Link

Document

Returns a string, of length at least minLength , consisting of string prepended with as many copies of padChar as are necessary to reach that length.

Usage

From source file:tech.tablesaw.columns.datetimes.DateTimeMapFunctions.java

/**
 * Returns a StringColumn with the year and day-of-year derived from this column concatenated into a String
 * that will sort lexicographically in temporal order.
 * <p>//from   ww  w  .j  av a 2s . c o m
 * This simplifies the production of plots and tables that aggregate values into standard temporal units (e.g.,
 * you want monthly data but your source data is more than a year long and you don't want months from different
 * years aggregated together).
 */
default StringColumn yearDay() {
    StringColumn newColumn = StringColumn.create(this.name() + " year & month");
    for (int r = 0; r < this.size(); r++) {
        long c1 = this.getLongInternal(r);
        if (DateTimeColumn.valueIsMissing(c1)) {
            newColumn.append(StringColumnType.missingValueIndicator());
        } else {
            String ym = String.valueOf(getYear(c1));
            ym = ym + "-" + Strings.padStart(String.valueOf(getDayOfYear(c1)), 3, '0');
            newColumn.append(ym);
        }
    }
    return newColumn;
}

From source file:org.apache.drill.exec.store.parquet.ParquetResultListener.java

public void printRowMajor(RecordBatchLoader batchLoader) {
    for (int i = 0; i < batchLoader.getRecordCount(); i++) {
        if (i % 50 == 0) {
            System.out.println();
            for (VectorWrapper vw : batchLoader) {
                ValueVector v = vw.getValueVector();
                System.out.print(
                        Strings.padStart(v.getField().getAsSchemaPath().getRootSegment().getPath(), 20, ' ')
                                + " ");

            }/*from   ww  w.ja v a  2  s  . co  m*/
            System.out.println();
            System.out.println();
        }

        for (final VectorWrapper vw : batchLoader) {
            final ValueVector v = vw.getValueVector();
            Object o = v.getAccessor().getObject(i);
            if (o instanceof byte[]) {
                try {
                    // TODO - in the dictionary read error test there is some data that does not look correct
                    // the output of our reader matches the values of the parquet-mr cat/head tools (no full comparison was made,
                    // but from a quick check of a few values it looked consistent
                    // this might have gotten corrupted by pig somehow, or maybe this is just how the data is supposed ot look
                    // TODO - check this!!
                    //              for (int k = 0; k < ((byte[])o).length; k++ ) {
                    //                // check that the value at each position is a valid single character ascii value.
                    //
                    //                if (((byte[])o)[k] > 128) {
                    //                  System.out.println("batch: " + batchCounter + " record: " + recordCount);
                    //                }
                    //              }
                    o = new String((byte[]) o, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.print(Strings.padStart(o + "", 20, ' ') + " ");
        }
        System.out.println();
    }
}

From source file:com.dmdirc.ServerEventHandler.java

@Handler
public void onNumeric(final NumericEvent event) {
    final String sansIrcd = "numeric_" + Strings.padStart(String.valueOf(event.getNumeric()), 3, '0');
    String target = "";

    if (owner.getConfigManager().hasOptionString("formatter", sansIrcd)) {
        target = sansIrcd;/* w w  w .j a  v  a2 s . c  o m*/
    } else if (owner.getConfigManager().hasOptionString("formatter", "numeric_unknown")) {
        target = "numeric_unknown";
    }

    final ServerNumericEvent coreEvent = new ServerNumericEvent(owner, event.getNumeric(), event.getToken());
    final String format = EventUtils.postDisplayable(eventBus, coreEvent, target);
    owner.handleNotification(format, (Object[]) event.getToken());
}

From source file:entities.InvMovimiento.java

public String determinarNumConcecutivo() {
    int fin = cfgDocumento.getFinDocumento();
    String aux = String.valueOf(fin);
    String numDocumento = String.valueOf(getInvMovimientoPK().getNumDoc());
    return cfgDocumento.getPrefijoDoc().concat(Strings.padStart(numDocumento, aux.length(), '0'));
}

From source file:com.netflix.spinnaker.clouddriver.aws.agent.ReconcileClassicLinkSecurityGroupsAgent.java

void reconcileInstances(AmazonEC2 ec2, Map<String, String> groupNamesToIds,
        Collection<ClassicLinkInstance> instances) {
    StringBuilder report = new StringBuilder();
    for (ClassicLinkInstance i : instances) {
        List<String> existingClassicLinkGroups = i.getGroups().stream().map(GroupIdentifier::getGroupId)
                .collect(Collectors.toList());

        int maxNewGroups = deployDefaults.getMaxClassicLinkSecurityGroups() - existingClassicLinkGroups.size();
        if (maxNewGroups > 0) {
            String asgName = i.getTags().stream().filter(t -> AUTOSCALING_TAG.equals(t.getKey()))
                    .map(Tag::getValue).findFirst().orElse(null);

            List<String> candidateGroupNames = getSecurityGroupNames(asgName);

            List<String> missingGroupIds = candidateGroupNames.stream().map(groupNamesToIds::get)
                    .filter(name -> name != null && !existingClassicLinkGroups.contains(name))
                    .limit(maxNewGroups).collect(Collectors.toList());

            if (!missingGroupIds.isEmpty()) {
                List<String> groupIds = new ArrayList<>(existingClassicLinkGroups);
                groupIds.addAll(missingGroupIds);
                if (deployDefaults
                        .getReconcileClassicLinkSecurityGroups() == AwsConfiguration.DeployDefaults.ReconcileMode.MODIFY) {
                    try {
                        ec2.attachClassicLinkVpc(new AttachClassicLinkVpcRequest().withVpcId(i.getVpcId())
                                .withGroups(groupIds).withInstanceId(i.getInstanceId()));
                    } catch (AmazonServiceException ase) {
                        log.warn("Failed calling attachClassicLinkVpc", ase);
                    }//  w  w  w  .ja v a  2  s  .  c  om
                }
                report.append("\n\t").append(Strings.padStart(i.getInstanceId(), 24, ' '))
                        .append(missingGroupIds);
            }
        }
    }
    if (report.length() > 0) {
        log.info("Attach to classicLinkVpc: account: " + account.getName() + ", region: " + region + report);
    }
}

From source file:tech.tablesaw.columns.datetimes.DateTimeMapFunctions.java

/**
 * Returns a StringColumn with the year and week-of-year derived from this column concatenated into a String
 * that will sort lexicographically in temporal order.
 * <p>//from  ww w.j a v  a 2s  . com
 * This simplifies the production of plots and tables that aggregate values into standard temporal units (e.g.,
 * you want monthly data but your source data is more than a year long and you don't want months from different
 * years aggregated together).
 */
default StringColumn hourMinute() {
    StringColumn newColumn = StringColumn.create(this.name() + " hour & minute");
    for (int r = 0; r < this.size(); r++) {
        long c1 = this.getLongInternal(r);
        if (DateTimeColumn.valueIsMissing(c1)) {
            newColumn.append(StringColumnType.missingValueIndicator());
        } else {
            String hm = Strings.padStart(String.valueOf(getHour(c1)), 2, '0');
            hm = hm + ":" + Strings.padStart(String.valueOf(getMinute(c1)), 2, '0');
            newColumn.append(hm);
        }
    }
    return newColumn;
}

From source file:pt.scanner.server.main.Scanner.java

@Override
public void run() {
    try {/*from w w w .ja  va  2s .co  m*/
        final Mat grayImg = imread(String.format("%s/calibration/background.jpg", root),
                CV_LOAD_IMAGE_GRAYSCALE);
        Utils.showImage(grayImg, 1000);
        Mat binImg = new Mat(grayImg.size(), CV_8UC1, BLACK);
        threshold(grayImg, binImg, 100, 255, CV_THRESH_BINARY);
        Utils.showImage(binImg, 1000);
        ByteBuffer buffer = binImg.getByteBuffer();
        IntStream.range(0, binImg.rows()).forEach(r -> {
            if (r < 2 || r > binImg.rows() - 3) {
                IntStream.range(0, binImg.cols()).forEach(c -> buffer.put(r * binImg.cols() + c, (byte) 255));
            } else {
                buffer.put(r * binImg.cols(), (byte) 255);
                buffer.put(r * binImg.cols() + binImg.cols() - 1, (byte) 255);
            }
        });
        // it is reusing the buffer - do not release
        Mat binImg2 = new Mat(binImg.rows(), binImg.cols(), CV_8UC1, new BytePointer(buffer));
        Utils.showImage(binImg2, 1000);
        /*
         * Finding Contours
         */
        MatVector contours = new MatVector();
        findContours(binImg2, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
        log.info("{}", contours.size());
        List<Contour> squares = LongStream.range(0, contours.size())
                .filter(i -> Double.compare(contourArea(contours.get(i)), 20000.0) > 0)
                .mapToObj(i -> contours.get(i))
                .sorted((c1, c2) -> Double.compare(contourArea(c1), contourArea(c2))).limit(30)
                .map(c -> new Contour(c, binImg2)).collect(Collectors.toList());
        Mat bg = new Mat(binImg2.size(), CV_8UC1, BLACK);
        squares.forEach(c -> {
            log.info("contour area {}", contourArea(c.getContour()));
            MatVector v = new MatVector(1);
            v.put(0, c.getContour());
            drawContours(bg, v, 0, new Scalar(255, 255, 255, 255));
            Utils.showImage(bg, 1000);
        });
        /*
         * Relating contours using nearness & position between lines
         */
        squares.forEach(s -> s.joinLines());
        Position.quadrants().forEach(pos -> {
            squares.forEach(c1 -> {
                Set<Line> l1 = c1.mainLines(pos);
                if (!l1.isEmpty()) {
                    Line f1 = l1.iterator().next();
                    squares.forEach(c2 -> {
                        Set<Line> l2 = c2.mainLines(pos);
                        if (!l2.isEmpty()) {
                            Line f2 = l2.iterator().next();
                            if (!c1.equals(c2) && !l1.isEmpty() && !l2.isEmpty()
                                    && ((f1.intersection(f2) != null && f1.angleDiff(f2) < 15)
                                            || (f1.intersection(f2) == null
                                                    && f1.distancePerpendicular(f2.midPoint()) < 15))) {
                                f1.addRelated(c2);
                                f2.addRelated(c1);
                                l1.add(f2);
                                l2.add(f1);
                            }
                        }
                    });
                }
            });
        });
        Map<Position, Map<String, List<Line>>> meanLines = new HashMap<>();
        Map<Position, Map<String, Line>> calibrationLines = new HashMap<>();
        /*
         * Creating final main line for each position on each contour
         */
        Position.quadrants().forEach(pos -> {
            meanLines.put(pos, new HashMap<>());
            squares.stream().filter(c -> (c.mainLines(pos).size() > 0)).forEach(c -> {
                Line mean = Line.meanLine(c.mainLines(pos)).expandedLine(grayImg.size());
                Set<Contour> related = c.mainLines(pos).stream().map(l -> l.getRelated())
                        .flatMap(con -> con.stream()).collect(Collectors.toSet());
                mean.getRelated().addAll(related);
                String key = related.stream().map(r -> r.getIndex()).sorted().map(r -> r.toString())
                        .reduce((s1, s2) -> s1 + "|" + s2).get();
                if (!meanLines.get(pos).containsKey(key)) {
                    meanLines.get(pos).put(key, new ArrayList<>());
                }
                log.debug("{} {} {}", pos, c, c.mainLines(pos));
                c.mainLines(pos).clear();
                c.mainLines(pos).add(mean);
                meanLines.get(pos).get(key).add(mean);
            });
            Map<String, Line> linesPerContourSet = meanLines.get(pos).entrySet().stream()
                    .collect(Collectors.toMap(e -> e.getKey(), e -> Line.meanLine(e.getValue())));
            calibrationLines.put(pos, linesPerContourSet);
            linesPerContourSet.values().forEach(l -> line(grayImg, point(l.p0), point(l.p1), pos.color()));
        });
        /*
         * Order contours using related main lines 1 - Find edge contours
         */
        Contour topLeftContour = squares.stream()
                .sorted((c1, c2) -> (int) Math.round(c1.getCentroid().distance(new Coordinate(0, 0))
                        - c2.getCentroid().distance(new Coordinate(0, 0))))
                .findFirst().get();
        Contour topRightContour = squares.stream()
                .sorted((c1,
                        c2) -> (int) Math.round(c1.getCentroid().distance(new Coordinate(grayImg.cols() - 1, 0))
                                - c2.getCentroid().distance(new Coordinate(grayImg.cols() - 1, 0))))
                .findFirst().get();
        Contour bottomLeftContour = squares.stream()
                .sorted((c1,
                        c2) -> (int) Math.round(c1.getCentroid().distance(new Coordinate(0, grayImg.cols() - 1))
                                - c2.getCentroid().distance(new Coordinate(0, grayImg.cols() - 1))))
                .findFirst().get();
        Contour bottomRightContour = squares.stream()
                .sorted((c1, c2) -> (int) Math.round(c1.getCentroid()
                        .distance(new Coordinate(grayImg.cols() - 1, grayImg.rows() - 1))
                        - c2.getCentroid().distance(new Coordinate(grayImg.cols() - 1, grayImg.rows() - 1))))
                .findFirst().get();
        /*
         * Order by region using related contours from main lines
         */
        topLeftContour.sortRelated(0, 3, Position.RIGHT);
        topLeftContour.mainLines(Position.RIGHT).iterator().next().getRelated()
                .forEach(c -> c.sortRelated(c.getIndex(), 1, Position.BOTTOM));
        topRightContour.sortRelated(12, 3, Position.LEFT);
        topRightContour.mainLines(Position.RIGHT).iterator().next().getRelated()
                .forEach(c -> c.sortRelated(c.getIndex(), 1, Position.BOTTOM));
        bottomLeftContour.sortRelated(24, 1, Position.TOP);
        bottomLeftContour.mainLines(Position.TOP).iterator().next().getRelated().stream()
                .filter(c -> c.getIndex() == 25).findFirst().get().sortRelated(25, 1, Position.RIGHT);
        bottomRightContour.sortRelated(27, 1, Position.TOP);
        bottomRightContour.mainLines(Position.TOP).iterator().next().getRelated().stream()
                .filter(c -> c.getIndex() == 28).findFirst().get().sortRelated(28, 1, Position.LEFT);
        squares.forEach(c -> writeText(grayImg, 2.0, (int) FastMath.round(c.getCentroid().x),
                (int) FastMath.round(c.getCentroid().y), new Scalar(255, 0, 255, 0), c.getIndex().toString()));
        /*
         * Debug printing
         */
        log.debug(calibrationLines.toString().replaceAll("\\], ", "]\n"));
        squares.forEach(s -> log.debug("{}", Corner.corners().stream().filter(cn -> s.getCorner(cn) != null)
                .collect(Collectors.toMap(cn -> cn, cn -> s.getCorner(cn)))));
        /*
         * calibration with laser on
         */
        IntStream.range(-1, 128).mapToObj(i -> Integer.toString(i))
                .map(i -> i.equals("-1")
                        ? imread(String.format("%s/calibration/laser.jpg", root), CV_LOAD_IMAGE_GRAYSCALE)
                        : imread(String.format("%s/imagens/capt%s.jpg", root, Strings.padStart(i, 3, '0')),
                                CV_LOAD_IMAGE_GRAYSCALE))
                .forEach(img -> {
                    Utils.showImage(img, 1000);
                    log.info("dilating");
                    Mat dilatedLaser = new Mat(img.size(), CV_8UC1, BLACK);
                    Mat kernel = getStructuringElement(MORPH_RECT, new Size(3, 3), new opencv_core.Point(1, 1));
                    dilate(img, dilatedLaser, kernel);
                    Utils.showImage(dilatedLaser, 1000);
                    log.info("blurring");
                    Mat blurredLaser = new Mat(img.size(), CV_8UC3, BLACK);
                    Mat blurredLaser2 = new Mat(img.size(), CV_8UC3, BLACK);
                    medianBlur(img, blurredLaser, 15);
                    Utils.showImage(blurredLaser, 1000);
                    blur(blurredLaser, blurredLaser2, new Size(15, 15));
                    Utils.showImage(blurredLaser2, 1000);
                    log.info("binary Image");
                    Mat binLaser = new Mat(img.size(), CV_8UC1, BLACK);
                    threshold(blurredLaser, binLaser, 50, 255, CV_THRESH_BINARY);
                    Utils.showImage(binLaser, 1000);
                    log.info("Thinning");
                    Mat thinned = ZhangSuenThinning.thinning(binLaser);
                    Utils.showImage(thinned, 1000);
                });
        Thread.sleep(20000);
    } catch (RuntimeException | InterruptedException e) {
        log.error(e.getMessage(), e);
    }
}

From source file:com.google.gerrit.server.mail.send.CommentSender.java

/** No longer used except for Velocity. Remove this method when VTL support is removed. */
@Deprecated/*from   w  ww . j a va2 s  .c  om*/
private void appendRangedComment(StringBuilder out, PatchFile fileData, Comment comment) {
    String prefix = getCommentLinePrefix(comment);
    String emptyPrefix = Strings.padStart(": ", prefix.length(), ' ');
    boolean firstLine = true;
    for (String line : getLinesByRange(comment.range, fileData, comment.side)) {
        out.append(firstLine ? prefix : emptyPrefix).append(line).append('\n');
        firstLine = false;
    }
    appendQuotedParent(out, comment);
    out.append(comment.message.trim()).append('\n');
}

From source file:tech.tablesaw.columns.datetimes.DateTimeMapFunctions.java

/**
 * Returns a StringColumn with the year and week-of-year derived from this column concatenated into a String
 * that will sort lexicographically in temporal order.
 * <p>/*from w  w w .j  a v a 2 s  .c o  m*/
 * This simplifies the production of plots and tables that aggregate values into standard temporal units (e.g.,
 * you want monthly data but your source data is more than a year long and you don't want months from different
 * years aggregated together).
 */
default StringColumn yearWeek() {
    StringColumn newColumn = StringColumn.create(this.name() + " year & month");
    for (int r = 0; r < this.size(); r++) {
        long c1 = this.getLongInternal(r);
        if (DateTimeColumn.valueIsMissing(c1)) {
            newColumn.append(StringColumnType.missingValueIndicator());
        } else {
            String ym = String.valueOf(getYear(c1));
            ym = ym + "-" + Strings.padStart(String.valueOf(getWeekOfYear(c1)), 2, '0');
            newColumn.append(ym);
        }
    }
    return newColumn;
}

From source file:org.eclipse.xtext.generator.trace.AbstractTraceRegionToString.java

protected String render(final AbstractTraceRegionToString.Insert it, final int width) {
    final String first = Strings.padStart(Integer.toString(it.region.id, this.radix), width, '0');
    String _xifexpression = null;
    if (((it.location != null) && (it.location.id >= 0))) {
        String _string = Integer.toString(it.location.id, this.radix);
        _xifexpression = ((first + "_") + _string);
    } else {/*from   ww w .  j a v a 2s. co m*/
        _xifexpression = first;
    }
    return _xifexpression;
}