List of usage examples for com.google.common.collect Ordering natural
@GwtCompatible(serializable = true) @SuppressWarnings("unchecked") public static <C extends Comparable> Ordering<C> natural()
From source file:com.github.steveash.jg2p.align.AlignerViterbi.java
private List<Alignment> createAlignments(Word x, Word y, PathXYTable t, int bestPathCount) { List<Alignment> results = Lists.newArrayListWithCapacity(bestPathCount); Iterable<PathXYTable.Entry> lastEntries = t.get(x.unigramCount(), y.unigramCount()); for (PathXYTable.Entry lastEntry : lastEntries) { if (lastEntry.score < ProbTable.minLogProb) continue; results.add(decodePathFrom(x, y, t, lastEntry)); }// w ww .j a va 2 s . c o m Collections.sort(results, Ordering.natural().reverse()); return results; }
From source file:com.facebook.hiveio.schema.HiveTableSchemaImpl.java
/** * Compute number of columns from the data. * @param columnPositions column positions to compute on * @return number of columns/* w ww . j a v a 2 s. c o m*/ */ private static int sizeFromIndexes(Map<String, Integer> columnPositions) { if (columnPositions.isEmpty()) { return 0; } return Ordering.natural().max(columnPositions.values()) + 1; }
From source file:dk.ilios.spanner.internal.ConsoleOutput.java
/** * Prints a summary of a successful trial result. *///from ww w . j ava2 s. c om void processTrial(Trial.Result result) { Trial baseline = result.getExperiment().getBaseline(); trialsCompleted++; stdout.printf("Trial Report (%d of %d):%n Experiment %s%n", trialsCompleted, numberOfTrials, result.getExperiment()); if (!result.getTrialMessages().isEmpty()) { stdout.println(" Messages:"); for (String message : result.getTrialMessages()) { stdout.print(" "); stdout.println(message); } } Trial trial = result.getTrial(); // Group measurements by their description // TODO Why? All measurements for a single trial should have the same description ImmutableListMultimap<String, Measurement> measurementsIndex = new ImmutableListMultimap.Builder<String, Measurement>() .orderKeysBy(Ordering.natural()) .putAll(Multimaps.index(trial.measurements(), new Function<Measurement, String>() { @Override public String apply(Measurement input) { return input.description(); } })).build(); stdout.println(" Results:"); for (Map.Entry<String, Collection<Measurement>> entry : measurementsIndex.asMap().entrySet()) { Collection<Measurement> measurements = entry.getValue(); String unit = measurements.iterator().next().value().unit(); double[] weightedValues = new double[measurements.size()]; int i = 0; for (Measurement measurement : measurements) { weightedValues[i] = measurement.value().magnitude() / measurement.weight(); i++; } Percentile percentile = new Percentile(); percentile.setData(weightedValues); DescriptiveStatistics descriptiveStatistics = new DescriptiveStatistics(weightedValues); stdout.printf(" %s%s: min=%.2f, 1st qu.=%.2f, median=%.2f (%s), mean=%.2f, 3rd qu.=%.2f, max=%.2f%n", entry.getKey(), unit.isEmpty() ? "" : "(" + unit + ")", descriptiveStatistics.getMin(), percentile.evaluate(25), percentile.evaluate(50), calculateDiff(percentile.evaluate(50), baseline), descriptiveStatistics.getMean(), percentile.evaluate(75), descriptiveStatistics.getMax()); } instrumentSpecs.add(trial.instrumentSpec()); Scenario scenario = trial.scenario(); benchmarkSpecs.add(scenario.benchmarkSpec()); numMeasurements += trial.measurements().size(); }
From source file:com.facebook.buck.intellij.ideabuck.impl.BuckCellManagerImpl.java
private Optional<CellImpl> findCellByCanonicalPath(String canonicalPath) { if (canonicalPath == null) { return Optional.empty(); }/*from w w w. j av a2 s . c o m*/ return mBuckCellSettingsProvider.getCells().stream().filter(cell -> { String root = mPathMacroManager.expandPath(cell.getRoot()); return canonicalPath.equals(root) || canonicalPath.startsWith(root + File.separator); }).max(Ordering.natural().onResultOf(cell -> cell.getRoot().length())).map(CellImpl::new); }
From source file:io.druid.indexer.HadoopIngestionSpec.java
public static HadoopIngestionSpec updateSegmentListIfDatasourcePathSpecIsUsed(HadoopIngestionSpec spec, ObjectMapper jsonMapper, UsedSegmentLister segmentLister) throws IOException { String dataSource = "dataSource"; String type = "type"; String multi = "multi"; String children = "children"; String segments = "segments"; String ingestionSpec = "ingestionSpec"; Map<String, Object> pathSpec = spec.getIOConfig().getPathSpec(); Map<String, Object> datasourcePathSpec = null; if (pathSpec.get(type).equals(dataSource)) { datasourcePathSpec = pathSpec;/*from www . j a v a2 s . c om*/ } else if (pathSpec.get(type).equals(multi)) { List<Map<String, Object>> childPathSpecs = (List<Map<String, Object>>) pathSpec.get(children); for (Map<String, Object> childPathSpec : childPathSpecs) { if (childPathSpec.get(type).equals(dataSource)) { datasourcePathSpec = childPathSpec; break; } } } if (datasourcePathSpec != null) { Map<String, Object> ingestionSpecMap = (Map<String, Object>) datasourcePathSpec.get(ingestionSpec); DatasourceIngestionSpec ingestionSpecObj = jsonMapper.convertValue(ingestionSpecMap, DatasourceIngestionSpec.class); List<DataSegment> segmentsList = segmentLister .getUsedSegmentsForInterval(ingestionSpecObj.getDataSource(), ingestionSpecObj.getInterval()); VersionedIntervalTimeline<String, DataSegment> timeline = new VersionedIntervalTimeline<>( Ordering.natural()); for (DataSegment segment : segmentsList) { timeline.add(segment.getInterval(), segment.getVersion(), segment.getShardSpec().createChunk(segment)); } final List<TimelineObjectHolder<String, DataSegment>> timeLineSegments = timeline .lookup(ingestionSpecObj.getInterval()); final List<WindowedDataSegment> windowedSegments = Lists.newArrayList(); for (TimelineObjectHolder<String, DataSegment> holder : timeLineSegments) { for (PartitionChunk<DataSegment> chunk : holder.getObject()) { windowedSegments.add(new WindowedDataSegment(chunk.getObject(), holder.getInterval())); } } datasourcePathSpec.put(segments, windowedSegments); } return spec; }
From source file:eu.lp0.cursus.scoring.scores.impl.GenericRacePositionsData.java
@Override protected LinkedListMultimap<Integer, Pilot> calculateRacePositionsWithOrder(Race race) { // Create a lap order list containing all pilots List<Pilot> lapOrder = new ArrayList<Pilot>(scores.getPilots().size()); lapOrder.addAll(scores.getLapOrder(race)); Set<Pilot> pilotsWithLaps = ImmutableSet.copyOf(lapOrder); SortedSet<Pilot> pilotsWithoutLaps = new TreeSet<Pilot>(new PilotRaceNumberComparator()); pilotsWithoutLaps.addAll(Sets.difference(scores.getPilots(), pilotsWithLaps)); lapOrder.addAll(pilotsWithoutLaps);/* w w w.j a va 2s.co m*/ // Add penalties to race points Map<Pilot, Integer> racePoints = scores.getRacePoints(race); Map<Pilot, Integer> racePenalties = scores.getRacePenalties(race); Map<Pilot, Integer> racePointsWithPenalties = new HashMap<Pilot, Integer>(scores.getPilots().size() * 2); for (Pilot pilot : scores.getPilots()) { racePointsWithPenalties.put(pilot, racePoints.get(pilot) + racePenalties.get(pilot)); } // Invert race points with ordered lists of pilots TreeMultimap<Integer, Pilot> invRacePoints = TreeMultimap.create(Ordering.natural(), Ordering.explicit(lapOrder)); Multimaps.invertFrom(Multimaps.forMap(racePointsWithPenalties), invRacePoints); // Calculate race positions LinkedListMultimap<Integer, Pilot> racePositions = LinkedListMultimap.create(); LinkedList<SortedSet<Pilot>> pilotPointsOrdering = new LinkedList<SortedSet<Pilot>>(); int position = 1; if (simulatedToEnd) { Set<Pilot> simulatedRacePoints = scores.getSimulatedRacePoints(race); for (Integer points : invRacePoints.keySet()) { SortedSet<Pilot> pilots = Sets.filter(invRacePoints.get(points), Predicates.not(Predicates.in(simulatedRacePoints))); if (!pilots.isEmpty()) { pilotPointsOrdering.add(pilots); } } for (Integer points : invRacePoints.keySet()) { SortedSet<Pilot> pilots = Sets.filter(invRacePoints.get(points), Predicates.in(simulatedRacePoints)); if (!pilots.isEmpty()) { pilotPointsOrdering.add(pilots); } } } else { for (Integer points : invRacePoints.keySet()) { pilotPointsOrdering.add(invRacePoints.get(points)); } } for (SortedSet<Pilot> pilots : pilotPointsOrdering) { switch (equalPositioning) { case ALWAYS: // Always put pilots with the same points in the same position racePositions.putAll(position, pilots); position += pilots.size(); break; case WITHOUT_LAPS: // Add everyone with laps (by removing pilots without laps from the set) in separate positions for (Pilot pilot : Sets.difference(pilots, pilotsWithoutLaps)) { racePositions.put(position, pilot); position++; } // Add everyone without laps (by removing pilots with laps from the set) in the same position Set<Pilot> pilots2 = Sets.difference(pilots, pilotsWithLaps); racePositions.putAll(position, pilots2); position += pilots2.size(); break; case NEVER: // Always put pilots with the same points in separate positions for (Pilot pilot : pilots) { racePositions.put(position, pilot); position++; } break; } } return racePositions; }
From source file:com.google.caliper.runner.ConsoleOutput.java
/** * Prints a summary of a successful trial result. *//*from w ww . ja v a 2 s . co m*/ void processTrial(TrialResult result) { trialsCompleted++; stdout.printf("Trial Report (%d of %d):%n Experiment %s%n", trialsCompleted, numberOfTrials, result.getExperiment()); if (!result.getTrialMessages().isEmpty()) { stdout.println(" Messages:"); for (String message : result.getTrialMessages()) { stdout.print(" "); stdout.println(message); } } Trial trial = result.getTrial(); ImmutableListMultimap<String, Measurement> measurementsIndex = new ImmutableListMultimap.Builder<String, Measurement>() .orderKeysBy(Ordering.natural()) .putAll(Multimaps.index(trial.measurements(), new Function<Measurement, String>() { @Override public String apply(Measurement input) { return input.description(); } })).build(); stdout.println(" Results:"); for (Entry<String, Collection<Measurement>> entry : measurementsIndex.asMap().entrySet()) { Collection<Measurement> measurements = entry.getValue(); ImmutableSet<String> units = FluentIterable.from(measurements) .transform(new Function<Measurement, String>() { @Override public String apply(Measurement input) { return input.value().unit(); } }).toSet(); double[] weightedValues = new double[measurements.size()]; int i = 0; for (Measurement measurement : measurements) { weightedValues[i] = measurement.value().magnitude() / measurement.weight(); i++; } Percentile percentile = new Percentile(); percentile.setData(weightedValues); DescriptiveStatistics descriptiveStatistics = new DescriptiveStatistics(weightedValues); String unit = Iterables.getOnlyElement(units); stdout.printf(" %s%s: min=%.2f, 1st qu.=%.2f, median=%.2f, mean=%.2f, 3rd qu.=%.2f, max=%.2f%n", entry.getKey(), unit.isEmpty() ? "" : "(" + unit + ")", descriptiveStatistics.getMin(), percentile.evaluate(25), percentile.evaluate(50), descriptiveStatistics.getMean(), percentile.evaluate(75), descriptiveStatistics.getMax()); } instrumentSpecs.add(trial.instrumentSpec()); Scenario scenario = trial.scenario(); vmSpecs.add(scenario.vmSpec()); benchmarkSpecs.add(scenario.benchmarkSpec()); numMeasurements += trial.measurements().size(); }
From source file:com.facebook.buck.jvm.java.MavenUberJar.java
private static ImmutableSortedSet<Path> toOutputPaths(Iterable<? extends BuildRule> rules) { return FluentIterable.from(rules).transform(new Function<BuildRule, Path>() { @Nullable/*from ww w .ja v a2 s. c o m*/ @Override public Path apply(BuildRule input) { Path pathToOutput = input.getPathToOutput(); if (pathToOutput == null) { return null; } return input.getProjectFilesystem().resolve(pathToOutput); } }).filter(Objects::nonNull).toSortedSet(Ordering.natural()); }
From source file:org.linagora.linshare.core.facade.webservice.admin.impl.MailActivationFacadeImpl.java
@Override public List<MailActivationAdminDto> findAll(String domainId) throws BusinessException { User actor = checkAuthentication(Role.ADMIN); if (domainId == null) domainId = actor.getDomainId();/*from w w w .j a va 2 s. c o m*/ Validate.notEmpty(domainId, "domain identifier must be set."); Iterable<MailActivation> entities = service.findAll(actor, domainId); Iterable<MailActivationAdminDto> transform = Iterables.transform(entities, MailActivationAdminDto.toDto()); // Copy is made because the transaction is closed at the end of every // method in facade classes. return Ordering.natural().immutableSortedCopy(transform); }
From source file:com.b2international.index.revision.DefaultRevisionIndex.java
@Override public <T> T read(final String branchPath, final RevisionIndexRead<T> read) { if (RevisionIndex.isBaseRefPath(branchPath)) { final String branchPathWithoutBaseRef = branchPath.substring(0, branchPath.length() - 1); if (RevisionBranch.MAIN_PATH.equals(branchPathWithoutBaseRef)) { throw new IllegalArgumentException("Cannot query base of MAIN branch"); }//w w w. j a v a2s. c om final RevisionBranch parent = getParentBranch(branchPathWithoutBaseRef); final RevisionBranch branch = getBranch(branchPathWithoutBaseRef); final Set<Integer> commonPath = Sets.intersection(branch.segments(), parent.segments()); final RevisionBranch baseOfBranch = new RevisionBranch(parent.path(), Ordering.natural().max(commonPath), commonPath); return read(baseOfBranch, read); } else if (RevisionIndex.isRevRangePath(branchPath)) { final String[] branches = RevisionIndex.getRevisionRangePaths(branchPath); final String basePath = branches[0]; final String comparePath = branches[1]; final RevisionBranch base = getBranch(basePath); final RevisionBranch compare = getBranch(comparePath); final Set<Integer> compareSegments = Sets.difference(compare.segments(), base.segments()); return read(new RevisionBranch(comparePath, compare.segmentId(), compareSegments), read); } else { return read(getBranch(branchPath), read); } }