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() 

Source Link

Document

Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.

Usage

From source file:com.medigy.persist.model.person.Person.java

@Transient
public MaritalStatusType getCurrentMaritalStatus() {
    final List<MaritalStatus> maritalStatuses = getMaritalStatuses();
    if (maritalStatuses.size() == 0)
        return MaritalStatusType.Cache.UNKNOWN.getEntity();

    TreeSet<MaritalStatus> inverseSorted = new TreeSet<MaritalStatus>(Collections.reverseOrder());
    inverseSorted.addAll(maritalStatuses);
    return inverseSorted.first().getType();
}

From source file:org.apache.impala.analysis.TupleDescriptor.java

public void computeMemLayout() {
    if (hasMemLayout_)
        return;//w w w  . ja v a 2 s.  com
    hasMemLayout_ = true;

    boolean alwaysAddNullBit = hasNullableKuduScanSlots();

    // maps from slot size to slot descriptors with that size
    Map<Integer, List<SlotDescriptor>> slotsBySize = new HashMap<Integer, List<SlotDescriptor>>();

    // populate slotsBySize
    int numNullBits = 0;
    int totalSlotSize = 0;
    for (SlotDescriptor d : slots_) {
        if (!d.isMaterialized())
            continue;
        ColumnStats stats = d.getStats();
        if (stats.hasAvgSerializedSize()) {
            avgSerializedSize_ += d.getStats().getAvgSerializedSize();
        } else {
            // TODO: for computed slots, try to come up with stats estimates
            avgSerializedSize_ += d.getType().getSlotSize();
        }
        if (!slotsBySize.containsKey(d.getType().getSlotSize())) {
            slotsBySize.put(d.getType().getSlotSize(), new ArrayList<SlotDescriptor>());
        }
        totalSlotSize += d.getType().getSlotSize();
        slotsBySize.get(d.getType().getSlotSize()).add(d);
        if (d.getIsNullable() || alwaysAddNullBit)
            ++numNullBits;
    }
    // we shouldn't have anything of size <= 0
    Preconditions.checkState(!slotsBySize.containsKey(0));
    Preconditions.checkState(!slotsBySize.containsKey(-1));

    // assign offsets to slots in order of descending size
    numNullBytes_ = (numNullBits + 7) / 8;
    int slotOffset = 0;
    int nullIndicatorByte = totalSlotSize;
    int nullIndicatorBit = 0;
    // slotIdx is the index into the resulting tuple struct.  The first (largest) field
    // is 0, next is 1, etc.
    int slotIdx = 0;
    // sort slots in descending order of size
    List<Integer> sortedSizes = new ArrayList<Integer>(slotsBySize.keySet());
    Collections.sort(sortedSizes, Collections.reverseOrder());
    for (int slotSize : sortedSizes) {
        if (slotsBySize.get(slotSize).isEmpty())
            continue;
        for (SlotDescriptor d : slotsBySize.get(slotSize)) {
            Preconditions.checkState(d.isMaterialized());
            d.setByteSize(slotSize);
            d.setByteOffset(slotOffset);
            d.setSlotIdx(slotIdx++);
            slotOffset += slotSize;

            // assign null indicator
            if (d.getIsNullable() || alwaysAddNullBit) {
                d.setNullIndicatorByte(nullIndicatorByte);
                d.setNullIndicatorBit(nullIndicatorBit);
                nullIndicatorBit = (nullIndicatorBit + 1) % 8;
                if (nullIndicatorBit == 0)
                    ++nullIndicatorByte;
            }
            // non-nullable slots have 0 for the byte offset and -1 for the bit mask
            // to make sure IS NULL always evaluates to false in the BE without having
            // to check nullability explicitly
            if (!d.getIsNullable()) {
                d.setNullIndicatorBit(-1);
                d.setNullIndicatorByte(0);
            }
        }
    }
    Preconditions.checkState(slotOffset == totalSlotSize);

    byteSize_ = totalSlotSize + numNullBytes_;
}

From source file:org.ambraproject.struts2.AmbraFeedResult.java

/**
 * Build a <code>List&lt;Entry&gt;</code> from the Annotion Ids found by the query action.
 *
 * @param xmlBase     xml base url//from  w w  w  .  jav a 2  s  . c o m
 * @param annotations list of web annotations
 * @param trackbacks  list of trackbacks
 * @param maxResults  maximum number of results to display
 * @param formatting  if this parameter has the value FeedService.FEED_FORMATTING_COMPLETE, then display the entire
 *                    text of every available field
 * @return List of entries for the feed
 * @throws Exception Exception
 */
