Example usage for java.util Collections reverseOrder

List of usage examples for java.util Collections reverseOrder

Introduction

In this page you can find the example usage for java.util Collections reverseOrder.

Prototype

@SuppressWarnings("unchecked")
public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) 

Source Link

Document

Returns a comparator that imposes the reverse ordering of the specified comparator.

Usage

From source file:org.wso2.carbon.andes.admin.AndesAdminService.java

/**
 * Gets all subscriptions.//w w  w  .ja  va  2 s . c o  m
 * Suppressing 'MismatchedQueryAndUpdateOfCollection' as 'allSubscriptions' is used to convert
 * to an array.
 *
 * @return An array of {@link Subscription}.
 * @throws BrokerManagerAdminException
 */
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
public Subscription[] getAllSubscriptions() throws BrokerManagerAdminException {
    List<Subscription> allSubscriptions = new ArrayList<Subscription>();
    Subscription[] subscriptionsDTO;
    try {
        SubscriptionManagerService subscriptionManagerService = AndesBrokerManagerAdminServiceDSHolder
                .getInstance().getSubscriptionManagerService();
        List<org.wso2.carbon.andes.core.types.Subscription> subscriptions = subscriptionManagerService
                .getAllSubscriptions();
        subscriptionsDTO = new Subscription[subscriptions.size()];
        for (org.wso2.carbon.andes.core.types.Subscription sub : subscriptions) {
            Subscription subscriptionDTO = new Subscription();
            subscriptionDTO.setSubscriptionIdentifier(sub.getSubscriptionIdentifier());
            subscriptionDTO.setSubscribedQueueOrTopicName(sub.getSubscribedQueueOrTopicName());
            subscriptionDTO.setSubscriberQueueBoundExchange(sub.getSubscriberQueueBoundExchange());
            subscriptionDTO.setSubscriberQueueName(sub.getSubscriberQueueName());
            subscriptionDTO.setDurable(sub.isDurable());
            subscriptionDTO.setActive(sub.isActive());
            subscriptionDTO
                    .setNumberOfMessagesRemainingForSubscriber(sub.getNumberOfMessagesRemainingForSubscriber());
            subscriptionDTO.setSubscriberNodeAddress(sub.getSubscriberNodeAddress());

            allSubscriptions.add(subscriptionDTO);
        }
        CustomSubscriptionComparator comparator = new CustomSubscriptionComparator();
        Collections.sort(allSubscriptions, Collections.reverseOrder(comparator));
        allSubscriptions.toArray(subscriptionsDTO);
    } catch (SubscriptionManagerException e) {
        String errorMessage = e.getMessage();
        log.error(errorMessage, e);
        throw new BrokerManagerAdminException(errorMessage, e);
    }
    return subscriptionsDTO;
}

From source file:business.services.LabRequestService.java

@Transactional
public List<LabRequestRepresentation> findLabRequestsForUser(User user, boolean fetchDetails) {
    List<LabRequestRepresentation> representations = null;
    if (user.isLabUser() || user.isHubUser()) {
        representations = findLabRequestsForLabUserOrHubUser(user, fetchDetails);
    } else if (user.isPalga()) {
        // Palga/*from w ww.ja  va 2  s  .c  om*/
        List<LabRequest> labRequests = labRequestRepository.findAll(sortByIdDesc());
        representations = convertLabRequestsToRepresentations(labRequests, fetchDetails);
    } else {
        // fetch requests in status "LabRequest" for requester
        List<HistoricProcessInstance> historicInstances = new ArrayList<>();
        for (HistoricProcessInstance instance : requestService.getProcessInstancesForUser(user)) {
            String statusText = (String) instance.getProcessVariables().get("status");
            if (statusText != null) {
                RequestStatus status = RequestStatus.forDescription(statusText);
                if (status == RequestStatus.LAB_REQUEST) {
                    historicInstances.add(instance);
                }
            }
        }
        log.info("#instances: " + historicInstances.size());
        representations = new ArrayList<>();
        // find associated lab requests
        for (HistoricProcessInstance instance : historicInstances) {
            List<LabRequest> labRequests = labRequestRepository.findAllByProcessInstanceId(instance.getId(),
                    sortByIdDesc());
            representations.addAll(convertLabRequestsToRepresentations(labRequests, fetchDetails));
        }
    }
    Collections.sort(representations, Collections.reverseOrder(labRequestComparator));
    return representations;
}

