Determines the ranking score for each node, allowing for a sorting of nodes
within one sphere.

@param  sphereNodes The nodes for which the score is to be calculated.
@exception  org.openscience.cdk.exception.CDKException  Thrown if something goes wrong.
544171
private void calculateNodeScores(List<TreeNode> sphereNodes) throws CDKException {
        TreeNode treeNode = null;
        for (int i = 0; i < sphereNodes.size(); i++) {
            treeNode = (TreeNode) sphereNodes.get(i);
            treeNode.score += getElementRank(treeNode.symbol);
            if (treeNode.bondType <= 4) {
                treeNode.score += bondRankings[(int) treeNode.bondType];
            } else {
                throw new CDKException("Unknown bond type encountered in HOSECodeGenerator");
            }
        }
    }
1222824
View selectOriginNode() {
		double bestScore = 0;
		View best = null;

		if( verbose != null )
			verbose.println("selectOriginNode");
		for (int i = 0; i < graph.nodes.size(); i++) {
			double score = scoreNodeAsOrigin(graph.nodes.get(i));

			if( score > bestScore ) {
				bestScore = score;
				best = graph.nodes.get(i);
			}

			if( verbose != null )
				verbose.printf("  [%2d] score = %s\n",i,score);
		}
		if( verbose != null && best != null )
			verbose.println("     selected = "+best.index);

		return best;
	}
1041305
public static Graph sortDFS(Graph g, Graph sortedGraph) {
        int nodes = g.getNodes();
        final GHIntArrayList list = new GHIntArrayList(nodes);
        list.fill(nodes, -1);
        final GHBitSetImpl bitset = new GHBitSetImpl(nodes);
        final AtomicInteger ref = new AtomicInteger(-1);
        EdgeExplorer explorer = g.createEdgeExplorer();
        for (int startNode = 0; startNode >= 0 && startNode < nodes;
             startNode = bitset.nextClear(startNode + 1)) {
            new DepthFirstSearch() {
                @Override
                protected GHBitSet createBitSet() {
                    return bitset;
                }

                @Override
                protected boolean goFurther(int nodeId) {
                    list.set(nodeId, ref.incrementAndGet());
                    return super.goFurther(nodeId);
                }
            }.start(explorer, startNode);
        }
        return createSortedGraph(g, sortedGraph, list);
    }
657630
protected void determineNumberOfClusters() {
        if (!m_numberOfClustersDetermined
                && (m_cobwebTree != null)) {
            int[] numClusts = new int[1];
            numClusts[0] = 0;
            //  try {
            m_cobwebTree.assignClusterNums(numClusts);
            // }
            // catch (Exception e) {
//	e.printStackTrace();
//	numClusts[0] = 0;
            // }
            m_numberOfClusters = numClusts[0];

            m_numberOfClustersDetermined = true;
        }
    }
220675
private Set<Integer> perNodeRelease(final C thisNodeAddress, final C[] currentState, final int nodeCount, final int nodeRank) {
        final int numberIShouldHave = howManyShouldIHave(totalNumShards, nodeCount, minNodes, nodeRank);

        // destinationsAcquired reflects what we already have according to the currentState
        final List<Integer> destinationsAcquired = buildDestinationsAcquired(thisNodeAddress, currentState);

        final int numHad = destinationsAcquired.size();
        final Set<Integer> ret = new HashSet<>();
        if (destinationsAcquired.size() > numberIShouldHave) { // there's some to remove.
            final Random random = new Random();

            while (destinationsAcquired.size() > numberIShouldHave) {
                final int index = random.nextInt(destinationsAcquired.size());
                ret.add(destinationsAcquired.remove(index));
            }
        }

        if (LOGGER.isTraceEnabled() && ret.size() > 0)
            LOGGER.trace(thisNodeAddress.toString() + " removing shards " + ret + " because I have " +
                    numHad + " but shouldn't have more than " + numberIShouldHave + ".");

        return ret;
    }
