Example usage for java.util TreeSet add

List of usage examples for java.util TreeSet add

Introduction

In this page you can find the example usage for java.util TreeSet add.

Prototype

public boolean add(E e) 

Source Link

Document

Adds the specified element to this set if it is not already present.

Usage

From source file:ch.unil.genescore.pathway.GeneSetLibrary.java

License:asdf

/**
 * fills up  samplingWeightHelper_//from ww  w . j a  va2 s .c  om
 * 
 * key: gene_ids ; values: all pws that contain this gene (or metagene containing that gene.)  */
private void calculateSamplingWeightHelper() {
    HashMap<String, HashSet<GeneSet>> metaSet = new HashMap<String, HashSet<GeneSet>>();
    //Gene geneToProcess =null;      
    TreeSet<Gene> subGenes = null;
    for (GeneSet set : geneSets_) {
        for (Gene g : set.genes_) {
            if (g instanceof MetaGene) {
                MetaGene mg = (MetaGene) g;
                subGenes = mg.getGenes();
            } else {
                subGenes = new TreeSet<Gene>();
                subGenes.add(g);
            }

            //for (Gene subg : (MetaGene) g.getMetaGenes()))
            for (Gene geneToProcess : subGenes) {

                if (!metaSet.containsKey(geneToProcess.id_)) {
                    HashSet<GeneSet> setForG = new HashSet<GeneSet>();
                    setForG.add(set);
                    metaSet.put(geneToProcess.id_, setForG);
                } else {
                    metaSet.get(geneToProcess.id_).add(set);
                }
            }
        }
    }
    setSamplingWeightHelper(metaSet);
}

From source file:edu.purdue.cc.bionet.ui.DistributionAnalysisDisplayPanel.java

public void deselectOutliers() {
    Iterator<TreeNode> moleculeIterator = this.selectorTree
            .checkedDescendantIterator(this.selectorTree.getRoot(), MOLECULE);

    while (moleculeIterator.hasNext()) {
        DefaultMutableTreeNode moleculeNode = (DefaultMutableTreeNode) moleculeIterator.next();
        Molecule molecule = (Molecule) moleculeNode.getUserObject();

        Iterator<TreeNode> experimentIterator = this.selectorTree.checkedDescendantIterator(moleculeNode,
                EXPERIMENT);/*w ww  .j  a  v a 2s .co  m*/
        while (experimentIterator.hasNext()) {
            DefaultMutableTreeNode experimentNode = (DefaultMutableTreeNode) experimentIterator.next();

            Iterator<TreeNode> sampleIterator = this.selectorTree.checkedDescendantIterator(experimentNode,
                    SAMPLE);
            TreeSet<Sample> sampleSet = new TreeSet<Sample>();
            while (sampleIterator.hasNext()) {
                DefaultMutableTreeNode sampleNode = (DefaultMutableTreeNode) sampleIterator.next();
                sampleSet.add((Sample) sampleNode.getUserObject());
            }

            for (SampleGroup group : this.getSampleGroups()) {
                Collection<Sample> sampleUnion = new TreeSet<Sample>(group);
                sampleUnion.retainAll(sampleSet);
                Range range = Statistics.regularRange(molecule.getValues(sampleUnion).toDoubleArray());
                sampleIterator = this.selectorTree.checkedDescendantIterator(experimentNode, SAMPLE);

                while (sampleIterator.hasNext()) {
                    DefaultMutableTreeNode sampleNode = (DefaultMutableTreeNode) sampleIterator.next();
                    Sample sample = (Sample) sampleNode.getUserObject();
                    if (sampleUnion.contains(sample)
                            && !range.contains(molecule.getValue(sample).doubleValue()))
                        this.selectorTree.uncheck(sampleNode);
                }
            }
        }
    }
}

From source file:com.peterbochs.sourceleveldebugger.SourceLevelDebugger3.java

private void initSymbolTable() {
    //$hide>>$
    if (Global.debug) {
        System.out.println("--initSymbolTable");
    }/*w  ww .  j a  v a 2  s  .  c om*/

    TreeSet<Elf32_Sym> allSymbols = new TreeSet<Elf32_Sym>();
    for (Dwarf dwarf : peterDwarfPanel.dwarfs) {
        for (Elf32_Sym symbol : dwarf.symbols) {
            if (symbol.name.length() > 0) {
                allSymbols.add(symbol);
            }
        }
    }
    symbolTableModel.symbols = allSymbols;
    symbolTableModel.fireTableDataChanged();

    if (Global.debug) {
        System.out.println("--initSymbolTable end");
    }
    //$hide<<$
}

