Пример #1
0
def csv_from_stv_polls(election, polls, lang, outfile=None):
    with translation.override(lang):
        if outfile is None:
            outfile = StringIO()
        csvout = csv.writer(outfile, dialect='excel', delimiter=',')
        writerow = csvout.writerow

        make_csv_intro(writerow, election, lang)
        actions_desc = {
            'elect': _('Elect'),
            'eliminate': _('Eliminated'),
            'quota': _('Eliminated due to quota restriction')
        }
        from stv.parser import STVParser
        for poll in polls:
            writerow([])
            writerow([strforce(_("Poll name")), strforce(poll.name)])
            writerow([])
            questions = poll.questions
            indexed_cands = {}
            counter = 0
            for item in questions[0]['answers']:
                indexed_cands[str(counter)] = item
                counter += 1

            results_winners = poll.stv_results[0]
            results_all = poll.stv_results[1]
            result_steps = poll.stv_results[2]
            stv = STVParser(result_steps)
            rounds = list(stv.rounds())
            writerow([])
            writerow([strforce(_("Elected")), strforce(_("Departments"))])
            for winner_data in results_winners:
                winner_id = winner_data[0]
                winner = indexed_cands[str(winner_id)]
                winner = winner.split(':')
                winner_name = winner[0]
                winner_department = winner[1]
                writerow([strforce(winner_name), strforce(winner_department)])
            for num, round in rounds:
                round_name = _('Round ')
                round_name += str(num)
                writerow([])
                writerow([strforce(round_name)])
                writerow([strforce(_('Candidate')), strforce(_('Votes')),\
                    strforce(_('Draw')), strforce(_('Action'))])
                for name, cand in round['candidates'].iteritems():
                    actions = map(lambda x: x[0], cand['actions'])
                    actions = map(lambda x: x[0], cand['actions'])
                    draw = _("NO")
                    if 'random' in actions:
                        draw = _("YES")
                    action = None
                    if len(actions):
                        action = actions_desc.get(actions[-1])
                    votes = cand['votes']
                    cand_name = indexed_cands[str(name)]
                    cand_name = cand_name.split(':')[0]
                    writerow([strforce(cand_name),strforce(votes),\
                    strforce(draw), strforce(action)])
Пример #2
0
def csv_from_stv_polls(election, polls, lang, outfile=None):
    with translation.override(lang):
        if outfile is None:
            outfile = StringIO()
        csvout = csv.writer(outfile, dialect='excel', delimiter=',')
        writerow = csvout.writerow
        
        make_csv_intro(writerow, election, lang)
        actions_desc = {
            'elect': _('Elect'),
            'eliminate': _('Eliminated'),
            'quota': _('Eliminated due to quota restriction')}
        from stv.parser import STVParser
        for poll in polls:
            writerow([])
            writerow([strforce(_("Poll name")), strforce(poll.name)])
            writerow([])
            questions = poll.questions
            indexed_cands = {}
            counter = 0
            for item in questions[0]['answers']:
                indexed_cands[str(counter)] = item
                counter += 1

            results_winners = poll.stv_results[0]
            results_all = poll.stv_results[1]
            result_steps = poll.stv_results[2] 
            stv = STVParser(result_steps)
            rounds = list(stv.rounds())
            writerow([])
            writerow([strforce(_("Elected")), strforce(_("Departments"))])
            for winner_data in results_winners:
                 winner_id = winner_data[0]
                 winner = indexed_cands[str(winner_id)]
                 winner = winner.split(':')
                 winner_name = winner[0]
                 winner_department = winner[1]
                 writerow([strforce(winner_name), strforce(winner_department)])
            for num, round in rounds:
                round_name = _('Round ')
                round_name +=str(num)
                writerow([])
                writerow([strforce(round_name)])
                writerow([strforce(_('Candidate')), strforce(_('Votes')),\
                    strforce(_('Draw')), strforce(_('Action'))])
                for name, cand in round['candidates'].iteritems():
                    actions = map(lambda x: x[0], cand['actions'])
                    actions = map(lambda x: x[0], cand['actions'])
                    draw = _("NO")
                    if 'random' in actions:
                        draw = _("YES")
                    action = None
                    if len(actions):
                        action = actions_desc.get(actions[-1])
                    votes = cand['votes']  
                    cand_name = indexed_cands[str(name)]
                    cand_name = cand_name.split(':')[0]
                    writerow([strforce(cand_name),strforce(votes),\
                    strforce(draw), strforce(action)])
