Beispiel #1
0
 async def insertOrUpdateAccountInfo(self, discord_user_id: int):
     results = await self.getGw2AccountDataFromUserId(discord_user_id)
     results = {key: Json(value) for (key, value) in results.items()}
     # Insert all JSON data into database
     try:
         with db.create_connection(**config_data) as connection:
             with connection.cursor() as cur:
                 query = """
                     INSERT INTO Gw2AccountInfo VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
                      ON CONFLICT (id) DO UPDATE SET 
                      (account, achievements, skins, titles, minis, outfits, dyes, finishers, wallet, materials, 
                         bank, inventory, pvp, characters)
                      = (EXCLUDED.account, EXCLUDED.achievements, EXCLUDED.skins, EXCLUDED.titles, EXCLUDED.minis, 
                         EXCLUDED.outfits, EXCLUDED.dyes, EXCLUDED.finishers, EXCLUDED.wallet, EXCLUDED.materials, 
                         EXCLUDED.bank, EXCLUDED.inventory, EXCLUDED.pvp, EXCLUDED.characters)
                 """
                 cur.execute(
                     query,
                     (discord_user_id, results['account'], results['achievements'], results['skins'],
                      results['titles'], results['minis'], results['outfits'], results['dyes'], results['finishers'],
                      results['wallet'], results['materials'], results['bank'], results['inventory'], results['pvp'],
                      results['characters'])
                 )
                 connection.commit()
     except Exception as e:
         print(e)
Beispiel #2
0
 async def add(self, ctx, key: str):
     connection = db.create_connection(**config_data)
     discord_user_id = ctx.message.author.id
     if not self.check_key_exists(connection, discord_user_id):
         try:
             cur = connection.cursor()
             cur.execute("INSERT INTO Gw2ApiKeys VALUES (%s, %s)",
                         (discord_user_id, key))
             await ctx.send("Adding new key to be tracked.")
             connection.commit()
         except Exception as e:
             print(e)
     else:
         try:
             cur = connection.cursor()
             cur.execute("UPDATE Gw2ApiKeys SET api_key = %s WHERE id = %s",
                         (key, discord_user_id))
             await ctx.send(
                 "Key already stored. Updating old API key with new key.")
             connection.commit()
         except Exception as e:
             await ctx.send(
                 "There was an error storing your API key. Please try again later."
             )
             print(e)
     connection.close()
Beispiel #3
0
def launch_anova():
    with database.create_connection() as conn:
        cols = []
        for i in ANOVA_COLS:
            if i in request.args:
                cols.append(i)
        cols.append('Income')
        data = database.get(conn, cols)
        anova_result = analyzer.anova_cols(data, cols)
        return render_template("anova_result.html",
                               result=anova_result.split('\n'))
Beispiel #4
0
def analyze():
    field1 = escape(request.args.get('field1'))
    field2 = escape(request.args.get('field2'))
    with database.create_connection() as conn:
        data = database.get(conn, [field1, field2])
        contingency_table = analyzer.get_contingency_table(
            data, field1, field2)
        statistic, expected_table = analyzer.get_statistic_and_expected_table(
            contingency_table)
        return render_template("analysis.html",
                               field1=field1,
                               field2=field2,
                               contingency=contingency_table,
                               statistic=statistic,
                               expected=expected_table)
Beispiel #5
0
async def getUserAPIKey(discord_id: int) -> str:
    """
    Get the Discord User's API key from the database and return it.
    :param discord_id: The Discord User Account ID from message context object.
    :return: str: The Discord User's API Key.
    """
    result = None
    try:
        with db.create_connection(**config_data) as connection:
            with connection.cursor() as cur:
                print("In getUserAPIKey(). DiscordId: ", discord_id)
                cur.execute("SELECT api_key FROM Gw2ApiKeys WHERE id = %s", (discord_id,))
                result = cur.fetchone()['api_key']
                print(result)
    except Exception as e:
        print(e)
    return result
