def set_impact_analysis(self, mutant, result): if self.disabled: impacted_macros = result.all_macros else: impacted_macros = result.impacted_macros self.db.update( set( 'impact_analysis', { 'impacted_features': impacted_macros, 'not_impacted_features': [ feature for feature in result.all_macros if feature not in impacted_macros ], 'all_features': result.all_macros, 'all_features_len': len(result.all_macros), 'elapsed_time': str(result.elapsed_time) }), Query().name == mutant.get('name')) self.state.db.update(add('products', 2**len(result.all_macros)), Query().type == 'config') self.state.db.update(add('products_impacted', 2**len(impacted_macros)), Query().type == 'config')
def check_stocks(clip): stocks = db.search((where('type') == 'stock') & (where('clip') == clip)) winners = [] for stock in stocks: owner_id = stock['user_id'] pay_out = STOCK_PAYOUT * stock['shares'] db.update(add('bucks', pay_out), (where('type') == 'account') & (where('id') == owner_id)) db.update(add('total_payout', pay_out), (where('type') == 'stock') & (where('user_id') == owner_id) & (where('clip') == clip)) winners.append((stock['disp_name'], pay_out)) return winners
def my_add(self, cmdr, user, amount: int): if not user or not amount: self.errlog_add( "No \"client\" ({}) or \"amount\" ({}) given!".format( user.name, amount)) return try: # handle DB entry self.db_action.insert({ 'issuer': cmdr.id, 'user': user.id, 'action': 'add', 'amount': amount, 'when': datetime.now().timetuple() }) query = Query() if self.db_lending.contains(query.id == user.id): self.db_lending.upsert(add('borrowed', amount), query.id == user.id) else: self.db_lending.insert({ 'id': user.id, 'user': user.name, 'borrowed': amount }) logger.info("{} handed to {} \"{}\" Excavators".format( cmdr, user, amount)) result = self.db_lending.get(query.id == user.id) self.errlog_add( "Given {} **{}** Excavators. He has now **{}** in Total". format(user.name, amount, result['borrowed'])) except Exception as e: logger.error("Error occurred: {}".format(e), exc_info=True)
def add_tacos(self, amount, bonus=False): users_db.update(add('owned_tacos', amount), Query()['user_id'] == self.user_id) if bonus: users_db.update({'daily_bonus': False}, Query()['user_id'] == self.user_id) self.update()
async def give_coin(userid, coin_value=gen_coin_value()): db = TinyDB('db.json') cursor = Query() if user_exists(userid): db.update(add("wallet", coin_value), cursor.userid == userid) else: db.insert({"userid": userid, "wallet": coin_value})
def update_clients_with_rem_date_in_past(file="db.json") -> None: """Increments the 'times contacted' field for all clients with reminder dates in the past.""" with TinyDB(file) as db: query = Query() db.update(add("times contacted", 1), query["rem date"].test(is_rem_date_in_past))
def draw_match(self, pair): """ Add 0.5 point for each player in the pair """ player_one_doc = db.table('players').get(doc_id=pair[0]) player_two_doc = db.table('players').get(doc_id=pair[1]) pair_ids = [player_one_doc.doc_id, player_two_doc.doc_id] db.table('players').update(add('point', 0.5), doc_ids=pair_ids)
def create_match(self, pair, winner): self.history.append( Match(pair=self.get_name_from_ids([pair]), winner=winner).serialize()) db.table('tournaments').update(add('history', [self.history[-1]]), where('name') == self.name) self.matches.append(Match().serialize())
def start_game(update, context): if dont_spam(): return group_id = update.effective_chat.id if group_id in games: context.bot.send_message(chat_id=group_id, text='Игра уже идет в этом чате!') else: db.update(add('games', 1), Query().games.exists()) send_start_game_message(update, context)
def User_operator(uname): Querydata = Users.get(Query().name == uname) if Querydata == None: Users.insert({ 'name': uname, 'Coins': config['Options'].get('Coins_on_follow') }) else: Users.update(add('Coins', config['Options'].get('Coins_per_mes')), Query().name == uname)
def freq(groupid, num, refreshTime, freqCount): if data_tmp := tmpDB.table('freq').get(Q['group'] == groupid): # 如果有数据 if refreshTime != 0 and (time.time() - data_tmp['time'] >= refreshTime): # 刷新 tmpDB.table('freq').update({'time': time.time(), 'freq': 0}, Q['group'] == groupid) return False elif freqCount != 0 and num + data_tmp['freq'] > freqCount: # 大于限制且不为0 logger.info('群:{}大于频率限制:{}次/{}s'.format(groupid, freqCount, refreshTime)) return freqCount, refreshTime # 记录 tmpDB.table('freq').update(add('freq', num), Q['group'] == groupid)
def json_score_opponent_player(self, players_and_score, matchs_round, tournament_number, round_nb, start, end): """ Save last round informations in the jason database: save opponents, score, round number, rounds """ jtournament = TinyDB("jtournament.json", ensure_ascii=False, encoding="utf8", indent=4) tournament_table = jtournament.table("tournaments") tournament_id = None if tournament_number == 0: tournament_id = len(tournament_table) else: tournament_id = tournament_number round_number = tournament_table.get( doc_id=tournament_id)["Round number"] round_number = 1 tournament_table.update(add("Round number", round_number), doc_ids=[tournament_id]) sorted_players = sorted(players_and_score, key=lambda x: x[2], reverse=False) self.players = tournament_table.get(doc_id=tournament_id)["players"] saved_rounds = tournament_table.get(doc_id=tournament_id)["Rounds"] round_id = "Round number " + str(round_nb) round_infos = [start, end, matchs_round] saved_rounds[round_id] = round_infos tournament_table.update(set("Rounds", saved_rounds), doc_ids=[tournament_id]) opponents_ids = {} for i in range(4): opponents_ids[matchs_round[i][0][2]] = matchs_round[i][1][2] opponents_ids[matchs_round[i][1][2]] = matchs_round[i][0][2] self.sorted_opponent = sorted(opponents_ids.items(), reverse=False) index = 0 for i in sorted_players: self.players[index]["Score"] = i[3] index += 1 index = 0 for i in self.sorted_opponent: self.players[index]["Opponents"].append(i[1]) index += 1 dict_player = {"players": self.players} tournament_table.update(dict_player, doc_ids=[tournament_id])
def registerpost(gooseobject: dict, scoredict: dict) -> None: """ Registra uma postagem nova não analisada anteriormente :param gooseobject: Objeto beaver.post :param scoredict: Dicionário beaver.analyse.score """ table_domain = db.table('domains') query = Query() scoredict['hash'] = hashlib.md5(str(gooseobject['article_title'] + gooseobject['domain']).encode('utf-8')).hexdigest() table = db.table('posts') table.insert(scoredict) if score_table['tc'] <= float(scoredict['post']['average_score']) < score_table['safe']: # Tendenciosa/Modificada table_domain.update(add('score_td', +10), query.domain == gooseobject['domain']) elif float(scoredict['post']['average_score']) < score_table['tc']: # Falsa table_domain.update(add('score_unsafe', +10), query.domain == gooseobject['domain']) else: # Segura table_domain.update(add('score_safe', +10), query.domain == gooseobject['domain'])
async def on_message(message): # Make exception for bot-messages: if message.author == discord.User.bot: return time_since_epoch = time.time() litcoinlist = TinyDB("litcoin/LITCOIN" + message.server.id + ".json") levellist = TinyDB("level/LEVEL" + message.server.id + ".json") author = message.author.id if not levellist.contains(query["user"] == author): levellist.insert( {"user": author, "level": 1, "exp": 0, "exp_range_min": 15, "exp_range_max": 25, "time": time_since_epoch}) exp = randint(levellist.search(query["user"] == author)[0]["exp_range_min"], levellist.search(query["user"] == author)[0]["exp_range_max"]) if not litcoinlist.contains(query["user"] == author): litcoinlist.insert({"user": author, "balance": 500, "time": time_since_epoch, "gain": 1}) elif litcoinlist.search((query["user"] == author) & (query["time"] < time_since_epoch - 60)): litcoinlist.update(add("balance", (litcoinlist.search(query["user"] == author)[0]["gain"])), query["user"] == author) if levellist.search(query["user"] == author)[0]["time"] < time_since_epoch - 60: levellist.update(add("exp", exp), query["user"] == author) levellist.update({"time": time_since_epoch}, query["user"] == author) if levelup(levellist.search(query["user"] == author)[0]["exp"], levellist.search(query["user"] == author)[0]["level"]): levellist.update(add("level", 1), query["user"] == author) levellist.update({"exp": 0}, query["user"] == author) levelup_message = "`Level_BETA`: " + message.author.name + " leveled up to level `" + str( levellist.search(query["user"] == author)[0]["level"]) + "`" litcoinlist.update({"gain": levellist.search(query["user"] == author)[0]["level"]}, query["user"] == author) levelup_message += ", their litcoin gain per message has increased to `" + str( litcoinlist.search(query["user"] == author)[0]["gain"]) + "`" litcoinlist.update(add("balance", round((levellist.search(query["user"] == author)[0]["level"] ** 1.2) * 100)), query["user"] == author) levelup_message += " and `" + str(round((levellist.search(query["user"] == author)[0][ "level"] ** 1.2) * 100)) + "` LitCoins have been transfered to their account :moneybag:" levelup_message += " :clap::clap:" if not notifications_closed("level", message.server, message.channel): await hydroBot.send_message(message.channel, levelup_message) await hydroBot.process_commands(message)
def update_times_contacted(first_name: str, last_name: str, addition: int = 1, file="db.json") -> None: """Increments the 'times contacted' field in the database for all clients that match the first and last name.""" with TinyDB(file) as db: query = Query() db.update( add("times contacted", addition), (query["first name"].matches(first_name, flags=re.IGNORECASE)) & (query["last name"].matches(last_name, flags=re.IGNORECASE)))
def add_stats_to_user(self, guild: str, author_id: str, k: int, j: int, p: int, ch: int, g: int, sz: int, xd: int): table = self.database.table(guild) table.update_multiple([(add('k', k), where('author') == author_id), (add('j', j), where('author') == author_id), (add('p', p), where('author') == author_id), (add('ch', ch), where('author') == author_id), (add('g', g), where('author') == author_id), (add('sz', sz), where('author') == author_id), (add('xd', xd), where('author') == author_id)])
def update_only_emailed_clients(recipient_list, file="db.json") -> None: """Increments the 'times contacted' field for only clients that were just email reminders. Also, sets the reminder date for these clients to the default reminder date.""" with TinyDB(file) as db: for client in recipient_list: query = Query() db.update(add("times contacted", 1), (query["first name"].matches(client.get_first_name()) & (query["last name"].matches(client.get_last_name())))) db.update( set_val("rem date", datetime_to_string(default_rem_date)), (query["first name"].matches(client.get_first_name()) & (query["last name"].matches(client.get_last_name()))))
def add_tip(amt, account, send_to_id=None): # deduct amount db.update(subtract('bucks', amt), (where('type') == 'account') & (where('id') == account['id'])) if len( db.update(add('total', amt), (where('type') == 'usertips') & (where('id') == account['id']))) == 0: db.insert({ 'type': 'usertips', 'total': amt, 'id': account['id'], 'name': account["name"] }) if send_to_id is not None: db.update(add('bucks', amt), (where('type') == 'account') & (where('id') == send_to_id)) elif len(db.update(add('total', amt), (where('type') == 'tips'))) == 0: db.insert({'type': 'tips', 'total': amt}) else: result = db.get(where('type') == 'tips') return result
def update_points(self, user_id, points): users = self.db.table("User") User = Query() result = users.update(add("points", points), User.user_id == user_id) if not result: random_purchased_rewards = random.choice([ {"General Ticket": random.randint(1, 5)}, {"Free Drink Voucher": random.randint(1, 10)}, {}, {"Weekend Ticket": random.randint(1, 2)}, {}, ]) users.insert({ "user_id": user_id, "points": points, "purchased_rewards": random_purchased_rewards })
def increment_crawled_article_status(self, article_id: str, language: str, amount: int = 1): with self.lock: article_query = Query() article_query = (article_query.type == self.article_type) & (article_query.crawl_status >= 1) \ & (article_query.id == article_id) & (article_query.language == language) articles = self.get_article_db() found_objects = articles.search(article_query) if len(found_objects) > 1: logging.error( f"language {language} has multiple articles with id {article_id} stored in db" ) if any(found_objects): articles.update(add("crawl_status", amount), article_query) self.delete_downloaded_articles()
def start(update, context): if dont_spam(): return if update.effective_chat.id < 0: context.bot.send_message( chat_id=update.effective_chat.id, text='Привет! Чтобы узнать, как играть со мной, напиши /rules', reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton('Начать игру', callback_data='start_game') ]])) db.update(add('groups', 1), Query().groups.exists()) else: context.bot.send_message( chat_id=update.effective_chat.id, text= 'Добавить бота в чат: https://t.me/playnamegame_bot?startgroup=true' )
def start_round(update, context, secondary=False): if dont_spam(): return group_id = update.effective_chat.id user = update.effective_user if group_id not in games: context.bot.send_message(chat_id=group_id, text='В этом чате не идет игры!') return game = games[group_id] if game.round_going: context.bot.send_message(chat_id=group_id, text='В этом чате уже идет раунд!') return if not secondary and user not in game.participants: context.bot.send_message(chat_id=group_id, text=user_name(user) + ', сначала присоединись к игре!') return if not secondary: db.update(add('rounds', 1), Query().rounds.exists()) if len(game.leader_candidates) == 0: game.leader_candidates = set(game.participants.keys()) if len(game.leader_candidates) == 1: leader = random.choice(tuple(game.leader_candidates)) else: leader = random.choice( tuple(game.leader_candidates.difference(set([game.leader])))) game.leader = leader phrases_amount = 6 options = get_phrases(phrases_amount, game.lang) keyboard_markup = InlineKeyboardMarkup([[], []]) for i in range(phrases_amount): game.words_options.append(str(i + 1) + '. ' + options[i]) keyboard_markup.inline_keyboard[1].append( InlineKeyboardButton(str(i + 1), callback_data=str(i + 1))) keyboard_markup.inline_keyboard[0].append( InlineKeyboardButton("Посмотреть слова", callback_data="words")) context.bot.send_message(chat_id=group_id, text='Раунд начался, ведущим был выбран ' + user_name(leader, mention=True), reply_markup=keyboard_markup, parse_mode=ParseMode.MARKDOWN_V2) game.timer = threading.Timer(60.0, restart_round, args=[update, context]) game.timer.start()
def update_record(self, table, run_id, key, value): t = self.db.table(name=table) tx_rec = t.get(eid=run_id).get("outputs", []) if len(tx_rec) > 0 and isinstance(value, list): # fetch the resources dict, index # by filtering them from outputs list res_list = [(idx, x) for idx, x in enumerate(tx_rec) if "resources" in x] if len(res_list) != 0: res_idx = res_list[0][0] resources = res_list[0][1] if "resources" in value[0]: de = defaultdict(list, resources["resources"]) for i, j in value[0]["resources"].items(): de[i].extend(j) de = {"resources": de} tx_rec[res_idx] = de return t.update(tinySet(key, [de]), eids=[run_id]) return t.update(add(key, value), eids=[run_id])
def update_record(self, table, run_id, key, value): t = self.db.table(name=table) # get transaction record tx_rec = t.get(eid=run_id).get("outputs", []) if len(tx_rec) > 0 and isinstance(value, list): # fetch the resources dict, index # by filtering them from outputs list res_list = [(idx, x) for idx, x in enumerate(tx_rec) if "resources" in x] if len(res_list) != 0: res_idx = res_list[0][0] resources = res_list[0][1] if "resources" in value[0].keys(): de = resources["resources"] for i in value[0]["resources"]: de.append(i) de = {"resources": de} tx_rec[res_idx] = de res = t.update(tinySet(key, [de]), eids=[run_id]) return res return t.update(add(key, value), eids=[run_id])
def update_record(self, table, run_id, key, value): t = self.db.table(name=table) # get transaction record tx_rec = t.get(doc_id=run_id).get("outputs", []) if len(tx_rec) > 0 and isinstance(value, list): # fetch the resources dict, index # by filtering them from outputs list res_list = [(idx, x) for idx, x in enumerate(tx_rec) if "resources" in x] if len(res_list) != 0: res_idx = res_list[0][0] resources = res_list[0][1] if "resources" in list(value[0].keys()): de = resources["resources"] for i in value[0]["resources"]: de.append(i) de = {"resources": de} tx_rec[res_idx] = de res = t.update(tinySet(key, [de]), doc_ids=[run_id]) return res return t.update(add(key, value), doc_ids=[run_id])
def wrapper(self, *args, **kwargs): if self.ctx.__class__.__name__ == 'GroupMsg': # 群聊 # ------------------------------------------------------------------------ data_tmp = db_tmp.table('freq').search( Q['group'] == self.ctx.FromGroupId) if data_tmp: # 如果有数据 if self.db_config['refreshTime'] != 0 and ( time.time() - data_tmp[0]['time'] >= self.db_config['refreshTime']): # 刷新 db_tmp.table('freq').update( { 'time': time.time(), 'freq': 0 }, Q['group'] == self.ctx.FromGroupId) elif self.db_config['freq'] != 0 and self.num + data_tmp[ 0]['freq'] > self.db_config['freq']: # 大于限制且不为0 logger.info('群:{}大于频率限制:{}次/{}s'.format( self.ctx.FromGroupId, self.db_config['freq'], self.db_config['refreshTime'])) msg = self.db_config['msg_frequency'].format( time=self.db_config['refreshTime'], num=self.db_config['freq'], num_call=data_tmp[0]['freq'], r_time=round(self.db_config['refreshTime'] - (time.time() - data_tmp[0]['time']))) sendMsg.send_text(self.ctx, msg, self.db_config['at_warning']) return # 记录 db_tmp.table('freq').update( add('freq', self.num), Q['group'] == self.ctx.FromGroupId) else: # 没数据 logger.info('群:{}第一次调用'.format(self.ctx.FromGroupId)) db_tmp.table('freq').insert({ 'group': self.ctx.FromGroupId, 'time': time.time(), 'freq': self.num }) func(self, *args, **kwargs)
def join_game(update, context, secondary=False, callback_user=None): if dont_spam(): return group_id = update.effective_chat.id if secondary: user = callback_user else: user = update.effective_user if group_id not in games: context.bot.send_message(chat_id=group_id, text='В этом чате не идет игры') return game = games[group_id] if user in game.participants: context.bot.send_message(chat_id=group_id, text=user_name(user) + ', ты уже в игре') return game.participants[update.effective_user] = 0 game.leader_candidates.add(user) db.update(add('joins', 1), Query().joins.exists()) context.bot.send_message(chat_id=group_id, text=user_name(user) + ' присоединился к игре!')
def add(id): main_db = TinyDB('main_db.json') keyword_table = main_db.table("keyword_table") timeline_table = main_db.table("timeline_table") user_table = main_db.table("user_table") q = Query() word_lists = [] for keyword in keyword_table.all(): word_list = [] word_list.append(keyword["keyword"]) word_list += keyword["checkword"].split(",") word_lists.append(word_list) for word_list in word_lists: checker = 0 for checkword in word_list[1:]: checker += len( timeline_table.search(q.text.search(r"%s" % checkword))) if checker > 0: user_table.update(operations.add("keyword", word_list[0] + ","), q.ID.matches(r"%s" % id))
def check_wagers(clip, total_clip_count): add_play_record(clip) is_wager = where('type') == 'wager' # decrease count of miss db.update(decrement('count'), is_wager & (where('clip') != clip)) # delete the zeros db.remove(is_wager & (where('count') == 0)) # get the hits results = db.search(is_wager & (where('clip') == clip)) winners = [] for result in results: # pay out pay_out = result['amount'] + result[ 'amount'] * total_clip_count / result['start_count'] db.update(add('bucks', pay_out), (where('type') == 'account') & (where('id') == result['user_id'])) # record win add_win_record((result['user_id'], result['disp_name'], clip, pay_out)) # delete wager record db.remove(is_wager & (where('wager_id') == result['wager_id'])) winners.append((result['disp_name'], pay_out, result['clip'])) return winners
def index(): form = MoviePicker() if request.method == 'GET': movie_name = request.args.get('movie_name', '') if movie_name != '': movie_results = ia.search_movie(movie_name) choices = create_choices(movie_results[:6]) #form.choices = [('MadMax',0),('Interstellar',1)] #form.select_movie.choices = [('MadMax',0),('Interstellar',1)] form.select_movie.choices = choices return render_template('index.html', movie_name=movie_name, form=form) return render_template('index.html', movie_name=movie_name) if request.method == 'POST': if form.select_movie.data: selected_movie = ia.get_movie(form.select_movie.data) flash('Your movie has been added. :)') # selected_movie = movie_results[int(form.select_movie.data)] # ia.update(selected_movie, info=['main', 'plot']) new_movie = { 'title': selected_movie.get('title'), 'year': selected_movie.get('year'), 'genres': selected_movie.get('genres'), 'cover_url': selected_movie.get('cover url'), 'plot': selected_movie.get('plot outline'), 'movie_id': selected_movie.movieID, 'imdb_id': ia.get_imdbID(selected_movie), 'users': [form.user.data] } Movie = Query() if not db.search(Movie.movie_id == new_movie['movie_id']): db.insert(new_movie) elif db.search((Movie.movie_id == new_movie['movie_id']) & (~Movie.users.any(new_movie['users']))): db.update(add('users', new_movie['users'])) return redirect('/')
def give_bonus_taco(user): # Give daily 'talking once' bonus taco. db.update(add('owned_tacos', 1), Query().user_id == user) db.update({'daily_bonus': False}, Query().user_id == user) owned_tacos = db.search(Query().user_id == user)[0]['owned_tacos'] db_logs.insert({ 'giving_user': None, 'receiver_user': user, 'n_tacos': 1, 'type': 'bonus', 'date': today }) slack_client.api_call( "chat.postMessage", channel=user, as_user=True, text= "¡Toma! Aquí tienes *1 TACO de premio por participar hoy en la comunidad*. Ya tienes *{0:g}x :taco: * ¡Vuelve mañana a por más!" .format(owned_tacos)) return
def test_add_str(db): db.update(add('char', 'xyz'), where('char') == 'a') assert db.get(where('char') == 'axyz')['int'] == 1
def test_add_int(db): db.update(add('int', 5), where('char') == 'a') assert db.get(where('char') == 'a')['int'] == 6