From source file:com.google.gwt.emultest.java.util.TreeMapTest.java

/**
 * Test method for 'java.util.TreeMap.TreeMap(SortedMap)'.
 *
 * @see java.util.TreeMap#TreeMap(SortedMap)
 *//*from w  ww  .  j  a v  a  2 s . com*/
public void testConstructor_SortedMap() {
    K[] keys = getKeys();
    V[] values = getValues();
    SortedMap<K, V> sourceMap = new TreeMap<K, V>();
    _assertEmpty(sourceMap);

    // populate the source map
    sourceMap.put(keys[0], values[0]);
    sourceMap.put(keys[1], values[1]);
    sourceMap.put(keys[2], values[2]);

    TreeMap<K, V> copyConstructed = new TreeMap<K, V>(sourceMap);
    _assertEquals(sourceMap, copyConstructed);

    Comparator<K> comp = Collections.reverseOrder(getComparator());
    TreeMap<K, V> reversedTreeMap = new TreeMap<K, V>(comp);
    reversedTreeMap.put(keys[0], values[0]);
    reversedTreeMap.put(keys[1], values[1]);
    TreeMap<K, V> anotherTreeMap = new TreeMap<K, V>(reversedTreeMap);
    assertTrue(anotherTreeMap.comparator() == comp);
    assertEquals(keys[1], anotherTreeMap.firstKey());
    assertEquals(keys[0], anotherTreeMap.lastKey());
}

From source file:net.sourceforge.fenixedu.domain.candidacyProcess.mobility.MobilityIndividualApplicationProcess.java

List<ReceptionEmailExecutedAction> getAllReceptionEmailNotifications() {
    List<ReceptionEmailExecutedAction> list = new ArrayList<ReceptionEmailExecutedAction>();

    for (ErasmusCandidacyProcessExecutedAction executedAction : ((MobilityApplicationProcess) getCandidacyProcess())
            .getErasmusCandidacyProcessExecutedActionSet()) {
        if (executedAction.isReceptionEmailExecutedAction()
                && executedAction.getSubjectMobilityIndividualApplicationProcessSet().contains(this)) {
            list.add((ReceptionEmailExecutedAction) executedAction);
        }/*  w w w .j av a  2 s.c  o m*/
    }

    Collections.sort(list, Collections.reverseOrder(new BeanComparator("whenOccured")));

    return list;
}

From source file:org.wso2.carbon.andes.admin.AndesAdminService.java

/**
 * Gets all durable queue subscriptions.
 * Suppressing 'MismatchedQueryAndUpdateOfCollection' as 'allSubscriptions' is used to convert
 * to an array.//from  w  w w. j a  v  a2s  . c  o  m
 *
 * @return An array of {@link Subscription}.
 * @throws BrokerManagerAdminException
 */
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
public Subscription[] getAllDurableQueueSubscriptions() throws BrokerManagerAdminException {
    List<Subscription> allSubscriptions = new ArrayList<Subscription>();
    Subscription[] subscriptionsDTO;
    try {
        SubscriptionManagerService subscriptionManagerService = AndesBrokerManagerAdminServiceDSHolder
                .getInstance().getSubscriptionManagerService();
        List<org.wso2.carbon.andes.core.types.Subscription> subscriptions = subscriptionManagerService
                .getAllDurableQueueSubscriptions();
        subscriptionsDTO = new Subscription[subscriptions.size()];
        for (org.wso2.carbon.andes.core.types.Subscription sub : subscriptions) {
            Subscription subscriptionDTO = new Subscription();
            subscriptionDTO.setSubscriptionIdentifier(sub.getSubscriptionIdentifier());
            subscriptionDTO.setSubscribedQueueOrTopicName(sub.getSubscribedQueueOrTopicName());
            subscriptionDTO.setSubscriberQueueBoundExchange(sub.getSubscriberQueueBoundExchange());
            subscriptionDTO.setSubscriberQueueName(sub.getSubscriberQueueName());
            subscriptionDTO.setDurable(sub.isDurable());
            subscriptionDTO.setActive(sub.isActive());
            subscriptionDTO
                    .setNumberOfMessagesRemainingForSubscriber(sub.getNumberOfMessagesRemainingForSubscriber());
            subscriptionDTO.setSubscriberNodeAddress(sub.getSubscriberNodeAddress());

            allSubscriptions.add(subscriptionDTO);
        }
        CustomSubscriptionComparator comparator = new CustomSubscriptionComparator();
        Collections.sort(allSubscriptions, Collections.reverseOrder(comparator));
        allSubscriptions.toArray(subscriptionsDTO);
    } catch (SubscriptionManagerException e) {
        String errorMessage = e.getMessage();
        log.error(errorMessage, e);
        throw new BrokerManagerAdminException(errorMessage, e);
    }
    return subscriptionsDTO;
}

