@Autowired public ServerStatusService(SecurityService securityService, ServerInfoProvider... providerArray) { this.securityService = securityService; providers.addAll(Arrays.asList(providerArray)); providers.sort(Comparator.comparingDouble(ServerInfoProvider::priority)); }
/** * Find best split point, based on feature statistics. * * @return Best split point if it exists. */ public Optional<NodeSplit> findBestSplit() { return perFeatureStatistics.values().stream() .flatMap(x -> x.findBestSplit().map(Stream::of).orElse(Stream.empty())) .min(Comparator.comparingDouble(NodeSplit::getImpurity)); } }
private static Optional<List<Ticket>> ticketsBruteForce(Map<String, Fare> fares, Trip trip) { // Recursively enumerate all packages of tickets with which the trip can be done. // Take the cheapest. TicketPurchaseScoreCalculator ticketPurchaseScoreCalculator = new TicketPurchaseScoreCalculator(); return allShoppingCarts(fares, trip) .max(Comparator.comparingDouble(ticketPurchaseScoreCalculator::calculateScore)) .map(TicketPurchase::getTickets); }
@Override public Iterator<ServerHolder> pickServersToDrop(DataSegment toDrop, NavigableSet<ServerHolder> serverHolders) { List<ListenableFuture<Pair<Double, ServerHolder>>> futures = new ArrayList<>(); for (final ServerHolder server : serverHolders) { futures.add( exec.submit( () -> Pair.of(computeCost(toDrop, server, true), server) ) ); } final ListenableFuture<List<Pair<Double, ServerHolder>>> resultsFuture = Futures.allAsList(futures); try { // results is an un-ordered list of a pair consisting of the 'cost' of a segment being on a server and the server List<Pair<Double, ServerHolder>> results = resultsFuture.get(); return results.stream() // Comparator.comapringDouble will order by lowest cost... // reverse it because we want to drop from the highest cost servers first .sorted(Comparator.comparingDouble((Pair<Double, ServerHolder> o) -> o.lhs).reversed()) .map(x -> x.rhs).collect(Collectors.toList()) .iterator(); } catch (Exception e) { log.makeAlert(e, "Cost Balancer Multithread strategy wasn't able to complete cost computation.").emit(); } return Collections.emptyIterator(); }
private Comparator<PolicyStats> makeComparator() { switch (settings.report().sortBy().toLowerCase(US)) { case "policy": return Comparator.comparing(PolicyStats::name); case "hit rate": return Comparator.comparingDouble(PolicyStats::hitRate); case "hits": return Comparator.comparingLong(PolicyStats::hitCount); case "misses": return Comparator.comparingLong(PolicyStats::missCount); case "evictions": return Comparator.comparingLong(PolicyStats::evictionCount); case "admit rate": return Comparator.comparingLong(PolicyStats::admissionCount); case "steps": return Comparator.comparingLong(PolicyStats::operationCount); case "time": return Comparator.comparingLong(stats -> stats.stopwatch().elapsed(TimeUnit.NANOSECONDS)); default: throw new IllegalArgumentException("Unknown sort order: " + settings.report().sortBy()); } } }
private void parseSolutionsAndAddToResponse(List<List<Label.Transition>> solutions, PointList waypoints) { for (List<Label.Transition> solution : solutions) { final List<Trip.Leg> legs = tripFromLabel.getTrip(translation, graphExplorer, accessEgressWeighting, solution); final PathWrapper pathWrapper = tripFromLabel.createPathWrapper(translation, waypoints, legs); pathWrapper.setImpossible(solution.stream().anyMatch(t -> t.label.impossible)); pathWrapper.setTime((solution.get(solution.size()-1).label.currentTime - solution.get(0).label.currentTime)); response.add(pathWrapper); } Comparator<PathWrapper> c = Comparator.comparingInt(p -> (p.isImpossible() ? 1 : 0)); Comparator<PathWrapper> d = Comparator.comparingDouble(PathWrapper::getTime); response.getAll().sort(c.thenComparing(d)); }
.map(drivingClause -> calculateJoinComplementStats(leftStats, rightStats, drivingClause, criteria.size() - 1 + numberOfFilterClauses)) .filter(estimate -> !estimate.isOutputRowCountUnknown()) .max(comparingDouble(PlanNodeStatsEstimate::getOutputRowCount)) .map(estimate -> normalizer.normalize(estimate, types)) .orElse(PlanNodeStatsEstimate.unknown());
/** * Appends the specified element to the end of this list. * * @param userId userId * @param itemId itemId * @param score predicted score value */ public void addIndependently(int userId, int itemId, double score) { if (contextMultimap == null) { synchronized (this) { if (independentRanking) { contextMultimap = TreeMultimap.create(Comparator.comparingInt(k -> k), Comparator.comparingDouble(v -> -v.value)); } else { contextMultimap = TreeMultimap.create(Comparator.comparingInt(k -> k), Comparator.comparingInt(v -> v.key)); } } } contextMultimap.put(userId, new KeyValue<>(itemId, score)); }
int homeAirportListSize = Math.min(airportList.size() / 10, flightRoundTripsPerDay / 5); homeAirportList = airportList.stream() .sorted(Comparator.comparingDouble(centerAirport::getHaversineDistanceInKmTo)) .limit(homeAirportListSize) .collect(Collectors.toList());
Comparator.comparingDouble((ToDoubleFunction<BrokerAndSortedReplicas>) this::diskUsage) .thenComparingInt(bs -> bs.broker().id()); Comparator<Replica> replicaComparator = Comparator.comparingDouble(this::replicaSize).thenComparing(r -> r);
List<Replica> followers = clusterModel.partition(leaderReplica.topicPartition()).followers(); List<Broker> eligibleBrokers = followers.stream().map(Replica::broker) .sorted(Comparator.comparingDouble(a -> a.leadershipLoadForNwResources().expectedUtilizationFor(Resource.NW_IN))) .collect(Collectors.toList()); maybeApplyBalancingAction(clusterModel, leaderReplica, eligibleBrokers, ActionType.LEADERSHIP_MOVEMENT,
Comparator.comparingDouble((Broker b) -> utilizationPercentage(b, resource())).thenComparingInt(Broker::id)); if (_selfHealingDeadBrokersOnly) { candidateBrokers.addAll(clusterModel.aliveBrokers()); eligibleBrokers = new TreeSet<>(Comparator.comparingDouble((Broker b) -> utilizationPercentage(b, resource())) .thenComparingInt(Broker::id)); clusterModel.partition(replica.topicPartition()).followerBrokers().forEach(b -> {
double[] input = //... DoubleStream.of(input).boxed() .sorted(Comparator.comparingDouble(Math::abs)) .mapToDouble(a -> a).summaryStatistics();
Comparator.comparingDouble((Replica r) -> r.load().expectedUtilizationFor(resource())) .thenComparing(r -> r.topicPartition().toString()));
Entry<String, Double> min = Collections.min(map.entrySet(), Comparator.comparingDouble(Entry::getValue));
public Polygon(List<Point> points) { if (points.size() < 3) { throw new IllegalArgumentException( "Need at least three points, got " + points.size()); } this.points = new ArrayList<>(points); this.points.sort(comparingDouble(a -> Math.atan2(a.y, a.x))); }
@Test public void testRowSort() throws Exception { Table bush = Table.read().csv("../data/bush.csv"); Comparator<Row> rowComparator = Comparator.comparingDouble(o -> o.getShort("approval")); Table sorted = bush.sortOn(rowComparator); ShortColumn approval = sorted.shortColumn("approval"); for (int i = 0; i < bush.rowCount() - 2; i++) { assertTrue(approval.get(i) <= approval.get(i + 1)); } }
@Test public void testSwapReplicas() { Properties props = KafkaCruiseControlUnitTestUtils.getKafkaCruiseControlProperties(); props.setProperty(KafkaCruiseControlConfig.MAX_REPLICAS_PER_BROKER_CONFIG, Long.toString(10L)); props.setProperty(KafkaCruiseControlConfig.DISK_BALANCE_THRESHOLD_CONFIG, "1.05"); BalancingConstraint balancingConstraint = new BalancingConstraint(new KafkaCruiseControlConfig(props)); KafkaAssignerDiskUsageDistributionGoal goal = new KafkaAssignerDiskUsageDistributionGoal(balancingConstraint); ClusterModel clusterModel = createClusterModel(); Comparator<Replica> replicaComparator = Comparator.comparingDouble((Replica r) -> r.load().expectedUtilizationFor(DISK)) .thenComparing(r -> r); double meanDiskUsage = clusterModel.load().expectedUtilizationFor(DISK) / clusterModel.capacityFor(DISK); assertTrue(goal.swapReplicas(new BrokerAndSortedReplicas(clusterModel.broker(0), replicaComparator), new BrokerAndSortedReplicas(clusterModel.broker(1), replicaComparator), meanDiskUsage, clusterModel, Collections.emptySet())); assertFalse(goal.swapReplicas(new BrokerAndSortedReplicas(clusterModel.broker(0), replicaComparator), new BrokerAndSortedReplicas(clusterModel.broker(2), replicaComparator), meanDiskUsage, clusterModel, Collections.emptySet())); assertTrue(goal.swapReplicas(new BrokerAndSortedReplicas(clusterModel.broker(2), replicaComparator), new BrokerAndSortedReplicas(clusterModel.broker(3), replicaComparator), meanDiskUsage, clusterModel, Collections.emptySet())); }
static BytesRef encodeFloatRanges(Set<RangeFieldMapper.Range> ranges) throws IOException { List<RangeFieldMapper.Range> sortedRanges = new ArrayList<>(ranges); Comparator<RangeFieldMapper.Range> fromComparator = Comparator.comparingDouble(range -> ((Number) range.from).floatValue()); Comparator<RangeFieldMapper.Range> toComparator = Comparator.comparingDouble(range -> ((Number) range.to).floatValue()); sortedRanges.sort(fromComparator.thenComparing(toComparator)); final byte[] encoded = new byte[5 + (4 * 2) * sortedRanges.size()]; ByteArrayDataOutput out = new ByteArrayDataOutput(encoded); out.writeVInt(sortedRanges.size()); for (RangeFieldMapper.Range range : sortedRanges) { byte[] encodedFrom = encodeFloat(((Number) range.from).floatValue()); out.writeBytes(encodedFrom, encodedFrom.length); byte[] encodedTo = encodeFloat(((Number) range.to).floatValue()); out.writeBytes(encodedTo, encodedTo.length); } return new BytesRef(encoded, 0, out.getPosition()); }
static BytesRef encodeDoubleRanges(Set<RangeFieldMapper.Range> ranges) throws IOException { List<RangeFieldMapper.Range> sortedRanges = new ArrayList<>(ranges); Comparator<RangeFieldMapper.Range> fromComparator = Comparator.comparingDouble(range -> ((Number) range.from).doubleValue()); Comparator<RangeFieldMapper.Range> toComparator = Comparator.comparingDouble(range -> ((Number) range.to).doubleValue()); sortedRanges.sort(fromComparator.thenComparing(toComparator)); final byte[] encoded = new byte[5 + (8 * 2) * sortedRanges.size()]; ByteArrayDataOutput out = new ByteArrayDataOutput(encoded); out.writeVInt(sortedRanges.size()); for (RangeFieldMapper.Range range : sortedRanges) { byte[] encodedFrom = encodeDouble(((Number) range.from).doubleValue()); out.writeBytes(encodedFrom, encodedFrom.length); byte[] encodedTo = encodeDouble(((Number) range.to).doubleValue()); out.writeBytes(encodedTo, encodedTo.length); } return new BytesRef(encoded, 0, out.getPosition()); }