Example usage for com.google.common.collect Ordering natural

List of usage examples for com.google.common.collect Ordering natural

Introduction

In this page you can find the example usage for com.google.common.collect Ordering natural.

Prototype

@GwtCompatible(serializable = true)
@SuppressWarnings("unchecked") 
public static <C extends Comparable> Ordering<C> natural() 

Source Link

Document

Returns a serializable ordering that uses the natural order of the values.

Usage

From source file:org.apache.ctakes.temporal.ae.baselines.F1BaselineEventTimeRelationAnnotator.java

@Override
protected List<IdentifiedAnnotationPair> getCandidateRelationArgumentPairs(JCas jCas, Annotation sentence) {
    List<EventMention> events = JCasUtil.selectCovered(jCas, EventMention.class, sentence);

    if (events.size() == 0) {
        return Lists.newArrayList();
    }/*  w  w  w. ja va  2 s. co  m*/

    // compute token distance for each time-event pair
    HashMap<IdentifiedAnnotationPair, Integer> distanceLookup = new HashMap<IdentifiedAnnotationPair, Integer>();
    for (EventMention event : events) {
        if (event.getClass().equals(EventMention.class)) {
            // get only times preceding this event:
            List<TimeMention> times = JCasUtil.selectCovered(jCas, TimeMention.class, sentence.getBegin(),
                    event.getBegin());
            if (times.size() == 0)
                continue;
            for (TimeMention time : times) {
                // ignore subclasses like Procedure and Disease/Disorder
                IdentifiedAnnotationPair pair = new IdentifiedAnnotationPair(time, event);
                List<BaseToken> baseTokens = JCasUtil.selectBetween(jCas, BaseToken.class, pair.getArg1(),
                        pair.getArg2());
                int distance = baseTokens.size();
                distanceLookup.put(pair, distance);
            }
        }

    }

    if (distanceLookup.size() == 0)
        return Lists.newArrayList();

    // find the pair where the distance between entities is the smallest and return it
    List<IdentifiedAnnotationPair> rankedPairs = new ArrayList<IdentifiedAnnotationPair>(
            distanceLookup.keySet());
    Function<IdentifiedAnnotationPair, Integer> getValue = Functions.forMap(distanceLookup);
    Collections.sort(rankedPairs, Ordering.natural().onResultOf(getValue));

    List<IdentifiedAnnotationPair> results = new ArrayList<IdentifiedAnnotationPair>();
    Set<EventMention> relTimes = new HashSet<EventMention>();
    for (IdentifiedAnnotationPair result : rankedPairs) {
        if (!relTimes.contains(result.getArg2())) {
            relTimes.add((EventMention) result.getArg2());
            results.add(result);
            Sentence sent = JCasUtil.selectCovering(jCas, Sentence.class, result.getArg1().getBegin(),
                    result.getArg1().getEnd()).get(0);
            System.out.println(sent.getCoveredText());
            System.out.println("Relation found: CONTAINS(" + result.getArg1().getCoveredText() + ","
                    + result.getArg2().getCoveredText() + ")\n");
        }
    }
    return results;
}

From source file:org.onebusaway.nyc.vehicle_tracking.impl.inference.state.BlockState.java

/**
 * This compareTo method is for definite ordering in CategoricalDist; such
 * ordering allows for reproducibility in testing.
 *///from  w  w w  . j  a v a 2  s . c  o  m
@Override
public int compareTo(BlockState rightBs) {

    if (this == rightBs)
        return 0;

    final int res = ComparisonChain.start().compare(this.destinationSignCode, rightBs.destinationSignCode)
            .compare(this.blockInstance, rightBs.blockInstance, Ordering.from(BlockInstanceComparator.INSTANCE))
            .compare(this.blockLocation, rightBs.blockLocation,
                    Ordering.from(ScheduledBlockLocationComparator.INSTANCE))
            .compare(this.runTrip, rightBs.runTrip, Ordering.natural().nullsLast()).result();
    return res;
}

From source file:me.taylorkelly.mywarp.bukkit.commands.printer.InfoPrinter.java

/**
 * Gets information text./* ww  w. j  a  v  a 2s. com*/
 *
 * @param receiver the Actor who will receive the text
 * @return the text
 */