From source file:org.ligoj.app.plugin.id.ldap.dao.UserLdapRepository.java

@Override
public Page<UserOrg> findAll(final Collection<GroupOrg> requiredGroups, final Set<String> companies,
        final String criteria, final Pageable pageable) {
    // Create the set with the right comparator
    final List<Sort.Order> orders = IteratorUtils
            .toList(ObjectUtils.defaultIfNull(pageable.getSort(), new ArrayList<Sort.Order>()).iterator());
    orders.add(DEFAULT_ORDER);/*w  ww . ja va 2  s . co m*/
    final Sort.Order order = orders.get(0);
    Comparator<UserOrg> comparator = ObjectUtils.defaultIfNull(COMPARATORS.get(order.getProperty()),
            DEFAULT_COMPARATOR);
    if (order.getDirection() == Direction.DESC) {
        comparator = Collections.reverseOrder(comparator);
    }
    final Set<UserOrg> result = new TreeSet<>(comparator);

    // Filter the users traversing firstly the required groups and their members,
    // the companies, then the criteria
    final Map<String, UserOrg> users = findAll();
    if (requiredGroups == null) {
        // No constraint on group
        addFilteredByCompaniesAndPattern(users.keySet(), companies, criteria, result, users);
    } else {
        // User must be within one the given groups
        for (final GroupOrg requiredGroup : requiredGroups) {
            addFilteredByCompaniesAndPattern(requiredGroup.getMembers(), companies, criteria, result, users);
        }
    }

    // Apply in-memory pagination
    return inMemoryPagination.newPage(result, pageable);
}

From source file:org.apache.hadoop.hive.ql.optimizer.SharedWorkOptimizer.java

private static List<Entry<String, Long>> rankTablesByAccumulatedSize(ParseContext pctx) {
    Map<String, Long> tableToTotalSize = new HashMap<>();
    for (Entry<String, TableScanOperator> e : pctx.getTopOps().entrySet()) {
        TableScanOperator tsOp = e.getValue();
        String tableName = tsOp.getConf().getTableMetadata().getDbName() + "."
                + tsOp.getConf().getTableMetadata().getTableName();
        long tableSize = tsOp.getStatistics() != null ? tsOp.getStatistics().getDataSize() : 0L;
        Long totalSize = tableToTotalSize.get(tableName);
        if (totalSize != null) {
            tableToTotalSize.put(tableName, StatsUtils.safeAdd(totalSize, tableSize));
        } else {//  ww w.  j  a v a  2  s  .  co  m
            tableToTotalSize.put(tableName, tableSize);
        }
    }
    List<Entry<String, Long>> sortedTables = new LinkedList<>(tableToTotalSize.entrySet());
    Collections.sort(sortedTables, Collections.reverseOrder(new Comparator<Map.Entry<String, Long>>() {
        public int compare(Map.Entry<String, Long> o1, Map.Entry<String, Long> o2) {
            return (o1.getValue()).compareTo(o2.getValue());
        }
    }));
    return sortedTables;
}