1297333
static SquareNode findSeedNode(List<SquareNode> cluster) {
		SquareNode seed = null;

		for (int i = 0; i < cluster.size(); i++) {
			SquareNode n = cluster.get(i);
			int numConnections = n.getNumberOfConnections();
			if( numConnections == 0 || numConnections > 2 )
				continue;
			seed = n;
			break;
		}
		return seed;
	}
557608
@Override
    public Collection<FacetRank> calculateRank(@NotNull Collection<Facet> facets) {
        return rankingAlgorithm.calculate(facets);
    }
454206
public static List<INodeEntry> rankOrderedNodes(Collection<INodeEntry> nodes, String rankProperty,
            boolean rankAscending) {
        final ArrayList<INodeEntry> nodes1 = new ArrayList<>(nodes);
        //reorder based on configured rank property and order
        final INodeEntryComparator comparator = new INodeEntryComparator(rankProperty);

        Collections.sort(nodes1, rankAscending ? comparator : Collections.reverseOrder(comparator));
        return nodes1;
    }
1055833
def assign_best_matches(self, xg):
        
        logging.info("assigning best matches for {} nodes".format(len(xg.nodes())))
        for i in xg.nodes():
            xrefmap = self._neighborscores_by_ontology(xg, i)
            for (ontid,score_node_pairs) in xrefmap.items():
                score_node_pairs.sort(reverse=True)
                (best_score,best_node) = score_node_pairs[0]
                logging.info("BEST for {}: {} in {} from {}".format(i, best_node, ontid, score_node_pairs))
                edge = xg[i][best_node]
                dirn = self._dirn(edge, i, best_node)
                best_kwd = 'best_' + dirn
                if len(score_node_pairs) == 1 or score_node_pairs[0] > score_node_pairs[1]:
                    edge[best_kwd] = 2
                else:
                    edge[best_kwd] = 1
                for (score,j) in score_node_pairs:
                    edge_ij = xg[i][j]
                    dirn_ij = self._dirn(edge_ij, i, j)
                    edge_ij['cpr_'+dirn_ij] = score / sum([s for s,_ in score_node_pairs])
        for (i,j,edge) in xg.edges(data=True):
            # reciprocal score is set if (A) i is best for j, and (B) j is best for i
            rs = 0
            if 'best_fwd' in edge and 'best_rev' in edge:
                rs = edge['best_fwd'] * edge['best_rev']
            edge['reciprocal_score'] = rs
            edge['cpr'] = edge['cpr_fwd'] * edge['cpr_rev']
409428
public static List<RedisClusterNode> sortByLatency(Iterable<RedisClusterNode> clusterNodes) {

        List<RedisClusterNode> ordered = LettuceLists.newList(clusterNodes);
        ordered.sort(LatencyComparator.INSTANCE);
        return ordered;
    }
1187796
private String getSphereCode(List<TreeNode> sphereNodes) throws CDKException {
        if (sphereNodes == null || sphereNodes.size() < 1) {
            return sphereDelimiters[sphere - 1];
        }
        TreeNode treeNode = null;
        StringBuffer code = new StringBuffer();
        /*
         * append the tree node code to the HOSECode in their now determined
         * order, using commas to separate nodes from different branches
         */
        IAtom branch = sphereNodes.get(0).source.atom;
        StringBuffer tempCode = null;
        for (int i = 0; i < sphereNodes.size(); i++) {
            treeNode = sphereNodes.get(i);
            tempCode = new StringBuffer();
            if (!treeNode.source.stopper && !treeNode.source.atom.equals(branch)) {
                branch = treeNode.source.atom;
                code.append(',');
            }

            if (!treeNode.source.stopper && treeNode.source.atom.equals(branch)) {
                if (treeNode.bondType <= 4) {
                    tempCode.append(bondSymbols[(int) treeNode.bondType]);
                } else {
                    throw new CDKException("Unknown bond type");
                }
                if (treeNode.atom != null && !treeNode.atom.getFlag(CDKConstants.VISITED)) {
                    tempCode.append(getElementSymbol(treeNode.symbol));
                } else if (treeNode.atom != null && treeNode.atom.getFlag(CDKConstants.VISITED)) {
                    tempCode.append('&');
                    treeNode.stopper = true;
                }
                code.append(tempCode + createChargeCode(treeNode.atom));
                treeNode.hSymbol = tempCode.toString();
            }
            if (treeNode.atom != null) treeNode.atom.setFlag(CDKConstants.VISITED, true);
            if (treeNode.source.stopper) treeNode.stopper = true;
        }
        code.append(sphereDelimiters[sphere - 1]);
        return code.toString();
    }