public String getText(Actor receiver) {
    StrBuilder info = new StrBuilder();
    // heading
    info.append(ChatColor.GOLD);
    info.append(MESSAGES.getString("info.heading",
            ChatColor.getByChar(warp.getType().getColorCharacter()) + warp.getName() + ChatColor.GOLD));
    info.appendNewLine();

    // creator
    info.append(ChatColor.GRAY);

    info.append(MESSAGES.getString("info.created-by"));
    info.append(" ");
    info.append(ChatColor.WHITE);
    Profile creator = warp.getCreator();
    info.append(creator.getName().or(creator.getUniqueId().toString()));
    if (receiver instanceof LocalPlayer && warp.isCreator((LocalPlayer) receiver)) {
        info.append(" ");
        info.append(MESSAGES.getString("info.created-by-you"));
    }
    info.appendNewLine();

    // location
    info.append(ChatColor.GRAY);
    info.append(MESSAGES.getString("info.location"));
    info.append(" ");
    info.append(ChatColor.WHITE);
    info.append(MESSAGES.getString("info.location.position", warp.getPosition().getFloorX(),
            warp.getPosition().getFloorY(), warp.getPosition().getFloorZ(), warp.getWorld().getName()));

    info.appendNewLine();

    // if the warp is modifiable, show information about invitations
    if (warp.isModifiable(receiver)) {

        // invited players
        info.append(ChatColor.GRAY);
        info.append(MESSAGES.getString("info.invited-players"));
        info.append(" ");
        info.append(ChatColor.WHITE);

        Set<Profile> invitedPlayers = warp.getInvitedPlayers();
        if (invitedPlayers.isEmpty()) {
            info.append("-");
        } else {
            List<String> invitedPlayerNames = new ArrayList<String>();
            for (Profile profile : invitedPlayers) {
                invitedPlayerNames.add(profile.getName().or(profile.getUniqueId().toString()));
            }
            Collections.sort(invitedPlayerNames);
            info.appendWithSeparators(invitedPlayerNames, ", ");
        }
        info.appendNewLine();

        // invited groups
        info.append(ChatColor.GRAY);
        info.append(MESSAGES.getString("info.invited-groups"));
        info.append(" ");
        info.append(ChatColor.WHITE);

        List<String> invitedGroups = Ordering.natural().sortedCopy(warp.getInvitedGroups());
        if (invitedGroups.isEmpty()) {
            info.append("-");
        } else {
            info.appendWithSeparators(invitedGroups, ", ");
        }
        info.appendNewLine();
    }

    // creation date
    info.append(ChatColor.GRAY);
    info.append(MESSAGES.getString("info.creation-date", warp.getCreationDate()));
    info.append(" ");
    info.append(ChatColor.WHITE);
    info.append(DateFormat.getDateInstance(DateFormat.DEFAULT, LocaleManager.getLocale())
            .format(warp.getCreationDate()));

    info.appendNewLine();

    // visits
    info.append(ChatColor.GRAY);
    info.append(MESSAGES.getString("info.visits"));
    info.append(" ");
    info.append(ChatColor.WHITE);
    info.append(MESSAGES.getString("info.visits.per-day", warp.getVisits(), warp.getVisitsPerDay()));
    return info.toString();
}

From source file:uk.ac.open.kmi.iserve.discovery.disco.impl.OperationDataflowMatcher.java

/**
 * Perform a match between two URIs (from {@code origin} to {@code destination})
 * and returns the result./*  w ww  . j ava 2 s.co m*/
 *
 * @param origin      URI of the element to match
 * @param destination URI of the element to match against
 * @return {@link uk.ac.open.kmi.iserve.discovery.api.MatchResult} with the result of the matching.
 */
@Override
public MatchResult match(URI origin, URI destination) {

    Set<URI> originOutputs = this.serviceManager.listOutputs(origin);
    Set<URI> destinationInputs = this.serviceManager.listInputs(destination);

    // Obtain all combinations of matches
    Table<URI, URI, MatchResult> matches = this.conceptMatcher.match(originOutputs, destinationInputs);
    // Collect the best match results for each of the destination's inputs
    // We should try and maximise the fulfillment of destination's inputs rather than be guided by the origin outputs
    ImmutableSet.Builder<MatchResult> builder = ImmutableSet.builder();

    for (Map.Entry<URI, Map<URI, MatchResult>> entry : matches.columnMap().entrySet()) {
        Map<URI, MatchResult> matchesMap = entry.getValue();
        Ordering<URI> valueComparator = Ordering.from(MatchResultComparators.BY_TYPE)
                .onResultOf(Functions.forMap(matchesMap)) // Order by value
                .compound(Ordering.natural()); // Order by URI eventually

        URI bestMatchUri = valueComparator.max(matchesMap.keySet());
        log.info("The best match for {} is {}, with a Match Result of {}", entry.getKey(), bestMatchUri,
                matchesMap.get(bestMatchUri).getMatchType());

        builder.add(matchesMap.get(bestMatchUri));
    }

    MatchResult result = INTERSECTION.apply(builder.build());
    log.info("Combined match result - {}", result);
    return result;
}

From source file:it.anyplace.sync.discovery.utils.AddressRanker.java