From source file:com.atolcd.pentaho.di.ui.trans.steps.gisgeoprocessing.GisGeoprocessingDialog.java

private String[] getFieldsFromType(String type) {

    String fieldNamesFromType[] = null;

    try {/*from   w  w  w .  j a  va2 s  . c  o  m*/

        // Rcupration des colonnes de l'tape prcdente
        RowMetaInterface r = transMeta.getPrevStepFields(stepname);
        if (r != null) {

            // Filtrage par type de colonne texte
            TreeSet<String> fieldsTree = new TreeSet<String>();
            String[] fieldNames = r.getFieldNames();
            String[] fieldNamesAndTypes = r.getFieldNamesAndTypes(0);

            for (int i = 0; i < fieldNames.length; i++) {
                if (fieldNamesAndTypes[i].toLowerCase().contains(type.toLowerCase())) {
                    if (fieldNames[i] != null && !fieldNames[i].isEmpty()) {
                        fieldsTree.add(fieldNames[i]);
                    }
                }
            }

            fieldNamesFromType = fieldsTree.toArray(new String[] {});

        }

    } catch (KettleException ke) {
        new ErrorDialog(shell,
                BaseMessages.getString(PKG, "ChangeFileEncodingDialog.FailedToGetFields.DialogTitle"),
                BaseMessages.getString(PKG, "ChangeFileEncodingDialog.FailedToGetFields.DialogMessage"), ke);
    }

    return fieldNamesFromType;

}

From source file:com.offbynull.voip.kademlia.FindSubcoroutine.java