private List<Entry> buildAnnotationFeed(String xmlBase, List<AnnotationView> annotations,
        List<LinkbackView> trackbacks, int maxResults, String formatting) throws Exception {

    // Combine annotations and trackbacks sorted by date
    SortedMap<Date, Object> map = new TreeMap<Date, Object>(Collections.reverseOrder());

    if (annotations != null) {
        for (AnnotationView annotation : annotations) {
            if (annotation.getType().equals(AnnotationType.REPLY)) {
                //AnnotationView rootAnnotation = getAnnotationRoot(annotation);
                map.put(annotation.getCreated(), annotation);
            } else {
                map.put(annotation.getCreated(), annotation);
            }

        }
    }

    if (trackbacks != null) {
        for (LinkbackView trackback : trackbacks) {
            map.put(trackback.getCreated(), trackback);
        }
    }

    // Add each Article as a Feed Entry
    List<Entry> entries = new ArrayList<Entry>();

    int i = 0;
    for (Object view : map.values()) {
        entries.add(newEntry(view, xmlBase, formatting));

        // i starts with 1, if maxResults=0 this will not interrupt the loop
        if (++i == maxResults)
            break;
    }
    return entries;
}

From source file:org.apache.archiva.metadata.repository.stats.DefaultRepositoryStatisticsManager.java

@Override
public List<RepositoryStatistics> getStatisticsInRange(MetadataRepository metadataRepository,
        String repositoryId, Date startTime, Date endTime) throws MetadataRepositoryException {
    List<RepositoryStatistics> results = new ArrayList<>();
    List<String> list = metadataRepository.getMetadataFacets(repositoryId, RepositoryStatistics.FACET_ID);
    Collections.sort(list, Collections.reverseOrder());
    for (String name : list) {
        try {/*  w  w  w.  j av a  2s  .c om*/
            Date date = createNameFormat().parse(name);
            if ((startTime == null || !date.before(startTime)) && (endTime == null || !date.after(endTime))) {
                RepositoryStatistics stats = (RepositoryStatistics) metadataRepository
                        .getMetadataFacet(repositoryId, RepositoryStatistics.FACET_ID, name);
                results.add(stats);
            }
        } catch (ParseException e) {
            log.error("Invalid scan result found in the metadata repository: " + e.getMessage());
            // continue and ignore this one
        }
    }
    return results;
}

