示例#1
0
    def test_get_results(self):
        poll = Poll("test", "fake id")
        poll.add_option(None, ["option #1", "This is the first option"])
        poll.add_option(None, ["option #2", "This is the second option"])
        poll.start_poll()
        for i in range(1333):
            choice = i % 3 != 0
            option = "1" if choice else "2"
            poll.submit_vote(str(i), str(i) + " name", [option])
        self.assertEqual(
            poll.get_results(), """The winner is: option #1

option #1: 67%   888 votes
option #2: 33%   445 votes

Total votes: 1333""")

        poll2 = Poll("test", "fake id")
        poll2.add_option(None, ["option #1", "This is the first option"])
        poll2.add_option(None, ["option #2", "This is the second option"])
        poll2.start_poll()
        for i in range(100):
            choice = i % 2 != 0
            option = "1" if choice else "2"
            poll2.submit_vote(str(i), str(i) + " name", [option])
        self.assertEqual(
            poll2.get_results(), """Its a Tie!

option #1: 50%   50 votes
option #2: 50%   50 votes

Total votes: 100""")
示例#2
0
    def test_get_polls_with_options_returns_poll_with_correct_options(self):

        test_poll = Poll("options_test")
        test_poll.add_options_from_list(
            [PollOption("first"),
             PollOption("second"),
             PollOption("third")])

        test_poll2 = Poll("second_test")
        test_poll2.add_options_from_list(
            [PollOption("fourth"),
             PollOption("fifth"),
             PollOption("sixth")])

        self.db.add_poll(test_poll)
        self.db.add_poll(test_poll2)

        output = self.db.get_polls_with_name("options_test")
        self.assertEqual(len(output), 1)
        self.assertEqual(len(output[0].poll_options),
                         len(test_poll.poll_options))
        for actual, expected in zip(output[0].poll_options,
                                    test_poll.poll_options):
            self.assertEqual(actual.name, expected.name)

        output = self.db.get_polls_with_name("second_test")
        self.assertEqual(len(output), 1)
        self.assertEqual(len(output[0].poll_options),
                         len(test_poll2.poll_options))
        for actual, expected in zip(output[0].poll_options,
                                    test_poll2.poll_options):
            self.assertEqual(actual.name, expected.name)
示例#3
0
 def __init__(self):
     self.client = zulip.Client(site="https://chunkzz.zulipchat.com/api/")
     self.subscribe_all()
     self.chatbot = ChatBot(
         "Omega", trainer='chatterbot.trainers.ChatterBotCorpusTrainer')
     self.chatbot.train("chatterbot.corpus.english")
     self.crypto = Crypto()
     self.trans = Translate()
     self.g = Giphy()
     self.w = WikiPedia()
     self.tw = Twimega()
     self.motivate = Motivate()
     self.shortenedurl = Urlshortener()
     self.hacknews = Hackernews()
     self.geo = Geocode()
     self.weather = Weather()
     self.dict_ = Dictionary()
     self.joke = Joke()
     self.pnr = Pnr()
     self.mustread = Mustread()
     self.ss = Ss()
     self.cricket = Cricket()
     self.poll = Poll()
     self.subkeys = [
         "crypto", "translate", "define", "joke", "weather", "giphy", "pnr",
         "mustread", "poll", "hackernews", "hn", "HN", "motivate",
         "twitter", "screenshot", "memo", "cricnews", "help", "shorturl"
     ]
def ExtractPollsFromTable(table, riding_number, riding_name):
    polls = []
    rows = table.find_all('tr')
    date_column, sample_size_column, party_columns = FindColumnHeaders(rows[0])
    for row in rows[1:]:
        columns = row.find_all('td')
        date_string = columns[date_column].find('span', '').get_text()
        parsed_date = datetime.datetime.strptime(date_string, '%B %d, %Y')
        sample_size_string = columns[sample_size_column].get_text().strip()
        if sample_size_string:
            sample_size = float(sample_size_string.replace(',', ''))
        else:
            sample_size = 0
        poll = Poll(parsed_date, sample_size, riding_number, riding_name)
        for party_name, party_index in party_columns.items():
            if party_index >= 0:
                number_string = columns[party_index].get_text()
                try:
                    support = float(number_string) / 100
                except:
                    support = 0
                party_code = party_names[party_name]
                poll.party_support[party_code] = support
        polls.append(poll)
    return polls
