Consensus by simple plurality, unweighted.

    Resolves ties by two heuristics:

    1. Prefer the aa that follows the preceding consensus aa type most often
       in the original sequences.
    2. Finally, prefer the less-common aa type.
774982
def make_simple_col_consensus(bg_freqs):
    
    # Hack: use default kwargs to persist across iterations
    def col_consensus(col, prev_col=[], prev_char=[]):
        # Count the amino acid types in this column
        aa_counts = sequtils.aa_frequencies(col)
        assert aa_counts, "Column is all gaps! That's not allowed."
        # Take the most common residue(s)
        best_char, best_score = max(aa_counts.iteritems(),
                                    key=lambda kv: kv[1])
        # Resolve ties
        ties = [aa for aa in aa_counts if aa_counts[aa] == best_score]
        if len(ties) > 1:
            # Breaker #1: most common after the prev. consensus char
            # Resolve a tied col by restricting to rows where the preceding
            # char is the consensus type for that (preceding) col
            if prev_char and prev_col:
                mc_next = Counter(
                        [b for a, b in zip(prev_col, col)
                            if a == prev_char[0] and b in ties]
                        ).most_common()
                ties_next = [x[0] for x in mc_next
                        if x[1] == mc_next[0][1]]
                if ties_next:
                    ties = ties_next
            if len(ties) > 1:
                # Breaker #2: lowest overall residue frequency
                ties.sort(key=lambda aa: bg_freqs[aa])
            best_char = ties[0]
        else:
            assert best_char == ties[0], \
                    'WTF %s != %s[0]' % (best_char, ties)
        # Save values for tie-breaker #1
        prev_col[:] = col
        prev_char[:] = best_char
        return best_char
    return col_consensus
792877
function syncStrategy(node, oAggregation, mAggregations) {
			var childNode,
				vChild,
				aChildren = [];

			for (childNode = node.firstChild; childNode; childNode = childNode.nextSibling) {
				vChild = fnCallback(node, oAggregation, mAggregations, childNode);
				if (vChild) {
					aChildren.push(unwrapSyncPromise(vChild));
				}
			}
			return SyncPromise.resolve(aChildren);
		}
404979
private int trPivot(int ISAd, int first, int last) {
        int middle;
        int t;

        t = last - first;
        middle = first + t / 2;

        if (t <= 512) {
            if (t <= 32) {
                return trMedian3(ISAd, first, middle, last - 1);
            } else {
                t >>= 2;
                return trMedian5(ISAd, first, first + t, middle, last - 1 - t, last - 1);
            }
        }
        t >>= 3;
        first = trMedian3(ISAd, first, first + t, first + (t << 1));
        middle = trMedian3(ISAd, middle - t, middle, middle + t);
        last = trMedian3(ISAd, last - 1 - (t << 1), last - 1 - t, last - 1);
        return trMedian3(ISAd, first, middle, last);
    }
1242871
private boolean isForwardAxis() {

        final String content = mToken.getContent();
        return (mToken.getType() == TokenType.TEXT && ("child".equals(content) || ("descendant"
            .equals(content)
            || "descendant-or-self".equals(content)
            || "attribute".equals(content)
            || "self".equals(content)
            || "following".equals(content) || "following-sibling".equals(content) || "namespace"
                .equals(content))));
    }
213250
private boolean isReconciling() {
        AggregatorState currentState = this.state.get();
        return currentState == AggregatorState.ReconciliationNeeded
                || currentState == AggregatorState.Reconciling;
    }