From source file:com.notepadlite.NoteListFragment.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void listNotes() {
    // Get number of files
    int numOfFiles = getNumOfNotes(getActivity().getFilesDir());
    int numOfNotes = numOfFiles;

    // Get array of file names
    String[] listOfFiles = getListOfNotes(getActivity().getFilesDir());
    ArrayList<String> listOfNotes = new ArrayList<>();

    // Remove any files from the list that aren't notes
    for (int i = 0; i < numOfFiles; i++) {
        if (NumberUtils.isNumber(listOfFiles[i]))
            listOfNotes.add(listOfFiles[i]);
        else//  w ww  . ja  v a2 s. c  o  m
            numOfNotes--;
    }

    // Declare ListView
    final ListView listView = (ListView) getActivity().findViewById(R.id.listView1);

    // Create arrays of note lists
    String[] listOfNotesByDate = new String[numOfNotes];
    String[] listOfNotesByName = new String[numOfNotes];

    NoteListItem[] listOfTitlesByDate = new NoteListItem[numOfNotes];
    NoteListItem[] listOfTitlesByName = new NoteListItem[numOfNotes];

    ArrayList<NoteListItem> list = new ArrayList<>(numOfNotes);

    for (int i = 0; i < numOfNotes; i++) {
        listOfNotesByDate[i] = listOfNotes.get(i);
    }

    // If sort-by is "by date", sort in reverse order
    if (sortBy.equals("date"))
        Arrays.sort(listOfNotesByDate, Collections.reverseOrder());

    // Get array of first lines of each note
    for (int i = 0; i < numOfNotes; i++) {
        try {
            String title = listener.loadNoteTitle(listOfNotesByDate[i]);
            String date = listener.loadNoteDate(listOfNotesByDate[i]);
            listOfTitlesByDate[i] = new NoteListItem(title, date);
        } catch (IOException e) {
            showToast(R.string.error_loading_list);
        }
    }

    // If sort-by is "by name", sort alphabetically
    if (sortBy.equals("name")) {
        // Copy titles array
        System.arraycopy(listOfTitlesByDate, 0, listOfTitlesByName, 0, numOfNotes);

        // Sort titles
        Arrays.sort(listOfTitlesByName, NoteListItem.NoteComparatorTitle);

        // Initialize notes array
        for (int i = 0; i < numOfNotes; i++)
            listOfNotesByName[i] = "new";

        // Copy filenames array with new sort order of titles and nullify date arrays
        for (int i = 0; i < numOfNotes; i++) {
            for (int j = 0; j < numOfNotes; j++) {
                if (listOfTitlesByName[i].getNote().equals(listOfTitlesByDate[j].getNote())
                        && listOfNotesByName[i].equals("new")) {
                    listOfNotesByName[i] = listOfNotesByDate[j];
                    listOfNotesByDate[j] = "";
                    listOfTitlesByDate[j] = new NoteListItem("", "");
                }
            }
        }

        // Populate ArrayList with notes, showing name as first line of the notes
        list.addAll(Arrays.asList(listOfTitlesByName));
    } else if (sortBy.equals("date"))
        list.addAll(Arrays.asList(listOfTitlesByDate));

    // Create the custom adapters to bind the array to the ListView
    final NoteListDateAdapter dateAdapter = new NoteListDateAdapter(getActivity(), list);
    final NoteListAdapter adapter = new NoteListAdapter(getActivity(), list);

    // Display the ListView
    if (showDate)
        listView.setAdapter(dateAdapter);
    else
        listView.setAdapter(adapter);

    // Finalize arrays to prepare for handling clicked items
    final String[] finalListByDate = listOfNotesByDate;
    final String[] finalListByName = listOfNotesByName;

    // Make ListView handle clicked items
    listView.setClickable(true);
    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
            if (sortBy.equals("date")) {
                if (directEdit)
                    listener.editNote(finalListByDate[position]);
                else
                    listener.viewNote(finalListByDate[position]);
            } else if (sortBy.equals("name")) {
                if (directEdit)
                    listener.editNote(finalListByName[position]);
                else
                    listener.viewNote(finalListByName[position]);
            }
        }
    });

    // Make ListView handle contextual action bar
    final ArrayList<String> cab = new ArrayList<>(numOfNotes);

    listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            // Respond to clicks on the actions in the CAB
            switch (item.getItemId()) {
            case R.id.action_export:
                mode.finish(); // Action picked, so close the CAB
                listener.exportNote(cab.toArray());
                return true;
            case R.id.action_delete:
                mode.finish(); // Action picked, so close the CAB
                listener.deleteNote(cab.toArray());
                return true;
            default:
                return false;
            }
        }

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            listener.hideFab();

            // Inflate the menu for the CAB
            MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.context_menu, menu);

            // Clear any old values from cab array
            cab.clear();

            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            listener.showFab();
        }

        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
            // Add/remove filenames to cab array as they are checked/unchecked
            if (checked) {
                if (sortBy.equals("date"))
                    cab.add(finalListByDate[position]);
                if (sortBy.equals("name"))
                    cab.add(finalListByName[position]);
            } else {
                if (sortBy.equals("date"))
                    cab.remove(finalListByDate[position]);
                if (sortBy.equals("name"))
                    cab.remove(finalListByName[position]);
            }

            // Update the title in CAB
            if (cab.size() == 0)
                mode.setTitle("");
            else
                mode.setTitle(cab.size() + " " + listener.getCabString(cab.size()));
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }
    });

    // If there are no saved notes, then display the empty view
    if (numOfNotes == 0) {
        TextView empty = (TextView) getActivity().findViewById(R.id.empty);
        listView.setEmptyView(empty);
    }
}

From source file:com.diablominer.DiabloMiner.DiabloMiner.java