Beispiel #6
0
    async def getCurrentGw2AccountInfo(self, discord_user_id: int):
        results = None
        try:
            with db.create_connection(**config_data) as connection:
                with connection.cursor() as cur:
                    query = """
                        SELECT * FROM Gw2AccountInfo WHERE id = %s
                    """
                    cur.execute(
                        query,
                        (discord_user_id,)
                    )
                    results = cur.fetchone()

        except Exception as e:
            print(e)
        return results
Beispiel #7
0
def main():
    leboncoin = wrapper.Wrapper()
    item_type = "appartement"
    results = leboncoin.get_research("10", item_type)["ads"]
    #print_item(results[0])
    print("gonna create table")
    connection = database.create_connection("./database/leboncoin.db")
    database.creat_table(connection)
    print("creation complete")
    print("gonna add all items")
    for result in results:
        item_to_add = item.Item(result)
        database.insert_if_not_exist(connection, item_to_add, item_type)
    print("insert done !")

    #leboncoin.print_item(results[0])
    #leboncoin.export_to_excel(results,"test_result.csv")
    """for result in results:
Beispiel #8
0
def post_insert_data():
    form_result = {}
    if request.json is None:
        if (request.form.get('EmploymentField')
                not in VALUES['EmploymentField']
                or request.form.get('EmploymentStatus')
                not in VALUES['EmploymentStatus']
                or request.form.get('Gender') not in VALUES['Gender']
                or request.form.get('LanguageAtHome')
                not in VALUES['LanguageAtHome'] or
                request.form.get('JobWherePref') not in VALUES['JobWherePref']
                or request.form.get('SchoolDegree')
                not in VALUES['SchoolDegree']
                or request.form.get('CityPopulation')
                not in VALUES['CityPopulation']
                or request.form.get('MaritalStatus')
                not in VALUES['MaritalStatus']
                or request.form.get('JobPref') not in VALUES['JobPref']
                or request.form.get('HasDebt') not in VALUES['HasDebt']):
            return render_template("insert.html",
                                   selected=VALUES,
                                   message="Value error")
        form_result['EmploymentField'] = request.form.get('EmploymentField')
        form_result['EmploymentStatus'] = request.form.get('EmploymentStatus')
        form_result['Gender'] = request.form.get('Gender')
        form_result['LanguageAtHome'] = request.form.get('LanguageAtHome')
        form_result['JobWherePref'] = request.form.get('JobWherePref')
        form_result['SchoolDegree'] = request.form.get('SchoolDegree')
        form_result['CityPopulation'] = request.form.get('CityPopulation')
        form_result['HasDebt'] = request.form.get('HasDebt')
        form_result['JobPref'] = request.form.get('JobPref')
        form_result['MaritalStatus'] = request.form.get('MaritalStatus')
        try:
            form_result['Income'] = int(request.form.get('Income'))
        except ValueError:
            return render_template("insert.html",
                                   selected=VALUES,
                                   message="Income must be int")
    else:
        form_result = request.json
    with database.create_connection() as conn:
        return render_template("insert.html",
                               selected=VALUES,
                               message=database.insert(conn, form_result))
Beispiel #9
0
 async def startGw2Session(self, discord_user_id: int):
     results = await self.getGw2AccountDataFromUserId(discord_user_id)
     results = Json(results)
     # Insert all JSON data into database
     try:
         with db.create_connection(**config_data) as connection:
             with connection.cursor() as cur:
                 query = """
                     INSERT INTO Gw2SessionInfo (id, StartInfo, StartTime) VALUES (%s, %s, %s)
                     ON CONFLICT (id) DO UPDATE SET
                     (StartInfo, StartTime) = (EXCLUDED.StartInfo, EXCLUDED.StartTime)
                 """
                 cur.execute(
                     query,
                     (discord_user_id, results, dt.utcnow(),)
                 )
                 connection.commit()
     except Exception as e:
         print(e)
Beispiel #10
0
    async def wvw_session(self, ctx):
        discord_user_id = ctx.message.author.id
        result = None
        try:
            with db.create_connection(**config_data) as connection:
                with connection.cursor() as cur:
                    query = """
                        SELECT * FROM Gw2SessionInfo WHERE id = %s
                    """
                    cur.execute(
                        query,
                        (discord_user_id,)
                    )
                    result = cur.fetchone()
        except Exception as e:
            await ctx.send("Error processing !session wvw")
        else:
            #
            startAchievementInfo = {value['id']: value for value in result['startinfo']['achievements']}
            endAchievementInfo = {value['id']: value for value in result['endinfo']['achievements']}

            startDeaths = {'current': sum([character['deaths'] for character in result['startinfo']['characters']])}
            endDeaths = {'current': sum([character['deaths'] for character in result['endinfo']['characters']])}

            startTime = result['starttime']
            endTime = result['endtime']
            startWvWInfo = {
                'WvW Repairs': startAchievementInfo.get(306, {'current': 0}),
                'WvW Kills': startAchievementInfo.get(283, {'current': 0}),
                'Yak Escort': startAchievementInfo.get(285, {'current': 0}),
                'WvW Yak Kills': startAchievementInfo.get(288, {'current': 0}),
                'WvW Camps': startAchievementInfo.get(291, {'current': 0}),
                'WvW Towers': startAchievementInfo.get(297, {'current': 0}),
                'WvW Keeps': startAchievementInfo.get(300, {'current': 0}),
                'WvW Castles': startAchievementInfo.get(294, {'current': 0}),
                'Warclaw Kills': startAchievementInfo.get(4641, {'current': 0, 'repeated':0}),
                'Warclaw Gate Damage': startAchievementInfo.get(4644, {'current': 0, 'repeated':0}),
                'Deaths': startDeaths
            }
            endWvWInfo = {
                'WvW Repairs': endAchievementInfo.get(306, {'current': 0}),
                'WvW Kills': endAchievementInfo.get(283, {'current': 0}),
                'Yak Escort': endAchievementInfo.get(285, {'current': 0}),
                'WvW Yak Kills': endAchievementInfo.get(288, {'current': 0}),
                'WvW Camps': endAchievementInfo.get(291, {'current': 0}),
                'WvW Towers': endAchievementInfo.get(297, {'current': 0}),
                'WvW Keeps': endAchievementInfo.get(300, {'current': 0}),
                'WvW Castles': endAchievementInfo.get(294, {'current': 0}),
                'Warclaw Kills': endAchievementInfo.get(4641, {'current': 0, 'repeated':0}),
                'Warclaw Gate Damage': endAchievementInfo.get(4644, {'current': 0, 'repeated':0}),
                'Deaths': endDeaths
            }
            # print(startWvWInfo)
            # Normalize Warclaw Kills
            if 'repeated' in startWvWInfo['Warclaw Kills']:
                startWvWInfo['Warclaw Kills']['current'] += startWvWInfo['Warclaw Kills']['repeated'] * 5
                endWvWInfo['Warclaw Kills']['current'] += endWvWInfo['Warclaw Kills']['repeated'] * 5

            # Normalize Warclaw Gate Damage
            if 'repeated' in startWvWInfo['Warclaw Gate Damage']:
                startWvWInfo['Warclaw Gate Damage']['current'] += startWvWInfo['Warclaw Gate Damage']['repeated'] * 100000
                endWvWInfo['Warclaw Gate Damage']['current'] += endWvWInfo['Warclaw Gate Damage']['repeated'] * 100000

            # Get the difference between each current value in the WvWInfo Dicts
            wvwDiff = {key: endWvWInfo[key]['current'] - startWvWInfo[key]['current'] for key in startWvWInfo.keys()}
            print(wvwDiff['Deaths'])
            # Calculate time difference
            timeElapsed = endTime - startTime
            hours, remainder = divmod(timeElapsed.seconds, 3600)
            minutes, seconds = divmod(remainder, 60)
            playTimeStr = "{}h {}m {}s".format(hours, minutes, seconds)

            embed_time_format = "%X UTC"

            user = ctx.message.author
            if embed_perms(ctx.message):

                desc = """
                    You started playing at **{}** and stopped at **{}** for a total playtime of **{}**\n
                    \n
                    `Note: Deaths are tracked globally`
                """.format(startTime.strftime(embed_time_format), endTime.strftime(embed_time_format), playTimeStr)
                # Default to the numerator if denominator is 0 for Kill Death Ratio
                wvw_kdr = wvwDiff['WvW Kills'] / wvwDiff['Deaths'] if wvwDiff['Deaths'] else wvwDiff['WvW Kills']
                em = discord.Embed(title="WvW Session Stats", description=desc, timestamp=ctx.message.created_at, color=0xFF0000)
                # Playtime information
                # KDR
                em.add_field(name='WvW Kills :crossed_swords:', value=wvwDiff['WvW Kills'], inline=True)
                em.add_field(name='Deaths :skull:', value=wvwDiff['Deaths'], inline=True)
                em.add_field(name='KDR', value=wvw_kdr, inline=True)
                # Zero Width space unicode character
                # em.add_field(name='\u200b', value='\u200b', inline=False)
                # WvW Information
                em.add_field(name='Camps Flipped :circus_tent:', value=wvwDiff['WvW Camps'], inline=True)
                em.add_field(name='Towers Seized :synagogue:', value=wvwDiff['WvW Towers'], inline=True)
                em.add_field(name='Keeps Captured :european_castle:', value=wvwDiff['WvW Keeps'], inline=True)
                em.add_field(name='Castles Liberated :japanese_castle:', value=wvwDiff['WvW Castles'], inline=True)
                em.add_field(name='Yaks Slapped :meat_on_bone:', value=wvwDiff['WvW Yak Kills'], inline=True)
                em.add_field(name='Yaks Escorted :ram:', value=wvwDiff['Yak Escort'], inline=True)
                em.add_field(name='Supply Spent Repairing :tools:', value=wvwDiff['WvW Repairs'], inline=True)
                em.add_field(name='Warclaw Maul Kills :lion:', value=wvwDiff['Warclaw Kills'], inline=True)
                em.add_field(name='Warclaw Gate Damage :shinto_shrine:', value=wvwDiff['Warclaw Gate Damage'], inline=True)
                em.set_author(name=user.display_name, icon_url=user.avatar_url)
                await ctx.send(embed=em)
Beispiel #11
0
def main():

    db_conn = database.create_connection('coronavirus.db')

    now = datetime.datetime.now()
    processTime = now.strftime("%m-%d-%Y %H:%M:%S")

    URL = 'https://en.wikipedia.org/wiki/2019%E2%80%9320_coronavirus_pandemic#covid19-container'
    page = requests.get(URL)
    soup = BeautifulSoup(page.content, 'html.parser')
    last_modification_string = ''

    # Obtenemos la descripción de la última modificacion
    try:
        last_modification = soup.find('li', id='footer-info-lastmod').getText()
        last_modification_string = last_modification.replace(
            ' This page was last edited on ', '')
        last_modification_string = last_modification_string.replace(
            u'\xa0', u'')
        last_modification_string = last_modification_string.replace('.', '')
    except:
        print('can\'t get last time exception')

    # Obtenemos los datos de los paises
    country_table = soup.find('table',
                              class_=[
                                  'wikitable', 'plainrowheaders', 'sortable',
                                  'jquery-tablesorter'
                              ])
    tbody = country_table.find('tbody')
    trs = tbody.find_all('tr')

    for tr in trs:
        isACountry = False
        countryData = {}

        ths = tr.find_all('th')
        for th in ths:
            country_link = th.find('a')
            if country_link:
                if len(country_link.text) > 3:
                    isACountry = True
                    countryData['get_datetime'] = processTime
                    countryData['country_name'] = country_link.text
            #print(country_link['href'])

        if isACountry == True:
            tds = tr.find_all('td')
            if len(tds) >= 3:
                if tds:
                    countryData['cases'] = textToInt(tds[0].text)
                    countryData['deaths'] = textToInt(tds[1].text)
                    countryData['deaths_rate'] = (countryData['deaths'] *
                                                  100) / countryData['cases']
                    countryData['recovery'] = textToInt(tds[2].text)
                    countryData['recovery_rate'] = (countryData['recovery'] *
                                                    100) / countryData['cases']
                    countryData[
                        'original_last_modification'] = last_modification_string

                    new_country_id = country_numbers.insertOne(
                        db_conn, countryData)

            #print(countryData)

    database.close_connection(db_conn)