示例#5
0
 def test_add_option(self):
     poll = Poll("test", "fake id")
     poll.add_option(None, ["option #1", "This is the first option"])
     self.assertEqual(
         str(poll), r"test{'option #1': {'id': 'option #1', 'description'"
         r": 'This is the first option', 'voters': [], 'index'"
         r": 0}}{}fake id")
示例#6
0
    def __init__(self, curr_directory, output_directory, max_file_size,
                 plugins_file, es_url):
        """Initializes the Efetch Helper"""
        # Setup directory references
        self.curr_dir = curr_directory
        self.resource_dir = self.curr_dir + os.path.sep + u'resources' + os.path.sep
        self.icon_dir = self.resource_dir + u'icons' + os.path.sep
        self.output_dir = output_directory
        self.max_file_size = max_file_size
        if not os.path.isdir(self.icon_dir):
            logging.error(u'Could not find icon directory ' + self.icon_dir)

        self.pathspec_helper = PathspecHelper(output_directory, max_file_size)

        # Create plugin manager and begin polling for changes to plugins
        self.plugin_manager = EfetchPluginManager(plugins_file, self.curr_dir)
        self.poll = Poll(self.plugin_manager)
        self.poll.start()

        self.standard_office_2007_extensions = [
            'xlsx', 'docx', 'pptx', 'dotx', 'docm', 'doct', 'xlsm', 'xltx',
            'xltm', 'pptx', 'pptm', 'potx', 'ppam', 'ppsx', 'ppsm', 'sldx',
            'sldm'
        ]

        # Elastic Search DB setup
        if es_url:
            self.db_util = DBUtil()
        else:
            self.db_util = DBUtil(es_url)
示例#7
0
def handler(event, contest):
    logger.info("Start!")

    main_loop = IOLoop.instance()

    poll = Poll(main_loop)
    cal = poll.cal
    delete = Delete()
    update_and_delete = UpdateAndDelete(main_loop, delete)

    table = event['table']
    queue_url = event['queueUrl']
    message_count = event['messageCount']

    poll.messages(sqs_receive_message, queue_url, message_count)

    logger.info("Receive API count: {}".format(poll.fetch_count))
    logger.info("Fetched messages: {}".format(poll.message_count))

    update_and_delete.execute(sqs_delete_message_batch, db_update_item,
                              queue_url, table, cal.stats)

    logger.info("Update API count: {}".format(update_and_delete.update_count))
    logger.info("Delete API count: {}".format(delete.delete_count))
    logger.info("Delete Message count: {}".format(delete.message_count))

    return "Lambda job finished successfully."
示例#8
0
 def __init__(self):
     self.client = zulip.Client(site="https://fazeup.zulipchat.com/api/")
     self.subscribe_all()
     self.hacknews = Hackernews()
     self.trans = Translate()
     self.movie = Movie()
     self.lyrics = Lyrics()
     self.holiday = Holiday()
     self.currency = Currency()
     self.cricket = Cricket()
     # self.chatbot.train("chatterbot.corpus.english")
     self.crypto = Crypto()
     self.trans = Translate()
     self.g = Giphy()
     self.w = WikiPedia()
     # self.tw = Twimega()
     # self.motivate = Motivate()
     self.shortenedurl = Urlshortener()
     self.geo = Geocode()
     self.weather = Weather()
     self.dict_ = Dictionary()
     self.joke = Joke()
     self.pnr = Pnr()
     self.mustread = Mustread()
     self.ss = Ss()
     self.cricket = Cricket()
     self.poll = Poll()
     print("done init")
     self.subkeys = [
         "crypto", "translate", "define", "joke", "weather", "giphy", "pnr",
         "mustread", "poll", "hackernews", "hn", "HN", "motivate",
         "twitter", "screenshot", "memo", "cricnews", "help", "shorturl",
         "movie", "currency", "holiday", "lyrics"
     ]