private void testAndRankAndWait() throws InterruptedException {
    logger.trace("testing and ranking peer addresses");
    List<Future<DeviceAddress>> futures = Lists.newArrayList();
    for (final DeviceAddress deviceAddress : preprocessDeviceAddresses(sourceAddresses)) {
        futures.add(executorService.submit(new Callable<DeviceAddress>() {

            @Override/*from ww  w.  j  av  a  2  s .c om*/
            public DeviceAddress call() {
                return testAndRank(deviceAddress);
            }
        }));
    }
    for (Future<DeviceAddress> future : futures) {
        try {
            DeviceAddress deviceAddress = future.get(TCP_CONNECTION_TIMEOUT * 2, TimeUnit.MILLISECONDS);
            if (deviceAddress != null) {
                targetAddresses.add(deviceAddress);
            }
        } catch (ExecutionException ex) {
            throw new RuntimeException(ex);
        } catch (TimeoutException ex) {
            logger.warn("test address timeout : {}", ex.toString());
        }
    }
    Collections.sort(targetAddresses, Ordering.natural().onResultOf(new Function<DeviceAddress, Comparable>() {
        @Override
        public Comparable apply(DeviceAddress a) {
            return a.getScore();
        }
    }));
}

From source file:com.google.idea.blaze.android.run.BlazeAndroidRunConfigurationValidationUtil.java

public static void validateExecution(@Nullable Module module, @Nullable AndroidFacet facet,
        @Nullable ProjectViewSet projectViewSet) throws ExecutionException {
    List<ValidationError> errors = Lists.newArrayList();
    errors.addAll(validateModule(module));
    if (module != null) {
        errors.addAll(validateFacet(facet, module));
    }/*w  w w  .j a va2s.c o  m*/
    if (projectViewSet == null) {
        errors.add(ValidationError.fatal("Could not load project view. Please resync project"));
    }

    if (errors.isEmpty()) {
        return;
    }
    ValidationError topError = Ordering.natural().max(errors);
    if (topError.isFatal()) {
        throw new ExecutionException(topError.getMessage());
    }
}

From source file:google.registry.tools.AuthModule.java

@Provides
@ClientScopeQualifier/*from  ww w .  java  2s. c o  m*/
String provideClientScopeQualifier(@OAuthClientId String clientId,
        @Config("requiredOauthScopes") ImmutableSet<String> scopes) {
    return clientId + " " + Joiner.on(" ").join(Ordering.natural().sortedCopy(scopes));
}

From source file:com.google.gitiles.RefServlet.java

private static Ordering<Ref> tagComparator(final TimeCache timeCache, final RevWalk walk) {
    return Ordering.natural().onResultOf(new Function<Ref, Long>() {
        @Override/*from   w  w w .  ja va  2 s. c  o m*/
        public Long apply(Ref ref) {
            try {
                return timeCache.getTime(walk, ref.getObjectId());
            } catch (IOException e) {
                throw new UncheckedExecutionException(e);
            }
        }
    }).reverse().compound(RefComparator.INSTANCE);
}

From source file:uk.ac.ebi.atlas.acceptance.selenium.pages.HeatmapTableWithSearchFormAndBarChartPage.java

private List<WebElement> getXTicks(WebElement axisDiv) {
    List<WebElement> ticks = axisDiv.findElements(By.className("tickLabel"));

    //This is a patch because in some browser the X axis tick divs are ordered randomly,
    //but we can use the distance from X=0 to reorder the tick values
    Comparator distanceFromZeroComparator = Ordering.natural().onResultOf(new Function<WebElement, Integer>() {
        @Override/*from   w w  w.j a v a  2 s .  c  om*/
        public Integer apply(org.openqa.selenium.WebElement webElement) {
            String distanceFromZero = StringUtils.substringBefore(webElement.getCssValue("left"), "px");
            return Integer.parseInt(distanceFromZero);
        }
    });
    Collections.sort(ticks, distanceFromZeroComparator);

    return ticks;
}

From source file:com.facebook.buck.apple.MultiarchFileInfos.java

/**
 * Generate a fat rule from thin rules.//from  w  w  w.j  ava  2  s.  c o m
 *
 * Invariant: thinRules contain all the thin rules listed in info.getThinTargets().
 */
public static BuildRule requireMultiarchRule(BuildRuleParams params, BuildRuleResolver resolver,
        MultiarchFileInfo info, ImmutableSortedSet<BuildRule> thinRules) {
    Optional<BuildRule> existingRule = resolver.getRuleOptional(info.getFatTarget());
    if (existingRule.isPresent()) {
        return existingRule.get();
    }

    ImmutableSortedSet<SourcePath> inputs = FluentIterable.from(thinRules)
            .transform(SourcePaths.getToBuildTargetSourcePath()).toSortedSet(Ordering.natural());
    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
    SourcePathResolver pathResolver = new SourcePathResolver(ruleFinder);
    MultiarchFile multiarchFile = new MultiarchFile(
            params.copyWithDeps(Suppliers.ofInstance(ImmutableSortedSet.of()), Suppliers.ofInstance(thinRules)),
            pathResolver, ruleFinder, info.getRepresentativePlatform().getLipo(), inputs,
            BuildTargets.getGenPath(params.getProjectFilesystem(), params.getBuildTarget(), "%s"));
    resolver.addToIndex(multiarchFile);
    return multiarchFile;
}