:: Alternative Vote ALGORITHM. :://
167418
protected function compute (): void
    {
        $candidateCount = $this->_selfElection->countCandidates();
        $majority = $this->_selfElection->sumValidVotesWeightWithConstraints() / 2;

        $candidateDone = [];
        $result = [];
        $CandidatesWinnerCount = 0;
        $CandidatesLoserCount = 0;

        $iteration = 0;

        while (count($candidateDone) < $candidateCount) :
            $score = $this->makeScore($candidateDone);
            $maxScore = max($score);
            $minScore = min($score);

            $this->_Stats[++$iteration] = $score;

            if ( $maxScore > $majority ) :
                foreach ($score as $candidateKey => $candidateScore) :
                    if ($candidateScore !== $maxScore) :
                        continue;
                    else :
                        $candidateDone[] = $candidateKey;
                        $result[++$CandidatesWinnerCount][] = $candidateKey;
                    endif;
                endforeach;
            else :
                $LosersToRegister = [];

                foreach ($score as $candidateKey => $candidateScore) :
                    if ($candidateScore !== $minScore) :
                        continue;
                    else :
                        $LosersToRegister[] = $candidateKey;
                    endif;
                endforeach;

                // Tie Breaking
                $round = count($LosersToRegister);
                for ($i = 1 ; $i < $round ; $i++) : // A little silly. But ultimately shorter and simpler.
                    $LosersToRegister = $this->tieBreaking($LosersToRegister);
                endfor;

                $CandidatesLoserCount += count($LosersToRegister);
                $candidateDone = array_merge($candidateDone, $LosersToRegister);
                $result[$candidateCount - $CandidatesLoserCount + 1] = $LosersToRegister;
            endif;

        endwhile;

        $this->_Result = $this->createResult($result);
    }
1012040
def choose(n, k):
    
    if 0 <= k <= n:
        ntok = 1
        ktok = 1
        for t in xrange(1, min(k, n - k) + 1):
            ntok *= n
            ktok *= t
            n -= 1
        return ntok // ktok
    else:
        return 0
400069
def find_vote_casts(provider: Provider, vote: Vote, choice_index: int) -> Iterable[VoteCast]:
    ''''''

    vote_casts = provider.listtransactions(vote.vote_choice_address[choice_index])
    for tx in vote_casts:
        raw_tx = provider.getrawtransaction(tx, 1)

        sender = find_tx_sender(provider, raw_tx)
        confirmations = raw_tx["confirmations"]
        blocknum = provider.getblock(raw_tx["blockhash"])["height"]
        yield VoteCast(vote, sender, blocknum, confirmations, raw_tx["blocktime"])
598725
def oridam_generate_patterns(word_in,cm,ed=1,level=0,pos=0,candidates=None):
    
    alternates = cm.get(word_in[pos],[])
    if not candidates:
        candidates = []
    assert ed <= len(word_in), 'edit distance has to be comparable to word size [ins/del not explored]'
    if (pos >len(word_in)) or ed == 0:
        return candidates
    pfx = ''
    sfx = ''
    curr_candidates = []
    for p in range(0,pos):
        pfx = pfx + word_in[p]
    for p in range(pos+1,len(word_in)):
        sfx = sfx + word_in[p]
    for alt in alternates:
        word_alt = pfx + alt + sfx
        if not (word_alt in candidates):
            candidates.append( word_alt )
            curr_candidates.append( word_alt )
    for n_pos in range(pos,len(word_in)):
        # already what we have ' candidates ' of this round are edit-distance 1
        for word in curr_candidates:
            oridam_generate_patterns(word,cm,ed-1,level+1,n_pos,candidates)
    if level == 0:
        #candidates.append(word_in)
        for n_pos in range(pos,len(word_in)):
            oridam_generate_patterns(word_in,cm,ed, level+1,n_pos,candidates)
    return candidates
596968
def evaluate(grid):
    ""
    if is_won(grid): return -1
    succs = successors(grid)
    return -min(map(evaluate, succs)) if succs else 0
749129
def community_post_votes(self, post_id, **kwargs):
        ""
        api_path = "/api/v2/community/posts/{post_id}/votes.json"
        api_path = api_path.format(post_id=post_id)
        return self.call(api_path, **kwargs)