示例#9
0
    def test_get_polls_ID_values_match_as_expected(self):
        test_poll = Poll("poll")
        self.db.add_poll(test_poll)
        output = self.db.get_polls_with_name("poll")

        self.assertEqual(len(output), 1)
        self.assertEqual(output[0].id, test_poll.id)
示例#10
0
    def test_get_polls_name_exists_returns_poll(self):

        self.db.add_poll(Poll("poll"))
        output = self.db.get_polls_with_name("poll")

        self.assertEqual(len(output), 1)
        self.assertTrue(output[0].name == "poll")
示例#11
0
def handler(event, contest):
    logger.info("Start!")

    executor = ThreadPoolExecutor(max_workers=1000)
    main_loop = asyncio.new_event_loop()
    main_loop.set_default_executor(executor)
    asyncio.set_event_loop(main_loop)

    poll = Poll(main_loop)
    cal = poll.cal
    update_and_delete = UpdateAndDelete(main_loop, executor)

    table = event['table']
    queue_url = event['queueUrl']
    message_count = event['messageCount']

    poll.messages(sqs, queue_url, message_count)

    logger.info("Receive API count: {}".format(poll.fetch_count))
    logger.info("Fetched messages: {}".format(poll.message_count))

    update_and_delete.execute(sqs_client, db, queue_url, table, cal.stats)

    logger.info("Update API count: {}".format(update_and_delete.update_count))
    logger.info("Delete API count: {}".format(update_and_delete.delete_count))
    logger.info("Delete Message count: {}".format(
        update_and_delete.deleted_message_count))

    main_loop.close()
    executor.shutdown()

    return "Lambda job finished successfully."
示例#12
0
def test_load_invalid():
    with pytest.raises(InvalidPollError):
        Poll.load('bla')

    with pytest.raises(InvalidPollError):
        poll = Poll.create('user0123', 'Spam?', 'en', ['Yes', 'Maybe', 'No'],
                           secret=True, public=True, max_votes=2)
        Poll(poll.connection, 'user3210')
示例#13
0
def prompt_create_poll():
    poll_title = input("Enter poll title: ")
    poll_owner = input("Enter poll owner: ")
    poll = Poll(title=poll_title, owner=poll_owner)
    poll.save()

    while (new_option := input(NEW_OPTION_PROMPT)):
        poll.add_option(new_option)
示例#14
0
def gmail():
    if request.method == "GET":
        return render_template("email.html")
    elif request.method == "POST":
        form = request.form
        something = form["something"]
        p = Poll(something=something)
        p.save()
        return render_template("email.html")
示例#15
0
def return_matches(list_of_token):
    httpretty.enable()
    add_fixtures()

    result = Poll().matches(list_of_token)
    first = result[0]

    assert first['date'] == '2015-04-15'
    teardown()
示例#16
0
def poll_for_tests():
    poll = Poll()
    poll.storage = Mock()
    poll.storage.data = {
        'is_started': False,
        'is_music_upload': False,
        'messages': []
    }
    return poll
示例#17
0
 def test_submit_vote(self):
     poll = Poll("test", "fake id")
     poll.add_option(None, ["option #1", "This is the first option"])
     poll.add_option(None, ["option #2", "This is the second option"])
     poll.start_poll()
     poll.submit_vote("test pollr id", "test name", ["1"])
     self.assertEqual(
         str(poll.voters), r"{'test pollr id': test pollr id "
         r"test name option #1}")
    def aggregate_polls(self, to_date, num_days, logger):
        relevant_polls = []
        from_date = to_date - dt.timedelta(days=num_days)

        for poll in self.polls:
            if to_date >= poll.median_date >= from_date:
                relevant_polls.append(poll)

        results_list = {}

        for poll in relevant_polls:
            for party, vote in poll.results.iteritems():
                results_list[party] = np.round(
                    np.sum(
                        np.trim_zeros(
                            np.array([
                                self.weights[poll.pollster]
                                for poll in relevant_polls
                            ]) * np.array([
                                exp_decay(to_date - poll.median_date, num_days)
                                for poll in relevant_polls
                            ]) * np.array([
                                poll.results[party] for poll in relevant_polls
                            ])) /
                        (np.array([
                            self.weights[poll.pollster]
                            for poll in relevant_polls
                        ]) * np.array([
                            exp_decay(to_date - poll.median_date, num_days)
                            for poll in relevant_polls
                        ]))[np.array([
                            self.weights[poll.pollster]
                            for poll in relevant_polls
                        ]) * np.array([
                            exp_decay(to_date - poll.median_date, num_days)
                            for poll in relevant_polls
                        ]) * np.array(
                            [poll.results[party]
                             for poll in relevant_polls]) > 0].sum()), 2)

        others = [
            party for party in results_list.keys()
            if party not in (Parties.ALP, Parties.LIB)
        ]
        aggregated_poll = Poll('aggregate', 'aggregate',
                               (to_date - from_date) / 2, 0, results_list,
                               None, others)
        change = sum([
            aggregated_poll.results[party] for party in aggregated_poll.results
        ])
        old_others = aggregated_poll.results[Parties.OTH]
        aggregated_poll.results[Parties.OTH] = old_others - change + 100
        logger.info('Aggregated {} polls: {}'.format(len(relevant_polls),
                                                     aggregated_poll.results))
        return aggregated_poll