void execute(String[] args) throws Exception {
    threads.add(Thread.currentThread());

    Options options = new Options();
    options.addOption("u", "user", true, "bitcoin host username");
    options.addOption("p", "pass", true, "bitcoin host password");
    options.addOption("o", "host", true, "bitcoin host IP");
    options.addOption("r", "port", true, "bitcoin host port");
    options.addOption("l", "url", true, "bitcoin host url");
    options.addOption("x", "proxy", true, "optional proxy settings IP:PORT<:username:password>");
    options.addOption("g", "worklifetime", true, "maximum work lifetime in seconds");
    options.addOption("d", "debug", false, "enable debug output");
    options.addOption("dt", "debugtimer", false, "run for 1 minute and quit");
    options.addOption("D", "devices", true, "devices to enable, default all");
    options.addOption("f", "fps", true, "target GPU execution timing");
    options.addOption("na", "noarray", false, "turn GPU kernel array off");
    options.addOption("v", "vectors", true, "vector size in GPU kernel");
    options.addOption("w", "worksize", true, "override GPU worksize");
    options.addOption("ds", "ksource", false, "output GPU kernel source and quit");
    options.addOption("h", "help", false, "this help");

    PosixParser parser = new PosixParser();

    CommandLine line = null;/* w  ww.ja v a2  s. c  om*/

    try {
        line = parser.parse(options, args);

        if (line.hasOption("help")) {
            throw new ParseException("");
        }
    } catch (ParseException e) {
        System.out.println(e.getLocalizedMessage() + "\n");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("DiabloMiner -u myuser -p mypassword [args]\n", "", options,
                "\nRemember to set rpcuser and rpcpassword in your ~/.bitcoin/bitcoin.conf "
                        + "before starting bitcoind or bitcoin --daemon");
        return;
    }

    String splitUrl[] = null;
    String splitUser[] = null;
    String splitPass[] = null;
    String splitHost[] = null;
    String splitPort[] = null;

    if (line.hasOption("url"))
        splitUrl = line.getOptionValue("url").split(",");

    if (line.hasOption("user"))
        splitUser = line.getOptionValue("user").split(",");

    if (line.hasOption("pass"))
        splitPass = line.getOptionValue("pass").split(",");

    if (line.hasOption("host"))
        splitHost = line.getOptionValue("host").split(",");

    if (line.hasOption("port"))
        splitPort = line.getOptionValue("port").split(",");

    int networkStatesCount = 0;

    if (splitUrl != null)
        networkStatesCount = splitUrl.length;

    if (splitUser != null)
        networkStatesCount = Math.max(splitUser.length, networkStatesCount);

    if (splitPass != null)
        networkStatesCount = Math.max(splitPass.length, networkStatesCount);

    if (splitHost != null)
        networkStatesCount = Math.max(splitHost.length, networkStatesCount);

    if (splitPort != null)
        networkStatesCount = Math.max(splitPort.length, networkStatesCount);

    if (networkStatesCount == 0) {
        error("You forgot to give any bitcoin connection info, please add either -l, or -u -p -o and -r");
        System.exit(-1);
    }

    int j = 0;

    for (int i = 0; j < networkStatesCount; i++, j++) {
        String protocol = "http";
        String host = "localhost";
        int port = 8332;
        String path = "/";
        String user = "diablominer";
        String pass = "diablominer";
        byte hostChain = 0;

        if (splitUrl != null && splitUrl.length > i) {
            String[] usernameFix = splitUrl[i].split("@", 3);
            if (usernameFix.length > 2)
                splitUrl[i] = usernameFix[0] + "+++++" + usernameFix[1] + "@" + usernameFix[2];

            URL url = new URL(splitUrl[i]);

            if (url.getProtocol() != null && url.getProtocol().length() > 1)
                protocol = url.getProtocol();

            if (url.getHost() != null && url.getHost().length() > 1)
                host = url.getHost();

            if (url.getPort() != -1)
                port = url.getPort();

            if (url.getPath() != null && url.getPath().length() > 1)
                path = url.getPath();

            if (url.getUserInfo() != null && url.getUserInfo().length() > 1) {
                String[] userPassSplit = url.getUserInfo().split(":");

                user = userPassSplit[0].replace("+++++", "@");

                if (userPassSplit.length > 1 && userPassSplit[1].length() > 1)
                    pass = userPassSplit[1];
            }
        }

        if (splitUser != null && splitUser.length > i)
            user = splitUser[i];

        if (splitPass != null && splitPass.length > i)
            pass = splitPass[i];

        if (splitHost != null && splitHost.length > i)
            host = splitHost[i];

        if (splitPort != null && splitPort.length > i)
            port = Integer.parseInt(splitPort[i]);

        NetworkState networkState;

        try {
            networkState = new JSONRPCNetworkState(this, new URL(protocol, host, port, path), user, pass,
                    hostChain);
        } catch (MalformedURLException e) {
            throw new DiabloMinerFatalException(this, "Malformed connection paramaters");
        }

        if (networkStateHead == null) {
            networkStateHead = networkStateTail = networkState;
        } else {
            networkStateTail.setNetworkStateNext(networkState);
            networkStateTail = networkState;
        }
    }

    networkStateTail.setNetworkStateNext(networkStateHead);

    if (line.hasOption("proxy")) {
        final String[] proxySettings = line.getOptionValue("proxy").split(":");

        if (proxySettings.length >= 2) {
            proxy = new Proxy(Type.HTTP,
                    new InetSocketAddress(proxySettings[0], Integer.valueOf(proxySettings[1])));
        }

        if (proxySettings.length >= 3) {
            Authenticator.setDefault(new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(proxySettings[2], proxySettings[3].toCharArray());
                }
            });
        }
    }

    if (line.hasOption("worklifetime"))
        workLifetime = Integer.parseInt(line.getOptionValue("worklifetime")) * 1000;

    if (line.hasOption("debug"))
        debug = true;

    if (line.hasOption("debugtimer")) {
        debugtimer = true;
    }

    if (line.hasOption("devices")) {
        String devices[] = line.getOptionValue("devices").split(",");
        enabledDevices = new HashSet<String>();
        for (String s : devices) {
            enabledDevices.add(s);

            if (Integer.parseInt(s) == 0) {
                error("Do not use 0 with -D, devices start at 1");
                System.exit(-1);
            }
        }
    }

    if (line.hasOption("fps")) {
        GPUTargetFPS = Float.parseFloat(line.getOptionValue("fps"));

        if (GPUTargetFPS < 0.1) {
            error("--fps argument is too low, adjusting to 0.1");
            GPUTargetFPS = 0.1;
        }
    }

    if (line.hasOption("noarray")) {
        GPUNoArray = true;
    }

    if (line.hasOption("worksize"))
        GPUForceWorkSize = Integer.parseInt(line.getOptionValue("worksize"));

    if (line.hasOption("vectors")) {
        String tempVectors[] = line.getOptionValue("vectors").split(",");

        GPUVectors = new Integer[tempVectors.length];

        try {
            for (int i = 0; i < GPUVectors.length; i++) {
                GPUVectors[i] = Integer.parseInt(tempVectors[i]);

                if (GPUVectors[i] > 16) {
                    error("DiabloMiner now uses comma-seperated vector layouts, use those instead");
                    System.exit(-1);
                } else if (GPUVectors[i] != 1 && GPUVectors[i] != 2 && GPUVectors[i] != 3 && GPUVectors[i] != 4
                        && GPUVectors[i] != 8 && GPUVectors[i] != 16) {
                    error(GPUVectors[i] + " is not a vector length of 1, 2, 3, 4, 8, or 16");
                    System.exit(-1);
                }
            }

            Arrays.sort(GPUVectors, Collections.reverseOrder());
        } catch (NumberFormatException e) {
            error("Cannot parse --vector argument(s)");
            System.exit(-1);
        }
    } else {
        GPUVectors = new Integer[1];
        GPUVectors[0] = 1;
    }

    if (line.hasOption("ds"))
        GPUDebugSource = true;

    info("Started");

    StringBuilder list = new StringBuilder(networkStateHead.getQueryUrl().toString());
    NetworkState networkState = networkStateHead.getNetworkStateNext();

    while (networkState != networkStateHead) {
        list.append(", " + networkState.getQueryUrl());
        networkState = networkState.getNetworkStateNext();
    }

    info("Connecting to: " + list);

    long previousHashCount = 0;
    double previousAdjustedHashCount = 0.0;
    long previousAdjustedStartTime = startTime = (now()) - 1;
    StringBuilder hashMeter = new StringBuilder(80);
    Formatter hashMeterFormatter = new Formatter(hashMeter);

    int deviceCount = 0;

    List<List<? extends DeviceState>> allDeviceStates = new ArrayList<List<? extends DeviceState>>();

    List<? extends DeviceState> GPUDeviceStates = new GPUHardwareType(this).getDeviceStates();
    deviceCount += GPUDeviceStates.size();
    allDeviceStates.add(GPUDeviceStates);

    while (running.get()) {
        for (List<? extends DeviceState> deviceStates : allDeviceStates) {
            for (DeviceState deviceState : deviceStates) {
                deviceState.checkDevice();
            }
        }

        long now = now();
        long currentHashCount = hashCount.get();
        double adjustedHashCount = (double) (currentHashCount - previousHashCount)
                / (double) (now - previousAdjustedStartTime);
        double hashLongCount = (double) currentHashCount / (double) (now - startTime) / 1000.0;

        if (now - startTime > TIME_OFFSET * 2) {
            double averageHashCount = (adjustedHashCount + previousAdjustedHashCount) / 2.0 / 1000.0;

            hashMeter.setLength(0);

            if (!debug) {
                hashMeterFormatter.format("\rmhash: %.1f/%.1f | accept: %d | reject: %d | hw error: %d",
                        averageHashCount, hashLongCount, blocks.get(), rejects.get(), hwErrors.get());
            } else {
                hashMeterFormatter.format("\rmh: %.1f/%.1f | a/r/hwe: %d/%d/%d | gh: ", averageHashCount,
                        hashLongCount, blocks.get(), rejects.get(), hwErrors.get());

                double basisAverage = 0.0;

                for (List<? extends DeviceState> deviceStates : allDeviceStates) {
                    for (DeviceState deviceState : deviceStates) {
                        hashMeterFormatter.format("%.1f ",
                                deviceState.getDeviceHashCount() / 1000.0 / 1000.0 / 1000.0);
                        basisAverage += deviceState.getBasis();
                    }
                }

                basisAverage = 1000 / (basisAverage / deviceCount);

                hashMeterFormatter.format("| fps: %.1f", basisAverage);
            }

            System.out.print(hashMeter);
        } else {
            System.out.print("\rWaiting...");
        }

        if (now() - TIME_OFFSET * 2 > previousAdjustedStartTime) {
            previousHashCount = currentHashCount;
            previousAdjustedHashCount = adjustedHashCount;
            previousAdjustedStartTime = now - 1;
        }

        if (debugtimer && now() > startTime + 60 * 1000) {
            System.out.print("\n");
            info("Debug timer is up, quitting...");
            System.exit(0);
        }

        try {
            if (now - startTime > TIME_OFFSET)
                Thread.sleep(1000);
            else
                Thread.sleep(1);
        } catch (InterruptedException e) {
        }
    }

    hashMeterFormatter.close();
}

