Beispiel #1
0
def get_incomes_sold(playerID, day):
    '''
	Obtention de la totalité des ventes en euros
	'''
    db = Db()
    recipe_prod = db.select(
        "SELECT price_sale_production, id_recipe FROM Production WHERE \
		(id_player = %d AND day_production = %d)" % (playerID, day))

    if (len(recipe_prod) == 0):
        return internal_server_error()

    incomes = 0.0
    for arecipe in recipe_prod:
        theId = arecipe['id_recipe']
        thecost = arecipe['price_sale_production']

        solds = db.select(
            "SELECT quantity_sales FROM Sales WHERE (id_player = %d AND day_sales = %d  AND \
			id_recipe = %d)" % (playerID, day, theId))

        incomes = incomes + (float(solds[0]['quantity_sales']) *
                             float(thecost))

    db.close()
    return incomes
Beispiel #2
0
def get_mapitems(playerID):
    '''
	Obtention des items d'un joueur présent dans une partie
	'''
    db = Db()
    itemsPlayer = []

    #Récupération du jour courant
    day = get_current_day()

    if day == -1:
        return []  #Erreur. Pas de jour alors pas de mapsItemps possible

    #Récupération du joueur à partir de son id
    player = db.select("SELECT * FROM Player WHERE id_player = %d" %
                       (playerID))

    if (len(player) != 1):
        return []

    #Récupération ads items
    items_ads = db.select("SELECT * FROM Adspace WHERE (id_player = %d AND day_adspace = %d)"\
     %(playerID, day))

    #Le joueur a choisi de ne pas prendre de support pub
    if (len(items_ads) == 0):
        itemsPlayer.append({
            "kind": "stand",
            "owner": player[0]['name_player'],
            "location": {
                "latitude": player[0]['lat_player'],
                "longitude": player[0]['lon_player']
            },
            "influence": player[0]['rayon_player']
        })

    if (len(items_ads) > 0):
        for anAdd in items_ads:
            itemsPlayer.append({
                "kind": "ad",
                "owner": player[0]['name_player'],
                "location": {
                    "latitude": anAdd['lat_adspace'],
                    "longitude": anAdd['lon_adspace']
                },
                "influence": anAdd['influence_adspace']
            })

        itemsPlayer.append({
            "kind": "stand",
            "owner": player[0]['name_player'],
            "location": {
                "latitude": player[0]['lat_player'],
                "longitude": player[0]['lon_player']
            },
            "influence": player[0]['rayon_player']
        })

    db.close()
    return itemsPlayer
Beispiel #3
0
def connexionpost(idmonde):

    db = Db()
    get_json = request.get_json()
    table = {}
    tablemtp = {}
    Temps = {}
    if 'mail' in get_json:
        if 'password' in get_json:
            table['mail'] = get_json['mail']
            tablemtp['mtp'] = get_json['password']
            bonmtp = db.select(
                "SELECT id_joueur FROM Joueur WHERE joueur_mail = %(mail)s AND joueur_mtp = %(mtp)s",
                {
                    "mail": table["mail"],
                    "mtp": tablemtp['mtp']
                })

            if len(bonmtp) != 0:
                db.close()
                return jsonResponse({'idjoueur': bonmtp[0]['id_joueur']})
            else:
                db.close()
                abort(404)
        else:
            db.close()
            abort(404)
    db.close()
    abort(404)
 def __init__(self):
     self.db = Db('animals.db')
     self.animal_data = None
     self.viable_questions = None
     self.query = 'select * from animals'
     self.rounds = 0
     self.question = None
Beispiel #5
0
def get_player_infos(playerID, gameid, stringProdOrSellingPrice):
    '''
	Obtention des informations concernant un joueur
	qui se trouve dans la partie
	'''
    #Récupération de l'id du joueur
    db = Db()
    player = db.select("SELECT * FROM Player WHERE (id_player = %d AND ingame_player = %d)"\
     %(playerID, gameid))

    print(playerID)
    print(player)
    print(len(player))

    if (len(player) == 0):
        return {}

    playerInfos = {
        "cash": player[0]['cash_player'],
        "sales": get_numberTot_sold(playerID),
        "profit": get_profits(playerID),
        "drinksOffered": get_drinksOffered(playerID, stringProdOrSellingPrice)
    }
    db.close()
    return playerInfos
