Elect a candidate, updating internal state to track this.
        Calculate the paper count to be transferred on to other candidates,
        and if required schedule a distribution fo papers.
355624
def elect(self, candidate_aggregates, candidate_id):
        

        # somewhat paranoid cross-check, but we've had this bug before..
        assert(candidate_id not in self.candidates_elected)

        elected_no = len(self.candidates_elected) + 1
        self.candidates_elected[candidate_id] = True

        transfer_value = 0
        excess_votes = paper_count = None
        if len(self.candidates_elected) != self.vacancies:
            excess_votes = max(candidate_aggregates.get_vote_count(candidate_id) - self.quota, 0)
            assert(excess_votes >= 0)
            paper_count = self.candidate_bundle_transactions.get_paper_count(candidate_id)
            if paper_count > 0:
                transfer_value = fractions.Fraction(excess_votes, paper_count)
            assert(transfer_value >= 0)
            self.election_distributions_pending.append((candidate_id, transfer_value, excess_votes))
        self.results.candidate_elected(
            CandidateElected(
                candidate_id=candidate_id,
                order=elected_no,
                excess_votes=excess_votes,
                paper_count=paper_count,
                transfer_value=transfer_value))
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);
    }
875929
def tick(self):
        
        if self.state == AuctionState.NOMINATE:
            # if no nominee submitted, exception
            if self.nominee is None:
                raise InvalidActionError("Tick was invoked during nomination but no nominee was selected.")
            self.state = AuctionState.BID
            # initialize bids array to hold each owner's bid
            # this holds the latest bids submitted for the current bidding phase
            self.bids = [self.bid if i == self.turn_index else 0 for i in range(len(self.owners))]
            # this holds the bids submitted on a given tick
            self.tickbids = [0] * len(self.owners)
        elif self.state == AuctionState.BID:
            # If no new bids submitted, we're done with this bid and the player gets what they bid for
            if not any(bid > 0 for bid in self.tickbids):
                winner = self._winning_owner()
                winner.buy(self.nominee, self.bid)
                self._player_ownership[self._nominee_index] = self.winning_owner_index()
                self.undrafted_players.remove(self.nominee)
                self.nominee = None
                self._nominee_index = -1
                # check if we're done, or move to the next player who still has space
                done = True
                for i in range(len(self.owners)):
                    next_turn = (self.turn_index + 1 + i) % len(self.owners)
                    if self.owners[next_turn].remaining_picks() > 0:
                        self.turn_index = next_turn
                        done = False
                        break
                # if we didn't move on, we're done
                if done:
                    self.state = AuctionState.DONE
                else:
                    self.state = AuctionState.NOMINATE
            else:
                # new bids have been submitted,
                # randomly pick the bid to accept from the highest,
                # then everyone gets a chance to submit more
                top_idxs = [i for i, bid in enumerate(self.tickbids) if bid == max(self.tickbids)]
                accept_idx = random.choice(top_idxs)
                # set this as the new bid
                self.bid = self.tickbids[accept_idx]
                # update the bids for this round
                self.bids[accept_idx] = self.bid
                # clear this for the next tick
                self.tickbids = [0] * len(self.owners)
546962
private int collectCandidates(Map<Long, Score> candidates,
                                List<Bucket> buckets,
                                int threshold) {
    int ix;
    for (ix = 0; ix < threshold &&
           candidates.size() < (CUTOFF_FACTOR_1 * max_search_hits); ix++) {
      Bucket b = buckets.get(ix);
      long[] ids = b.records;
      double score = b.getScore();
      
      for (int ix2 = 0; ix2 < b.nextfree; ix2++) {
        Score s = candidates.get(ids[ix2]);
        if (s == null) {
          s = new Score(ids[ix2]);
          candidates.put(ids[ix2], s);
        }
        s.score += score;
      }
      if (DEBUG)
        System.out.println("Bucket " + b.nextfree + " -> " + candidates.size());
    }
    return ix;
  }