9879
private void score_decide(Chunk chks[], Chunk nids, Chunk wrks, Chunk tree, int nnids[]) {
      for( int row=0; row<nids._len; row++ ) { // Over all rows
        int nid = (int)nids.at80(row);         // Get Node to decide from
        if( isDecidedRow(nid)) {               // already done
          nnids[row] = (nid-_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._col == -1 && DTree.isRootNode(dn)) { nnids[row] = (nid-_leaf); continue; }
        if( dn._split._col == -1 ) { // Might have a leftover non-split
          nid = dn._pid;             // Use the parent split decision then
          int xnid = oob ? nid2Oob(nid) : nid;
          nids.set0(row, xnid);
          nnids[row] = xnid-_leaf;
          dn = _tree.decided(nid); // Parent steers us
        }

        assert !isDecidedRow(nid);
        nid = dn.ns(chks,row); // Move down the tree 1 level
        if( !isDecidedRow(nid) ) {
          int xnid = oob ? nid2Oob(nid) : nid;
          nids.set0(row, xnid);
          nnids[row] = xnid-_leaf;
        } else {
          nnids[row] = nid-_leaf;
        }
      }
    }
390125
def vote_init(vote: Vote, inputs: dict, change_address: str) -> bytes:
    ''''''

    network_params = net_query(vote.deck.network)
    deck_vote_tag_address = deck_vote_tag(vote.deck)

    tx_fee = network_params.min_tx_fee  # settle for min tx fee for now

    for utxo in inputs['utxos']:
        utxo['txid'] = unhexlify(utxo['txid'])
        utxo['scriptSig'] = unhexlify(utxo['scriptSig'])

    outputs = [
        {"redeem": 0.01, "outputScript": transactions.monosig_script(deck_vote_tag_address)},
        {"redeem": 0, "outputScript": transactions.op_return_script(vote.to_protobuf)},
        {"redeem": float(inputs['total']) - float(tx_fee) - float(0.01),
         "outputScript": transactions.monosig_script(change_address)
         }]

    return transactions.make_raw_transaction(inputs['utxos'], outputs)
330253
function pushByzantinePrevote(h, p, idv, address, isApproved) {
    if(address !== null ){
        // mutex.lock( [ "assocByzantinePhase["+h+"].phase["+p+"]" ], function( unlock ){
            if(!assocByzantinePhase[h].phase[p] || 
                typeof assocByzantinePhase[h].phase[p] === 'undefined' || 
                Object.keys(assocByzantinePhase[h].phase[p]).length === 0){
                assocByzantinePhase[h].phase[p] =  {"proposal":{}, "received_addresses":[],
                "prevote_approved":[], "prevote_opposed":[], "prevote_temp_gossip":{},
                "precommit_approved":[], "precommit_opposed":[], "precommit_temp_gossip":{}};     
            }
            if(assocByzantinePhase[h].phase[p].prevote_approved.indexOf(address) === -1 && assocByzantinePhase[h].phase[p].prevote_opposed.indexOf(address) === -1){
                // console.log("byllllogg BYZANTINE_PREVOTE:" +h + p + "-1-idv:"+idv + "-pidv:" + assocByzantinePhase[h].phase[p].proposal.idv + "-address:" 
                    // + address+"-isApproved:"+isApproved+":"+(isApproved === 1)+ (assocByzantinePhase[h].phase[p].proposal.idv === idv));
                if(isApproved === 1 && assocByzantinePhase[h].phase[p].proposal.idv === idv && assocByzantinePhase[h].phase[p].proposal.isValid === 1){  
                    // console.log("byllllogg BYZANTINE_PREVOTE:" +h + p + "-2-idv:"+idv + "-address:" + address+"-isApproved:"+isApproved);
                    assocByzantinePhase[h].phase[p].prevote_approved.push(address);
                }
                else{
                    // console.log("byllllogg BYZANTINE_PREVOTE:" +h + p + "-3-idv:"+idv + "-address:" + address+"-isApproved:"+isApproved);
                    assocByzantinePhase[h].phase[p].prevote_opposed.push(address);
                }
                pushReceivedAddresses(assocByzantinePhase[h].phase[p].received_addresses, address);
            }
        //     unlock();
        // });
    }   
}
578211
def vote_random(candidates, votes, n_winners):
    
    rcands = list(candidates)
    shuffle(rcands)
    rcands = rcands[:min(n_winners, len(rcands))]
    best = [(i, 0.0) for i in rcands]
    return best
467935
def iteration(self, node_status=True):
        
        # One iteration changes the opinion of several voters using the following procedure:
        # - select randomly one voter (speaker 1)
        # - select randomly one of its neighbours (speaker 2)
        # - if the two voters agree, their neighbours take their opinion

        self.clean_initial_status(self.available_statuses.values())

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

        delta = {}
        status_delta = {st: 0 for st in self.available_statuses.values()}

        # select a random node
        speaker1 = list(self.graph.nodes())[np.random.randint(0, self.graph.number_of_nodes())]

        # select a random neighbour
        neighbours = list(self.graph.neighbors(speaker1))
        if isinstance(self.graph, nx.DiGraph):
            # add also the predecessors
            neighbours += list(self.graph.predecessors(speaker1))

        speaker2 = neighbours[np.random.randint(0, len(neighbours))]

        if self.status[speaker1] == self.status[speaker2]:
            # select listeners (all neighbours of two speakers)
            neighbours = list(self.graph.neighbors(speaker1)) + list(self.graph.neighbors(speaker2))

            if isinstance(self.graph, nx.DiGraph):
                # assumed if a->b then b can be influenced by a
                # but not the other way around - the link between the speakers doesn't matter
                neighbours = list(self.graph.successors(speaker1)) + list(self.graph.successors(speaker2))

            # update status of listeners
            for listener in neighbours:
                if self.status[speaker1] != self.status[listener]:
                    delta[listener] = self.status[speaker1]
                    status_delta[self.status[listener]] += 1
                    for x in self.available_statuses.values():
                        if x != self.status[listener]:
                            status_delta[x] -= 1

                self.status[listener] = self.status[speaker1]

        node_count = {st: len([n for n in self.status if self.status[n] == st])
                      for st in self.available_statuses.values()}

        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()}
