Esempio n. 1
0
 def get_formatted_stats(self, fmt, user=None):
     stats = self.get_stats(user=user, rename_users=True, load_users=False)
     if fmt == 'json':
         return json.dumps(stats, indent=1)
     elif fmt in ('text', 'html'):
         return BallotCounter.stats_as_text(stats)
     elif fmt in ('xlsx', 'ods'):
         return BallotCounter.stats_as_spreadsheet(fmt, stats)
     else:
         return None
Esempio n. 2
0
 def get_formatted_stats(self, fmt, user=None):
     stats = self.get_stats(user=user, rename_users=True, load_users=False)
     if fmt == 'json':
         return json.dumps(stats, indent=1)
     elif fmt in ('text', 'html'):
         return BallotCounter.stats_as_text(stats)
     elif fmt in ('xlsx', 'ods'):
         return BallotCounter.stats_as_spreadsheet(fmt, stats)
     else:
         return None
Esempio n. 3
0
 def load_archived_ballots(self):
     bc = BallotCounter()
     if settings.BALLOT_SAVEFILE_FORMAT is not None:
         try:
             filename = settings.BALLOT_SAVEFILE_FORMAT % {
                 'election_id': self.id,
                 'voting_system': self.voting_system}
             bc.load_ballots(filename)
         except:
             import traceback
             traceback.print_exc()
     return bc
Esempio n. 4
0
 def load_archived_ballots(self):
     bc = BallotCounter()
     if settings.BALLOT_SAVEFILE_FORMAT is not None:
         try:
             filename = settings.BALLOT_SAVEFILE_FORMAT % {
                 'election_id': self.id,
                 'voting_system': self.voting_system
             }
             bc.load_ballots(filename)
         except:
             import traceback
             traceback.print_exc()
     return bc
Esempio n. 5
0
    def process_votes(self):
        if self.deadline_joined_org:
            votes = ElectionVote.objects.select_related('candidate__user').filter(election=self, user__userprofile__joined_org__lt = self.deadline_joined_org)
        else:
            votes = ElectionVote.objects.select_related('candidate__user').filter(election=self)

        votemap = {}
        for vote in votes:
            if not votemap.has_key(vote.user_id):
                votemap[vote.user_id] = []
            votemap[vote.user_id].append(vote)

        ballots = []
        for user_id in votemap:
            ballot = [(int(v.value), v.candidate) for v in votemap[user_id]]
            ballots.append(ballot)

        ballot_counter = BallotCounter(ballots)
        return ballot_counter.results(self.voting_system), ballot_counter
Esempio n. 6
0
    def process_votes(self):
        if self.deadline_joined_org:
            votes = ElectionVote.objects.select_related(
                'candidate__user').filter(
                    election=self,
                    user__userprofile__joined_org__lt=self.deadline_joined_org)
        else:
            votes = ElectionVote.objects.select_related(
                'candidate__user').filter(election=self)

        votemap = {}
        for vote in votes:
            if not votemap.has_key(vote.user_id):
                votemap[vote.user_id] = []
            votemap[vote.user_id].append(vote)

        ballots = []
        for user_id in votemap:
            ballot = [(int(v.value), v.candidate) for v in votemap[user_id]]
            ballots.append(ballot)

        ballot_counter = BallotCounter(ballots)
        return ballot_counter.results(self.voting_system), ballot_counter
Esempio n. 7
0
    def get_stats(self, user=None, load_users=True, rename_users=False):
        """Load stats from the DB and convert to pythonic format.

        We expect stats to change over time, so the function provides
        reasonable defaults for everything we care about even if the
        JSON turns out to be incomplete. Changes to our stats logic will
        not require a schema change, but stats cannot readily be queried.
        Pros and cons...
        """
        stats = {
            'ranking_matrix': [],
            'pairwise_matrix': [],
            'candidates': [],
            'ballot_lengths': {},
            'ballots': 0,
            'ballot_length_average': 0,
            'ballot_length_most_common': 0}

        # Parse the stats JSON, if it exists.
        try:
            stats.update(json.loads(self.stats))
        except:
            pass

        # Convert ballot_lengths keys (back) to ints
        for k in stats['ballot_lengths'].keys():
            stats['ballot_lengths'][int(k)] = stats['ballot_lengths'][k]
            del stats['ballot_lengths'][k]

        # Censor the statistics, if we only want to publish details about
        # the top N candidates.
        if self.stats_limit:
            excluded = set([])
            if not user or not user.is_staff:
                excluded |= set(cand.user.username for cand in
                                self.get_winners()[self.stats_limit:])
            if user and user.username in excluded:
                excluded.remove(user.username)
            stats = BallotCounter.exclude_candidate_stats(stats, excluded)

        # Convert usernames to users. Let's hope usernames never change!
        for i, c in enumerate(stats['candidates']):
            try:
                if not c:
                    pass
                elif load_users:
                    stats['candidates'][i] = User.objects.get(username=c)
                elif rename_users:
                    u = User.objects.get(username=c)
                    stats['candidates'][i] = '%s (%s)' % (u.get_name(), c)
            except:
                pass

        # Create more accessible representations of the tables
        stats['rankings'] = {}
        stats['victories'] = {}
        for i, c in enumerate(stats['candidates']):
            if stats.get('ranking_matrix'):
                stats['rankings'][c] = stats['ranking_matrix'][i]
            if stats.get('pairwise_matrix'):
                stats['victories'][c] = stats['pairwise_matrix'][i]

        return stats
Esempio n. 8
0
    def get_stats(self, user=None, load_users=True, rename_users=False):
        """Load stats from the DB and convert to pythonic format.

        We expect stats to change over time, so the function provides
        reasonable defaults for everything we care about even if the
        JSON turns out to be incomplete. Changes to our stats logic will
        not require a schema change, but stats cannot readily be queried.
        Pros and cons...
        """
        stats = {
            'ranking_matrix': [],
            'pairwise_matrix': [],
            'candidates': [],
            'ballot_lengths': {},
            'ballots': 0,
            'ballot_length_average': 0,
            'ballot_length_most_common': 0
        }

        # Parse the stats JSON, if it exists.
        try:
            stats.update(json.loads(self.stats))
        except:
            pass

        # Convert ballot_lengths keys (back) to ints
        for k in stats['ballot_lengths'].keys():
            stats['ballot_lengths'][int(k)] = stats['ballot_lengths'][k]
            del stats['ballot_lengths'][k]

        # Censor the statistics, if we only want to publish details about
        # the top N candidates.
        if self.stats_limit:
            excluded = set([])
            if not user or not user.is_staff:
                excluded |= set(
                    cand.user.username
                    for cand in self.get_winners()[self.stats_limit:])
            if user and user.username in excluded:
                excluded.remove(user.username)
            stats = BallotCounter.exclude_candidate_stats(stats, excluded)

        # Convert usernames to users. Let's hope usernames never change!
        for i, c in enumerate(stats['candidates']):
            try:
                if not c:
                    pass
                elif load_users:
                    stats['candidates'][i] = User.objects.get(username=c)
                elif rename_users:
                    u = User.objects.get(username=c)
                    stats['candidates'][i] = '%s (%s)' % (u.get_name(), c)
            except:
                pass

        # Create more accessible representations of the tables
        stats['rankings'] = {}
        stats['victories'] = {}
        for i, c in enumerate(stats['candidates']):
            if stats.get('ranking_matrix'):
                stats['rankings'][c] = stats['ranking_matrix'][i]
            if stats.get('pairwise_matrix'):
                stats['victories'][c] = stats['pairwise_matrix'][i]

        return stats