329773
public static void validateClusterNodeCounts(final Cluster lhs, final Cluster rhs) {
        if(!lhs.getNodeIds().equals(rhs.getNodeIds())) {
            throw new VoldemortException("Node ids are not the same [ lhs cluster node ids ("
                                         + lhs.getNodeIds()
                                         + ") not equal to rhs cluster node ids ("
                                         + rhs.getNodeIds() + ") ]");
        }
    }
1115224
protected int[] score_decide(Chunk chks[], int nnids[]) {
    int [] res = nnids.clone();
    for( int row=0; row<nnids.length; row++ ) { // Over all rows
      int nid = nnids[row];          // Get Node to decide from
      if( isDecidedRow(nid)) {               // already done
        res[row] -= _leaf;
        continue;
      }
      // Score row against current decisions & assign new split
      boolean oob = isOOBRow(nid);
      if( oob ) nid = oob2Nid(nid); // sampled away - we track the position in the tree
      DTree.DecidedNode dn = _tree.decided(nid);
      if( dn._split == null ) { // Might have a leftover non-split
        if( DTree.isRootNode(dn) ) { res[row] = nid - _leaf; continue; }
        nid = dn._pid;             // Use the parent split decision then
        int xnid = oob ? nid2Oob(nid) : nid;
        nnids[row] = xnid;
        res[row] = xnid - _leaf;
        dn = _tree.decided(nid); // Parent steers us
      }
      assert !isDecidedRow(nid);
      nid = dn.getChildNodeID(chks,row); // Move down the tree 1 level
      if( !isDecidedRow(nid) ) {
        if( oob ) nid = nid2Oob(nid); // Re-apply OOB encoding
        nnids[row] = nid;
      }
      res[row] = nid-_leaf;
    }
    return res;
  }