From source file:com.act.biointerpretation.mechanisminspection.MechanisticValidator.java

private TreeMap<Integer, List<Ero>> findBestRosThatCorrectlyComputeTheReaction(Reaction rxn, Long newRxnId)
        throws IOException {
    /* Look up any cached results and return immediately if they're available.
     * Note: this only works while EROs ignore cofactors.  If cofactors need to be involved, we should just remove this.
     *//*w ww  .  jav a2 s  .c  o m*/
    Map<Long, Integer> substrateToCoefficientMap = new HashMap<>();
    Map<Long, Integer> productToCoefficientMap = new HashMap<>();

    for (Long id : rxn.getSubstrates()) {
        substrateToCoefficientMap.put(id, rxn.getSubstrateCoefficient(id));
    }
    for (Long id : rxn.getProducts()) {
        productToCoefficientMap.put(id, rxn.getSubstrateCoefficient(id));
    }

    {
        Pair<Long, TreeMap<Integer, List<Ero>>> cachedResults = cachedEroResults
                .get(Pair.of(substrateToCoefficientMap, productToCoefficientMap));
        if (cachedResults != null) {
            LOGGER.debug("Got hit on cached ERO results: %d == %d", newRxnId, cachedResults.getLeft());
            cacheHitCounter++;
            return cachedResults.getRight();
        }
    }

    List<Molecule> substrateMolecules = new ArrayList<>();
    for (Long id : rxn.getSubstrates()) {
        String inchi = mapNewChemIdToInChI(id);
        if (inchi == null) {
            String msg = String.format("Missing inchi for new chem id %d in cache", id);
            LOGGER.error(msg);
            throw new RuntimeException(msg);
        }

        if (inchi.contains("FAKE")) {
            LOGGER.debug("The inchi is a FAKE, so just ignore the chemical.");
            continue;
        }

        Molecule mol;
        try {
            mol = MolImporter.importMol(blacklistedInchisCorpus.renameInchiIfFoundInBlacklist(inchi));

            // We had to clean the molecule after importing since based on our testing, the RO only matched the molecule
            // once we cleaned it. Else, the RO did not match the chemical.
            Cleaner.clean(mol, TWO_DIMENSION);

            // We had to aromatize the molecule so that aliphatic related ROs do not match with aromatic compounds.
            mol.aromatize(MoleculeGraph.AROM_BASIC);
        } catch (chemaxon.formats.MolFormatException e) {
            LOGGER.error("Error occurred while trying to import inchi %s: %s", inchi, e.getMessage());
            return null;
        }

        /* Some ROs depend on multiple copies of a given molecule (like #165), and the Reactor won't run without all of
         * those molecules available.  Duplicate a molecule in the substrates list based on its coefficient in the
         * reaction. */
        Integer coefficient = rxn.getSubstrateCoefficient(id);
        if (coefficient == null) {
            // Default to just one if we don't have a clear coefficient to use.
            LOGGER.warn("Converting coefficient null -> 1 for rxn %d/chem %d", newRxnId, id);
            coefficient = 1;
        }

        for (int i = 0; i < coefficient; i++) {
            substrateMolecules.add(mol);
        }
    }

    Set<String> expectedProducts = new HashSet<>();

    for (Long id : rxn.getProducts()) {
        String inchi = mapNewChemIdToInChI(id);
        if (inchi == null) {
            String msg = String.format("Missing inchi for new chem id %d in cache", id);
            LOGGER.error(msg);
            throw new RuntimeException(msg);
        }

        if (inchi.contains("FAKE")) {
            LOGGER.debug("The inchi is a FAKE, so just ignore the chemical.");
            continue;
        }

        String transformedInchi = removeChiralityFromChemical(inchi);
        if (transformedInchi == null) {
            return null;
        }
        expectedProducts.add(transformedInchi);
    }

    TreeMap<Integer, List<Ero>> scoreToListOfRos = new TreeMap<>(Collections.reverseOrder());
    for (Map.Entry<Ero, Reactor> entry : reactors.entrySet()) {
        Integer score = scoreReactionBasedOnRO(entry.getValue(), substrateMolecules, expectedProducts,
                entry.getKey(), newRxnId);
        if (score > ROScore.DEFAULT_UNMATCH_SCORE.getScore()) {
            List<Ero> vals = scoreToListOfRos.get(score);
            if (vals == null) {
                vals = new ArrayList<>();
                scoreToListOfRos.put(score, vals);
            }
            vals.add(entry.getKey());
        }
    }

    // Cache results for any future similar reactions.
    cachedEroResults.put(Pair.of(substrateToCoefficientMap, productToCoefficientMap),
            Pair.of(newRxnId, scoreToListOfRos));

    return scoreToListOfRos;
}