From source file:cn.edu.bjtu.cit.recommender.Recommender.java

@SuppressWarnings("unchecked")
public int run(String[] args) throws Exception {
    if (args.length < 2) {
        System.err.println();//from w w w  . j  a  v  a2 s.c o  m
        System.err.println("Usage: " + this.getClass().getName()
                + " [generic options] input output [profiling] [estimation] [clustersize]");
        System.err.println();
        printUsage();
        GenericOptionsParser.printGenericCommandUsage(System.err);

        return 1;
    }
    OptionParser parser = new OptionParser(args);

    Pipeline pipeline = new MRPipeline(Recommender.class, getConf());

    if (parser.hasOption(CLUSTER_SIZE)) {
        pipeline.getConfiguration().setInt(ClusterOracle.CLUSTER_SIZE,
                Integer.parseInt(parser.getOption(CLUSTER_SIZE).getValue()));
    }

    if (parser.hasOption(PROFILING)) {
        pipeline.getConfiguration().setBoolean(Profiler.IS_PROFILE, true);
        this.profileFilePath = parser.getOption(PROFILING).getValue();

    }

    if (parser.hasOption(ESTIMATION)) {
        estFile = parser.getOption(ESTIMATION).getValue();
        est = new Estimator(estFile, clusterSize);
    }

    if (parser.hasOption(OPT_REDUCE)) {
        pipeline.getConfiguration().setBoolean(OPT_REDUCE, true);
    }

    if (parser.hasOption(OPT_MSCR)) {
        pipeline.getConfiguration().setBoolean(OPT_MSCR, true);
    }

    if (parser.hasOption(ACTIVE_THRESHOLD)) {
        threshold = Integer.parseInt(parser.getOption("at").getValue());
    }

    if (parser.hasOption(TOP)) {
        top = Integer.parseInt(parser.getOption("top").getValue());
    }

    profiler = new Profiler(pipeline);
    /*
     * input node
     */
    PCollection<String> lines = pipeline.readTextFile(args[0]);

    if (profiler.isProfiling() && lines.getSize() > 10 * 1024 * 1024) {
        lines = lines.sample(0.1);
    }

    /*
     * S0 + GBK
     */
    PGroupedTable<Long, Long> userWithPrefs = lines.parallelDo(new MapFn<String, Pair<Long, Long>>() {

        @Override
        public Pair<Long, Long> map(String input) {
            String[] split = input.split(Estimator.DELM);
            long userID = Long.parseLong(split[0]);
            long itemID = Long.parseLong(split[1]);
            return Pair.of(userID, itemID);
        }

        @Override
        public float scaleFactor() {
            return est.getScaleFactor("S0").sizeFactor;
        }

        @Override
        public float scaleFactorByRecord() {
            return est.getScaleFactor("S0").recsFactor;
        }
    }, Writables.tableOf(Writables.longs(), Writables.longs())).groupByKey(est.getClusterSize());

    /*
     * S1
     */
    PTable<Long, Vector> userVector = userWithPrefs
            .parallelDo(new MapFn<Pair<Long, Iterable<Long>>, Pair<Long, Vector>>() {
                @Override
                public Pair<Long, Vector> map(Pair<Long, Iterable<Long>> input) {
                    Vector userVector = new RandomAccessSparseVector(Integer.MAX_VALUE, 100);
                    for (long itemPref : input.second()) {
                        userVector.set((int) itemPref, 1.0f);
                    }
                    return Pair.of(input.first(), userVector);
                }

                @Override
                public float scaleFactor() {
                    return est.getScaleFactor("S1").sizeFactor;
                }

                @Override
                public float scaleFactorByRecord() {
                    return est.getScaleFactor("S1").recsFactor;
                }
            }, Writables.tableOf(Writables.longs(), Writables.vectors()));

    userVector = profiler.profile("S0-S1", pipeline, userVector, ProfileConverter.long_vector(),
            Writables.tableOf(Writables.longs(), Writables.vectors()));

    /*
     * S2
     */
    PTable<Long, Vector> filteredUserVector = userVector
            .parallelDo(new DoFn<Pair<Long, Vector>, Pair<Long, Vector>>() {

                @Override
                public void process(Pair<Long, Vector> input, Emitter<Pair<Long, Vector>> emitter) {
                    if (input.second().getNumNondefaultElements() > threshold) {
                        emitter.emit(input);
                    }
                }

                @Override
                public float scaleFactor() {
                    return est.getScaleFactor("S2").sizeFactor;
                }

                @Override
                public float scaleFactorByRecord() {
                    return est.getScaleFactor("S2").recsFactor;
                }

            }, Writables.tableOf(Writables.longs(), Writables.vectors()));

    filteredUserVector = profiler.profile("S2", pipeline, filteredUserVector, ProfileConverter.long_vector(),
            Writables.tableOf(Writables.longs(), Writables.vectors()));

    /*
     * S3 + GBK
     */
    PGroupedTable<Integer, Integer> coOccurencePairs = filteredUserVector
            .parallelDo(new DoFn<Pair<Long, Vector>, Pair<Integer, Integer>>() {
                @Override
                public void process(Pair<Long, Vector> input, Emitter<Pair<Integer, Integer>> emitter) {
                    Iterator<Vector.Element> it = input.second().iterateNonZero();
                    while (it.hasNext()) {
                        int index1 = it.next().index();
                        Iterator<Vector.Element> it2 = input.second().iterateNonZero();
                        while (it2.hasNext()) {
                            int index2 = it2.next().index();
                            emitter.emit(Pair.of(index1, index2));
                        }
                    }
                }

                @Override
                public float scaleFactor() {
                    float size = est.getScaleFactor("S3").sizeFactor;
                    return size;
                }

                @Override
                public float scaleFactorByRecord() {
                    float recs = est.getScaleFactor("S3").recsFactor;
                    return recs;
                }
            }, Writables.tableOf(Writables.ints(), Writables.ints())).groupByKey(est.getClusterSize());

    /*
     * S4
     */
    PTable<Integer, Vector> coOccurenceVector = coOccurencePairs
            .parallelDo(new MapFn<Pair<Integer, Iterable<Integer>>, Pair<Integer, Vector>>() {
                @Override
                public Pair<Integer, Vector> map(Pair<Integer, Iterable<Integer>> input) {
                    Vector cooccurrenceRow = new RandomAccessSparseVector(Integer.MAX_VALUE, 100);
                    for (int itemIndex2 : input.second()) {
                        cooccurrenceRow.set(itemIndex2, cooccurrenceRow.get(itemIndex2) + 1.0);
                    }
                    return Pair.of(input.first(), cooccurrenceRow);
                }

                @Override
                public float scaleFactor() {
                    return est.getScaleFactor("S4").sizeFactor;
                }

                @Override
                public float scaleFactorByRecord() {
                    return est.getScaleFactor("S4").recsFactor;
                }
            }, Writables.tableOf(Writables.ints(), Writables.vectors()));

    coOccurenceVector = profiler.profile("S3-S4", pipeline, coOccurenceVector, ProfileConverter.int_vector(),
            Writables.tableOf(Writables.ints(), Writables.vectors()));

    /*
     * S5 Wrapping co-occurrence columns
     */
    PTable<Integer, VectorOrPref> wrappedCooccurrence = coOccurenceVector
            .parallelDo(new MapFn<Pair<Integer, Vector>, Pair<Integer, VectorOrPref>>() {

                @Override
                public Pair<Integer, VectorOrPref> map(Pair<Integer, Vector> input) {
                    return Pair.of(input.first(), new VectorOrPref(input.second()));
                }

                @Override
                public float scaleFactor() {
                    return est.getScaleFactor("S5").sizeFactor;
                }

                @Override
                public float scaleFactorByRecord() {
                    return est.getScaleFactor("S5").recsFactor;
                }

            }, Writables.tableOf(Writables.ints(), VectorOrPref.vectorOrPrefs()));

    wrappedCooccurrence = profiler.profile("S5", pipeline, wrappedCooccurrence, ProfileConverter.int_vopv(),
            Writables.tableOf(Writables.ints(), VectorOrPref.vectorOrPrefs()));

    /*
     * S6 Splitting user vectors
     */
    PTable<Integer, VectorOrPref> userVectorSplit = filteredUserVector
            .parallelDo(new DoFn<Pair<Long, Vector>, Pair<Integer, VectorOrPref>>() {

                @Override
                public void process(Pair<Long, Vector> input, Emitter<Pair<Integer, VectorOrPref>> emitter) {
                    long userID = input.first();
                    Vector userVector = input.second();
                    Iterator<Vector.Element> it = userVector.iterateNonZero();
                    while (it.hasNext()) {
                        Vector.Element e = it.next();
                        int itemIndex = e.index();
                        float preferenceValue = (float) e.get();
                        emitter.emit(Pair.of(itemIndex, new VectorOrPref(userID, preferenceValue)));
                    }
                }

                @Override
                public float scaleFactor() {
                    return est.getScaleFactor("S6").sizeFactor;
                }

                @Override
                public float scaleFactorByRecord() {
                    return est.getScaleFactor("S6").recsFactor;
                }
            }, Writables.tableOf(Writables.ints(), VectorOrPref.vectorOrPrefs()));

    userVectorSplit = profiler.profile("S6", pipeline, userVectorSplit, ProfileConverter.int_vopp(),
            Writables.tableOf(Writables.ints(), VectorOrPref.vectorOrPrefs()));

    /*
     * S7 Combine VectorOrPrefs
     */
    PTable<Integer, VectorAndPrefs> combinedVectorOrPref = wrappedCooccurrence.union(userVectorSplit)
            .groupByKey(est.getClusterSize())
            .parallelDo(new DoFn<Pair<Integer, Iterable<VectorOrPref>>, Pair<Integer, VectorAndPrefs>>() {

                @Override
                public void process(Pair<Integer, Iterable<VectorOrPref>> input,
                        Emitter<Pair<Integer, VectorAndPrefs>> emitter) {
                    Vector vector = null;
                    List<Long> userIDs = Lists.newArrayList();
                    List<Float> values = Lists.newArrayList();
                    for (VectorOrPref vop : input.second()) {
                        if (vector == null) {
                            vector = vop.getVector();
                        }
                        long userID = vop.getUserID();
                        if (userID != Long.MIN_VALUE) {
                            userIDs.add(vop.getUserID());
                        }
                        float value = vop.getValue();
                        if (!Float.isNaN(value)) {
                            values.add(vop.getValue());
                        }
                    }
                    emitter.emit(Pair.of(input.first(), new VectorAndPrefs(vector, userIDs, values)));
                }

                @Override
                public float scaleFactor() {
                    return est.getScaleFactor("S7").sizeFactor;
                }

                @Override
                public float scaleFactorByRecord() {
                    return est.getScaleFactor("S7").recsFactor;
                }
            }, Writables.tableOf(Writables.ints(), VectorAndPrefs.vectorAndPrefs()));

    combinedVectorOrPref = profiler.profile("S5+S6-S7", pipeline, combinedVectorOrPref,
            ProfileConverter.int_vap(), Writables.tableOf(Writables.ints(), VectorAndPrefs.vectorAndPrefs()));
    /*
     * S8 Computing partial recommendation vectors
     */
    PTable<Long, Vector> partialMultiply = combinedVectorOrPref
            .parallelDo(new DoFn<Pair<Integer, VectorAndPrefs>, Pair<Long, Vector>>() {
                @Override
                public void process(Pair<Integer, VectorAndPrefs> input, Emitter<Pair<Long, Vector>> emitter) {
                    Vector cooccurrenceColumn = input.second().getVector();
                    List<Long> userIDs = input.second().getUserIDs();
                    List<Float> prefValues = input.second().getValues();
                    for (int i = 0; i < userIDs.size(); i++) {
                        long userID = userIDs.get(i);
                        if (userID != Long.MIN_VALUE) {
                            float prefValue = prefValues.get(i);
                            Vector partialProduct = cooccurrenceColumn.times(prefValue);
                            emitter.emit(Pair.of(userID, partialProduct));
                        }
                    }
                }

                @Override
                public float scaleFactor() {
                    return est.getScaleFactor("S8").sizeFactor;
                }

                @Override
                public float scaleFactorByRecord() {
                    return est.getScaleFactor("S8").recsFactor;
                }

            }, Writables.tableOf(Writables.longs(), Writables.vectors())).groupByKey(est.getClusterSize())
            .combineValues(new CombineFn<Long, Vector>() {

                @Override
                public void process(Pair<Long, Iterable<Vector>> input, Emitter<Pair<Long, Vector>> emitter) {
                    Vector partial = null;
                    for (Vector vector : input.second()) {
                        partial = partial == null ? vector : partial.plus(vector);
                    }
                    emitter.emit(Pair.of(input.first(), partial));
                }

                @Override
                public float scaleFactor() {
                    return est.getScaleFactor("combine").sizeFactor;
                }

                @Override
                public float scaleFactorByRecord() {
                    return est.getScaleFactor("combine").recsFactor;
                }
            });

    partialMultiply = profiler.profile("S8-combine", pipeline, partialMultiply, ProfileConverter.long_vector(),
            Writables.tableOf(Writables.longs(), Writables.vectors()));

    /*
     * S9 Producing recommendations from vectors
     */
    PTable<Long, RecommendedItems> recommendedItems = partialMultiply
            .parallelDo(new DoFn<Pair<Long, Vector>, Pair<Long, RecommendedItems>>() {

                @Override
                public void process(Pair<Long, Vector> input, Emitter<Pair<Long, RecommendedItems>> emitter) {
                    Queue<RecommendedItem> topItems = new PriorityQueue<RecommendedItem>(11,
                            Collections.reverseOrder(BY_PREFERENCE_VALUE));
                    Iterator<Vector.Element> recommendationVectorIterator = input.second().iterateNonZero();
                    while (recommendationVectorIterator.hasNext()) {
                        Vector.Element element = recommendationVectorIterator.next();
                        int index = element.index();
                        float value = (float) element.get();
                        if (topItems.size() < top) {
                            topItems.add(new GenericRecommendedItem(index, value));
                        } else if (value > topItems.peek().getValue()) {
                            topItems.add(new GenericRecommendedItem(index, value));
                            topItems.poll();
                        }
                    }
                    List<RecommendedItem> recommendations = new ArrayList<RecommendedItem>(topItems.size());
                    recommendations.addAll(topItems);
                    Collections.sort(recommendations, BY_PREFERENCE_VALUE);
                    emitter.emit(Pair.of(input.first(), new RecommendedItems(recommendations)));
                }

                @Override
                public float scaleFactor() {
                    return est.getScaleFactor("S9").sizeFactor;
                }

                @Override
                public float scaleFactorByRecord() {
                    return est.getScaleFactor("S9").recsFactor;
                }

            }, Writables.tableOf(Writables.longs(), RecommendedItems.recommendedItems()));

    recommendedItems = profiler.profile("S9", pipeline, recommendedItems, ProfileConverter.long_ri(),
            Writables.tableOf(Writables.longs(), RecommendedItems.recommendedItems()));

    /*
     * Profiling
     */
    if (profiler.isProfiling()) {
        profiler.writeResultToFile(profileFilePath);
        profiler.cleanup(pipeline.getConfiguration());
        return 0;
    }
    /*
     * asText
     */
    pipeline.writeTextFile(recommendedItems, args[1]);
    PipelineResult result = pipeline.done();
    return result.succeeded() ? 0 : 1;
}