734252
def get_consensus_at(block_height, proxy=None, hostport=None):
    
    assert proxy or hostport, 'Need either proxy or hostport'
    if proxy is None:
        proxy = connect_hostport(hostport)

    consensus_schema = {
        'type': 'object',
        'properties': {
            'consensus': {
                'anyOf': [
                    {
                        'type': 'string',
                        'pattern': OP_CONSENSUS_HASH_PATTERN,
                    },
                    {
                        'type': 'null'
                    },
                ],
            },
        },
        'required': [
            'consensus',
        ],
    }

    resp_schema = json_response_schema( consensus_schema )
    resp = {}
    try:
        resp = proxy.get_consensus_at(block_height)
        resp = json_validate(resp_schema, resp)
        if json_is_error(resp):
            return resp

    except ValidationError as ve:
        if BLOCKSTACK_DEBUG:
            log.exception(ve)

        resp = {'error': 'Server response did not match expected schema.  You are likely communicating with an out-of-date Blockstack node.', 'http_status': 502}
        return resp

    except socket.timeout:
        log.error("Connection timed out")
        resp = {'error': 'Connection to remote host timed out.', 'http_status': 503}
        return resp

    except socket.error as se:
        log.error("Connection error {}".format(se.errno))
        resp = {'error': 'Connection to remote host failed.', 'http_status': 502}
        return resp

    except Exception as ee:
        if BLOCKSTACK_DEBUG:
            log.exception(ee)

        log.error("Caught exception while connecting to Blockstack node: {}".format(ee))
        resp = {'error': 'Failed to contact Blockstack node.  Try again with `--debug`.', 'http_status': 500}
        return resp

    if resp['consensus'] is None:
        # node hasn't processed this block 
        return {'error': 'The node has not processed block {}'.format(block_height), 'http_status': 503}

    return resp['consensus']
195866
def iteration(self, node_status=True):
        
        # One iteration changes the opinion of N agent pairs using the following procedure:
        # - first one agent is selected
        # - then a second agent is selected based on a probability that decreases with the distance to the first agent
        # - if the two agents have a distance smaller than epsilon, then they change their status to the average of
        # their previous statuses

        self.clean_initial_status(None)

        actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)}

        if self.actual_iteration == 0:
            self.actual_iteration += 1
            delta, node_count, status_delta = self.status_delta(self.status)
            if node_status:
                return {"iteration": 0, "status": self.status.copy(),
                        "node_count": node_count.copy(), "status_delta": status_delta.copy()}
            else:
                return {"iteration": 0, "status": {},
                        "node_count": node_count.copy(), "status_delta": status_delta.copy()}

        # interact with peers
        for i in range(0, self.graph.number_of_nodes()):
            # select a random node
            n1 = list(self.graph.nodes())[np.random.randint(0, self.graph.number_of_nodes())]
            # select all of the node's neighbours (no digraph possible)
            neighbours = list(self.graph.neighbors(n1))
            if len(neighbours) == 0:
                continue
        
            # compute probabilities to select a second node among the neighbours
            selection_prob = np.array([self.prob(np.abs(actual_status[neighbours[i]]-actual_status[n1]),
                                               self.params['model']['gamma'],0.00001) for i in range(len(neighbours))])
            selection_prob = selection_prob/np.sum(selection_prob)
            cumulative_selection_probability = np.cumsum(selection_prob)

            # select second nodebased on selection probabilities above
            r = np.random.random_sample()
            n2 = 0
            while cumulative_selection_probability[n2] < r:
                n2 = n2+1

            n2 = neighbours[n2]
            # update status of n1 and n2
            diff = np.abs(actual_status[n1]-actual_status[n2])
            if diff < self.params['model']['epsilon']:
                avg = (actual_status[n1]+actual_status[n2])/2.0
                actual_status[n1] = avg
                actual_status[n2] = avg
            
        delta, node_count, status_delta = self.status_delta(actual_status)
        self.status = actual_status
        self.actual_iteration += 1

        if node_status:
            return {"iteration": self.actual_iteration - 1, "status": delta.copy(),
                    "node_count": node_count.copy(), "status_delta": status_delta.copy()}
        else:
            return {"iteration": self.actual_iteration - 1, "status": {},
                    "node_count": node_count.copy(), "status_delta": status_delta.copy()}
321294
def similarity(self, other):
        """"""
        ratio = SequenceMatcher(a=self.value, b=other.value).ratio()
        similarity = self.Similarity(ratio)
        return similarity