From source file:ubc.pavlab.gotrack.beans.TrackView.java

private void createAllTerms(Map<String, Map<Edition, Map<GeneOntologyTerm, Set<EvidenceReference>>>> data) {
    log.info("fetch All Terms");
    allAnnotations.clear();//w  w w  .  j a  va2s. c  om

    for (Map<Edition, Map<GeneOntologyTerm, Set<EvidenceReference>>> series : data.values()) {
        // We sort the editions so that newer versions will not be overwritten with older ones
        // This matters if we don't have go_term info for old editions
        List<Edition> eds = new ArrayList<Edition>(series.keySet());
        Collections.sort(eds, Collections.reverseOrder());
        for (Edition e : eds) {
            Map<GeneOntologyTerm, Set<EvidenceReference>> annots = series.get(e);
            for (Entry<GeneOntologyTerm, Set<EvidenceReference>> goEntry : annots.entrySet()) {
                GeneOntologyTerm go = goEntry.getKey();
                Set<EvidenceReference> evidence = goEntry.getValue();

                Set<EvidenceReference> allEvidence = allAnnotations.get(go);
                if (allEvidence == null) {
                    allEvidence = new HashSet<>();
                    allAnnotations.put(go, allEvidence);
                }

                allEvidence.addAll(evidence);

            }
        }
    }
    log.info("All Terms Fetched");

}

