Example usage for org.apache.commons.lang3.tuple Pair getLeft

List of usage examples for org.apache.commons.lang3.tuple Pair getLeft

Introduction

In this page you can find the example usage for org.apache.commons.lang3.tuple Pair getLeft.

Prototype

public abstract L getLeft();

Source Link

Document

Gets the left element from this pair.

When treated as a key-value pair, this is the key.

Usage

From source file:com.act.lcms.plotter.WriteAndPlotMS1Results.java

private void writeFeedMS1Values(List<Pair<Double, Double>> concentrationIntensity, OutputStream os)
        throws IOException {
    PrintStream out = new PrintStream(os);
    for (Pair<Double, Double> ci : concentrationIntensity) {
        out.format("%f\t%f\n", ci.getLeft(), ci.getRight());
    }/*from   w ww .  jav a2  s.c  o  m*/
    out.flush();
}

From source file:com.javiermoreno.springboot.mvc.users.UserCtrl.java

/**
 * Retrieves the users registered in the application.
 * @param page page of the results//w w w  . j  a  v a 2 s . co  m
 * @param amount how many results
 * @param direction ASC or DESC
 * @param sortingProperty name of the property used for sorting
 * @return 
 */
@RequestMapping(method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(value = "GET /users", notes = "Paginable.")
public HttpEntity<DailyUserPageResource> showAll(@RequestParam(defaultValue = "0") int page,
        @RequestParam(defaultValue = "25") int amount, @RequestParam(required = false) Sort.Direction direction,
        @RequestParam(required = false) String sortingProperty) {

    Pair<List<DailyUser>, Long> data = userService.retrieveAllUsers(page, amount, direction, sortingProperty);

    DailyUserPageResource resource = new DailyUserPageResource();
    resource.users = data.getLeft();
    resource.page = page;
    resource.amount = amount;
    resource.total = data.getRight();
    resource.lastPageNumber = (int) (resource.total / resource.amount);

    resource.add(
            linkTo(methodOn(UserCtrl.class).showAll(page, amount, direction, sortingProperty)).withSelfRel());
    resource.add(linkTo(methodOn(UserCtrl.class).showAll(0, amount, direction, sortingProperty))
            .withRel("firstPage"));
    resource.add(linkTo(
            methodOn(UserCtrl.class).showAll(resource.lastPageNumber, amount, direction, sortingProperty))
                    .withRel("lastPage"));
    if (page > 0) {
        resource.add(linkTo(methodOn(UserCtrl.class).showAll(page - 1, amount, direction, sortingProperty))
                .withRel("prevPage"));
    }
    if (page + amount < resource.total) {
        resource.add(linkTo(methodOn(UserCtrl.class).showAll(page + 1, amount, direction, sortingProperty))
                .withRel("nextPage"));
    }
    for (int i = max(0, page - 5); i < min(page + 5, resource.lastPageNumber); i++) {
        resource.add(linkTo(methodOn(UserCtrl.class).showAll(i, amount, direction, sortingProperty))
                .withRel("page" + i));
    }

    return new ResponseEntity<>(resource, HttpStatus.OK);
}

From source file:fredboat.audio.GuildPlayer.java

public Pair<Boolean, String> skipTracksForMemberPerms(TextChannel channel, Member member,
        List<AudioTrackContext> list) {
    Pair<Boolean, String> pair = canMemberSkipTracks(member, list);

    if (pair.getLeft()) {
        skipTracks(list);/*w w w. j a  v  a 2  s  . c  o m*/
    } else {
        TextUtils.replyWithName(channel, member, pair.getRight());
    }

    return pair;
}

From source file:at.gridtec.lambda4j.function.bi.BiFunction2.java

/**
 * Applies this function to the given tuple.
 *
 * @param tuple The tuple to be applied to the function
 * @return The return value from the function, which is its result.
 * @throws NullPointerException If given argument is {@code null}
 * @see org.apache.commons.lang3.tuple.Pair
 *//* ww w.j a va  2s  .  c  o m*/
default R apply(@Nonnull Pair<T, U> tuple) {
    Objects.requireNonNull(tuple);
    return apply(tuple.getLeft(), tuple.getRight());
}

From source file:com.qq.tars.service.monitor.TARSPropertyMonitorService.java

private MultiKeyMap call(List<String> groupBy, List<String> conditions) throws IOException {
    String template = "{\"groupby\":%s,\"method\":\"query\",\"dataid\":\"tars_property\","
            + "\"filter\":%s,\"indexs\":[\"value\"]}";

    ObjectMapper mapper = new ObjectMapper();
    String request = String.format(template, mapper.writeValueAsString(groupBy),
            mapper.writeValueAsString(conditions));

    List<Pair<String, Integer>> addrs = adminService.getEndpoints("tars.tarsqueryproperty.NoTarsObj");
    if (addrs.isEmpty()) {
        throw new IOException("tars.tarsqueryproperty.NoTarsObj not found");
    }/*from   www  .java2s.c o m*/

    Pair<String, Integer> addr = addrs.get(0);
    log.info("tars.tarsqueryproperty.NoTarsObj, use {}:{}", addr.getLeft(), addr.getRight());

    TCPClient client = new TCPClient(addr.getLeft(), addr.getRight());
    List<String> response = client.sendAndReceive(request.getBytes(), 60000);

    log.debug("request={}", request);
    log.debug("reponse={}", StringUtils.join(response, "\n"));

    String line1 = response.get(0);
    if (!line1.startsWith("Ret:")) {
        throw new IOException(String.format("line #1, doesn't start with \"Ret:\", line=%s", line1));
    }
    int ret = Integer.parseInt(line1.substring(line1.lastIndexOf(':') + 1));
    if (ret == -1) {
        throw new IOException(String.format("line #1, Ret=%s", ret));
    }

    String line6 = response.get(5);
    if (!line6.startsWith("linecount:")) {
        throw new IOException(String.format("line #6, doesn't start with \"linecount:\", line=%s", line6));
    }
    int count = Integer.parseInt(line6.substring(line6.lastIndexOf(':') + 1));
    if (count + 7 != response.size()) {
        throw new IOException(String.format("line #6, size not match, %s vs %s", count + 7, response.size()));
    }

    String lastLine = response.get(response.size() - 1);
    if (!"endline".equals(lastLine)) {
        throw new IOException(
                String.format("line #%s, doesn't equal to \"endline\", line=%s", response.size(), lastLine));
    }

    MultiKeyMap result = new MultiKeyMap();
    for (int i = 6; i < response.size() - 1; i++) {
        String line = StringUtils.removeEnd(response.get(i), ",");
        String[] tokens = line.split(",");
        if (tokens.length != groupBy.size() + 1) {
            throw new IOException(String.format("line format error, line=%s", line));
        }

        String[] key = new String[groupBy.size()];
        int j = 0;
        for (; j < key.length; j++) {
            key[j] = tokens[j];
        }

        double[] value = new double[] { Double.parseDouble(tokens[j]) };
        result.put(new MultiKey(key), value);
    }
    return result;
}

From source file:io.cloudslang.lang.compiler.modeller.MetadataModellerImpl.java

@Override
public MetadataModellingResult createModel(ParsedDescriptionData parsedDescriptionData) {
    List<ParsedDescriptionSection> topLevelDescriptions = parsedDescriptionData.getTopLevelDescriptions();
    List<RuntimeException> errors = new ArrayList<>(parsedDescriptionData.getErrors());
    Pair<Metadata, List<RuntimeException>> executableMetadata = null;

    // executable metadata
    if (CollectionUtils.isNotEmpty(topLevelDescriptions)) {
        if (topLevelDescriptions.size() > 1) {
            errors.add(new RuntimeException("Multiple top level descriptions found at line numbers: "
                    + getLineNumbers(topLevelDescriptions)));
        }//from w  ww .  j  a v  a  2 s.co  m
        executableMetadata = transformToExecutableMetadata(topLevelDescriptions.get(0).getData());
        errors.addAll(executableMetadata.getRight());
    }

    // step metadata
    Pair<List<StepMetadata>, List<RuntimeException>> stepsModellingResult = transformStepsData(
            parsedDescriptionData.getStepDescriptions());
    List<StepMetadata> stepDescriptions = stepsModellingResult.getLeft();
    errors.addAll(stepsModellingResult.getRight());

    return new MetadataModellingResult(
            executableMetadata == null ? new Metadata() : executableMetadata.getLeft(), stepDescriptions,
            errors);
}

From source file:com.nextdoor.bender.operation.conditional.ConditionalOperation.java

public Stream<InternalEvent> getOutputStream(Stream<InternalEvent> input) {
    /*//from   ww w .  jav a 2 s  . c om
     * outputStreams keeps track of the output Stream of each Condition.
     */
    List<Stream<InternalEvent>> outputStreams = new ArrayList<Stream<InternalEvent>>(
            this.conditionsAndProcs.size());

    /*
     * From a list of operation configurations in each condition construct queues and streams.
     */
    this.filtersAndQueues = new ArrayList<Pair<FilterOperation, Queue<InternalEvent>>>(
            this.conditionsAndProcs.size());
    for (Pair<FilterOperation, List<OperationProcessor>> filterAndProcs : this.conditionsAndProcs) {

        FilterOperation filter = filterAndProcs.getLeft();
        List<OperationProcessor> procs = filterAndProcs.getRight();

        /*
         * Construct a Queue for each conditional. This is the input to each Condition.
         */
        Queue<InternalEvent> queue = new Queue<InternalEvent>(
                new LinkedBlockingQueue<InternalEvent>(procs.size()));

        this.filtersAndQueues.add(new ImmutablePair<FilterOperation, Queue<InternalEvent>>(filter, queue));

        /*
         * Connect the condition's input Queue with operations. Each operation returns a stream with its
         * operation concatenated on.
         */
        Stream<InternalEvent> conditionInput = queue.jdkStream();
        for (OperationProcessor proc : procs) {
            conditionInput = proc.perform(conditionInput);
        }

        /*
         * Last input is the output.
         */
        outputStreams.add(conditionInput);
    }

    /*
     * Condition Consumer Threads
     * 
     * Combine each condition's output stream and write to the output Queue. When all data is consumed
     * the last condition closes the output Queue.
     */
    Queue<InternalEvent> outputQueue = new Queue<InternalEvent>(
            new LinkedBlockingQueue<InternalEvent>(this.conditionsAndProcs.size()));
    AtomicInteger lock = new AtomicInteger(outputStreams.size());

    outputStreams.forEach(stream -> {
        this.es.execute(new StreamToQueue(stream, outputQueue, lock));
    });

    /*
     * Consume input Stream in a thread and publish to each condition's Queue.
     */
    new Thread(new Runnable() {
        @Override
        public void run() {
            input.forEach(ievent -> {
                boolean matches = false;

                for (Pair<FilterOperation, Queue<InternalEvent>> filterAndQueue : filtersAndQueues) {
                    FilterOperation filter = filterAndQueue.getLeft();

                    /*
                     * If event passes the filter offer event to queue.
                     */
                    if (filter.test(ievent)) {
                        filterAndQueue.getRight().offer(ievent);
                        matches = true;
                        break;
                    }
                }

                /*
                 * Send to output queue if no case matches
                 */
                if (!matches && !filterNonMatch) {
                    outputQueue.offer(ievent);
                }
            });

            /*
             * Close queues when source queue is consumed.
             */
            for (Pair<FilterOperation, Queue<InternalEvent>> filterAndQueue : filtersAndQueues) {
                filterAndQueue.getRight().close();
            }
        }
    }).start();

    return outputQueue.jdkStream();
}

From source file:com.norconex.importer.handler.transformer.impl.StripBetweenTransformer.java

@Override
protected void transformStringContent(String reference, StringBuilder content, ImporterMetadata metadata,
        boolean parsed, boolean partialContent) {
    int flags = Pattern.DOTALL | Pattern.UNICODE_CASE;
    if (!caseSensitive) {
        flags = flags | Pattern.CASE_INSENSITIVE;
    }/*from   w ww.  java2s  . c o  m*/
    for (Pair<String, String> pair : stripPairs) {
        List<Pair<Integer, Integer>> matches = new ArrayList<Pair<Integer, Integer>>();
        Pattern leftPattern = Pattern.compile(pair.getLeft(), flags);
        Matcher leftMatch = leftPattern.matcher(content);
        while (leftMatch.find()) {
            Pattern rightPattern = Pattern.compile(pair.getRight(), flags);
            Matcher rightMatch = rightPattern.matcher(content);
            if (rightMatch.find(leftMatch.end())) {
                if (inclusive) {
                    matches.add(new ImmutablePair<Integer, Integer>(leftMatch.start(), rightMatch.end()));
                } else {
                    matches.add(new ImmutablePair<Integer, Integer>(leftMatch.end(), rightMatch.start()));
                }
            } else {
                break;
            }
        }
        for (int i = matches.size() - 1; i >= 0; i--) {
            Pair<Integer, Integer> matchPair = matches.get(i);
            content.delete(matchPair.getLeft(), matchPair.getRight());
        }
    }
}

From source file:edu.ksu.cis.santos.mdcf.dms.test.SymbolTableTest.java

<T extends Member> void allMembers(final Class<T> clazz) throws Exception {
    final SymbolTable st = SymbolTableTest.ST;
    final StringBuilder sb = new StringBuilder();

    final String className = clazz.getSimpleName();

    final String title = "All (Declared and Inherited) " + className + "s";
    appendln(sb, title);//  w w  w  . j  a va 2s  . co  m
    for (int i = 0; i < title.length(); i++) {
        sb.append('=');
    }
    appendln(sb);

    final Set<String> featureNames = featureOrDeviceNames();

    for (final String featureName : featureNames) {
        appendln(sb);
        sb.append("* ");
        sb.append(shorten(featureName));
        sb.append(": ");
        final Collection<Pair<Feature, T>> c = st.filterp(st.allMemberMap(featureName), clazz).values();
        for (final Pair<Feature, T> p : c) {
            sb.append('(');
            sb.append(shorten(p.getLeft().name));
            sb.append(", ");
            final Member right = p.getRight();
            sb.append(right instanceof Attribute ? "attr:" : "inv:");
            sb.append(right.name);
            sb.append("), ");
        }
        deleteLastChars(sb, 2);
    }

    testExpectedResult("dms.test.symbol.all" + className.toLowerCase() + "s", sb.toString());
}

From source file:ca.craigthomas.visualclassifier.commandline.TrainCommand.java

public void execute() {
    NeuralNetwork bestModel = null;//from w  ww  . j a va  2s . c  om
    DataSet bestFold = null;
    double[] tp = new double[arguments.folds];
    double[] fp = new double[arguments.folds];
    double[] tn = new double[arguments.folds];
    double[] fn = new double[arguments.folds];
    double[] precision = new double[arguments.folds];
    double[] recall = new double[arguments.folds];
    double[] f1 = new double[arguments.folds];
    double bestF1 = 0;

    // Step 1: create the dataset
    if (!arguments.csvFile.isEmpty()) {
        loadFromCSV();
    } else {
        loadFromDirectories();
    }

    if (mDataSet == null) {
        LOGGER.log(Level.SEVERE, "no data set could be built, exiting");
        return;
    }

    // Step 2: Generate layer information
    List<Integer> layerSizes = new ArrayList<>();
    layerSizes.add(mDataSet.getNumColsSamples());
    if (arguments.layer1 != 0) {
        layerSizes.add(arguments.layer1);
    }
    if (arguments.layer2 != 0) {
        layerSizes.add(arguments.layer2);
    }
    layerSizes.add(arguments.outputLayer);

    // Step 3: generate the folds and train the model
    for (int fold = 0; fold < arguments.folds; fold++) {
        LOGGER.log(Level.INFO, "processing fold " + (fold + 1));
        LOGGER.log(Level.INFO, "randomizing dataset");
        mDataSet.randomize();
        LOGGER.log(Level.INFO, "generating training and testing sets");
        Pair<DataSet, DataSet> split = mDataSet.splitEqually(arguments.split);
        DataSet trainingData = split.getLeft();
        DataSet testingData = split.getRight();
        LOGGER.log(Level.INFO, "training neural network...");
        trainingData.randomize();
        Trainer trainer = new Trainer.Builder(layerSizes, trainingData).maxIterations(arguments.iterations)
                .heartBeat(arguments.heartBeat).learningRate(arguments.learningRate).lambda(arguments.lambda)
                .build();
        trainer.train();

        // Step 4: evaluate each model
        NeuralNetwork model = trainer.getNeuralNetwork();
        Prediction prediction = new Prediction(model, arguments.predictionThreshold);
        prediction.predict(testingData);
        System.out.println("True Positives " + prediction.getTruePositives());
        System.out.println("False Positives " + prediction.getFalsePositives());
        System.out.println("True Negatives " + prediction.getTrueNegatives());
        System.out.println("False Negatives " + prediction.getFalseNegatives());
        System.out.println("Precision " + prediction.getPrecision());
        System.out.println("Recall " + prediction.getRecall());
        System.out.println("F1 " + prediction.getF1());

        tp[fold] = prediction.getTruePositives();
        fp[fold] = prediction.getFalsePositives();
        tn[fold] = prediction.getTrueNegatives();
        fn[fold] = prediction.getFalseNegatives();
        precision[fold] = prediction.getPrecision();
        recall[fold] = prediction.getRecall();
        f1[fold] = prediction.getF1();
        if (f1[fold] > bestF1) {
            bestModel = model;
            bestFold = mDataSet.dup();
            bestF1 = f1[fold];
        }
    }

    // Step 6: save the best information to the specified directory
    if (!arguments.saveDir.isEmpty()) {
        saveResults(bestModel, bestFold);
    }

    // Step 5: compute the overall statistics
    System.out.println("Overall Statistics");
    System.out.println("True Positives " + StatUtils.mean(tp) + " (" + StatUtils.variance(tp) + ")");
    System.out.println("False Positives " + StatUtils.mean(fp) + " (" + StatUtils.variance(fp) + ")");
    System.out.println("True Negatives " + StatUtils.mean(tn) + " (" + StatUtils.variance(tn) + ")");
    System.out.println("False Negatives " + StatUtils.mean(fn) + " (" + StatUtils.variance(fn) + ")");
    System.out.println("Precision " + StatUtils.mean(precision) + " (" + StatUtils.variance(precision) + ")");
    System.out.println("Recall " + StatUtils.mean(recall) + " (" + StatUtils.variance(recall) + ")");
    System.out.println("F1 " + StatUtils.mean(f1) + " (" + StatUtils.variance(f1) + ")");
}