500220
protected function electCandidate(Candidate $candidate)
    {
        $this->logger->notice("Electing a candidate: $candidate");

        $candidate->setState(Candidate::ELECTED);
        ++$this->electedCandidates;
        --$this->candidatesToElect;

        if ($this->electedCandidates < $this->election->getWinnersCount()) {
            $surplus = $candidate->getVotes() - $this->quota;
            if ($surplus > 0) {
                $this->transferSurplusVotes($surplus, $candidate);
            } else {
                $this->logger->notice("No surplus votes from $candidate to reallocate");
            }
        }

        return;
    }
876201
def gather_votes(self):
        
        async def slave_task(addr, candidates):
            r_manager = await self.env.connect(addr)
            return await r_manager.gather_votes(candidates)

        if len(self.candidates) == 0:
            self._log(logging.DEBUG, "Could not gather votes because there "
                      "are no candidates!")
            self._votes = []
            return
        self._log(logging.DEBUG, "Gathering votes for {} candidates."
                  .format(len(self.candidates)))

        if self._single_env:
            self._votes = self.env.gather_votes(self.candidates)
        else:
            mgrs = self.get_managers()
            tasks = create_tasks(slave_task, mgrs, self.candidates)
            self._votes = run(tasks)
25351
def MoVPluRunOff(profile):
    

    # Currently, we expect the profile to contain complete ordering over candidates.
    elecType = profile.getElecType()
    if elecType != "soc" and elecType != "toc" and elecType != "csv":
        print("ERROR: unsupported profile type")
        exit()

    # Initialization
    prefcounts = profile.getPreferenceCounts()
    len_prefcounts = len(prefcounts)
    rankmaps = profile.getRankMaps()
    # print(rankmaps)
    ranking = MechanismPlurality().getRanking(profile)
    # print("ranking=", ranking)

    # 1st round: find the top 2 candidates in plurality scores
    # Compute the 1st-place candidate in plurality scores
    max_cand = ranking[0][0][0]

    # Compute the 2nd-place candidate in plurality scores
    # Automatically using tie-breaking rule--numerically increasing order
    if len(ranking[0][0]) > 1:
        second_max_cand = ranking[0][0][1]
        if len(ranking[0][0]) > 2:
            third_max_cand = ranking[0][0][2]
        else:
            third_max_cand = ranking[0][1][0]
    else:
        second_max_cand = ranking[0][1][0]
        if len(ranking[0][1]) > 1:
            third_max_cand = ranking[0][1][1]
        else:
            third_max_cand = ranking[0][2][0]

    top_2 = [max_cand, second_max_cand]
    # 2nd round: find the candidate with maximum plurality score
    dict_top2 = {max_cand: 0, second_max_cand: 0}
    for i in range(len_prefcounts):
        vote_top2 = {key: value for key, value in rankmaps[i].items() if key in top_2}
        # print(vote_top2)
        top_position = min(vote_top2.values())
        keys = [x for x in vote_top2.keys() if vote_top2[x] == top_position]
        for key in keys:
            dict_top2[key] += prefcounts[i]

    # the original winner-- d
    # print("dict_top2=", dict_top2)
    d = max(dict_top2.items(), key=lambda x: x[1])[0]
    c_1 = top_2[0] if top_2[1] == d else top_2[1]
    # the candidate with third highest plurality score
    c_2 = third_max_cand
    # print("d=", d, c_1, c_2)

    Type1_1 = Type1_2 = 0
    plu_d = plu_c_1 = plu_c_2 = 0

    # ------------count the votes of CASE I & II---------------
    for i in range(len_prefcounts):
        if rankmaps[i][d] < rankmaps[i][c_1]:
            Type1_1 += prefcounts[i]
        elif rankmaps[i][d] > rankmaps[i][c_1]:
            Type1_2 += prefcounts[i]

        if rankmaps[i][d] == 1:
            plu_d += prefcounts[i]
        elif rankmaps[i][c_1] == 1:
            plu_c_1 += prefcounts[i]
        elif rankmaps[i][c_2] == 1:
            plu_c_2 += prefcounts[i]
    # print("plu=", plu_d, plu_c_1, plu_c_2)
    # -------------------CASE I------------------------------
    MoV_I = math.floor((Type1_1 - Type1_2)/2) + 1

    # -------------------CASE II-------------------------------
    if math.floor((plu_d + plu_c_2)/2) + 1 <= plu_c_1:
        MoV_II = math.floor((plu_d - plu_c_2)/2) + 1
    else:
        MoV_II = plu_d - math.floor((plu_d + plu_c_1 + plu_c_2)/3) + 1
        # MoV_II = math.floor((plu_d * 2 - plu_c_1 - plu_c_2) / 3) + 1  # old version

    # -------------------CASE III-----------------------------
    MoV_d = dict()
    remaining = sorted(rankmaps[0].keys())
    remaining.remove(d)
    remaining.remove(c_1)

    for e in remaining:
        # ------------count the votes of CASE III---------------
        T1 = T2 = T3 = T4 = T5 = T6 = T7 = T8 = 0
        for i in range(len_prefcounts):
            if rankmaps[i][d] == 1:
                if rankmaps[i][c_1] < rankmaps[i][e]:
                    T1 += prefcounts[i]
                elif rankmaps[i][e] < rankmaps[i][c_1]:
                    T2 += prefcounts[i]
            elif rankmaps[i][c_1] == 1:
                if rankmaps[i][d] < rankmaps[i][e]:
                    T3 += prefcounts[i]
                elif rankmaps[i][e] < rankmaps[i][d]:
                    T4 += prefcounts[i]
            elif rankmaps[i][e] == 1:
                if rankmaps[i][d] < rankmaps[i][c_1]:
                    T5 += prefcounts[i]
                elif rankmaps[i][c_1] < rankmaps[i][d]:
                    T6 += prefcounts[i]
            else:
                if rankmaps[i][d] < rankmaps[i][e]:
                    T7 += prefcounts[i]
                elif rankmaps[i][e] < rankmaps[i][d]:
                    T8 += prefcounts[i]

        if math.floor((T3 + T4 + T5 + T6)/2) + 1 <= T1 + T2:
            CHANGE1 = math.floor((T3 + T4 - T5 - T6)/2) + 1
        else:
            CHANGE1 = T3 + T4 - T1 -T2 + 1

        x = min(T3, CHANGE1)
        if T1 + T2 + T3 + T7 - x < T4 + T5 + T6 + T8 + x:
            MoV_d[e] = CHANGE1
        else:
            CHANGE2 = math.floor((T1 + T2 + T3 + T7 - T4 - T5 - T6 - T8)/2) - x + 1
            MoV_d[e] = CHANGE1 + CHANGE2

    MoV_III = min(MoV_d.items(), key=lambda x: x[1])[1]
    # ------------------------Overall MoV---------------------------------
    # print(MoV_d)
    # print(MoV_I, MoV_II, MoV_III)
    MoV = min(MoV_I, MoV_II, MoV_III)

    return MoV