From source file:com.anjalimacwan.fragment.NoteListFragment.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void listNotes() {
    // Get number of files
    int numOfFiles = getNumOfNotes(getActivity().getFilesDir());
    int numOfNotes = numOfFiles;

    // Get array of file names
    String[] listOfFiles = getListOfNotes(getActivity().getFilesDir());
    ArrayList<String> listOfNotes = new ArrayList<>();

    // Remove any files from the list that aren't notes
    for (int i = 0; i < numOfFiles; i++) {
        if (NumberUtils.isNumber(listOfFiles[i]))
            listOfNotes.add(listOfFiles[i]);
        else/*ww w .  j a  v  a2s  .c o  m*/
            numOfNotes--;
    }

    // Declare ListView
    final ListView listView = (ListView) getActivity().findViewById(R.id.listView1);

    // Create arrays of note lists
    String[] listOfNotesByDate = new String[numOfNotes];
    String[] listOfNotesByName = new String[numOfNotes];

    NoteListItem[] listOfTitlesByDate = new NoteListItem[numOfNotes];
    NoteListItem[] listOfTitlesByName = new NoteListItem[numOfNotes];

    ArrayList<NoteListItem> list = new ArrayList<>(numOfNotes);

    for (int i = 0; i < numOfNotes; i++) {
        listOfNotesByDate[i] = listOfNotes.get(i);
    }

    // If sort-by is "by date", sort in reverse order
    if (sortBy.equals("date"))
        Arrays.sort(listOfNotesByDate, Collections.reverseOrder());

    // Get array of first lines of each note
    for (int i = 0; i < numOfNotes; i++) {
        try {
            String title = listener.loadNoteTitle(listOfNotesByDate[i]);
            String date = listener.loadNoteDate(listOfNotesByDate[i]);
            listOfTitlesByDate[i] = new NoteListItem(title, date);
        } catch (IOException e) {
            showToast(R.string.error_loading_list);
        }
    }

    // If sort-by is "by name", sort alphabetically
    if (sortBy.equals("name")) {
        // Copy titles array
        System.arraycopy(listOfTitlesByDate, 0, listOfTitlesByName, 0, numOfNotes);

        // Sort titles
        Arrays.sort(listOfTitlesByName, NoteListItem.NoteComparatorTitle);

        // Initialize notes array
        for (int i = 0; i < numOfNotes; i++)
            listOfNotesByName[i] = "new";

        // Copy filenames array with new sort order of titles and nullify date arrays
        for (int i = 0; i < numOfNotes; i++) {
            for (int j = 0; j < numOfNotes; j++) {
                if (listOfTitlesByName[i].getNote().equals(listOfTitlesByDate[j].getNote())
                        && listOfNotesByName[i].equals("new")) {
                    listOfNotesByName[i] = listOfNotesByDate[j];
                    listOfNotesByDate[j] = "";
                    listOfTitlesByDate[j] = new NoteListItem("", "");
                }
            }
        }

        // Populate ArrayList with notes, showing name as first line of the notes
        list.addAll(Arrays.asList(listOfTitlesByName));
    } else if (sortBy.equals("date"))
        list.addAll(Arrays.asList(listOfTitlesByDate));

    // Create the custom adapters to bind the array to the ListView
    final NoteListDateAdapter dateAdapter = new NoteListDateAdapter(getActivity(), list);
    final NoteListAdapter adapter = new NoteListAdapter(getActivity(), list);

    // Display the ListView
    if (showDate)
        listView.setAdapter(dateAdapter);
    else
        listView.setAdapter(adapter);

    // Finalize arrays to prepare for handling clicked items
    final String[] finalListByDate = listOfNotesByDate;
    final String[] finalListByName = listOfNotesByName;

    // Make ListView handle clicked items
    listView.setClickable(true);
    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
            if (sortBy.equals("date")) {
                if (directEdit)
                    listener.editNote(finalListByDate[position]);
                else
                    listener.viewNote(finalListByDate[position]);
            } else if (sortBy.equals("name")) {
                if (directEdit)
                    listener.editNote(finalListByName[position]);
                else
                    listener.viewNote(finalListByName[position]);
            }
        }
    });

    // Make ListView handle contextual action bar
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        final ArrayList<String> cab = new ArrayList<>(numOfNotes);

        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
        listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                // Respond to clicks on the actions in the CAB
                switch (item.getItemId()) {
                case R.id.action_export:
                    mode.finish(); // Action picked, so close the CAB
                    listener.exportNote(cab.toArray());
                    return true;
                case R.id.action_delete:
                    mode.finish(); // Action picked, so close the CAB
                    listener.deleteNote(cab.toArray());
                    return true;
                default:
                    return false;
                }
            }

            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                listener.hideFab();

                // Inflate the menu for the CAB
                MenuInflater inflater = mode.getMenuInflater();
                inflater.inflate(R.menu.context_menu, menu);

                // Clear any old values from cab array
                cab.clear();

                return true;
            }

            @Override
            public void onDestroyActionMode(ActionMode mode) {
                listener.showFab();
            }

            @Override
            public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
                // Add/remove filenames to cab array as they are checked/unchecked
                if (checked) {
                    if (sortBy.equals("date"))
                        cab.add(finalListByDate[position]);
                    if (sortBy.equals("name"))
                        cab.add(finalListByName[position]);
                } else {
                    if (sortBy.equals("date"))
                        cab.remove(finalListByDate[position]);
                    if (sortBy.equals("name"))
                        cab.remove(finalListByName[position]);
                }

                // Update the title in CAB
                if (cab.size() == 0)
                    mode.setTitle("");
                else
                    mode.setTitle(cab.size() + " " + listener.getCabString(cab.size()));
            }

            @Override
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }
        });
    }

    // If there are no saved notes, then display the empty view
    if (numOfNotes == 0) {
        TextView empty = (TextView) getActivity().findViewById(R.id.empty);
        listView.setEmptyView(empty);
    }
}

From source file:org.sakaiproject.gradebookng.tool.panels.SettingsGradingSchemaPanel.java

/**
 * Helper to sort the bottom percents maps. Caters for both letter grade and P/NP types
 *
 * @param gradingScaleName name of the grading schema so we know how to sort.
 * @param percents//  w w  w .j av  a  2  s . c o  m
 * @return
 */
private Map<String, Double> sortBottomPercents(final String gradingScaleName,
        final Map<String, Double> percents) {

    Map<String, Double> rval = null;

    if (StringUtils.equals(gradingScaleName, "Pass / Not Pass")) {
        rval = new TreeMap<>(Collections.reverseOrder()); // P before NP.
    } else if (StringUtils.contains(gradingScaleName, "Letter Grades")
            || StringUtils.contains(gradingScaleName, "Grade Points")) {
        rval = new TreeMap<>(new LetterGradeComparator()); // letter grade mappings
    } else {
        // Order by percent.
        DoubleComparator doubleComparator = new DoubleComparator(percents);
        rval = new TreeMap<String, Double>(doubleComparator);
    }
    rval.putAll(percents);

    return rval;
}