Beispiel #6
0
 def has_user(self, username):
     db = Db()
     db.execute('select count(1) from user where username = ?',
                (username, ))
     row = db.fetchone()
     count = row[0]
     return count > 0
    def _fetch_counts(whorls, whorl_names):
        db = Db()
        db.connect()

        # result dict. 'total' is the total number of entries, 'sig_matches' is
        # the number matching signature in whorls, other keys are variables in
        # signature.
        counts = {}

        # query an incrementally updated totals table which has an index on
        # unique (variable, value)
        md5_whorls = FingerprintHelper.value_or_md5(whorls)
        try:
            for i in whorl_names:
                counts[i] = db.get_whorl_value_count(i, md5_whorls[i],
                                                     config.epoched)

            total = db.get_total_count(config.epoched)

            matching = db.get_signature_matches_count(whorls['signature'],
                                                      config.epoched)
        finally:
            db.close()

        return counts, total, matching
Beispiel #8
0
 def execute(self):
     db = Db()
     l = text_to_list(self.file_contents)
     d = list_to_dict(l)
     db.update_word_counts(d, self.doc_type)
     db.update_doctype_count(self.count, self.doc_type)
     return self.count
Beispiel #9
0
    def __init__(self):
        self._db = Db(False)
        self._db.connect('uq_catalogue', 'tomquirk', '', 'localhost')

        # development use only
        self._dev_course_count = 0
        self._dev_plan_count = 0
Beispiel #10
0
def novel():
    db = Db()
    classifies = db.selectAll('select * from gysw_classify')

    for classify in classifies:
        target_url = 'https://www.biquge5200.cc/' + classify['path']
        try:
            r = requests.get(target_url)
            root = etree.HTML(r.text)

            novel_list = root.xpath('//div[@class="r"]//li')

            arr = []
            for novel in novel_list:
                url = novel.xpath('span[@class="s2"]/a/@href')[0]
                book_name = novel.xpath('span[@class="s2"]/a/text()')[0]
                author_name = novel.xpath('span[@class="s5"]/text()')[0]
                classify_id = classify['id']
                arr.append((url, book_name, author_name, classify_id))

            print('开始保存数据....')
            db.insertMany('insert into gysw_novel (`url`, `book_name`, `author_name`, `classify_id`) values (%s, %s, %s, %s)', tuple(arr))
            db.close()
        except Exception as e:
            print(e)

    print('操作结束')
    db.close()
Beispiel #11
0
 def delete_filter(self, filter_id, wait_time=1):
     google = OAuth2Session(client_id, token=self.token())
     if self.token()['expires_at'] < time()+10:
         google = self.refresh_token()
         if google == 'refresh_error':
             return 'refresh_error'
     url = "https://www.googleapis.com/gmail/v1/users/me/settings/filters/{}".format(filter_id)
     r = google.delete(url)
     if str(r.status_code)[0] == '2':
         db = Db()
         sql = 'DELETE FROM filter WHERE filter_id = %s;'
         data = [filter_id]
         db.query(sql, data, True)
         return True
     elif r.status_code == 429:
         if wait_time <= 8:
             sleep(wait_time)
             return self.delete_filter(filter_id, wait_time*2)
         else:
             print(r.status_code, r.text)
             return False
     else:
         if wait_time <= 1:
             sleep(1)
             wait_time = 2
             return self.delete_filter(filter_id, wait_time)
         else:
             print(r.status_code, r.text)
             return False
Beispiel #12
0
 def test_delete(self):
     db = Db()
     key = str(uuid.uuid4())
     value = "test1"
     db.set(key, value)
     db.delete(key)
     assert db.get(key) is None
Beispiel #13
0
 def test_get(self):
     db = Db()
     key = str(uuid.uuid4())
     value = "test1"
     db.set(key, value)
     assert db.get(key) == value
     db.delete(key)
Beispiel #14
0
def main(args):
    parser = argparse.ArgumentParser()
    parser.add_argument("--input", help="directory of input files")
    parser.add_argument("--project", help="use this project corpus")
    parser.add_argument("--depth", help="depth of markov chain to use")
    args = parser.parse_args()

    if args.depth == None:
        depth = 2
    else:
        depth = int(args.depth)

    directory_name = args.input
    db = Db()
    db.init_project(args.project, depth)
    files = list_files(directory_name)
    for file in files:
        post_list = read_json(directory_name, file)
        post_count = len(post_list)
        i = 0
        for post in post_list:
            i = i + 1
            author = post.get("author")
            # thread = post.get("thread")
            post_text = html_to_text(post.get("post"))
            print file + ": " + str(i) + " out of " + str(post_count)
            if post_text is not None:
                MarkovParser("700Level", db).parse(post_text, author, depth)