@Override
public List<Node> run(Continuation cnt) throws Exception {
    Context ctx = (Context) cnt.getContext();

    ctx.addOutgoingMessage(subAddress, logAddress, info("Finding {}", findId));

    // Set up subcoroutine router
    Address routerAddress = subAddress.appendSuffix("finderreq" + idGenerator.generate());
    SubcoroutineRouter msgRouter = new SubcoroutineRouter(routerAddress, ctx);
    Controller msgRouterController = msgRouter.getController();

    // Get initial set of nodes to query from routing table
    List<Node> startNodes = router.find(findId, maxResults, false); // do not include stale nodes, we only want to contact alive nodes
    ctx.addOutgoingMessage(subAddress, logAddress,
            info("Route table entries closest to {}: {}", findId, startNodes));

    // Create sorted set of nodes to contact
    IdXorMetricComparator idClosenessComparator = new IdXorMetricComparator(findId);
    TreeSet<Node> contactSet = new TreeSet<>((x, y) -> idClosenessComparator.compare(x.getId(), y.getId()));
    contactSet.addAll(startNodes);//from w ww .j a va2s. c  om

    // Create a sorted set of nodes to retain closest nodes in
    TreeSet<Node> closestSet = new TreeSet<>((x, y) -> idClosenessComparator.compare(x.getId(), y.getId()));

    // Execute requests
    Map<Subcoroutine<?>, Node> requestSubcoroutineToNodes = new HashMap<>(); // executing requests
    Set<Id> queriedSet = new HashSet<>(); // ids that have already been queried
    while (true) {
        // If there's room left to query more contacts that are closer to findId, do so... 
        while (msgRouterController.size() < maxConcurrentRequests && !contactSet.isEmpty()) {
            // Get next farthest away node to contact
            Node contactNode = contactSet.pollLast();

            // Add it to set of set of ids that have already been queried.. if it's already there, it means that it's already been
            // queried by this find, so skip it...
            boolean added = queriedSet.add(contactNode.getId());
            if (!added) {
                continue;
            }

            // Add it to the set of closest nodes (will be removed if node fails to respond)
            closestSet.add(contactNode);

            // If we already have maxResult closer nodes to findId, skip this node
            if (closestSet.size() > maxResults) {
                Node removedNode = closestSet.pollLast();
                if (removedNode == contactNode) {
                    continue;
                }
            }

            // Initialize query
            Address destinationAddress = addressTransformer.toAddress(contactNode.getLink())
                    .appendSuffix(ROUTER_EXT_HANDLER_RELATIVE_ADDRESS);
            RequestSubcoroutine<FindResponse> reqSubcoroutine = new RequestSubcoroutine.Builder<FindResponse>()
                    .sourceAddress(routerAddress, idGenerator).destinationAddress(destinationAddress)
                    .timerAddress(timerAddress)
                    .request(new FindRequest(advertiseSelf ? baseId : null, findId, maxResults))
                    .addExpectedResponseType(FindResponse.class).attemptInterval(Duration.ofSeconds(2L))
                    .maxAttempts(5).throwExceptionIfNoResponse(false).build();

            ctx.addOutgoingMessage(subAddress, logAddress, info("Querying node {}", contactNode));

            // Add query to router
            msgRouterController.add(reqSubcoroutine, AddBehaviour.ADD_PRIME_NO_FINISH);
            requestSubcoroutineToNodes.put(reqSubcoroutine, contactNode);
        }

        // If there are no more requests running, it means we're finished
        if (msgRouterController.size() == 0) {
            ctx.addOutgoingMessage(subAddress, logAddress, info("Find complete: {}", closestSet));
            return new ArrayList<>(closestSet);
        }

        // Wait for next messange forward to the router
        cnt.suspend();
        ForwardResult fr = msgRouter.forward();

        // If a request completed from the forwarded message
        if (fr.isForwarded() && fr.isCompleted()) { // calling isCompleted by itself may throw an exception, check isForwarded first
            // Get response
            FindResponse findResponse = (FindResponse) fr.getResult();

            if (findResponse == null) {
                // If failure, then mark as stale and remove from closest
                // DONT BOTHER WITH TRYING TO CALCULATE LOCKING/UNLOCKING LOGIC. THE LOGIC WILL BECOME EXTREMELY CONVOLUTED. THE QUERY
                // DID 5 REQUEST. IF NO ANSWER WAS GIVEN IN THE ALLOTED TIME, THEN MARK AS STALE!
                Node contactedNode = requestSubcoroutineToNodes.remove(fr.getSubcoroutine());
                try {
                    // not allowed to mark self as stale -- we may want to find self, but if we do and it's not responsive dont try to
                    // mark it as stale
                    if (!contactedNode.getId().equals(baseId)) {
                        router.stale(contactedNode);
                    }
                } catch (NodeNotFoundException nnfe) { // may have been removed (already marked as stale) / may not be in routing tree
                    // Do nothing
                }
                closestSet.remove(contactedNode);
            } else {
                // If success, then add returned nodes to contacts
                Node[] nodes = findResponse.getNodes();
                contactSet.addAll(Arrays.asList(nodes));

                // If we don't want to find our own ID / query ourselves... remove any reference to our own ID in the contactSet
                // TODO: optimize this by removing before it's added to contactSet
                if (ignoreSelf) {
                    contactSet.removeIf(x -> x.getId().equals(baseId));
                }
            }
        }
    }
}

From source file:hu.ppke.itk.nlpg.purepos.decoder.AbstractDecoder.java

protected Set<Entry<Integer, Double>> pruneGuessedTags(Map<Integer, Double> guessedTags) {
    TreeSet<Entry<Integer, Double>> set = new TreeSet<Map.Entry<Integer, Double>>(
            /* reverse comparator */
            new Comparator<Entry<Integer, Double>>() {

                @Override/*  w  w w  .j av a2 s. co  m*/
                public int compare(Entry<Integer, Double> o1, Entry<Integer, Double> o2) {
                    if (o1.getValue() > o2.getValue())
                        return -1;
                    else if (o1.getValue() < o2.getValue())
                        return 1;
                    else
                        return Double.compare(o1.getKey(), o2.getKey());
                }
            });

    int maxTag = SuffixGuesser.getMaxProbabilityTag(guessedTags);
    double maxVal = guessedTags.get(maxTag);
    double minval = maxVal - sufTheta;
    for (Entry<Integer, Double> entry : guessedTags.entrySet()) {
        if (entry.getValue() > minval) {
            set.add(entry);
        }
    }
    if (set.size() > maxGuessedTags) {
        Iterator<Entry<Integer, Double>> it = set.descendingIterator();
        while (set.size() > maxGuessedTags) {
            it.next();
            it.remove();
        }
    }

    return set;
}