264584
def get_candidates(self, obj):
        
        return CandidateElectionSerializer(
            obj.candidate_elections.all(), many=True
        ).data
1016785
def get_candidate_electoral_votes(self, candidate):
        
        candidate_election = CandidateElection.objects.get(
            candidate=candidate, election=self
        )

        return candidate_election.electoral_votes.all()
396543
def _calculatePolicy(self):
        """"""
        cmd = '''
              UPDATE policy
                 SET action = (
                     SELECT action
                       FROM (SELECT state, action, MAX(value)
                               FROM Q
                              GROUP BY state) AS A
                       WHERE policy.state = A.state
                       GROUP BY state);'''
        self._cur.execute(cmd)
        self._conn.commit()
645099
def save(self, *args, **kwargs):
        
        self.uid = '{}_{}_ballotmeasure:{}'.format(
            self.division.uid,
            self.election_day.uid,
            self.number
        )
        super(BallotMeasure, self).save(*args, **kwargs)
1068160
function (idx) {
			// Ensures that an index is within the number of candidates
			if (idx >= json.length || idx < 0) {
				if (json.length == 0)
					throw new Error("Candidate index is out of bounds (no candidates returned; requested " + idx + ")");
				else
					throw new Error("Candidate index is out of bounds (" + json.length + " candidates; indicies 0 through " +
						(json.length - 1) + " available; requested " + idx + ")");
			}
		}