1079256
private void reconcile() {

    // If nonContiguousMsgIds is empty then nothing to reconcile.
    if (nonContiguousMsgIds.isEmpty()) {
      return;
    }

    // This happens when a passive is started after Active has moved on and
    // passive starts to see msgIDs starting from a number > 0.
    // Once the sync is completed, fast forward highestContiguousMsgId.
    // Post sync completion assuming platform will send all msgIds beyond highestContiguousMsgId.
    if (highestContiguousMsgId == -1L && isSyncCompleted) {
      Long min = nonContiguousMsgIds.last();
      LOGGER.info("Setting highestContiguousMsgId to {} from -1", min);
      highestContiguousMsgId = min;
      nonContiguousMsgIds.removeIf(msgId -> msgId <= min);
    }

    for (long msgId : nonContiguousMsgIds) {
      if (msgId <= highestContiguousMsgId) {
        nonContiguousMsgIds.remove(msgId);
      } else if (msgId > highestContiguousMsgId + 1) {
        break;
      } else {
        // the order is important..
        highestContiguousMsgId = msgId;
        nonContiguousMsgIds.remove(msgId);
      }
    }

  }
979161
def get_consensus(block):
    """"""
    from collections import Counter

    # Take aligned (non-insert) chars from all rows; transpose
    columns = zip(*[[c for c in row['seq'] if not c.islower()]
                    for row in block['sequences']])
    cons_chars = [Counter(col).most_common()[0][0] for col in columns]
    cons_chars = [c if c != '-' else 'X' for c in cons_chars]
    assert len(cons_chars) == block['query_length']
    cons_sequence = {
        'index': 1,
        'id': 'consensus',
        'description': '',
        'dbxrefs': {},
        'phylum': '',
        'taxchar': '',
        'head_len': None,
        'tail_len': None,
        'head_seq': '',
        'tail_seq': '',
        'length': block['query_length'],
        'seq': ''.join(cons_chars),
    }
    return cons_sequence
778984
function(cb){
				// validate proposer ID
				byzantine.getCoordinators(conn, objUnit.hp, objJoint.phase, function(err, proposer, round_index, witnesses){	
					if(err)
						return cb("error occured when getCoordinators err:" + err);		
					if(proposer !== objJoint.proposer[0].address)
						return cb("proposer incorrect,Expected: "+ proposer +" Actual :" + objJoint.proposer[0].address);
					if(round_index !== objUnit.round_index)
						return cb("proposer round_index incorrect ,Expected: "+ round_index +" Actual :" + objUnit.round_index);
					objValidationState.unit_hash_to_sign = objectHash.getProposalHashToSign(objUnit);
					//validate proposer signature
					validateProposer(conn, objJoint.proposer[0], objUnit, objValidationState, cb);
				});
			}