From source file:MailHandlerDemo.java

/**
 * Example for various kinds of custom sorting, formatting, and filtering
 * for multiple attachment messages. The subject will contain the most
 * severe record and a count of remaining records. The log records are
 * ordered from most severe to least severe. The body uses a custom
 * formatter that includes a summary by date and time. The attachment use
 * XML and plain text formats. Each attachment has a different set of
 * filtering. The attachment names are generated from either a fixed name or
 * are built using the number and type of the records formatted. On close
 * any remaining messages are sent. Use the LogManager config option or
 * extend the MemoryHandler to emulate this behavior via the
 * logging.properties./* w w  w .  j ava 2  s . c om*/
 */
private static void initCustomAttachments() {
    MailHandler h = new MailHandler();

    //Sort records by severity keeping the severe messages at the top.
    h.setComparator(Collections.reverseOrder(new SeverityComparator()));

    //Use subject to provide a hint as to what is in the email.
    h.setSubject(new CollectorFormatter());

    //Make the body give a simple summary of what happened.
    h.setFormatter(new SummaryFormatter());

    //Create 3 attachments.
    h.setAttachmentFormatters(new XMLFormatter(), new XMLFormatter(), new SimpleFormatter());

    //Filter each attachment differently.
    h.setAttachmentFilters(null, new DurationFilter(3L, 1000L), new DurationFilter(1L, 15L * 60L * 1000L));

    //Creating the attachment name formatters.
    h.setAttachmentNames(new CollectorFormatter("all.xml"),
            new CollectorFormatter("{3} records and {5} errors.xml"),
            new CollectorFormatter("{5,choice,0#no errors|1#1 error|1<" + "{5,number,integer} errors}.txt"));

    LOGGER.addHandler(h);
}