Пример #3
0
def test_parse():
    parser = STVParser(SAMPLE)
    rounds = list(parser.rounds())
    assert rounds == [
        (None, {
            'candidates': {
                7: {
                    'actions': [],
                    'votes': '0.0'
                }
            }
        }),
        (1, {
            'candidates': {
                5: {
                    'actions': [('random', (5, [5, 6], '-ELIMINATE')),
                                ('eliminate', (5, '10'))],
                    'votes':
                    '10'
                },
                6: {
                    'actions': [('random', (5, [5, 6], '-ELIMINATE'))],
                    'votes': '10'
                },
                7: {
                    'actions': [],
                    'votes': '10'
                },
                8: {
                    'actions': [],
                    'votes': '10'
                }
            }
        }),
        (2, {
            'candidates': {
                6: {
                    'actions': [('elect', (6, 20.0)), ('quota', (6, '0.'))],
                    'votes': '20.0'
                },
                7: {
                    'actions': [('transfer', [7, 6, '2', '3.5', '7.0'])],
                    'votes': '0.0'
                }
            }
        }),
    ]
Пример #4
0
def build_stv_doc(title,
                  name,
                  institution_name,
                  voting_start,
                  voting_end,
                  extended_until,
                  data,
                  language,
                  filename="election_results.pdf",
                  new_page=True):
    with translation.override(language[0]):
        pageinfo = _("Zeus Elections - Poll Results")
        title = _('Results')
        DATE_FMT = "%d/%m/%Y %H:%M"
        if isinstance(voting_start, datetime.datetime):
            voting_start = _('Start: %(date)s') % {
                'date': voting_start.strftime(DATE_FMT)
            }

        if isinstance(voting_end, datetime.datetime):
            voting_end = _('End: %(date)s') % {
                'date': voting_end.strftime(DATE_FMT)
            }

        if extended_until and isinstance(extended_until, datetime.datetime):
            extended_until = _('Extension: %(date)s') % {
                'date': extended_until.strftime(DATE_FMT)
            }
        else:
            extended_until = ""

        if not isinstance(data, list):
            data = [(name, data)]

        # reset pdfdoc timestamp in order to force a fresh one to be used in
        # pdf document metadata.
        pdfdoc._NOWT = None

        elements = []

        doc = SimpleDocTemplate(filename, pagesize=A4)

        styles = getSampleStyleSheet()
        styles.add(
            ParagraphStyle(name='Zeus',
                           fontName='LinLibertine',
                           fontSize=12,
                           leading=16,
                           alignment=TA_JUSTIFY))
        styles.add(
            ParagraphStyle(name='ZeusBold',
                           fontName='LinLibertineBd',
                           fontSize=12,
                           leading=16,
                           alignment=TA_JUSTIFY))

        styles.add(
            ParagraphStyle(name='ZeusSubHeading',
                           fontName='LinLibertineBd',
                           fontSize=14,
                           alignment=TA_JUSTIFY,
                           spaceAfter=16))

        styles.add(
            ParagraphStyle(name='ZeusHeading',
                           fontName='LinLibertineBd',
                           fontSize=16,
                           alignment=TA_CENTER,
                           spaceAfter=16))
        intro_contents = [voting_start, voting_end, extended_until]

        make_heading(elements, styles, [title, name, institution_name])
        make_intro(elements, styles, intro_contents)
        make_election_voters(elements, styles, data, stv=True)

        for poll_name, poll_results, questions, poll_voters in data:
            poll_intro_contents = [poll_name]
            parties_results = []
            candidates_results = {}

            #total_votes, blank_votes, parties_results, candidates_results = \
            #    load_results(poll_results)
            if new_page:
                elements.append(PageBreak())
            elements.append(Spacer(1, 12))
            elements.append(Spacer(1, 12))
            elements.append(Spacer(1, 12))
            make_subheading(elements, styles, poll_intro_contents)
            elements.append(Spacer(1, 12))
            make_intro(elements, styles, intro_contents)
            make_poll_voters(elements, styles, poll_voters)
            elements.append(Spacer(1, 12))
            #make dict with indexing as key and name as value
            counter = 0
            indexed_cands = {}
            for item in questions[0]['answers']:
                indexed_cands[str(counter)] = item
                counter += 1
            elected = [[_('Elected')]]
            json_data = poll_results[0]
            for item in json_data:
                elected.append([indexed_cands[item[0]]])
            t = Table(elected)
            my_table_style = TableStyle([
                ('FONT', (0, 0), (-1, -1), 'LinLibertine'),
                ('ALIGN', (1, 1), (-2, -2), 'LEFT'),
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ])
            t.setStyle(my_table_style)
            elements.append(t)

            actions_desc = {
                'elect': _('Elect'),
                'eliminate': _('Eliminated'),
                'quota': _('Eliminated due to quota restriction')
            }

            table_header = [_('Candidate'), _('Votes'), _('Draw'), _('Action')]

            stv = STVParser(poll_results[2])
            rounds = list(stv.rounds())

            for num, round in rounds:
                round_name = _('Round ')
                round_name += str(num)
                elements.append(Paragraph(round_name, styles['Zeus']))
                round_table = []
                temp_table = []
                temp_table.append(table_header)
                for name, cand in round['candidates'].iteritems():
                    actions = map(lambda x: x[0], cand['actions'])
                    draw = _("NO")
                    if 'random' in actions:
                        draw = _("YES")
                    action = None
                    if len(actions):
                        action = actions_desc.get(actions[-1])
                    votes = cand['votes']
                    cand_name = indexed_cands[str(name)]
                    cand_name = cand_name.split(':')[0]
                    row = [cand_name, votes, draw, action]
                    temp_table.append(row)
                round_table = Table(temp_table)
                round_table.setStyle(my_table_style)
                elements.append(round_table)
                elements.append(Spacer(1, 12))

        doc.build(elements,
                  onFirstPage=make_first_page_hf,
                  onLaterPages=make_later_pages_hf(pageinfo))