示例#19
0
 def getAPoll(self,pollquestion):
     connection=dbapi2.connect(current_app.config['dsn'])
     cursor=connection.cursor()
     cursor.execute("""SELECT VOTENUMBER,CHOICENUMBER FROM POLLS WHERE POLLQUESTION=%s""",(pollquestion,))
     temp2=cursor.fetchone()
     votenumber=temp2[0]
     choicenumber=temp2[1]
     poll=Poll(pollquestion,creatorname)
     poll.votenumber=votenumber
     poll.choicenumber=choicenumber
     return poll
示例#20
0
    def test_get_winner(self):
        poll = Poll("test", "fake id")
        poll.add_option(None, ["option #1", "This is the first option"])
        poll.add_option(None, ["option #2", "This is the second option"])
        poll.start_poll()
        for i in range(100):
            choice = i % 3 != 0
            option = "1" if choice else "2"
            poll.submit_vote(str(i), str(i) + " name", [option])
        self.assertEqual(poll.get_winner()["id"], "option #1")

        poll2 = Poll("test", "fake id")
        poll2.add_option(None, ["option #1", "This is the first option"])
        poll2.add_option(None, ["option #2", "This is the second option"])
        poll2.start_poll()
        for i in range(100):
            choice = i % 2 != 0
            option = "1" if choice else "2"
            poll2.submit_vote(str(i), str(i) + " name", [option])
        self.assertFalse(poll2.get_winner())
示例#21
0
def pull_foreach_userid(list_of_userid):
    req_urls = []
    expected_urls = map(helpers.match_history_uri, list_of_userid)

    httpretty.enable()
    add_fixtures(lambda _, uri, __: req_urls.append(uri))

    Poll().match_tokens(list_of_userid)

    assert req_urls == expected_urls
    teardown()
示例#22
0
def poll_player_stats(list_of_userid):
    req_urls = []
    expected_urls = map(helpers.player_stats_uri, list_of_userid)

    httpretty.enable()
    add_fixtures(lambda _, uri, __: req_urls.append(uri))

    Poll().player_stats(list_of_userid)

    assert req_urls == expected_urls
    teardown()
示例#23
0
 async def poll(self, ctx, title: str):
     """Create a poll with a one-word title!"""
     # add check for poll with existing name
     poll = Poll(title, ctx.guild.id, ctx.channel.id, ctx.author.id)
     await self.get_config_from_user(ctx, poll, new_poll=True)
     entries = await self.get_entries_from_user(ctx)
     poll.add_entries(
         entries[:poll.max_entries])  # TODO add feedback for max entries
     if not self.add_poll(poll):
         await ctx.send('Couldn\'t create poll')
         return
     await ctx.send('Poll created!', embed=self.make_poll_embed(poll, ctx))