531068
private function rateNodes($nodes)
    {
        $this->logger->info('[Rating] Rating nodes...');

        $candidates = [];

        /** @var DOMElement $node */
        foreach ($nodes as $node) {
            if (is_null($node->parentNode)) {
                continue;
            }

            // Discard nodes with less than 25 characters, without blank space
            if (mb_strlen($node->getTextContent(true)) < 25) {
                continue;
            }

            $ancestors = $node->getNodeAncestors();

            // Exclude nodes with no ancestor
            if (count($ancestors) === 0) {
                continue;
            }

            // Start with a point for the paragraph itself as a base.
            $contentScore = 1;

            // Add points for any commas within this paragraph.
            $contentScore += count(explode(',', $node->getTextContent(true)));

            // For every 100 characters in this paragraph, add another point. Up to 3 points.
            $contentScore += min(floor(mb_strlen($node->getTextContent(true)) / 100), 3);

            $this->logger->debug(sprintf('[Rating] Node score %s, content: \'%s\'', $contentScore, substr($node->nodeValue, 0, 128)));

            /** @var $ancestor DOMElement */
            foreach ($ancestors as $level => $ancestor) {
                $this->logger->debug('[Rating] Found ancestor, initializing and adding it as a candidate...');
                if (!$ancestor->isInitialized()) {
                    $ancestor->initializeNode($this->configuration->getWeightClasses());
                    $candidates[] = $ancestor;
                }

                /*
                 * Node score divider:
                 *  - parent:             1 (no division)
                 *  - grandparent:        2
                 *  - great grandparent+: ancestor level * 3
                 */

                if ($level === 0) {
                    $scoreDivider = 1;
                } elseif ($level === 1) {
                    $scoreDivider = 2;
                } else {
                    $scoreDivider = $level * 3;
                }

                $currentScore = $ancestor->contentScore;
                $ancestor->contentScore = $currentScore + ($contentScore / $scoreDivider);

                $this->logger->debug(sprintf('[Rating] Ancestor score %s, value: \'%s\'', $ancestor->contentScore, substr($ancestor->nodeValue, 0, 128)));
            }
        }

        /*
         * After we've calculated scores, loop through all of the possible
         * candidate nodes we found and find the one with the highest score.
         */

        $topCandidates = [];
        foreach ($candidates as $candidate) {

            /*
             * Scale the final candidates score based on link density. Good content
             * should have a relatively small link density (5% or less) and be mostly
             * unaffected by this operation.
             */

            $candidate->contentScore = $candidate->contentScore * (1 - $candidate->getLinkDensity());

            for ($i = 0; $i < $this->configuration->getMaxTopCandidates(); $i++) {
                $aTopCandidate = isset($topCandidates[$i]) ? $topCandidates[$i] : null;

                if (!$aTopCandidate || $candidate->contentScore > $aTopCandidate->contentScore) {
                    array_splice($topCandidates, $i, 0, [$candidate]);
                    if (count($topCandidates) > $this->configuration->getMaxTopCandidates()) {
                        array_pop($topCandidates);
                    }
                    break;
                }
            }
        }

        $topCandidate = isset($topCandidates[0]) ? $topCandidates[0] : null;
        $parentOfTopCandidate = null;

        /*
         * If we still have no top candidate, just use the body as a last resort.
         * We also have to copy the body node so it is something we can modify.
         */

        if ($topCandidate === null || $topCandidate->nodeName === 'body') {
            $this->logger->info('[Rating] No top candidate found or top candidate is the body tag. Moving all child nodes to a new DIV node.');

            // Move all of the page's children into topCandidate
            $topCandidate = new DOMDocument('1.0', 'utf-8');
            $topCandidate->encoding = 'UTF-8';
            $topCandidate->appendChild($topCandidate->createElement('div', ''));
            $kids = $this->dom->getElementsByTagName('body')->item(0)->childNodes;

            // Cannot be foreached, don't ask me why.
            for ($i = 0; $i < $kids->length; $i++) {
                $import = $topCandidate->importNode($kids->item($i), true);
                $topCandidate->firstChild->appendChild($import);
            }

            // Candidate must be created using firstChild to grab the DOMElement instead of the DOMDocument.
            $topCandidate = $topCandidate->firstChild;
        } elseif ($topCandidate) {
            $this->logger->info(sprintf('[Rating] Found top candidate, score: %s', $topCandidate->contentScore));
            // Find a better top candidate node if it contains (at least three) nodes which belong to `topCandidates` array
            // and whose scores are quite closed with current `topCandidate` node.
            $alternativeCandidateAncestors = [];
            for ($i = 1; $i < count($topCandidates); $i++) {
                // In some cases we may end up with a top candidate with zero content score. To avoid dividing by zero
                // we have to use max() and replace zero with a low value like 0.1
                if ($topCandidates[$i]->contentScore / max($topCandidate->contentScore, 0.1) >= 0.75) {
                    array_push($alternativeCandidateAncestors, $topCandidates[$i]->getNodeAncestors(false));
                }
            }

            $MINIMUM_TOPCANDIDATES = 3;
            if (count($alternativeCandidateAncestors) >= $MINIMUM_TOPCANDIDATES) {
                $parentOfTopCandidate = $topCandidate->parentNode;

                // Check if we are actually dealing with a DOMNode and not a DOMDocument node or higher
                while ($parentOfTopCandidate->nodeName !== 'body' && $parentOfTopCandidate->nodeType === XML_ELEMENT_NODE) {
                    $listsContainingThisAncestor = 0;
                    for ($ancestorIndex = 0; $ancestorIndex < count($alternativeCandidateAncestors) && $listsContainingThisAncestor < $MINIMUM_TOPCANDIDATES; $ancestorIndex++) {
                        $listsContainingThisAncestor += (int)in_array($parentOfTopCandidate, $alternativeCandidateAncestors[$ancestorIndex]);
                    }
                    if ($listsContainingThisAncestor >= $MINIMUM_TOPCANDIDATES) {
                        $topCandidate = $parentOfTopCandidate;
                        break;
                    }
                    $parentOfTopCandidate = $parentOfTopCandidate->parentNode;
                }
            }

            /*
             * Because of our bonus system, parents of candidates might have scores
             * themselves. They get half of the node. There won't be nodes with higher
             * scores than our topCandidate, but if we see the score going *up* in the first
             * few steps up the tree, that's a decent sign that there might be more content
             * lurking in other places that we want to unify in. The sibling stuff
             * below does some of that - but only if we've looked high enough up the DOM
             * tree.
             */

            $parentOfTopCandidate = $topCandidate->parentNode;
            $lastScore = $topCandidate->contentScore;

            // The scores shouldn't get too low.
            $scoreThreshold = $lastScore / 3;

            /* @var DOMElement $parentOfTopCandidate */
            while ($parentOfTopCandidate->nodeName !== 'body') {
                $parentScore = $parentOfTopCandidate->contentScore;
                if ($parentScore < $scoreThreshold) {
                    break;
                }

                if ($parentScore > $lastScore) {
                    // Alright! We found a better parent to use.
                    $topCandidate = $parentOfTopCandidate;
                    $this->logger->info('[Rating] Found a better top candidate.');
                    break;
                }
                $lastScore = $parentOfTopCandidate->contentScore;
                $parentOfTopCandidate = $parentOfTopCandidate->parentNode;
            }

            // If the top candidate is the only child, use parent instead. This will help sibling
            // joining logic when adjacent content is actually located in parent's sibling node.
            $parentOfTopCandidate = $topCandidate->parentNode;
            while ($parentOfTopCandidate->nodeName !== 'body' && count($parentOfTopCandidate->getChildren(true)) === 1) {
                $topCandidate = $parentOfTopCandidate;
                $parentOfTopCandidate = $topCandidate->parentNode;
            }
        }

        /*
         * Now that we have the top candidate, look through its siblings for content
         * that might also be related. Things like preambles, content split by ads
         * that we removed, etc.
         */

        $this->logger->info('[Rating] Creating final article content document...');

        $articleContent = new DOMDocument('1.0', 'utf-8');
        $articleContent->createElement('div');

        $siblingScoreThreshold = max(10, $topCandidate->contentScore * 0.2);
        // Keep potential top candidate's parent node to try to get text direction of it later.
        $parentOfTopCandidate = $topCandidate->parentNode;
        $siblings = $parentOfTopCandidate->getChildren();

        $hasContent = false;

        $this->logger->info('[Rating] Adding top candidate siblings...');

        /** @var DOMElement $sibling */
        foreach ($siblings as $sibling) {
            $append = false;

            if ($sibling === $topCandidate) {
                $this->logger->debug('[Rating] Sibling is equal to the top candidate, adding to the final article...');

                $append = true;
            } else {
                $contentBonus = 0;

                // Give a bonus if sibling nodes and top candidates have the example same classname
                if ($sibling->getAttribute('class') === $topCandidate->getAttribute('class') && $topCandidate->getAttribute('class') !== '') {
                    $contentBonus += $topCandidate->contentScore * 0.2;
                }
                if ($sibling->contentScore + $contentBonus >= $siblingScoreThreshold) {
                    $append = true;
                } elseif ($sibling->nodeName === 'p') {
                    $linkDensity = $sibling->getLinkDensity();
                    $nodeContent = $sibling->getTextContent(true);

                    if (mb_strlen($nodeContent) > 80 && $linkDensity < 0.25) {
                        $append = true;
                    } elseif ($nodeContent && mb_strlen($nodeContent) < 80 && $linkDensity === 0 && preg_match('/\.( |$)/', $nodeContent)) {
                        $append = true;
                    }
                }
            }

            if ($append) {
                $this->logger->debug(sprintf('[Rating] Appending sibling to final article, content is: \'%s\'', substr($sibling->nodeValue, 0, 128)));

                $hasContent = true;

                if (!in_array(strtolower($sibling->nodeName), $this->alterToDIVExceptions)) {
                    /*
                     * We have a node that isn't a common block level element, like a form or td tag.
                     * Turn it into a div so it doesn't get filtered out later by accident.
                     */

                    $sibling = NodeUtility::setNodeTag($sibling, 'div');
                }

                $import = $articleContent->importNode($sibling, true);
                $articleContent->appendChild($import);

                /*
                 * No node shifting needs to be check because when calling getChildren, an array is made with the
                 * children of the parent node, instead of using the DOMElement childNodes function, which, when used
                 * along with appendChild, would shift the nodes position and the current foreach will behave in
                 * unpredictable ways.
                 */
            }
        }

        $articleContent = $this->prepArticle($articleContent);

        if ($hasContent) {
            // Find out text direction from ancestors of final top candidate.
            $ancestors = array_merge([$parentOfTopCandidate, $topCandidate], $parentOfTopCandidate->getNodeAncestors());
            foreach ($ancestors as $ancestor) {
                $articleDir = $ancestor->getAttribute('dir');
                if ($articleDir) {
                    $this->setDirection($articleDir);
                    $this->logger->debug(sprintf('[Rating] Found article direction: %s', $articleDir));
                    break;
                }
            }

            return $articleContent;
        } else {
            return false;
        }
    }