Пример #5
0
def build_stv_doc(title, name, institution_name, voting_start, voting_end,
              extended_until, data, language, filename="election_results.pdf", new_page=True):
    with translation.override(language[0]):
        pageinfo = _("Zeus Elections - Poll Results")
        title = _('Results')
        DATE_FMT = "%d/%m/%Y %H:%M"
        if isinstance(voting_start, datetime.datetime):
            voting_start = _('Start: %(date)s') % {'date':
            voting_start.strftime(DATE_FMT)}

        if isinstance(voting_end, datetime.datetime):
            voting_end = _('End: %(date)s') % {'date':
            voting_end.strftime(DATE_FMT)}

        if extended_until and isinstance(extended_until, datetime.datetime):
            extended_until = _('Extension: %(date)s') % {'date':
            extended_until.strftime(DATE_FMT)}
        else:
            extended_until = ""

        if not isinstance(data, list):
            data = [(name, data)]

        # reset pdfdoc timestamp in order to force a fresh one to be used in
        # pdf document metadata.
        pdfdoc._NOWT = None

        elements = []

        doc = SimpleDocTemplate(filename, pagesize=A4)

        styles = getSampleStyleSheet()
        styles.add(ParagraphStyle(name='Zeus',
                                  fontName='LinLibertine',
                                  fontSize=12,
                                  leading=16,
                                  alignment=TA_JUSTIFY))

        styles.add(ParagraphStyle(name='ZeusSubHeading',
                                  fontName='LinLibertineBd',
                                  fontSize=14,
                                  alignment=TA_JUSTIFY,
                                  spaceAfter=16))

        styles.add(ParagraphStyle(name='ZeusHeading',
                                  fontName='LinLibertineBd',
                                  fontSize=16,
                                  alignment=TA_CENTER,
                                  spaceAfter=16))
        intro_contents = [
            voting_start,
            voting_end,
            extended_until
        ]

        make_heading(elements, styles, [title, name, institution_name])
        make_intro(elements, styles, intro_contents)
        make_election_voters(elements, styles, data, stv=True)

        for poll_name, poll_results, questions, poll_voters in data:
            poll_intro_contents = [
                poll_name
            ]
            parties_results = []
            candidates_results = {}

            #total_votes, blank_votes, parties_results, candidates_results = \
            #    load_results(poll_results)
            if new_page:
                elements.append(PageBreak())
            elements.append(Spacer(1, 12))
            elements.append(Spacer(1, 12))
            elements.append(Spacer(1, 12))
            make_subheading(elements, styles, poll_intro_contents)
            elements.append(Spacer(1, 12))
            make_intro(elements, styles, intro_contents)
            make_poll_voters(elements, styles, poll_voters)
            elements.append(Spacer(1, 12))
            #make dict with indexing as key and name as value
            counter = 0
            indexed_cands = {}
            for item in questions[0]['answers']:
                indexed_cands[str(counter)] = item
                counter += 1
            elected = [[_('Elected')]]
            json_data = poll_results[0]
            for item in json_data:
                elected.append([indexed_cands[item[0]]])
            t = Table(elected)
            my_table_style = TableStyle([('FONT', (0, 0), (-1, -1),'LinLibertine'),
                                         ('ALIGN',(1,1),(-2,-2),'LEFT'),
                                         ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
                                         ('BOX', (0,0), (-1,-1), 0.25, colors.black),
                                         ])
            t.setStyle(my_table_style)
            elements.append(t)

            actions_desc = {
                'elect': _('Elect'),
                'eliminate': _('Eliminated'),
                'quota': _('Eliminated due to quota restriction')}

            table_header = [_('Candidate'), _('Votes'), _('Draw'), _('Action')]

            stv = STVParser(poll_results[2])
            rounds = list(stv.rounds())

            for num, round in rounds:
                round_name = _('Round ')
                round_name += str(num)
                elements.append(Paragraph(round_name,styles['Zeus']))
                round_table = []
                temp_table = []
                temp_table.append(table_header)
                for name, cand in round['candidates'].iteritems():
                    actions = map(lambda x: x[0], cand['actions'])
                    draw = _("NO")
                    if 'random' in actions:
                        draw = _("YES")
                    action = None
                    if len(actions):
                        action = actions_desc.get(actions[-1])
                    votes = cand['votes']
                    cand_name = indexed_cands[str(name)]
                    cand_name = cand_name.split(':')[0]
                    row = [cand_name, votes, draw, action]
                    temp_table.append(row)
                round_table = Table(temp_table)
                round_table.setStyle(my_table_style)
                elements.append(round_table)
                elements.append(Spacer(1, 12))

        doc.build(elements, onFirstPage = make_first_page_hf,
                  onLaterPages = make_later_pages_hf(pageinfo))