214893
public static double averageCommonFeatureRank(double[] a, 
                                                  double[] b) {

        class Pair{
            public int i;
            public double v;
            public Pair(int index, double value){i=index;v=value;}
            public void set(int index, double value){
                i=index;
                v=value;
            }
        }
        class PairCompare implements Comparator<Pair>{
            // note that 1 and -1 have been switched so that sort will sort in
            // descending order
            // this method sorts by value first, then by index
            public int compare(Pair o1, Pair o2){
                if(o1.v < o2.v) return 1;
                else if(o1.v > o2.v) return -1;
                else{
                    if(o1.i < o2.i) return 1;
                    else if(o1.i > o2.i) return -1;
                    return 0;
                }
            }

            public boolean equals(Pair o1, Pair o2){
                return (compare(o1,o2)==0)?true:false;
            }
        }


        check(a, b);
        int size=a.length;

        // number of features to compare
        // calculate how much 10% is, rounded up.
        //int n = (int)Math.ceil(a.length/10.0);
        int n = 20;

        // generate array of index-value pairs for a
        Pair[] a_index = new Pair[size];
        for(int i=0;i<size;i++)
            a_index[i] = new Pair(i,a[i]);
        // generate array of index-value pairs for b
        Pair[] b_index = new Pair[size];
        for(int i=0;i<size;i++)
            b_index[i] = new Pair(i,b[i]);

        // sort the features in a_rank by weight
        Arrays.sort(a_index, new PairCompare());
        // sort the features in b_rank by weight
        Arrays.sort(b_index, new PairCompare());

        // a_index are index-value pairs, ordered by rank
        // this loop changes to a_rank which are rank-value, ordered by index
        // make indices start at 1 so inv(ind) is defined for all indices
        Pair[] a_rank = new Pair[size];
        int last_i = 1;
        for(int i=0;i<size;i++){
            Pair x = a_index[i];
            // share rank if tied
            if(i>0 && a_index[i].v==a_index[i-1].v)
                a_rank[x.i] = new Pair(last_i,x.v);
            else{
                a_rank[x.i] = new Pair(i+1,x.v);
                last_i=i+1;
            }
        }
        // do the same for b_index and b_rank
        last_i=1;
        Pair[] b_rank = new Pair[size];
        for(int i=0;i<size;i++){
            Pair x = b_index[i];
            // share rank if tied
            if(i>0 && b_index[i].v==b_index[i-1].v)
                b_rank[x.i] = new Pair(last_i,x.v);
            else{
                b_rank[x.i] = new Pair(i+1,x.v);
                last_i=i+1;
            }
        }

        // get best ranked n elements
        // nTop will be the top n ranking dimensions by weight
        // where nTop[i] is the ith highest ranking dimension (i.e. feature)
        int[] nTop = new int[n];
        boolean[] seenbefore = new boolean[size];
        Arrays.fill(seenbefore,false);
        int a_i=0;
        int b_i=0;
        for(int i=0;i<n;i++){
            // skip over features already encountered
            while(a_i<size && seenbefore[a_index[a_i].i])
                a_i++;
            while(b_i<size && seenbefore[b_index[b_i].i])
                b_i++;

            // assign rank by highest weight
            //  select the index from A when max(A)>max(B)
            if(a_i<size
                && 1 == (new PairCompare()).compare(a_index[a_i],b_index[b_i])
              ){
                nTop[i] = a_index[a_i].i;
                seenbefore[nTop[i]]=true;
                a_i++;
            }
            else{
                nTop[i] = b_index[b_i].i;
                seenbefore[nTop[i]]=true;
                b_i++;
            }
        }

        // computer the sum of the average rank for each top feature and divide
        //    by the number of top features
        double sum = 0;
        for(int i=0;i<n;i++){
            sum += 0.5*(a_rank[nTop[i]].i+b_rank[nTop[i]].i);
        }
        //return sum/n;
        return n/sum;

    }
1080680
def _prepare_consensus(FetcherClass, results):
    
    # _get_results returns lists of 2 item list, first element is service, second is the returned value.
    # when determining consensus amoung services, only take into account values returned.
    if hasattr(FetcherClass, "strip_for_consensus"):
        to_compare = [
            FetcherClass.strip_for_consensus(value) for (fetcher, value) in results
        ]
    else:
        to_compare = [value for fetcher, value in results]

    return to_compare, [fetcher._successful_service for fetcher, values in results]
1218958
private void diffClique(float[] weights, int p) {
		for (int t = 0; t < orders.length; t++) {
			if (data[p][t] == -1)
				continue;

			if (orders[t] == 0) {
				if (golds[p] != preds[p]) {
					int ts = data[p][t] + golds[p];
					int ps = data[p][t] + preds[p];
					adjust(weights, ts, ps);
				}
			}
			if (p > 0 && orders[t] == 1) {
				int ts = data[p][t] + (golds[p - 1] * ysize + golds[p]);
				int ps = data[p][t] + (preds[p - 1] * ysize + preds[p]);
				adjust(weights, ts, ps);
			}
		}
	}
1024445
def point_consensus(self, consensus_type):
        
        if "mean" in consensus_type:
            consensus_data = np.mean(self.data, axis=0)
        elif "std" in consensus_type:
            consensus_data = np.std(self.data, axis=0)
        elif "median" in consensus_type:
            consensus_data = np.median(self.data, axis=0)
        elif "max" in consensus_type:
            consensus_data = np.max(self.data, axis=0)
        elif "percentile" in consensus_type:
            percentile = int(consensus_type.split("_")[1])
            consensus_data = np.percentile(self.data, percentile, axis=0)
        else:
            consensus_data = np.zeros(self.data.shape[1:])
        consensus = EnsembleConsensus(consensus_data, consensus_type, self.ensemble_name,
                                      self.run_date, self.variable, self.start_date, self.end_date, self.units)
        return consensus