1086773
def apply(self, doc, split, train, **kwargs):
        
        logger.debug(f"Document: {doc}")

        # Get all the candidates in this doc that will be featurized
        cands_list = get_cands_list_from_split(
            self.session, self.candidate_classes, doc, split
        )

        feature_map = dict()

        # Make a flat list of all candidates from the list of list of
        # candidates. This helps reduce the number of queries needed to update.
        all_cands = itertools.chain.from_iterable(cands_list)
        records = list(
            get_mapping(self.session, Feature, all_cands, get_all_feats, feature_map)
        )
        batch_upsert_records(self.session, Feature, records)

        # Insert all Feature Keys
        if train:
            upsert_keys(self.session, FeatureKey, feature_map)

        # This return + yield makes a completely empty generator
        return
        yield
1034221
public function computeChangeSets()
    {
        $this->computeScheduleInsertsChangeSets();
        $this->computeScheduleUpsertsChangeSets();

        // Compute changes for other MANAGED documents. Change tracking policies take effect here.
        foreach ($this->identityMap as $className => $documents) {
            $class = $this->dm->getClassMetadata($className);
            if ($class->isEmbeddedDocument) {
                /* we do not want to compute changes to embedded documents up front
                 * in case embedded document was replaced and its changeset
                 * would corrupt data. Embedded documents' change set will
                 * be calculated by reachability from owning document.
                 */
                continue;
            }

            // If change tracking is explicit or happens through notification, then only compute
            // changes on document of that type that are explicitly marked for synchronization.
            switch (true) {
                case ($class->isChangeTrackingDeferredImplicit()):
                    $documentsToProcess = $documents;
                    break;

                case (isset($this->scheduledForDirtyCheck[$className])):
                    $documentsToProcess = $this->scheduledForDirtyCheck[$className];
                    break;

                default:
                    $documentsToProcess = [];
            }

            foreach ($documentsToProcess as $document) {
                // Ignore uninitialized proxy objects
                if ($document instanceof Proxy && !$document->__isInitialized__) {
                    continue;
                }
                // Only MANAGED documents that are NOT SCHEDULED FOR INSERTION, UPSERT OR DELETION are processed here.
                $oid = spl_object_hash($document);
                if (isset($this->documentInsertions[$oid])
                    || isset($this->documentUpserts[$oid])
                    || isset($this->documentDeletions[$oid])
                    || !isset($this->documentStates[$oid])
                ) {
                    continue;
                }

                $this->computeChangeSet($class, $document);
            }
        }
    }
1270210
function pickMostDue(s, state) {
  var prec = ['learning', 'overdue', 'due'];
  for (var i = 0; i < prec.length; i += 1) {
    var sched = prec[i];
    if (s[sched].length) {
      return s[sched].slice(0).sort(function (a, b) {
        var cardA = state.cardStates[a];
        var cardB = state.cardStates[b];
        if (cardA == null) {
          throw new Error('id not found in state: ' + a);
        }
        if (cardB == null) {
          throw new Error('id not found in state: ' + b);
        }

        var reviewDiff = cardA.lastReviewed == null && cardB.lastReviewed != null ? 1 : cardB.lastReviewed == null && cardA.lastReviewed != null ? -1 : cardA.lastReviewed == null && cardB.lastReviewed == null ? 0 : cardB.lastReviewed - cardA.lastReviewed;
        if (reviewDiff !== 0) {
          return -reviewDiff;
        }

        if (a === b) {
          throw new Error('comparing duplicate id: ' + a);
        }
        return b > a ? 1 : -1;
      })[0];
    }
  }
  return null;
}
206690
def _process_state_embryo(self, job_record):
        
        uow, is_duplicate = self.insert_and_publish_uow(job_record, 0, 0)
        self.update_job(job_record, uow, job.STATE_IN_PROGRESS)
20112
synchronized boolean update() {
        int elected = this.elected;
        int oldelected = this.oldelected;
        int lbfactor = this.lbfactor;
        if (lbfactor > 0) {
            this.lbstatus = ((elected - oldelected) * 1000) / lbfactor;
        }
        this.oldelected = elected;
        return elected != oldelected; // ping if they are equal
    }