cnx_p.listen(1) while 1: cnx, infos = cnx_p.accept() cmd = cnx.recv(1024) if cmd[:3] == b"GET": id = cmd[3:] with open("database.db", "rb") as f: db = pickle.Unpickler(f).load() cnx.send(db.get(id, b"invalid ID")) if id in db: if db[id][-1]: db[id] = db[id][:-1] + b"\0" else: db[id] = db[id][:-1] + b"\1" with open("database.db", "wb") as f: pickle.Pickler(f).dump(db) elif cmd[:3] == b"ADD": id_len = cmd[3] id = cmd[4:4 + id_len] with open("database.db", "rb") as f: db = pickle.Unpickler(f).load() if id in db: cnx.send(b"ID already in use.") else: db[id] = cmd[4 + id_len:] if len(db[id]) < 3: del db[id] cnx.send(b"invalid name") else: cnx.send(b"Added") with open("database.db", "wb") as f:
elif hab.completed == True: fix_tod = tod_user.items.get_by_id(tid) fix_tod.close() print('completed tod %s' % tod.name) else: print("ERROR: check HAB %s" % tid) elif tod.complete == 1: if hab.completed == False: r = main.complete_hab(hab) print(r) if r.ok == True: print('Completed hab %s' % hab.name) else: print('check hab ID %s' % tid) print(r.reason) elif hab.completed == True: expired_tids.append(tid) else: print("ERROR: check HAB %s" % tid) else: print("ERROR: check TOD %s" % tid) for tid in expired_tids: matchDict.pop(tid) pkl_file = open('twoWay_matchDict.pkl', 'wb') pkl_out = pickle.Pickler(pkl_file, -1) pkl_out.dump(matchDict) pkl_file.close() tod_user.commit()
def func(f): p = pickle.Pickler(f, protocol=protocol) p.persistent_id = persistent_id(zip_file) p.dump(obj)
def save(fichier, mots_trad): with open(fichier, "wb") as f: variable = pickle.Pickler(f) variable.dump(mots_trad)
#Auteur : Cyril AUREJAC #Formation AJC Consultant Réseau - Module Python #Exercice import random import os import pickle os.chdir("C:/Users/SkoreGaming/Documents/GitHub/Python") #on crée une liste de 10 entiers random entre 1 et 10 liste=[] for i in range(0,10): liste.append(random.randint(1,10)) #méthode d'ouverture en écriture, pas besoin de fermeture with open("test.py", "wb") as fichier: pick=pickle.Pickler(fichier) pick.dump(liste) #on recupere la liste en lecture with open("test.py", "rb") as fichier: depick=pickle.Unpickler(fichier) recup_liste=depick.load() print(recup_liste)
def save_score(score): with open('score', 'wb') as f_player: pickle_players = pickle.Pickler(f_player) pickle_players.dump(score)
import pickle import os """importer le dictionnaire contenant le meilleur score""" try: with open("F:/bureau/Python/tp/ZEPendu/donnee/MeilleurScore.flo", 'rb') as fichier: lePickle = pickle.Unpickler(fichier) MeilleurScore = lePickle.load() except FileNotFoundError: MeilleurScore = {} with open("F:/bureau/Python/tp/ZEPendu/donnee/MeilleurScore.flo", 'wb') as fichier: lePickle = pickle.Pickler(fichier) lePickle.dump(MeilleurScore) def sauvegardeScore(): with open("F:/bureau/Python/tp/ZEPendu/donnee/MeilleurScore.flo", 'wb') as fichier: monPickle = pickle.Pickler(fichier) monPickle.dump(MeilleurScore) if __name__ == "__main__": print(MeilleurScore) os.system("pause")
from COCODataset import COCODataset def _wordToInd(vocab): ret = {} for i, word in tqdm(enumerate(vocab)): assert word not in ret ret[word] = i return ret if __name__ == '__main__': assert not settings.vocabfilepath.is_file() with open(settings.vocabfilepath, 'wb') as dsf: pcklr = pickle.Pickler(dsf) dataset = COCODataset('coco/images/train2017', 'coco/annotations/captions_train2017.json', True) vocab = dataset.calcVocab() print('Vocabulary length:', len(vocab)) maxCaptionLen = dataset.calcMaxCaptionLen() print('Max caption length:', maxCaptionLen) wordToInd = _wordToInd(vocab) obj = { 'vocab': vocab, 'maxCaptionLen': maxCaptionLen, 'wordToInd': wordToInd
def saveScores(scores): scoreFile = open(saveFile, 'wb') scorePeek = pickle.Pickler(scoreFile) score = scorePeek.dump(scores) scoreFile.close()
def save(data): f = open(PATH, 'r+b') pickle.Pickler(f, 0).dump(data) f.close()
previous_findings += "*" try: with open('score', 'rb') as fichier_score: depickler = pickle.Unpickler(fichier_score) score = depickler.load() #existing/returning players if name in score.keys(): (life, word_to_search, previous_findings) = score[name] #new player else: score[name] = (life, word_to_search, previous_findings) #update file for new player with open('score', 'wb') as fichier_score: pickler = pickle.Pickler(fichier_score) pickler.dump(score) except: print("No score file. Creating it...") score[name] = (life, word_to_search, previous_findings) fichier_score = open('score', 'wb') pickler = pickle.Pickler(fichier_score) pickler.dump(score) fichier_score.close() #setup print("""Mr/Mrs {}, you have {} live to start. You are looking for {}. You have found {}.""".format(name, life, word_to_search, previous_findings))
import pickle score = { "joueur 1": 5, "joueur 2": 35, "joueur 3": 20, "joueur 4": 2, } with open("Ecriture_fichiers/fichier.txt", "wb") as donnees: mon_pickler = pickle.Pickler(donnees) mon_pickler.dump(score) with open("Ecriture_fichiers/fichier.txt", "rb") as fichier: mon_depickler = pickle.Unpickler(fichier) score_recup = mon_depickler.load() print(score_recup)
if w_svpt == w_svpt and w_1stIn == w_1stIn: winner.update_first_serve_success_percentage(w_1stIn, w_svpt) if w_bp_Faced == w_bp_Faced and w_bp_Saved == w_bp_Saved and w_SvGms == w_SvGms: winner.update_breakpoint_faced_and_savec(w_bp_Faced, w_bp_Saved, w_SvGms) loser.add_defeat(id_winner) loser.last_tournament_date = tournament_date loser.update_fatigue(tournament_date, sets_number) loser.update_surface_victory_percentage(surface, 'D') if l_svpt == l_svpt and l_ace == l_ace: loser.update_ace_percentage(l_ace, l_svpt) if l_svpt == l_svpt and l_df == l_df: loser.update_doublefault_percentage(l_df, l_svpt) if l_svpt == l_svpt and l_1stwon == l_1stwon and l_2ndwon == l_2ndwon: loser.update_winning_on_1st_serve_percentage(l_1stwon, l_svpt) loser.update_winning_on_2nd_serve_percentage(l_2ndwon, l_svpt) if l_svpt == l_svpt and l_1stIn == l_1stIn: loser.update_first_serve_success_percentage(l_1stIn, l_svpt) if l_bp_Faced == l_bp_Faced and l_bp_Saved == l_bp_Saved and l_SvGms == l_SvGms: loser.update_breakpoint_faced_and_savec(l_bp_Faced, l_bp_Saved, l_SvGms) whole_data += [match.get_data()] print(whole_data[0]) with open('Data_%i' % year_to_study, 'wb') as file: my_pickler = pickle.Pickler(file) my_pickler.dump(whole_data)
def writeDataOnFile(binary, output, dico): with open(binary, "wb") as bin: writer = pickle.Pickler(bin) writer.dump(dico) with open(output, 'w') as txt: txt.write(str(dico))
# encoding: utf-8 import pickle ########### EJEMPLO 1 ############## print '########### EJEMPLO 1 ##############' # Guardo en el archivo with open('ejemplo.pkl', 'wb') as archivo: pkl = pickle.Pickler(archivo) lista1 = [1, 2, 3] lista2 = [4, 5] diccionario = {'campo1': 1, 'campo2': 'dos'} pkl.dump(lista1) pkl.dump(None) pkl.dump(lista2) pkl.dump('Hola mundo') pkl.dump(diccionario) pkl.dump(1) # Leo del archivo with open('ejemplo.pkl', 'rb') as archivo: seguir_leyendo = True while seguir_leyendo: try: data = pickle.load(archivo) except EOFError: seguir_leyendo = False else: print '### Esta línea no es del archivo ###'
def launch(self, withresume): decaly = 0 decalx = -150 space = 120 firstRound = True while (True): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() self.clock.tick_busy_loop(30) self.background.updatecompteur() screen.fill((0, 0, 0)) self.background.blitStars() self.background.blitPlanets() #show the fog self.background.blitFog() screen.blit(self.single_sprites['menu_micshooter.png'], (120, 40)) self.compteur = self.compteur + 1 #update the particles particles.blitAndUpdate() if self.menustatus == 0: #change the selection if pygame.key.get_pressed()[pygame.K_UP]: if self.compteur >= 5: particles.addRandomExplosion(3) #print(self.selection) self.play_sound(self.sounds["menu.wav"]) self.selection = self.selection - 1 if self.selection == 0: self.selection = 3 self.compteur = 0 if pygame.key.get_pressed()[ pygame.K_DOWN] and self.compteur >= 5: particles.addRandomExplosion(3) #print(self.selection) self.play_sound(self.sounds["menu.wav"]) self.selection = self.selection + 1 if self.selection == 4: self.selection = 1 self.compteur = 0 #blit the help s = pygame.Surface((300, 300)) # the size of your rect s.set_alpha(64) # alpha level s.fill((99, 0, 201)) # this fills the entire surface screen.blit(s, (25, 150)) # (0,0) are the top-left coordinates screen.blit(self.littlefont.render("Use the arrow keys and", \ True, (255,255, 255)),(30,155)) screen.blit(self.littlefont.render("enter to navigate the menu. ", \ True, (255,255, 255)),(30,175)) screen.blit(self.littlefont.render("Game controls : ", \ True, (255,128, 128)),(30,210)) screen.blit(self.littlefont.render("Arrow keys : move your ship ", \ True, (255,255, 255)),(30,230)) screen.blit(self.littlefont.render("space : fire ", \ True, (255,255, 255)),(30,250)) if pygame.key.get_pressed( )[pygame. K_RETURN] and self.selection == 1 and self.compteur >= 5: self.compteur = 0 effects.fadeToColor(0, 0, 0) return #if pygame.key.get_pressed()[pygame.K_RETURN] and self.selection==3 and self.compteur>=5: #print("YAY") ##pygame.display.toggle_fullscreen() if pygame.key.get_pressed( )[pygame. K_RETURN] and self.selection == 3 and self.compteur >= 5: self.compteur = 0 exit() if pygame.key.get_pressed( )[pygame. K_RETURN] and self.selection == 2 and self.compteur >= 5: self.compteur = 0 self.selection = 1 self.menustatus = 1 #print the menu accordingly to the selection and the menu state if withresume == 0: if pygame.key.get_pressed()[K_ESCAPE]: exit() if self.selection == 1: if self.compteur < 30 and self.compteur % 2: screen.blit( self.single_sprites['lifeBonusLight.png'], (190 - 33 - decalx, 180 - 32 - decaly)) screen.blit(self.single_sprites['sprite_ship.png'], (190 - decalx, 180 - decaly)) screen.blit(self.single_sprites['menu_playblurry.png'], (270 - decalx, 200 - decaly)) else: screen.blit(self.single_sprites['menu_play.png'], (270 - decalx, 200 - decaly)) else: if self.selection == 1: if self.compteur < 30 and self.compteur % 2: screen.blit( self.single_sprites['lifeBonusLight.png'], (190 - 33 - decalx, 180 - 32 - decaly)) screen.blit(self.single_sprites['sprite_ship.png'], (190 - decalx, 180 - decaly)) screen.blit( self.single_sprites['menu_resumeblurry.png'], (270 - decalx, 200 - decaly)) else: screen.blit(self.single_sprites['menu_resume.png'], (270 - decalx, 200 - decaly)) if self.selection == 2: if self.compteur < 30 and self.compteur % 2: screen.blit( self.single_sprites['lifeBonusLight.png'], (190 - 33 - decalx, 180 - 32 + space - decaly)) screen.blit(self.single_sprites['sprite_ship.png'], (190 - decalx, 180 + space - decaly)) screen.blit(self.single_sprites['menu_optionsblurry.png'], (270 - decalx, 200 + space - decaly)) else: screen.blit(self.single_sprites['menu_options.png'], (270 - decalx, 200 + space - decaly)) #if self.selection==3: #if self.compteur<30 and self.compteur%2: #screen.blit(self.single_sprites['lifeBonusLight.png'],(190-33-decalx,180-32+(2*space)-decaly)) #screen.blit(self.single_sprites['sprite_ship.png'],(190-decalx,180+(2*space)-decaly)) ## pygame.display.toggle_fullscreen() if self.selection == 3: if self.compteur < 30 and self.compteur % 2: screen.blit(self.single_sprites['lifeBonusLight.png'], (190 - 33 - decalx, 180 - 32 + (2 * space) - decaly)) screen.blit(self.single_sprites['sprite_ship.png'], (190 - decalx, 180 + (2 * space) - decaly)) screen.blit(self.single_sprites['menu_quitblurry.png'], (270 - decalx, 200 + (2 * space) - decaly)) else: screen.blit(self.single_sprites['menu_quit.png'], (270 - decalx, 200 + (2 * space) - decaly)) elif self.menustatus == 1: #change the selection if pygame.key.get_pressed()[pygame.K_UP]: if self.compteur >= 5: self.play_sound(self.sounds["menu.wav"]) #print(self.selection) self.selection = self.selection - 1 if self.selection == 0: self.selection = 4 self.compteur = 0 if pygame.key.get_pressed()[ pygame.K_DOWN] and self.compteur >= 5: self.play_sound(self.sounds["menu.wav"]) #print(self.selection) self.selection = self.selection + 1 if self.selection == 5: self.selection = 1 self.compteur = 0 #decrease sound volume if pygame.key.get_pressed( )[pygame. K_LEFT] and self.selection == 1 and self.compteur >= 5 and ( self.config['sound'] > 0): self.play_sound(self.sounds["menu.wav"]) self.compteur = 0 self.config['sound'] = self.config['sound'] - 1 #increase sound volume if pygame.key.get_pressed()[pygame.K_RIGHT] \ and self.selection==1 and self.compteur>=5 \ and self.config['sound'] < 10: self.play_sound(self.sounds["menu.wav"]) self.compteur = 0 self.config['sound'] = self.config['sound'] + 1 #if (pygame.key.get_pressed()[pygame.K_LEFT] or pygame.key.get_pressed()[pygame.K_RIGHT]) \ #and self.selection==1 and self.compteur>=5: #self.play_sound(self.sounds["menu.wav"]) #self.compteur=0 #self.config['sound']= not self.config['sound'] if (pygame.key.get_pressed()[pygame.K_LEFT] or pygame.key.get_pressed()[pygame.K_RIGHT]) \ and self.selection==2 and self.compteur>=5: self.play_sound(self.sounds["menu.wav"]) self.compteur = 0 self.config['resolution'] = not self.config['resolution'] if self.config['resolution'] == 0: self.hud.offset = 0 if self.config['fullscreen'] == 0: common_pygame.pygame.display.set_mode((800, 600)) else: common_pygame.pygame.display.set_mode((800,600), \ common_pygame.pygame.FULLSCREEN) common_pygame.screenheight = 600 else: self.hud.offset = 100 if self.config['fullscreen'] == 0: common_pygame.pygame.display.set_mode((800, 500)) else: common_pygame.pygame.display.set_mode((800,500), \ common_pygame.pygame.FULLSCREEN) common_pygame.screenheight = 500 if (pygame.key.get_pressed()[pygame.K_RETURN] \ or pygame.key.get_pressed()[pygame.K_LEFT] or \ pygame.key.get_pressed()[pygame.K_RIGHT] )and \ self.selection==3: if self.config['resolution'] == 0: res = (800, 600) else: res = (800, 500) self.config['fullscreen'] = int( not self.config['fullscreen']) if self.config['fullscreen']: common_pygame.pygame.display.set_mode(res, \ common_pygame.pygame.FULLSCREEN) else: common_pygame.pygame.display.set_mode(res) #common_pygame.pygame.display.toggle_fullscreen() if pygame.key.get_pressed()[ pygame.K_RETURN] and self.selection == 4: #write the config into the file with open(os.path.join('data', 'config.conf'), 'wb') as fichier: mon_pickler = pickle.Pickler(fichier) mon_pickler.dump(self.config) self.compteur = 0 self.selection = 1 self.menustatus = 0 bar = pygame.Surface((10, 15)) # the size of your rect #bar.set_alpha(64) # alpha level if self.selection == 1: screen.blit(self.font.render("Sound :", True, (255, 0, 0)), (350, 200)) bar.fill((128, 0, 0)) else: bar.fill((128, 128, 128)) screen.blit( self.font.render("Sound :", True, (255, 255, 255)), (350, 200)) # this fills the entire surface #screen.blit(s, (25,150)) # (0,0) are the top-left coordinates for i in range(10): screen.blit(bar, (490 + (20 * i), 210)) if self.selection == 1: bar.fill((255, 0, 0)) else: bar.fill((255, 255, 255)) for i in range(self.config['sound']): screen.blit(bar, (490 + (20 * i), 210)) #else: #if self.config['sound']: #if self.selection==1: #screen.blit(self.font.render("Sound : on", True, (255,0, 0)),(350,200)) #else: #screen.blit(self.font.render("Sound : on", True, (255,255, 255)),(350,200)) #else: #if self.selection==1: #screen.blit(self.font.render("Sound : off", True, (255,0, 0)),(350,200)) #else: #screen.blit(self.font.render("Sound : off", True, (255,255, 255)),(350,200)) if self.config['resolution'] == 0: if self.selection == 2: screen.blit( self.font.render("Resolution : 800*600", True, (255, 0, 0)), (350, 250)) else: screen.blit( self.font.render("Resolution : 800*600", True, (255, 255, 255)), (350, 250)) else: if self.selection == 2: screen.blit( self.font.render("Resolution : 800*500", True, (255, 0, 0)), (350, 250)) else: screen.blit( self.font.render("Resolution : 800*500", True, (255, 255, 255)), (350, 250)) if self.config['fullscreen'] == 0: if self.selection == 3: screen.blit( self.font.render("Fullscreen : off", True, (255, 0, 0)), (350, 300)) else: screen.blit( self.font.render("Fullscreen : off", True, (255, 255, 255)), (350, 300)) else: if self.selection == 3: screen.blit( self.font.render("Fullscreen : on", True, (255, 0, 0)), (350, 300)) else: screen.blit( self.font.render("Fullscreen : on", True, (255, 255, 255)), (350, 300)) if self.selection == 4: screen.blit(self.font.render("go back", True, (255, 0, 0)), (350, 350)) else: screen.blit( self.font.render("go back", True, (255, 255, 255)), (350, 350)) if pygame.key.get_pressed()[K_ESCAPE]: self.menustatus = 0 pygame.display.flip()
def save_policy(policy, name=POLICY_FILE): file = open(name, 'wb') pickle.Pickler(file).dump(policy)
def save_state(state, filename): p = pickle.Pickler( compress.open(filename + compress_suffix, 'wb', **compress_kwargs)) p.fast = True p.dump(state)
raw_data_distrib[val.astype(int)] = c raw_data_distrib = raw_data_distrib / len(snv_table_nona) est_distrib = new_est.xi.dot(new_est.pi).dot(new_est.mu_matrix) overall_profile_dist = score_sig_1A_base(raw_data_distrib, est_distrib) metrics_list.append([ new_est.J, lr, pval, clonal_phi, clonal_xi, nb_mut_clonal, largest_subclonal_phi, largest_subclonal_xi, nb_mut_largest_subclonal, clonal_largest_sub_pidist, largest_pi_dist, overall_profile_dist, end - start ]) with open( '{}/{}/{}_clonesig_raw_results_restr_curated'.format( tcga_folder, patient_id, folder_type), 'wb') as raw_res: my_pickler = pickle.Pickler(raw_res) my_pickler.dump([new_est, lr, pval, cst_est, fitted_sigs]) id_cols = [ 'patient_id', 'mutation_set', 'cancer_loc', 'cosmic_type', 'prop_diploid', 'ploidy', 'purity', 'nb_mut', 'nb_sigs', 'nb_sigs_prefit', 'major_cn_mean', 'total_cn_mean', 'method', 'prefit_bool', 'sigprofiler_bool', 'dof' ] metrics_cols = [ 'nb_clones', 'lr', 'pval', 'clonal_phi', 'clonal_xi', 'nb_mut_clonal', 'largest_subclonal_phi', 'largest_subclonal_xi', 'nb_mut_largest_subclonal', 'clonal_largest_sub_pidist', 'largest_pi_dist', 'overall_profile_dist', 'runtime' ] id_df = pd.DataFrame(id_list, columns=id_cols) metrics_df = pd.DataFrame(metrics_list, columns=metrics_cols)
def main() : nbL=0 secureDel('dist2.txt',FILE_TYPE,False) with open ('nbLines.txt','r') as f : ln=f.read() tab=ln.strip().split(':') nbL=int(tab[1]) printLog("nbL = ", nbL) listDotsLines=[] for i in range(nbL) : HL=[] frmName='./Lines/Line' +str(i+1)+'.jpg' img=cv2.imread(frmName, 0) points=calcul_centers(img,echo=False)[0] rows,cols=img.shape imgName="./Lines/frames/inverted_"+str(i+1)+".jpg" erodInvert(img, ks1=(1,400), ks2=(0,0), invName=imgName) img2=cv2.imread(imgName, 0) # convert the grayscale image to binary image ret,thresh = cv2.threshold(img2, 127, 255, 0) # find contour in the binary image contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) #printLog("nb contours : ",len(contours)) for c in contours : x,y,w,h = cv2.boundingRect(c) y0=int(y+(h//2)) line0=((0,y0),(cols,y0)) HL.append(line0) points2=[] for p in points : yp=selectLine(HL,p,Y_AXIS) points2.append((p[0],yp)) # drawDotsLines(frmName, points2, HL,(i+1)) frmName=drawDotsLines(frmName, points2, None,(i+1)) img1=cv2.imread(frmName,0) # imvName='./Lines/frames/inverted_' +str(i+1)+'.jpg' imgName='./Lines/frames/vertical_' +str(i+1)+'.jpg' # VerticalMask(img1, ks1=(50,1),ks2=(5,1), # invName=imvName,dilName=imgName) erodInvert(img1, ks1=(100,3), ks2=(0,0), invName=imgName) k=cv2.imread(imgName,0) ret,thresh = cv2.threshold(k,127,255,0) contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) #printLog("nb contours : ",len(contours)) v_lines=[] for c in contours : x,y,w,h = cv2.boundingRect(c) xL=int(x+(w//2)) v_lines.append(((xL, 0),(xL, rows))) v_lines.sort() points3=[] for p in points2 : xp=selectLine(v_lines,p,X_AXIS) points3.append((xp,p[1])) frmName=drawDotsLines(frmName, points3, v_lines,(i+1)) dL=DotsLines(i+1, points3, HL, v_lines) listDotsLines.append(dL) writeDist(v_lines,sign="line "+str(i+1)+" : \n") with open('dLdata','wb') as dLfile : dLPickler=pickle.Pickler(dLfile) dLPickler.dump(listDotsLines)
def sauvegardeScore(): with open("F:/bureau/Python/tp/ZEPendu/donnee/MeilleurScore.flo", 'wb') as fichier: monPickle = pickle.Pickler(fichier) monPickle.dump(MeilleurScore)
lemmat.remove(val) elif val == '-': lemmat.remove(val) i = 0 try: while i < len(lemmat): if doc[p][i].isdigit() == False and doc[p][i] != lemmat[i]: doc[p][i] = lemmat[i] i += 1 except: doc[p] = doc[p] lemmat = [] p += 1 with open('liste_msg', 'wb') as file: liste_msg = pickle.Pickler(file) liste_msg.dump(doc) counting = len(dicti) frequency = defaultdict(int) for texte in doc: doublons(texte) for token in texte: frequency[token] += (1 * 100) / counting frequency[token] = round(frequency[token], 3) if frequency[token] > 30: if token not in base: base.append(token) marshal.dump(base, open("list_base", 'wb'))
def update(let, num, val): loc = let + str(num) db[loc] = UmatiVendDB.VendItem("", loc, res) def getRange(let): if (let in fivers): return range(1, 6) elif (let in tenners): return range(1, 11) else: raise Exception("F****D") for let in fivers + tenners: print("Set one value for all of row %s?" % let) res = sys.stdin.readline() if (res.lower().strip() in ["yes", "y"]): print("What value for row %s?" % let) res = int(sys.stdin.readline()) for num in getRange(let): update(let, num, res) else: for num in getRange(let): print("Whats the value for %s%d?" % (let, num)) res = int(sys.stdin.readline()) update(let, num, res) p = pickle.Pickler(open(path, 'wb')) p.dump(db)
def saveHighscore(score): fichier_scores = open("highscoreFolder", "wb") mon_pickler = pickle.Pickler(fichier_scores) mon_pickler.dump(score) fichier_scores.close()
def enregistrer_labyrinthe(self): """Enregistrer le status du labyrinthe""" with open(self._chemin, 'wb') as fichier: mon_pickler = pickle.Pickler(fichier) mon_pickler.dump(self)
def write(self, chemin_du_fichier, contenu): with open(chemin_du_fichier, 'wb') as fichier: pickler = pickle.Pickler(fichier) contenu = pickler.dump(contenu)
def enregistrer_scores(scores): fichier_scores = open(nom_fichier_scores, "wb") mon_pickler = pickle.Pickler(fichier_scores) mon_pickler.dump(scores) fichier_scores.close()
def save(self): with open(self.path, "wb") as save_perso: pickle.Pickler(save_perso).dump(self.pos) self.inventaire.save()
def __init__(self, filename): self.f = open(filename + ".pkl", "wb") self.pkl = pickle.Pickler(self.f, protocol=2) self.filename = filename self.oracle_test_data = {}
def main_voronoi(): size_grid = 100 density = 1 grid_step = 1 affichage = 'Polygone' delaunay = delaunay_gen(size_grid, density, grid_step) ## return delaunay ## gcfm = GetColorFromMap(size_grid) ## if affichage == 'Polygone' or affichage == 'Polygone2': gcfm = GetColorFromMap(size_grid) ####plt.figure() fig = plt.figure() ax = fig.add_subplot(111) if 1: for delau_point in delaunay.Liste: if affichage == 'Point': print("point") x = empty(0) y = empty(0) for bary in delau_point.Bary: x = hstack((x, bary.Pos[0][0])) y = hstack((y, bary.Pos[0][1])) try: x = hstack((x, x[0])) y = hstack((y, y[0])) ax.plot(x, y) except: print('x = %s, y = %s' % (x, y)) elif affichage == 'Polygone': nverts = len(delau_point.Bary) + 1 verts = empty((0, 2)) for bary in delau_point.Bary: verts = vstack((verts, bary.Pos)) try: ## if 1 : verts = vstack((verts, verts[0, :])) verts[verts[:, 0] <= 0, 0] = 0 verts[verts[:, 1] <= 0, 1] = 0 verts[verts[:, 0] > size_grid, 0] = size_grid verts[verts[:, 1] > size_grid, 1] = size_grid codes = ones(nverts, int) * Path.LINETO codes[0] = Path.MOVETO codes[nverts - 1] = Path.CLOSEPOLY path = Path(verts, codes) ind = delau_point.indice arg_color = delaunay.rand_pts[ind] if arg_color[0] < 0: arg_color[0] = 0 if arg_color[1] < 0: arg_color[1] = 0 color = gcfm.get_color(arg_color) patch = patches.PathPatch(path, facecolor=color, edgecolor='none') ax.add_patch(patch) except: print( '!!!!!!!!!! attention !!!!!!!!!!! \n poly_position= %s' % verts) elif affichage == 'Polygone2': point_water_array = empty((0, 2)) for point in delaunay.Liste: arg_color = delaunay.rand_pts[point.indice] if arg_color[0] < 0: arg_color[0] = 0 if arg_color[1] < 0: arg_color[1] = 0 # define water of point point.water = gcfm.iswater(arg_color) ## print('water : ' + str(point.water)) if point.water == 0: point_water_array = vstack((point_water_array, arg_color)) for point in delaunay.Liste: for bary in point.Bary: if bary.pos[0][0] < 0: bary.pos[0][0] = 0 if bary.pos[0][1] < 0: bary.pos[0][1] = 0 if bary.pos[0][0] > size_grid: bary.pos[0][0] = size_grid if bary.pos[0][1] > size_grid: bary.pos[0][1] = size_grid dist_from_ocean = sqrt(amin((point_water_array[:,0]-bary.pos[0][0])**2 + \ (point_water_array[:,1]-bary.pos[0][1])**2)) bary.altitude = dist_from_ocean delaunay, max_altitude = norm_altitude(delaunay) show_polygones(delaunay, size_grid, gcfm) plt.xlim([0, size_grid]) plt.ylim([0, size_grid]) plt.show() plt.pause(60) fichier_nom = ("fichier_delaunay%sx%s.txt" % (size_grid, size_grid)) mon_fichier = open(fichier_nom, "w") with open('donnees', 'wb') as fichier: mon_pickler = pickle.Pickler(fichier) mon_pickler.dump(delaunay)