981516
def reweight(self, weight, edges=None, copy=False):
    ''''''
    if not self.is_weighted():
      warnings.warn('Cannot supply weights for unweighted graph; '
                    'ignoring call to reweight')
      return self
    if edges is None:
      return self._update_edges(weight, copy=copy)
    ii, jj = self.pairs()[edges].T
    return self.add_edges(ii, jj, weight=weight, symmetric=False, copy=copy)
441943
List<AtomPair> findCongestedPairs() {

        List<AtomPair> pairs = new ArrayList<>();

        // only add a single pair between each ring system, otherwise we
        // may have many pairs that are actually all part of the same
        // congestion
        Set<IntTuple> ringpairs = new HashSet<>();

        // score at which to check for crossing bonds
        final double maybeCrossed = 1.0 / (2 * 2);

        final int numAtoms = mol.getAtomCount();
        for (int u = 0; u < numAtoms; u++) {
            for (int v = u + 1; v < numAtoms; v++) {
                double contribution = congestion.contribution(u, v);
                // <0 = bonded
                if (contribution <= 0)
                    continue;

                // we don't modify ring bonds with the class to when the atoms
                // same ring systems we can't reduce the congestion
                if (ringsystems[u] > 0 && ringsystems[u] == ringsystems[v])
                    continue;

                // an un-bonded atom pair is congested if they're and with a certain distance
                // or any of their bonds are crossing
                if (contribution >= MIN_SCORE || contribution >= maybeCrossed && haveCrossingBonds(u, v)) {

                    int uWeight = mol.getAtom(u).getProperty(AtomPlacer.PRIORITY);
                    int vWeight = mol.getAtom(v).getProperty(AtomPlacer.PRIORITY);

                    int[] path = uWeight > vWeight ? apsp.from(u).pathTo(v)
                                                   : apsp.from(v).pathTo(u);

                    // something not right here if the len is < 3
                    int len = path.length;
                    if (len < 3) continue;

                    // build the seqAt and bndAt lists from shortest path
                    int[] seqAt = new int[len - 2];
                    IBond[] bndAt = new IBond[len - 1];
                    makeAtmBndQueues(path, seqAt, bndAt);

                    // we already know about this collision between these ring systems
                    // so dont add the pair
                    if (ringsystems[u] > 0 && ringsystems[v] > 0 &&
                            !ringpairs.add(new IntTuple(ringsystems[u], ringsystems[v])))
                        continue;

                    // add to pairs to overlap
                    pairs.add(new AtomPair(u, v, seqAt, bndAt));
                }
            }
        }

        // sort the pairs to attempt consistent overlap resolution (order independent)
        Collections.sort(pairs, new Comparator<AtomPair>() {
            @Override
            public int compare(AtomPair a, AtomPair b) {
                int a1 = atoms[a.fst].getProperty(AtomPlacer.PRIORITY);
                int a2 = atoms[a.snd].getProperty(AtomPlacer.PRIORITY);
                int b1 = atoms[b.fst].getProperty(AtomPlacer.PRIORITY);
                int b2 = atoms[b.snd].getProperty(AtomPlacer.PRIORITY);
                int amin, amax;
                int bmin, bmax;
                if (a1 < a2) {
                    amin = a1;
                    amax = a2;
                }
                else {
                    amin = a2;
                    amax = a1;
                }
                if (b1 < b2) {
                    bmin = a1;
                    bmax = a2;
                }
                else {
                    bmin = a2;
                    bmax = a1;
                }
                int cmp = Integer.compare(amin, bmin);
                if (cmp != 0) return cmp;
                return Integer.compare(amax, bmax);
            }
        });

        return pairs;
    }