def update_token(self): '''atualiza o token no arquivo "config.json" e na interface.''' from functions import load_json, save_json entrada:str = self.inserir_token.get() if len(entrada) == 59: self.inserir_token.delete(0, tk.END) current_dict = load_json(path.config) current_dict['token'] = entrada save_json(path.config, current_dict) self.token_atual['text'] = f'Seu token atual é:\n{entrada}'
def remove_message(self): '''remove a mensagem selecionada do listbox de mensagens e a deleta do arquivo "message and reply.json".''' from functions import load_json, save_json lista_nomes = self.todas_mensagens.get(0, tk.END) try: selecionado = self.todas_mensagens.curselection()[0] except IndexError: pass else: nome_selecionado:str = lista_nomes[selecionado] self.todas_mensagens.delete(selecionado) message_and_reply_json = load_json(path.message_and_reply) del message_and_reply_json[nome_selecionado] save_json(path.message_and_reply, message_and_reply_json)
#!/usr/bin/env python3 """ init-db.py is the set-up script that has to be run before bot.py. It generates """ import sys import functions size = int(sys.argv[1]) states = functions.generate_boards(size) dictionary = functions.generate_database(states, 1000) functions.save_json('db.json', dictionary)
def save_all_json(self): '''salva toda a informação que o usuario preencheu na interface em forma de json, para que depois o interpretador do bot consiga interpretar''' import json from interfaces.commands.main import MainCommands from functions import load_json, save_json, have_in import re try: dict_base = load_json(path.message_and_reply) except json.decoder.JSONDecodeError: name = '1' dict_base = dict() else: if not self.load: name = '1' chaves_dict_base = list(dict_base.keys()) chaves_dict_base.reverse() for x in chaves_dict_base: try: chave = int(x) except ValueError: pass else: name = str(chave + 1) break else: name = self.load if self.new_name: name = self.new_name del dict_base[self.load] # anti-bug self.load = name dict_base[name] = {} lista_expected_message = self.listbox_messages.get(0, tk.END) dict_base[name][ 'expected message'] = lista_expected_message if not len( lista_expected_message) == 0 else None lista_reply = self.listbox_replys.get(0, tk.END) dict_base[name]['reply'] = list( map(lambda x: x.split('¨'), lista_reply)) if have_in( lista_reply, '¨', reverse=True ) else lista_reply if not len(lista_reply) == 0 else None lista_reactions = self.listbox_reactions.get(0, tk.END) dict_base[name]['reaction'] = list( map(lambda x: re.findall(r':[a-zA-Z_0-9]+:', x), lista_reactions)) if not len(lista_reactions) == 0 else None lista_conditions = self.listbox_conditions.get(0, tk.END) dict_base[name]['conditions'] = lista_conditions if not len( lista_conditions) == 0 else None if self.pin_or_del.get() == 'Fixar': dict_base[name]['pin'] = True elif self.pin_or_del.get() == 'Remover': dict_base[name]['delete'] = True dict_base[name]['where reply'] = self.variable_where_reply.get() dict_base[name]['where reaction'] = self.variable_where_reaction.get() dict_base[name]['delay'] = self.delay.get() save_json(path.message_and_reply, dict_base) MainCommands.refresh_messages(self)
import functions as fnc import gui if __name__ == "__main__": player_name_list = fnc.load_json() gui.vp_start_gui(player_name_list) fnc.save_json()
def move(array, speler): DRAWADJUST = 100 WINADJUST = 1000000000 LOSEADJUST = -1 board = array player = speler # init moves during game movesduringgame = functions.load_json(f'/tmp/moves') big_db = functions.load_json('db.json') freefields = functions.free_fields(deepcopy(board)) # did we lose when the other side moved? ff_json = functions.load_json(f'/tmp/freefields') count = ff_json['freefields'] # print(f'SAVED FREE FIELDS: {count}') # print(f'CURRENT FREE FIELDS: {freefields}') if freefields > count: #we lost :( adjust = LOSEADJUST functions.update_database(movesduringgame, big_db, adjust) functions.save_json('db.json', big_db) movesduringgame = {} boardhash = functions.gamestate_hash(board) # print('\n\n<BOT> BOARD HASH', str(boardhash)) # print('BH NOT IN BIG DB:') # print(boardhash not in big_db) if boardhash not in big_db: # print('inverting board') board = functions.invert_board(deepcopy(board)) # print(board) player = 2 if player == 1 else 1 boardhash = functions.gamestate_hash(board) # print('<BOT> str2' + str(boardhash)) possiblemoves = functions.fetch_moves(big_db, boardhash) # print('<BOT>' + str(possiblemoves)) newmove = functions.generate_move(possiblemoves) movesduringgame.update({boardhash: [newmove[0], newmove[1]]}) # print() # print('<BOT> mdg ' + str(movesduringgame)) # print('<BOT> bh ' + str(boardhash)) board = functions.update_board(board, newmove, player) endgame = functions.game_end(board) if endgame in [3, 1, 2]: if endgame == 3: # phew, a draw adjust = DRAWADJUST elif endgame == player: # WE WIN!!!!11!!!! adjust = WINADJUST else: # WE LOST :(((((( adjust = LOSEADJUST # print(big_db) # print('<BOT> bigdb (noup)'+str(big_db)) # print('<BOT> mdg '+str(movesduringgame)) functions.update_database(movesduringgame, big_db, adjust) # print('<BOT> bigdb '+str(big_db)) functions.save_json('db.json', big_db) movesduringgame = {} # reset array of played moves # detect if we draw or lose next turn free = functions.free_fields(board) freefields = {'freefields': free} if free == 1: emp_field = [-1, -1] for y in range(len(board)): for x in range(len(board)): if board[y][x] == 0: emp_field = [y, x] # fill it with the opposing player's number opp_player = 2 if player == 1 else 1 board = functions.update_board(deepcopy(board), emp_field, opp_player) endgame = functions.game_end(board) if endgame == 3: adjust = DRAWADJUST elif endgame == opp_player: adjust = LOSEADJUST functions.update_database(movesduringgame, big_db, adjust) functions.save_json('db.json', big_db) movesduringgame = {} freefields = {'freefields': 15} functions.save_json(f'/tmp/freefields', freefields) # write movesduringgame out to file functions.save_json(f'/tmp/moves', movesduringgame) # # print('<BOT> newmv '+str(newmove)) # print(f'<BOT> {type(newmove)}, {type(newmove[0])}, {type(newmove[1])}\n\n\n\n') return newmove
import functions from copy import deepcopy #initialise helpineedtoinitthis = {} functions.save_json(f'/tmp/moves', helpineedtoinitthis) helpineedtoinitthis = {'freefields': 15} functions.save_json('/tmp/freefields', helpineedtoinitthis) def move(array, speler): DRAWADJUST = 100 WINADJUST = 1000000000 LOSEADJUST = -1 board = array player = speler # init moves during game movesduringgame = functions.load_json(f'/tmp/moves') big_db = functions.load_json('db.json') freefields = functions.free_fields(deepcopy(board)) # did we lose when the other side moved? ff_json = functions.load_json(f'/tmp/freefields')
response = response.json() if "pages" in response: last_page = response['pages']['total'] for page in range(current_page,last_page+1): print "Page %s of %s" %(page,last_page) time.sleep(0.5) url = "http://www.loc.gov/pictures/search/?q=%s&sp=%s&fo=json" %(search_term,page) response = requests.get(url) if response.status_code == 200: response = response.json() if "results" in response: results = response['results'] images = parse_results(results,images) # Save the json to file save_json(images,"loc.json") ## STEP 2: Subset to images that likey have faces ###################################### # FaceDetect haar cascade file for opencv cascade_file = "FaceDetect/haarcascade_frontalface_default.xml" # Create the haar cascade face_cascade = cv2.CascadeClassifier(cascade_file) min_width=300 min_height=300 # Subset to large images with faces faces = dict()
async def on_message(message: discord.Message): setdelay = re.findall(r'^\!slowmode set ([0-9]+)', message.content) base = functions.load_json('whitelist.json') if isinstance( message.channel, discord.TextChannel) and config.slowmode and not ( message.author.id in base['whitelist'] or message.channel.id in base['channel whitelist'] or True in list( map( lambda r: True if r.id in base['role whitelist'] else False, message.author.roles))): if not message.author.id in who_cant_say: who_cant_say[message.author.id] = datetime.now( ) + timedelta(seconds=config.delay) else: if datetime.now() < who_cant_say[message.author.id]: await message.delete() await self.send_dm( f'O canal está em modo slow mode, você precisa esperar {config.delay} segundos para digitar novamente.', message) else: del who_cant_say[message.author.id] if message.content.lower().startswith( commands.APPEND_TO_WHITELIST): for var, key in [[message.mentions, 'whitelist'], [ message.channel_mentions, 'channel whitelist' ], [message.role_mentions, 'role whitelist']]: if len(var) >= 1: for m in var: if not m.id in base[key]: base[key].append(m.id) functions.save_json('whitelist.json', base) elif message.content.lower().startswith( commands.REMOVE_FROM_WHITELIST): for var, key in [[message.mentions, 'whitelist'], [ message.channel_mentions, 'channel whitelist' ], [message.role_mentions, 'role whitelist']]: if len(var) >= 1: for m in var: if m.id in base[key]: base[key].remove(m.id) functions.save_json('whitelist.json', base) elif setdelay: if message.author.id == message.guild.owner_id: config.delay = int(setdelay[0]) await self.send_dm( f'O slowmode foi definido para {config.delay} segundos.', message) else: await self.send_dm( 'Apenas o dono do servidor pode modificar o slow mode.', message) elif message.content.lower() == commands.TO_ACTIVE: if message.author.id == message.guild.owner_id: config.slowmode = True await self.send_dm('O slowmode foi ativado.', message) else: await self.send_dm( 'Apenas o dono do servidor pode ativar ou desativar o slow mode.', message) elif message.content.lower() == commands.TO_DESACTIVE: if message.author.id == message.guild.owner_id: config.slowmode = False await self.send_dm('O slowmode foi desativado.', message) else: await self.send_dm( 'Apenas o dono do servidor pode ativar ou desativar o slow mode.', message) elif message.content.lower() == commands.TO_LIST and isinstance( message.channel, discord.TextChannel): members = [] channels = [] roles = [] for ID in base['whitelist']: members.append(message.guild.get_member(ID).name) for ID in base['channel whitelist']: channels.append(message.guild.get_channel(ID).name) for ID in base['role whitelist']: roles.append(message.guild.get_roles(ID).name) await self.send_dm( f'Whitelist:\nMembros: {",".join(members) if len(members) >= 1 else "Nenhum"}\nCanais: {",".join(channels) if len(channels) >= 1 else "Nenhum"}\nCargos: {",".join(roles) if len(roles) >= 1 else "Nenhum"}', message)
subjects = [] # turn medium_brief into features (subject tag) # format seems to be type: material : size medium_tags = [ tag.strip().replace(".", "") for tag in image['image']['medium'].split(":") ] subjects = numpy.unique(subjects + medium_tags).tolist() subjects_dict = add_to_dict(subjects_dict, subjects, image_uid) # Finally, image meta data image_df.loc[image_uid, columns] = [ image['image']['title'], image['image']['creator'], image['image']['created_published_date'], "https:%s" % (image['image']['image']['thumb']), "https:%s" % (image['image']['image']['full']), "https:%s" % (image['image']['image']['square']), "https:%s" % image['image']['links']['item'], ",".join(image['image']['collection']), image['image']['medium_brief'], image['image']['created'] ] count += 1 # Save the data frames and then free up memory image_df.to_csv('../data/image_df.tsv', sep="\t", encoding='utf-8') emotion_df.to_csv('../data/emotion_df.tsv', sep="\t") save_json(subjects_dict, '../data/subjects.json') save_json(dates_dict, '../data/dates.json')
import numpy as np import matplotlib.pyplot as plt import subprocess, sys, os, fnmatch import functions as fun from random import randint #returns total volume used by file def get_item_space(item): subprocess.call('du ' +item+ ' > du_tmp/item.du',shell=True) return int(fun.read_file('du_tmp/item.du','r').split('\t')[0]) subprocess.call('rm -rf du_tmp; mkdir du_tmp',shell=True) top_directory = sys.argv[1] name = sys.argv[2] files = fun.recursive_glob(top_directory, '*') for i in range(0,len(files)): files[i]=(files[i],get_item_space(files[i])) fun.save_json(name,files) rm -rf du_tmp
def save(self): return save_json("saves/characters.JSON", {self.name: {"classrole": self.classrole, "xp": self.xp}})
def remove_all_message(self): from functions import save_json self.todas_mensagens.delete(0, tk.END) dict_to_save = dict() save_json(path.message_and_reply, dict_to_save)
if os.path.exists("data/loc_emotions.json"): emotions = json.load(open("data/loc_emotions.json","rb")) count = len(emotions) for image_pk,image in images.iteritems(): if count < limit and image_pk not in emotions: image_title = image['title'] print "Parsing %s of %s: %s" %(count,limit,image_title) image_url = "http:%s" %image['image']['full'] body = {'url':image_url} try: response = requests.post(emo_url, headers=headers, data=json.dumps(body)) if response.status_code == 200 and response.text != '[]': face_emotions = response.json()[0] face_emotions["image"] = image emotions[image_pk] = face_emotions except ConnectionError: pass count+=1 time.sleep(3.0) # only 30 per minute # Save json every 1000 images if count % 1000 == 0: print("Saving emotions data at count %s" %(count)) save_json(emotions,"data/loc_emotions.json")