270164
def _build_mat(self, ranks, n_candidates, prefcounts):
        

        mat = zeros((n_candidates, n_candidates))
        for i, j in itertools.combinations(range(n_candidates), 2):
            preference = ranks[:, i] - ranks[:, j]
            h_ij = dot((preference < 0), prefcounts)  # prefers i to j
            h_ji = dot((preference > 0), prefcounts)  # prefers j to i
            mat[i, j] = h_ij - h_ji
            mat[j, i] = h_ji - h_ij
        return mat
144578
def top2_reduced(votes):
    
    res = np.zeros(12)
    for vote in votes:
        # the top ranked alternative is in vote[0][0], second in vote[1][0]
        if vote[0][0] == 0: # i.e. the first alt is ranked first
            res[0] += 1
            if vote[1][0] == 2:
                res[4] += 1
            elif vote[1][0] == 3:
                res[5] += 1
        elif vote[0][0] == 1:
            res[1] += 1
            if vote[1][0] == 0:
                res[6] += 1
            elif vote[1][0] == 3:
                res[7] += 1
        elif vote[0][0] == 2:
            res[2] += 1
            if vote[1][0] == 0:
                res[8] += 1
            elif vote[1][0] == 1:
                res[9] += 1
        elif vote[0][0] == 3:
            res[3] += 1
            if vote[1][0] == 1:
                res[10] += 1
            elif vote[1][0] == 2:
                res[11] += 1
    res /= len(votes)
    return res
698414
def vote(session, nick, pid, response):
    """"""
    if not response:
        return "You have to vote something!"
    if response == "n" or response == "nay":
        response = "no"
    elif response == "y" or response == "aye":
        response = "yes"
    poll = get_open_poll(session, pid)
    if poll is None:
        return "That poll doesn't exist or isn't active. Use !poll list to see valid polls"
    old_vote = get_response(session, pid, nick)
    if old_vote is None:
        session.add(Poll_responses(pid=pid, response=response, voter=nick))
        return "%s voted %s." % (nick, response)
    else:
        if response == old_vote.response:
            return "You've already voted %s." % response
        else:
            msg = "%s changed their vote from %s to %s." % (nick, old_vote.response, response)
            old_vote.response = response
            return msg
1274433
function diceCoefficient(value, alternative) {
  var val = String(value).toLowerCase()
  var alt = String(alternative).toLowerCase()
  var left = val.length === 1 ? [val] : bigrams(val)
  var right = alt.length === 1 ? [alt] : bigrams(alt)
  var leftLength = left.length
  var rightLength = right.length
  var index = -1
  var intersections = 0
  var leftPair
  var rightPair
  var offset

  while (++index < leftLength) {
    leftPair = left[index]
    offset = -1

    while (++offset < rightLength) {
      rightPair = right[offset]

      if (leftPair === rightPair) {
        intersections++

        /* Make sure this pair never matches again */
        right[offset] = ''
        break
      }
    }
  }

  return (2 * intersections) / (leftLength + rightLength)
}
196240
function kruskal(weightFn) {
    weightFn = weightFn || function (edge) {
      return 1;
    };

    var _this$byGroup = this.byGroup(),
        nodes = _this$byGroup.nodes,
        edges = _this$byGroup.edges;

    var numNodes = nodes.length;
    var forest = new Array(numNodes);
    var A = nodes; // assumes byGroup() creates new collections that can be safely mutated

    var findSetIndex = function findSetIndex(ele) {
      for (var i = 0; i < forest.length; i++) {
        var eles = forest[i];

        if (eles.has(ele)) {
          return i;
        }
      }
    }; // start with one forest per node


    for (var i = 0; i < numNodes; i++) {
      forest[i] = this.spawn(nodes[i]);
    }

    var S = edges.sort(function (a, b) {
      return weightFn(a) - weightFn(b);
    });

    for (var _i = 0; _i < S.length; _i++) {
      var edge = S[_i];
      var u = edge.source()[0];
      var v = edge.target()[0];
      var setUIndex = findSetIndex(u);
      var setVIndex = findSetIndex(v);
      var setU = forest[setUIndex];
      var setV = forest[setVIndex];

      if (setUIndex !== setVIndex) {
        A.merge(edge); // combine forests for u and v

        setU.merge(setV);
        forest.splice(setVIndex, 1);
      }
    }

    return A;
  }