Beispiel #15
0
def affichejoueur():
    db = Db()
    joueur = db.select("SELECT * FROM Joueur")
    db.close()
    resp = make_response(json.dumps(joueur))
    resp.mimetype = 'application/json'
    return resp
    def single_whorl_uniqueness(whorl_name, whorl_value):
        db = Db()
        db.connect()

        md5_whorl_value = FingerprintHelper.value_or_md5(
            {whorl_name: whorl_value})[whorl_name]

        try:
            try:
                count = db.get_whorl_value_count(whorl_name, md5_whorl_value,
                                                 config.epoched)
            except TypeError:
                return {
                    'status':
                    "Error: that value has not yet been recorded for '" +
                    whorl_name + "'"
                }

            total = db.get_total_count(config.epoched)
        finally:
            db.close()

        uniqueness = {
            'bits': round(-log(count / float(total), 2), 2),
            'one_in_x': round(float(total) / count, 2)
        }

        return uniqueness
    def updateDatabase(currencies):
        db = Db()
        with urllib.request.urlopen(CoinmarketApi.coinApiUrl) as url:
            data = json.loads(url.read().decode())

            for currencySymbol in currencies:
                for currencyData in data:
                    if currencySymbol == currencyData["symbol"]:
                        name = currencyData["name"]
                        rank = currencyData["rank"]
                        priceUsd = currencyData["price_usd"]
                        priceBtc = currencyData["price_btc"]
                        marketCap = currencyData["market_cap_usd"]
                        availableSupply = currencyData["available_supply"]
                        totalSupply = currencyData["total_supply"]
                        maxSupply = currencyData["max_supply"]
                        change1h = currencyData["percent_change_1h"]
                        change24h = currencyData["percent_change_24h"]
                        change7d = currencyData["percent_change_7d"]
                        db.queryInsert("INSERT INTO \
                        coinmarket_data(symbol, name, rank, priceUsd, priceBtc, marketCap, availableSupply, totalSupply, maxSupply, change1h, change24h, change7d) \
                        VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"                                                                               , \
                        (currencySymbol, name, rank, priceUsd, priceBtc, marketCap, availableSupply, totalSupply, maxSupply, change1h, change24h, change7d))
                        break
                    else:
                        continue
Beispiel #18
0
def route_dbinit():
    """Cette route sert à initialiser (ou nettoyer) la base de données."""
    db = Db()
    dbbackconnection.executeFile("database_reset.sql")

    db.close()
    return "Done."
Beispiel #19
0
def dropAction(playerName):
    value_map = 0
    value_drinks = 0
    tomorrow = int(getToDay()) + 1
    querry_select_map = "SELECT MapItem_id, MapItem_rayon FROM MapItem WHERE MapItem_date = " + str(
        tomorrow)
    querry_select_drinks = "SELECT  v.Player_id, v.Recipe_id, v.Vendre_qte, r.Recipe_name FROM Vendre v, Recipe r WHERE v.Recipe_id = r.Recipe_id   AND v.Vendre_date = " + str(
        tomorrow)

    db = Db()
    result_map = db.select(querry_select_map)

    if len(result_map) != 0:
        for res_map in result_map:
            value_map = int(res_map['mapitem_rayon']) * int(
                res_map['mapitem_rayon']) * RANGE_PRIX
            actionCash(playerName, value_map, db)
            querry_delete_map = "DELETE FROM MapItem WHERE MapItem_id =" + str(
                res_map['mapitem_id'])
            db.execute(querry_delete_map)

    result_drinks = db.select(querry_select_drinks)
    if len(result_drinks) != 0:
        for res_drinks in result_drinks:
            value_drinks = prixProduction(
                res_drinks["recipe_name"]) * res_drinks["vendre_qte"]
            actionCash(playerName, value_drinks, db)
            querry_delete_vendre = "DELETE FROM Vendre WHERE Recipe_id = " + str(
                res_drinks["recipe_id"]) + "AND Player_ID =" + str(
                    res_drinks["player_id"]) + "AND Vendre_date = " + str(
                        tomorrow)
            db.execute(querry_delete_vendre)

    db.close()