From source file:edu.internet2.middleware.subject.provider.LdapSourceAdapter.java

/**
 * {@inheritDoc}/*from w  w w  . jav  a  2 s  .  c om*/
 */
@Override
public Set search(String searchValue) {
    Comparator cp = new LdapComparator();
    TreeSet result = new TreeSet(cp);
    Search search = getSearch("search");
    if (search == null) {
        log.error("searchType: \"search\" not defined.");
        return result;
    }
    Search searchA = getSearch("searchAttributes");
    boolean noAttrSearch = true;
    if (searchA != null)
        noAttrSearch = false;

    Iterator<SearchResult> ldapResults = getLdapResults(search, searchValue, allAttributeNames);
    if (ldapResults == null) {
        return result;
    }
    while (ldapResults.hasNext()) {
        SearchResult si = (SearchResult) ldapResults.next();
        Attributes attributes = si.getAttributes();
        Subject subject = createSubject(attributes);
        if (noAttrSearch)
            ((LdapSubject) subject).setAttributesGotten(true);
        result.add(subject);
    }

    log.debug("set has " + result.size() + " subjects");
    if (result.size() > 0)
        log.debug("first is " + ((Subject) result.first()).getName());
    return result;
}

From source file:edu.pitt.dbmi.deep.phe.i2b2.I2b2OntologyBuilder.java

private TreeSet<PartialPath> extractOntologyPartialPaths() throws OWLOntologyCreationException, IOException {

    final TreeSet<PartialPath> partialPaths = new TreeSet<PartialPath>();

    OWLOntologyManager m = OWLManager.createOWLOntologyManager();
    // OWLOntology o = m.loadOntologyFromOntologyDocument(pizza_iri);
    OWLOntology o = loadDeepPheOntology(m);
    OWLReasonerFactory reasonerFactory;/*  ww  w  .  j  a v a  2 s.c  o  m*/
    reasonerFactory = new StructuralReasonerFactory();
    OWLReasoner reasoner = reasonerFactory.createReasoner(o);
    OWLDataFactory fac = m.getOWLDataFactory();
    OWLClass elementConcept = fac.getOWLClass(IRI.create(CONST_TOP_LEVEL_ENTRY));

    final Queue<PartialPath> partialPathQueue = new LinkedList<PartialPath>();
    NodeSet<OWLClass> subClses = reasoner.getSubClasses(elementConcept, true);
    for (Node<OWLClass> subCls : subClses) {
        PartialPath path = new PartialPath();
        path.setReasoner(reasoner);
        path.setCls(subCls.getRepresentativeElement());
        path.setLevel(1);
        partialPathQueue.add(path);
    }

    while (true) {
        PartialPath path;
        path = partialPathQueue.poll();
        if (path == null) {
            break;
        } else {
            partialPathQueue.addAll(path.expand());
        }
        partialPaths.add(path);
    }

    PartialPath topLevel = new PartialPath();
    topLevel.setPath("\\DEEPPHE");
    topLevel.setLevel(0);
    topLevel.setLeaf(false);
    partialPaths.add(topLevel);

    return partialPaths;
}

From source file:model.DecomposableModel.java

/**
 * Return all the interactions considered by the model
 * //from  w  w  w.ja  v  a2 s . c  o  m
 * @return all the interactions considered by the model
 */
public TreeSet<Couple<Integer>> getInteractions() {
    TreeSet<Couple<Integer>> interactions = new TreeSet<Couple<Integer>>();
    for (int v1 = 0; v1 < dimensionsForVariables.length; v1++) {
        for (int v2 = v1 + 1; v2 < dimensionsForVariables.length; v2++) {
            if (containsInteraction(v1, v2)) {
                interactions.add(new Couple<Integer>(v1, v2));
            }
        }
    }
    return interactions;
}

From source file:net.sourceforge.doddle_owl.ui.InputDocumentSelectionPanel.java

public Set<Document> getDocSet() {
    TreeSet<Document> docSet = new TreeSet<Document>();
    ListModel listModel = inputDocList.getModel();
    for (int i = 0; i < listModel.getSize(); i++) {
        Document doc = (Document) listModel.getElementAt(i);
        docSet.add(doc);
    }//from   w ww  .ja  v a 2  s  .  c o m
    return docSet;
}