def gather_votes(): votelist = [] with open('temp/Blockchain.dat', 'rb') as blockfile: gen = pickle._load(blockfile) while True: try: block = pickle._load(blockfile) votelist.extend(block.data) except EOFError: break return votelist
def grabTree(filename): """从文件中读取决策树""" import pickle # open(filename,'r') 报如下错误: # UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte # 解决办法:open(filename,'rb') with open(filename, 'rb') as file: return pickle._load(file)
def load(file): try: return pickle.load(file) except: if is_py3: file.seek(0, 0) return pickle._load(file) raise
def GetClassScheduleList(): myClassScheduleFile = Path("..\Files\ClassScheduleFile.pickle") if myClassScheduleFile.is_file(): #the file exists with open("..\Files\ClassScheduleFile.pickle", "rb") as classScheduleFile: #Show File Information classScheduleList = pickle._load(classScheduleFile) return classScheduleList return [] #If the file does not exist, an empty list is created
def setdata(self): self.comboBox.clear() #设置之前先清空,避免形成追加 try: with open("INFOS.dat", "rb") as f: data = pickle._load(f) self.comboBox.addItems([each for each in data]) except: self.comboBox.insertItem(0, self.tr("默认选项"))
def GetTeacherList(): # Path: Displays the file path myTeacherFile = Path("..\Files\TeacherFile.pickle") if myTeacherFile.is_file(): #the file exists with open("..\Files\TeacherFile.pickle", "rb") as teacherFile: teacherList = pickle._load(teacherFile) #Show File Information return teacherList return [] #If the file does not exist, an empty list is created
def GetStudenList(): # Path: Displays the file path myStudentFile = Path("..\Files\StudentFile.pickle") if myStudentFile.is_file(): #the file exists with open("..\Files\StudentFile.pickle", "rb") as studentFile: studentList = pickle._load(studentFile) #Show File Information return studentList return [] #If the file does not exist, an empty list is created
def GetCourseList(): # Path: Displays the file path myCourseFile = Path("..\Files\CourseFile.pickle") if myCourseFile.is_file():#the file exists with open("..\Files\CourseFile.pickle", "rb") as courseFile: courseList = pickle._load(courseFile)#Show File Information return courseList return []#If the file does not exist, an empty list is created
def load_object(self, fname): try: fname = self.get_filename(fname) # print("Loading object from", fname) with open(fname, 'rb') as file: x = pickle._load(file) return x except IOError: return None
def GetAdministratorLogin(): #Path: Displays the file path myAdministratorLogin = Path("..\Files\AdministratorFile.pickle") if myAdministratorLogin.is_file(): #If the file exists with open("..\Files\AdministratorFile.pickle", "rb") as administratorFile: #Show File Information administratorLogin = pickle._load(administratorFile) return administratorLogin return [] #If the file does not exist, an empty list is created
def get_result(adminsk): votelist = [] with open('temp/Blockchain.dat', 'rb') as blockfile: gen = pickle._load(blockfile) while True: try: block = pickle._load(blockfile) votelist.extend(block.data) except EOFError: break candy = [] for vote in votelist: votedata_key = bytes(vote['Key'], 'utf-8') aeskey = enc.decrypt(adminsk, votedata_key) unlocked = aes.decrypt(bytes(vote['Vote Data'], 'utf-8'), aeskey) unlocked = str(unlocked)[2:-1] votedata = unlocked.split('***') votedata[1] = int(votedata[1]) candy.append(votedata[1]) return candy
def read_data(path): """Reads data from .pickle file. Args: path: Path tp .pickle file to read. Returns: Python object. """ with _BytesIO(_tf.io.read_file(path).numpy()) as file: return _load(file)
def tau_plots(): results = pickle._load(open("tau_variations.pkl", "rb")) fig_tau, axs_tau = plt.subplots(4, sharex=True, sharey=True) fig_tau.set_size_inches(10, 20, forward=True) fig_tau.suptitle("Exploring the tau-parameter", fontsize=20) for i, key in enumerate(sorted(results)): axs_tau[i].plot(results[key]) axs_tau[i].set_title(key) axs_tau[i].set_ylabel("Steps") axs_tau[-1].set_xlabel("Episodes") fig_tau.savefig("tau_variations.png")
def display(self): # for block in self.chain: # print("Block Height: ", block.height) # print("Data in block: ", block.data) # print("Merkle root: ", block.merkle) # print("Difficulty: ", block.difficulty) # print("Time stamp: ", block.timeStamp) # print("Previous hash: ", block.prevHash) # print("Nonce: ", block.nonce) # print("\t\t\t|\n|\n|\n") with open('blockchain.txt','rb') as blockfile: data = pickle._load(blockfile) return data
def weights_plots(): results = pickle._load(open("weights_variations.pkl", "rb")) fig_w, axs_w = plt.subplots(3, sharex=True, sharey=True) fig_w.set_size_inches(10, 20, forward=True) fig_w.suptitle("Exploring the weights initialization", fontsize=20) for i, key in enumerate(results): axs_w[i].plot(results[key]) axs_w[i].set_title(key) axs_w[i].set_ylabel("Steps") axs_w[-1].set_xlabel("Episodes") fig_w.savefig("weights_variations.png")
def lambda_plots(): results = pickle._load(open("lambda_variations.pkl", "rb")) fig_lamb, axs_lamb = plt.subplots(3, sharex=True, sharey=True) fig_lamb.set_size_inches(10, 20, forward=True) fig_lamb.suptitle("Exploring the lambda-parameter", fontsize=20) for i, key in enumerate(sorted(results)): axs_lamb[i].plot(np.mean(results[key], axis=0)) axs_lamb[i].set_title(key) axs_lamb[i].set_ylabel("Steps") axs_lamb[-1].set_xlabel("Episodes") fig_lamb.savefig("lambda_variations.png")
def run(self): # 网站名称为空的时候不读取文件 if self.webname == "": self.text_signal.emit("网站名称栏是空白,没有信息可以保存!") else: # 如果文件不存在则读取会报错,所以用try,如果不存在则创建一个文件 try: with open("INFOS.dat", "rb") as f: data = pickle._load(f) except: with open("INFOS.dat", "wb") as f: data = "" # 是字典类型就追加数据,否则就重建数据 if isinstance(data, dict): if self.webname in data: self.text_signal.emit("网站【{}】在原数据中有记录,现在更新数据...".format( self.webname)) else: self.text_signal.emit("网站【{}】在原数据中没有记录,现在追加数据...".format( self.webname)) info = {} info["weblink"] = self.weblink info["pattern"] = self.pattern info["start_url"] = self.start_url info["end_url"] = self.end_url info["pd"] = self.pd data[self.webname] = info with open("INFOS.dat", "wb") as f: pickle._dump(data, f) self.text_signal.emit("更新数据完成!") else: self.text_signal.emit("读取数据失败,可能是信息文件被破坏,现在新建数据...") data = {} info = {} info["weblink"] = self.weblink info["pattern"] = self.pattern info["start_url"] = self.start_url info["end_url"] = self.end_url info["pd"] = self.pd data[self.webname] = info with open("INFOS.dat", "wb") as f: pickle._dump(data, f) self.text_signal.emit("新建数据完成!") # 把所有的网站名称添加到下拉框中 self.combo_signal.emit()
def display(): #--print the information of blocks of the blockchain in the console try: with open('temp/Blockchain.dat', 'rb') as blockfile: for block in range(len(EVoting.chain)): data = pickle._load(blockfile) #--print all data of a block print("Block Height: ", data.height) print("Data in block: ", data.data) print("Number of votes: ", data.number_of_votes) print("Merkle root: ", data.merkle) print("Difficulty: ", data.DIFFICULTY) print("Time stamp: ", data.timeStamp) print("Previous hash: ", data.prevHash) print("Block Hash: ", data.hash) print("Nonce: ", data.nonce, '\n\t\t|\n\t\t|') except FileNotFoundError: print("\n.\n.\n.\n<<<File not found!!>>>")
def run(self): try: with open("INFOS.dat", "rb") as f: data = pickle._load(f) except: self.text_signal.emit("数据文件缺失,无法读取配置!") else: if self.webname in data: try: infos = data[self.webname] link = infos["weblink"] pattern = infos["pattern"] start_url = infos["start_url"] end_url = infos["end_url"] pd = infos["pd"] lis = [pattern, start_url, end_url, pd, link, self.webname] self.infos_signal.emit(lis) except: self.text_signal.emit("数据文件信息错误,无法生存配置!") else: self.text_signal.emit("数据文件中没有{}网址的信息,无法进行配置".format( self.webname))
def vector_field_plots(): results = pickle._load(open("vector_fields2.pkl", "rb")) fig, axs = plt.subplots(3, sharex=True, sharey=True) fig.set_size_inches(10, 20, forward=True) fig.suptitle("Exploring the vector fields", fontsize=20) x = np.linspace(-150, 30, 20) dx = np.linspace(-15, 15, 20) u, v = np.meshgrid(x, dx) for i, key in enumerate(results): dummy = np.zeros((results[key][0].shape[0], results[key][0].shape[1])) axs[0].quiver(u, v, results[key][0], dummy) axs[0].set_title("Trial no 1") axs[1].quiver(u, v, results[key][20], dummy) axs[1].set_title("Trial no 20") axs[2].quiver(u, v, results[key][99], dummy) axs[2].set_title("Trial no 100") fig.savefig("vector_fields.png")
def load(f, **kwargs): return _load(f)
print(list(zip("xyz", "ijk"))) print('-' * 30, "↑내장함수↑", '-' * 30) print('-' * 30, "↓외장함수↓", '-' * 30) #pickle:객체 상태를 유지하면서 파일 입출력 모듈 #dump함수를 이용... import pickle f = open("sleep.txt", "wb") data = {1: "big", 2: "data"} #f.write(data) pickle.dump(data, f) f.close() f = open("sleep.txt", "rb") data = pickle._load(f) print(data) import glob print(glob.glob("d*")) import random print(random.random()) for i in range(1, 7): print(random.randint(1, 46)) # a=set([1,2,2,3,2]) # print(len(a)) #정규표현식:일정 규칙을 갖는 문자열을 표현하는 방법,(정규식) #REGular EXpression;REDEX
@app.route('/thanks', methods = ['GET']) def thank(): return render_template('home.html') EVoting = Blockchain() EVoting.addGenesis() if __name__ == '__main__': app.run(port = 5000) # data = EVoting.display() # print(data) <<<<<<< HEAD with open('blockchain.txt','rb') as blockfile: for i in range(len(EVoting.chain)-1): data = pickle._load(blockfile) print("Block Height: ", data.height) print("Data in block: ", data.data) print("Merkle root: ", data.merkle) print("Difficulty: ", data.difficulty) print("Time stamp: ", data.timeStamp) print("Previous hash: ", data.prevHash) print("Nonce: ", data.nonce) ======= with open('blockchain.txt','rb') as blockfile: data = pickle._load(blockfile) data2 = pickle._load(blockfile)
def __init__(self): self.name = "ql" f = open("train_ql.pkl", "rb") #学習済みデータを読み込む self.q_as = pickle._load(f) f.close()
6: 61., 7: 57., 8: 57., 9: 63., 10: 66., 11: 66., 12: 66., 13: 66., 14: 64. } if os.path.exists(FILENAME) and os.path.isfile(FILENAME) and os.path.exists(EPOCHS_FILENAME) and os.path.isfile(EPOCHS_FILENAME): #Load previous model and continue training model = load_model(FILENAME) score = model.evaluate(x_test, y_test, verbose=0) initial_epochs = pickle._load(open( EPOCHS_FILENAME, "rb" )) print("Initial network accuracy: %.2f%%, loss: %.4f, epochs: %5d " % (score[1] * 100, score[0], initial_epochs)) else: # Create new model model = Sequential() model.add(Dense(3032, activation="sigmoid", input_dim=90, name="input")) model.add(Dense(15, activation='softmax', name="output")) model.compile(loss='categorical_crossentropy', optimizer="adadelta", metrics=['accuracy']) initial_epochs = 0 model.fit(x_train, y_train, batch_size=100000, epochs=TOTAL_EPOCHS, verbose=0, validation_data=(x_test, y_test), class_weight = class_weight,
def load(): from pickle import load as _load with open(path, 'rb') as f: return _load(f)
#=========================================================================""" # define an employee class import pickle class Employee: def __init__(self, eno, name, sal, addr): self.eno = eno self.name = name self.sal = sal self.addr = addr def display(self): print(" Employee no ", self.eno) print("Employee name ", self.name) print("Salary ", self.sal) print("Address ", self.addr) # Pickling - Create a emp data file to dump the object f = open("emp.dat", 'wb') e1 = Employee(100, "Praveen", 10000, "Hyd") pickle._dump(e1, f) print("Pickling of employee object done successfully") f.close() # Unpickling - Read the data file using load() f = open("emp.dat", 'rb') obj = pickle._load(f) print("Employee Object Contents ") print(obj.display())
use_mad_CO = True fLine = 'line_from_six_with_bbCO.pkl' if use_mad_CO: fParticleCO = 'particle_on_CO_mad_line.pkl' else: fParticleCO = 'particle_on_CO_six_line.pkl' # Load machine with open(fLine, 'rb') as fid: line = pysixtrack.Line.from_dict(pickle.load(fid)) # Load particle on CO with open(fParticleCO, 'rb') as fid: part_on_CO = pysixtrack.Particles.from_dict(pickle._load(fid)) # Load iconv with open('iconv.pkl', 'rb') as fid: iconv = pickle.load(fid) # Load sixtrack tracking data sixdump_all = sixtracktools.SixDump101('sixtrack/res/dump3.dat') # Assume first particle to be on the closed orbit Nele_st = len(iconv) sixdump_CO = sixdump_all[::2][:Nele_st] # Compute closed orbit using tracking closed_orbit = line.track_elem_by_elem(part_on_CO) # Check that closed orbit is closed
import pickle from dataset import importCSV data = importCSV() pickle.dump(data, open( "data/sensors.pkl", "wb" )) data = pickle._load(open( "data/sensors.pkl", "rb" )) x_train, x_test, y_train, y_test = data print(x_train.head())
def load_data(): f = gzip.open("./data/mnist.pkl.gz", "rb") traning_data, validation_data, test_data = pickle._load(f, encoding="latin1") f.close() return (traning_data, validation_data, test_data)
if vis: cv2.imwrite('result/result' + str(i) + '.png', im2show) # pdb.set_trace() # cv2.imshow('test', im2show) # cv2.waitKey(0) with open(det_file, 'wb') as f: pickle.dump(all_boxes, f, pickle.HIGHEST_PROTOCOL) print('Evaluating detections') imdb.evaluate_detections(all_boxes, output_dir) # imdb.evaluate_detections(all_boxes, output_dir) end = time.time() print("test time: %0.4fs" % (end - start)) else: all_boxes = [] if os.path.exists(det_file): print(det_file + " exit!") with open(det_file, 'rb') as fp: all_boxes = pickle._load(fp) print('Evaluating detections') imdb.evaluate_detections(all_boxes, output_dir) # imdb.evaluate_detections(all_boxes, output_dir) end = time.time() print("test time: %0.4fs" % (end - start))
__author__ = 'Matteo' __doc__='''This script is a sandbox.''' #interpreter change. import csv import pickle from Bio import SeqIO from Bio import Entrez file=open('geneX_pickled.dat','rb') gene=pickle._load(file) print(len(gene.keys()))
import pickle import numpy as np import pysixtrack import sixtracktools # Load machine with open('line.pkl', 'rb') as fid: line = pysixtrack.Line.from_dict(pickle.load(fid)) # Load particle on CO with open('particle_on_CO.pkl', 'rb') as fid: part_on_CO = pysixtrack.Particles.from_dict( pickle._load(fid)) # Load iconv with open('iconv.pkl', 'rb') as fid: iconv = pickle.load(fid) # Load sixtrack tracking data sixdump_all = sixtracktools.SixDump101('res/dump3.dat') # Assume first particle to be on the closed orbit Nele_st = len(iconv) sixdump_CO = sixdump_all[::2][:Nele_st] # Compute closed orbit using tracking closed_orbit = line.track_elem_by_elem(part_on_CO) # Check that closed orbit is closed pstart = closed_orbit[0].copy()