Beispiel #20
0
 def get_current_user(self):
     if self.is_logged_in():
         db = Db()
         data = (session['username'], )
         db.execute('select * from user where username = ?', data)
         row = db.fetchone()
         return row
     return None
Beispiel #21
0
 def __init__(self):
     self.__db = Db()
     self.hosts = HostManager(self.__db)
     self.interfaces = InterfaceManager(self.__db)
     self.mac_vendors = MacVendorManager(self.__db)
     self.host_services = HostServiceManager(self.__db)
     self.host_properties = HostPropertyManager(self.__db)
     self.networks = NetworkManager(self.__db)
Beispiel #22
0
 def setUp(self):
     self.db = Db(db_name='testdb')
     self.db.reset()
     self.db.insert_note({'note': 'bar', 'word': 'bar'})
     self.db.insert_note({'note': 'fred', 'word': 'fred'})
     self.db.insert_note({'note': 'foo', 'word': 'foo'})
     self.db.insert_note({'note': 'poo', 'word': 'poo'})
     self.db.insert_note({'note': 'goo', 'word': 'goo'})
 def epoch_update_totals(epoch_beginning):
     db = Db()
     db.connect()
     old_epoch_beginning = db.get_epoch_beginning()
     columns_to_update = FingerprintHelper.whorl_names.keys()
     columns_to_update.append('signature')
     db.epoch_update_totals(old_epoch_beginning, epoch_beginning,
                            columns_to_update, FingerprintHelper.md5_keys)
Beispiel #24
0
def test_get_reseller_stats(test_db_path):
    db = Db(test_db_path)
    ads = db.get_reseller_stats(1)
    ads_expected = [
        viewmodels.ResellerInfo("ad1.png", "http://www.ad1company.com", 0, 0, None),
        viewmodels.ResellerInfo("ad2.png", "http://www.ad2company.com", 0, 0, None)
    ]
    assert ads == ads_expected
Beispiel #25
0
def init_db():
    '''
	Initialisation de la base de données
	'''
    db = Db()
    db.executeFile('database.sql')
    db.close()
    return 'Database OK'
Beispiel #26
0
 def get(call_id):
     query = ("SELECT customer_id, user_id, call_time, notes, call_id "
              "FROM phone_call WHERE call_id = ?")
     data = (call_id, )
     db = Db()
     db.execute(query, data)
     row = db.fetchone()
     return Call.build_from_row(row)
Beispiel #27
0
 def __init__(self, arguments):
     self.reqparse = reqparse.RequestParser()
     for argument in arguments:
         argument_name = argument['name']
         argument_params = argument['params']
         self.reqparse.add_argument(argument_name, **argument_params)
     self.boxdb_database = Db()
     super().__init__()
Beispiel #28
0
 def insertData(self, temp):
     sqls = "insert into main ('code','en_name','name','en_code','logo','urls','price','gain','rate','high','low','upTime','upDate') values ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" % (
         temp['code'], temp['en_name'], temp['name'], temp['en_code'], temp['logo'], temp['urls'], temp['price'], temp['gain'], temp['rate'], temp['high'], temp['low'], temp['upTime'],
         temp['upDate'])
     db = Db()
     if db.ddl(sqls) > 0:
         print(temp['name'] + '----->采集成功')
     pass
Beispiel #29
0
 def test_correct_sql_run_when_setup_called(self):
     Db(self.conn, self.sql).setup(3)
     execute_args = self.conn.stub_cursor.execute_args
     self.assertEqual(len(execute_args), 4)
     self.assertEqual(execute_args[0], ('create_word_table_sql 3', ))
     self.assertEqual(execute_args[1], ('create_index_sql 3', ))
     self.assertEqual(execute_args[2], ('create_param_table_sql', ))
     self.assertEqual(execute_args[3], ('set_param_sql', ('depth', 3)))
Beispiel #30
0
 def search_value_page(self, value):
     all_categories, categories_text = self._get_categories()
     db = Db()
     for i in range(27, len(all_categories)):  # After failed case
         print(all_categories[i])
         self._searching_by_category(all_categories[i], db,
                                     categories_text[i])
         time.sleep(8)