542803
def determine_bulk_exclusions(self, candidate_aggregates):
        ""
        # adjustment as under (13C) - seems to only apply if more than one candidate was elected in a round
        continuing = self.get_continuing_candidates(candidate_aggregates)
        candidate_votes = candidate_aggregates.get_candidate_votes()
        by_votes = self.get_votes_to_candidates(continuing, candidate_aggregates)
        adjustment = sum(excess_votes for _, _, excess_votes in self.election_distributions_pending)
        candidate_notional_votes = self.get_candidate_notional_votes(candidate_aggregates, adjustment)
        leading_shortfall, vacancy_shortfall = self.get_leading_and_vacancy_shortfall(candidate_aggregates)

        def determine_candidate_A():
            # notional votes >= vacancy shortfall
            eligible = [candidate_id for candidate_id, notional in candidate_notional_votes.items() if notional >= vacancy_shortfall]
            if len(eligible) == 0:
                return None
            # lowest in the poll: tie is irrelevant
            eligible.sort(key=lambda candidate_id: candidate_votes[candidate_id])
            return eligible[0]

        sorted_votes = list(sorted(by_votes.keys()))

        def notional_lower_than_higher(candidate_id):
            "check notional votes of candidate is lower than the number of votes of the candidate standing immediately higher"
            votes = candidate_votes[candidate_id]
            votes_idx = sorted_votes.index(votes)
            # no higher candidate
            if votes_idx == len(sorted_votes) - 1:
                return False
            # legislation ambiguous, but if there's a tie above us let's check all the candidates on that count
            notional = candidate_notional_votes[candidate_id]
            higher_votes = sorted_votes[votes_idx + 1]
            acceptable = all(notional < candidate_votes[t] for t in by_votes[higher_votes])
            return acceptable

        def highest(eligible):
            "return the highest ranked candidate in candidates, by vote. if a tie, or list empty, return None"
            if not eligible:
                return
            binned = self.get_votes_to_candidates(eligible, candidate_aggregates)
            possible = binned[max(binned)]
            if len(possible) == 1:
                return possible[0]

        def determine_candidate_B(candidate_A):
            if candidate_A is not None:
                A_votes = candidate_votes[candidate_A]
                eligible = [candidate_id for candidate_id in continuing if candidate_votes[candidate_id] < A_votes]
            else:
                eligible = [candidate_id for candidate_id in continuing if candidate_notional_votes[candidate_id] < vacancy_shortfall]
            eligible = [candidate_id for candidate_id in eligible if notional_lower_than_higher(candidate_id)]
            return highest(eligible)

        def determine_candidate_C():
            eligible = [candidate_id for candidate_id in continuing if candidate_notional_votes[candidate_id] < leading_shortfall]
            # the candidate of those eligible which stands highest in the poll
            eligible.sort(key=lambda candidate_id: candidate_votes[candidate_id])
            return highest(eligible)

        def candidates_lte(candidate_id):
            votes = candidate_votes[candidate_id]
            lower_votes = [t for t in by_votes.keys() if t < votes]
            to_exclude = [candidate_id]
            for vote in lower_votes:
                to_exclude += [candidate_id for candidate_id in by_votes[vote] if candidate_id in continuing]
            return to_exclude

        # candidate A, B, C as under (13A)(a)
        to_exclude = None
        candidate_A = determine_candidate_A()
        candidate_B = determine_candidate_B(candidate_A)
        candidate_C = None
        if candidate_B:
            candidate_B_votes = candidate_votes[candidate_B]
            if candidate_B_votes < leading_shortfall:
                to_exclude = candidates_lte(candidate_B)
            else:
                candidate_C = determine_candidate_C()
                if candidate_C:
                    to_exclude = candidates_lte(candidate_C)
        if to_exclude and len(to_exclude) == 1:
            to_exclude = None
        return to_exclude, ExclusionReason("bulk", {
            "candidate_A": candidate_A,
            "candidate_B": candidate_B,
            "candidate_C": candidate_C
        })