1361909
protected void scoreAllTrees(double[] row, double[] preds) {
        java.util.Arrays.fill(preds, 0);
        scoreTreeRange(row, 0, _ntree_groups, preds);
    }
1226239
@Override public float[] scoreKey( Object modelKey, String [] colNames, String domains[][], double[] row ) {
    Key key = (Key)modelKey;
    String sk = key.toString();
    Value v = DKV.get(key);
    if (v == null)
      throw new IllegalArgumentException("Key "+sk+" not found!");
    try {
      return scoreModel(v.get(),colNames,domains,row);
    } catch(Throwable t) {
      Log.err(t);
      throw new IllegalArgumentException("Key "+sk+" is not a Model key");
    }
  }
349779
public DatanodeInfo[] bestNode(LocatedBlocks blks) throws IOException {
    // insert all known replica locations into a tree map where the
    // key is the DatanodeInfo
    TreeMap<DatanodeInfo, NodeRecord> map = 
      new TreeMap<DatanodeInfo, NodeRecord>();
    for (int i = 0; i < blks.getLocatedBlocks().size(); i++) {
      DatanodeInfo [] nodes = blks.get(i).getLocations();
      for (int j = 0; j < nodes.length; j++) {
        NodeRecord obj = map.get(nodes[j]);
        if (obj != null) {
          obj.frequency++;
        } else {
          map.put(nodes[j], new NodeRecord(nodes[j], 1));
        }
      }
    }
    // sort all locations by their frequency of occurance
    Collection<NodeRecord> values = map.values();
    NodeRecord[] nodes = (NodeRecord[]) 
                         values.toArray(new NodeRecord[values.size()]);
    Arrays.sort(nodes, new NodeRecordComparator());
    try {
      List<NodeRecord> candidates = bestNode(nodes, false);
      return candidates.toArray(new DatanodeInfo[candidates.size()]);
    } catch (IOException e) {
      return new DatanodeInfo[] {randomNode()};
    }
  }