示例#24
0
def matches():
    log('matches', 'fetching stats for %d users' % len(vars.USERS))

    tokens = Poll().match_tokens(vars.USERS)
    if len(tokens) == 0:
        log('matches', 'no tokens, exiting')
        return

    matches = Poll().matches(tokens)
    if len(matches) == 0:
        log('matches', 'no matches, exiting')
        return

    log('matches', "recieved %d match tokens" % len(matches))

    auth = firebase.FirebaseAuthentication(vars.SECRET, vars.EMAIL)
    endpoint = firebase.FirebaseApplication(vars.FB_URL)
    endpoint.authentication = auth

    Push(endpoint).matches(matches)
    log('matches', "pushed %d matches to firebase" % len(matches))
示例#25
0
def pull_matches(list_of_token):
    match_ids_slug = "136200860+136199918"
    req_urls = []
    expected_url = helpers.multi_match_uri(match_ids_slug)

    httpretty.enable()
    add_fixtures(lambda _, uri, __: req_urls.append(uri))

    Poll().matches(list_of_token)
    matches_url = req_urls[0]

    assert matches_url == expected_url
    teardown()
示例#26
0
def test_load():
    poll = Poll.create('user0123', 'Spam?', 'en', ['Yes', 'Maybe', 'No'],
                       secret=True, public=True, max_votes=2, bars=True)

    # because of :memory: database, load() cannot be used directly
    poll2 = Poll(poll.connection, poll.id)
    assert poll.creator_id == poll2.creator_id
    assert poll.message == poll2.message
    assert poll.secret == poll2.secret
    assert poll.public == poll2.public
    assert poll.max_votes == poll2.max_votes
    assert poll.vote_options == poll2.vote_options
    assert poll.bars == poll2.bars
示例#27
0
def test_poll_save_load(capsys):
    """ Test saving and loading a poll """

    # Test saving a poll
    poll = Poll(time_length=TimeLength("hours", 5),
                votes=[],
                prompt="foo",
                channel_id=1234)

    poll.save()
    assert os.path.isfile(f"{POLL_DIR}/{poll.poll_id}.json")

    # Test Loading a poll
    other_poll = Poll()
    other_poll.load(poll.poll_id)

    assert poll.poll_id == other_poll.poll_id
    assert poll.expiry == other_poll.expiry
    assert poll.prompt == other_poll.prompt
    assert poll.choices == other_poll.choices
    assert poll.votes == other_poll.votes
    assert poll.channel_id == other_poll.channel_id

    # Test error loading poll
    with open(f"{POLL_DIR}/1234.json", "w") as stream:
        stream.write("{}")
    with pytest.raises(ValueError) as error:
        other_poll.load("1234")

    assert "Something went wrong with poll 1234" in str(error)

    # Test delete
    poll.delete()
    other_poll.delete()
    assert not os.path.isfile(poll.poll_id)

    poll.delete()
    assert f"Warning: {poll.poll_id} does not exist" in capsys.readouterr().out
示例#28
0
def handler(event, contest):
    logger.info("Start!")

    main_loop = IOLoop.instance()

    poll = Poll(main_loop)

    queue_url = event['queueUrl']
    message_count = event['messageCount']

    poll.messages(sqs_receive_message, queue_url, message_count)

    logger.info("Receive API count: {}".format(poll.fetch_count))
    logger.info("Fetched messages: {}".format(poll.message_count))
示例#29
0
 def test_update_description(self):
     poll = Poll("test", "fake id")
     poll.add_option(None, ["option #1", "This is the first option"])
     poll.add_option(None, ["option #2", "This is the second option"])
     poll.update_description("option #1",
                             "updated first option description")
     self.assertEqual(
         str(poll.options),
         r"{'option #1': {'id': 'option #1', 'description': "
         r"'updated first option description', 'voters': [], "
         r"'index': 0},"
         r" 'option #2': {'id': 'option #2', 'description': "
         r"'This is the second option', 'voters': [], "
         r"'index': 1}}")
示例#30
0
def autoRun(userName, password):
    miui_url = 'http://www.miui.com/member.php?mod=logging&action=miuilogin'
    geek_url = 'http://geek.miui.com/index.php?m=member&c=index&a=login'

    opener = login(miui_url, userName, password)
    dailySignIn(opener)

    #geek community;1) first take the task; 2)login geek section
    geekSignIn(opener)
    geek_opener = login(geek_url, userName, password)
    geekDraw(opener)

    poller = Poll(opener)
    poller.autoPoll()