Пример #6
0
def csv_from_stv_polls(election, polls, lang, outfile=None):
    with translation.override(lang):
        if outfile is None:
            outfile = StringIO()
        csvout = csv.writer(outfile, dialect='excel', delimiter=',')
        writerow = csvout.writerow
        
        # election details
        DATE_FMT = "%d/%m/%Y %H:%S"
        voting_start = _('Start: %s') % (election.voting_starts_at.strftime(DATE_FMT))
        voting_end = _('End: %s') % (election.voting_ends_at.strftime(DATE_FMT))
        extended_until = ""
        if election.voting_extended_until:
            extended_until = _('Extension: %s') % \
                (election.voting_extended_until.strftime(DATE_FMT))

        writerow([strforce(election.name)])
        writerow([strforce(election.institution.name)])
        writerow([strforce(voting_start)])
        writerow([strforce(voting_end)])

        if extended_until:
            writerow([strforce(extended_until)])
        writerow([])
        # until here write election name, date etc...
        actions_desc = {
            'elect': _('Elect'),
            'eliminate': _('Eliminated'),
            'quota': _('Eliminated due to quota restriction')}
        from stv.parser import STVParser
        for poll in polls:
            writerow([])
            writerow([strforce(poll.name)])
            writerow([])
            questions = poll.questions
            indexed_cands = {}
            counter = 0
            for item in questions[0]['answers']:
                indexed_cands[str(counter)] = item
                counter += 1

            results_winners = poll.stv_results[0]
            results_all = poll.stv_results[1]
            result_steps = poll.stv_results[2] 
            stv = STVParser(result_steps)
            rounds = list(stv.rounds())
            writerow([])
            writerow([strforce(_("Elected")), strforce(_("Departments"))])
            for winner_data in results_winners:
                 winner_id = winner_data[0]
                 winner = indexed_cands[str(winner_id)]
                 winner = winner.split(':')
                 winner_name = winner[0]
                 winner_department = winner[1]
                 writerow([strforce(winner_name), strforce(winner_department)])
            for num, round in rounds:
                round_name = _('Round ')
                round_name +=str(num)
                writerow([])
                writerow([strforce(round_name)])
                writerow([strforce(_('Candidate')), strforce(_('Votes')),\
                    strforce(_('Draw')), strforce(_('Action'))])
                for name, cand in round['candidates'].iteritems():
                    actions = map(lambda x: x[0], cand['actions'])
                    actions = map(lambda x: x[0], cand['actions'])
                    draw = _("NO")
                    if 'random' in actions:
                        draw = _("YES")
                    action = None
                    if len(actions):
                        action = actions_desc.get(actions[-1])
                    votes = cand['votes']  
                    cand_name = indexed_cands[str(name)]
                    cand_name = cand_name.split(':')[0]
                    writerow([strforce(cand_name),strforce(votes),\
                    strforce(draw), strforce(action)])