From source file:structuredoutputcbr.adaptation.Adaptation.java

/**
 * Apply the relaxation constrains specified in the description of the new problem
 *//* w w  w  . j a v  a 2s  .co  m*/
private void applyRelaxations() {
    //List of all muscular relaxations
    ArrayList<OntologyElement> muscular_groups_handicaps = this.new_case.getDescription()
            .getAttributeOntologies(this.relaxations_key);

    //Iterate over all the relaxations
    for (OntologyElement group : muscular_groups_handicaps) {
        //The planning of the actual new case
        ArrayList<CaseBlock> planning = this.new_case.getSolution().getAttributeComponents(this.planning_key);

        //All the exercises of specific muscular group
        ArrayList<OntologyElement> exercises_mg = StructuredOutputCBR.ontology.getElement(group.getName())
                .getRelationValues("exercises");

        //All the exercises of specific muscular group in the actual planning
        ArrayList<CaseBlock> exercises_mg_planing = this
                .getAllExercisesFromMuscularGroup(this.getAllExercisesFromAPlanning(planning), group);

        //All the combinations of exercises in muscular grups whit size exercises_mg_planing
        ArrayList<ArrayList<OntologyElement>> combinations = this.nCr(exercises_mg,
                exercises_mg_planing.size());

        //Sort element with the sepecific criterium detailed in the documentation union - intersection <TIME CONSUMING!!!!!!!!!!!!!>
        Collections.sort(combinations, Collections.reverseOrder(new ComparatorBetweenCombinations(group)));

        int used_exercises = 0;

        //Iterate over all the exercises of a planning and substitute the ones from specifc muscular group
        for (int day = 0; day < this.new_case.getDescription().getAttributeInteger(this.sessions_key,
                0); day++) {
            for (int ex = 0; ex < this.new_case.getSolution().getAttributeComponents(this.planning_key).get(day)
                    .getAttributeComponents(this.program_key).size(); ex++) {
                if (this.new_case.getSolution().getAttributeComponents(this.planning_key).get(day)
                        .getAttributeComponents(this.program_key).get(ex)
                        .getAttributeOntology(this.exercise_key, 0).getRelationValues("muscular groups")
                        .contains(group)) {
                    this.new_case.getSolution().getAttributeComponents(this.planning_key).get(day)
                            .getAttributeComponents(this.program_key).get(ex)
                            .setAttributeContent(this.exercise_key, combinations.get(0).get(used_exercises));
                    used_exercises++;
                }
            }
        }

    }

}