Best Python code snippet using stestr_python
firebase.py
Source:firebase.py
1import time2import datetime3import csv4import copy5import threading6import firebase_admin7from firebase_admin import credentials8from firebase_admin import db9from firebase_admin import auth10import requests11from bs4 import BeautifulSoup12import re13class Firebase:14 def __init__(self):15 self.JST = datetime.timezone(datetime.timedelta(hours =+ 9), 'JST')16 self.TERMINAL = { 3 : 'ç²¾ç®æ©',17 4 : 'æºå¸¯ç«¯æ«',18 5 : 'è»è¼ç«¯æ«',19 7 : 'å¸å£²æ©',20 8 : 'å¸å£²æ©',21 9 : 'å
¥éæ©',22 18 : 'å¸å£²æ©',23 20 : 'å¸å£²æ©ç',24 21 : 'å¸å£²æ©ç',25 22 : 'æ¹ææ©',26 23 : 'ç°¡ææ¹ææ©',27 24 : 'çªå£ç«¯æ«',28 25 : 'çªå£ç«¯æ«',29 26 : 'æ¹æ端æ«',30 27 : 'æºå¸¯é»è©±',31 28 : 'ä¹ç¶ç²¾ç®æ©',32 29 : 'é£çµ¡æ¹ææ©',33 31 : 'ç°¡æå
¥éæ©',34 70 : 'VIEW ALTTE',35 72 : 'VIEW ALTTE',36 199 : 'ç©è²©ç«¯æ«',37 200 : 'èªè²©æ©'}38 self.parseCSV()39 self.cred = credentials.Certificate('./nfc-history-firebase-adminsdk.json')40 firebase_admin.initialize_app(self.cred, {41 'databaseURL' : 'https://nfc-history.firebaseio.com/'42 })43 44 self.usersRef = db.reference('users/')45 self.getUsersData()46 if not isinstance(self.usersData, dict):47 self.usersData = {}48 49 self.devicesRef = db.reference('devices')50 self.getDevicesData()51 if not isinstance(self.devicesData, dict):52 self.devicesData = {}53 54 def __del__(self):55 self.updateDB()56 57 def __threadInit(self):58 self.thread = threading.Thread(target = self.__run)59 self.thread.daemon = True60 self.thread.start()61 62 def __run(self):63 thread = threading.Timer(10, __run)64 thread.start()65 66 self.refreshDB()67 68 def parseCSV(self):69 file = open('./StationCode.csv', 'r')70 71 dataReader = csv.reader(file)72 self.stationInfo = {}73 array = []74 ar = []75 header = next(dataReader)76 77 for row in dataReader:78 if not row[0] in array:79 array.append(row[0])80 self.stationInfo[int(row[0])] = {}81 ar = []82 if not row[1] in ar:83 ar.append(row[1])84 self.stationInfo[int(row[0])][int(row[1])] = {}85 self.stationInfo[int(row[0])][int(row[1])][int(row[2])] = {86 'CompanyName' : row[3],87 'LineName' : row[4],88 'StationName' : row[5]89 }90 91 file.close()92 93 def updateDB(self):94 self.usersRef.update(self.usersData)95 self.devicesRef.update(self.devicesData)96 97 def refreshDB(self):98 #self.updateDB()99 self.getUsersData()100 self.getDevicesData()101 102 def getUsersData(self):103 self.usersData = copy.deepcopy(self.usersRef.get())104 105 def getDevicesData(self):106 self.devicesData = copy.deepcopy(self.devicesRef.get())107 108 def setChipID(self, chipID, email):109 self.refreshDB()110 if not chipID in self.devicesData:111 user = auth.get_user_by_email(email)112 print(user.uid)113 self.devicesData[chipID] = user.uid114 self.updateDB()115 116 def updateBalance(self, chipID, idm, balance):117 self.refreshDB()118 uid = self.devicesData[chipID]119 120 if not uid in self.usersData:121 self.usersData[uid] = {}122 if not 'card_info' in self.usersData[uid]:123 self.usersData[uid]['card_info'] = {}124 if not idm in self.usersData[uid]['card_info']:125 self.usersData[uid]['card_info'][idm] = {}126 if not 'card_list' in self.usersData[uid]:127 self.usersData[uid]['cars_list'] = []128 self.usersData[uid]['card_list'].append(idm)129 if not 'info' in self.usersData[uid]['card_info'][idm]:130 self.usersData[uid]['card_info'][idm]['info'] = {131 'balance' : 0,132 'lastUpdate' : 0,133 'read' : 0,134 'rides' : 0,135 'usage' : 0136 }137 self.usersData[uid]['card_info'][idm]['info']['balance'] = balance138 self.usersData[uid]['card_info'][idm]['info']['lastUpdate'] = datetime.datetime.fromtimestamp(time.time(), self.JST).strftime("%Y/%m/%d %H:%M:%S")139 self.usersData[uid]['card_info'][idm]['info']['read'] += 1140 self.updateDB()141 142 def updateHistory(self, chipID, idm, history):143 self.refreshDB()144 uid = self.devicesData[chipID]145 146 if not 'history_arry' in self.usersData[uid]['card_info'][idm]:147 self.usersData[uid]['card_info'][idm]['history_arry'] = []148 149 if not str(history) in self.usersData[uid]['card_info'][idm]['history_arry']:150 cp_history = history151 history_list = []152 153 for i in range(16):154 history_list.append(cp_history % 0x100)155 cp_history = cp_history >> 8156 print('{:X}'.format(history_list[i]))157 158 if history_list[14] == 1:159 self.usersData[uid]['card_info'][idm]['history_arry'].append(str(history))160 terminal = self.TERMINAL[history_list[15]]161 process = 'éè³æ¯æ'162 163 year = (history_list[11] >> 1) + 2000164 month = ((history_list[11] & 1) << 3) | (history_list[10] >> 5)165 day = history_list[10] & 0b11111166 167 date = str(year) + '/' + str(month) + '/' + str(day)168 enterRegion = history_list[0] >> 6169 print(history_list[0])170 enter = self.stationInfo[enterRegion][history_list[9]][history_list[8]]['StationName']171 exitRegion = (history_list[0] >> 4) & 0b11172 exit_ = self.stationInfo[exitRegion][history_list[7]][history_list[6]]['StationName']173 usage = self.scripeUsage(enter, exit_)174 self.usersData[uid]['card_info'][idm]['info']['usage'] += usage175 self.usersData[uid]['card_info'][idm]['info']['rides'] += 1176 print(enter, exit_, usage)177 #print(date, enterRegion, exitRegion, history_list[9], history_list[8], history_list[7], history_list[6])178 if usage != -1:179 historyInfo = {180 'terminal' : terminal,181 'process' : process,182 'date' : date,183 'enter' : enter,184 'exit' : exit_,185 'usage' : usage186 }187 if not 'history_info' in self.usersData[uid]['card_info'][idm]:188 self.usersData[uid]['card_info'][idm]['history_info'] = []189 self.usersData[uid]['card_info'][idm]['history_info'].insert(0, historyInfo)190 self.updateDB()191 192 def scripeUsage(self, from_, to):193 targetUrl = "https://transit.yahoo.co.jp/search/result?from=" + from_ + "&to=" + to + "&type=5&ticket=ic&s=1"194 r = requests.get(targetUrl)195 if not r.ok:196 return -1197 soup = BeautifulSoup(r.text, 'html.parser')198 raw = soup.find(class_='fare').find(class_='mark').get_text()199 return int(re.findall('[0-9 | ,]+', raw)[0].replace(',', ''))200 201 def test(self, chipID, idm, history):202 self.testData[history] = {203 'chipID' : chipID,204 'idm' : idm205 }206 self.testRef.update(self.testData)207if __name__ == '__main__':208 firebase = Firebase()209 #firebase.updateBalance('111111', 999, str(1145141919810000))210 firebase.updateHistory('111111', str(1145141919810000), 0x160100022754A556A5AC8E0000010450)...
history_.py
Source:history_.py
1import pandas as pd2import numpy as np3import matplotlib.pyplot as plt4import seaborn as sns5import math6plt.rc('font', family='Times New Roman')7font_size = 168def plot_metric_df(history_list, task_name, val_flag='test_'):9 if 'relapse_risk' in task_name:10 metric_list = ['loss', 'f1']11 else:12 metric_list = ['r2', 'mae', 'mse']13 fig = plt.figure(figsize=(20, 4))14 L = len(metric_list)15 row = math.floor(math.sqrt(L))16 col = L / row17 for i, metric in enumerate(metric_list):18 plt.subplot(row, col, i+1)19 show_metric(history_list, metric, val_flag)20 fig.subplots_adjust(top=0.8)21 legend_labels = ['ours',22 # 'enh_nonrelapse',23 'ATT+MLP',24 # 'vanilla_nonrelapse',25 'LGB',26 # 'lightgbm_nonrelapse',27 'Lasso',28 # 'lasso_nonrelapse'29 ]30 plt.legend(labels= legend_labels,31 ncol = len(legend_labels),32 # loc='best', 33 loc='upper center', 34 fontsize=14,35 bbox_to_anchor=(-1.2, 1, 1, 0.2),36 borderaxespad = 0.,37 )38 # plt.title('{} {}'.format(task_name, metric), fontsize=font_size)39def show_metric(history_list, metrics_name, val_flag=''):40 marker_list = ['*', 'd', 's', 'x', 'o']41 metrics_name_dict = {'r2':'R-square', 'mae':'mean absolute error', 'mse':'mean squared error'}42 for m, history in enumerate(history_list):43 history_metric = history.filter(regex=r'\b{}{}\b'.format(val_flag, metrics_name))[:3000]44 plt.plot(history_metric, linestyle=':', marker=marker_list[m], linewidth=2)45 plt.xticks(range(0, 11), fontsize=font_size)46 plt.yticks(fontsize=font_size)47 plt.ylabel(metrics_name_dict[metrics_name], fontsize=font_size)48 plt.xlabel('Round', fontsize=font_size)49def plot_history_df(history_list, task_name, val_flag=''):50 if 'relapse_risk' in task_name:51 metric_list = ['loss', 'f1']52 else:53 metric_list = ['loss', 'r2']54 plt.figure(figsize=(12, 4))55 L = len(metric_list)56 row = math.floor(math.sqrt(L))57 col = L / row58 for i, metric in enumerate(metric_list):59 plt.subplot(row, col, i+1)60 show_history(history_list, metric, val_flag)61 plt.legend(labels=['attention', 'attention+mlp', 'attention+label corrected',62 'attention+mlp+label corrected(ours)', 'mlp', 'mlp+label corrected'],63 fontsize=14)64 # plt.title('{} {}'.format(metric, task_name), fontsize=font_size)65def show_history(history_list, metrics_name, val_flag=''):66 marker_list = ['^', 'd', 's', '*', 'x', 'o']67 for m, history in enumerate(history_list):68 history_metric = history.filter(regex=r'\b{}{}'.format(val_flag, metrics_name))[:3000]69 history_ = np.mean(history_metric, axis=1)70 len_ = history_.shape[0]71 plt.plot(history_, linewidth=2, marker=marker_list[m], markevery=200)72 plt.fill_between(range(len_), np.min(history_metric, axis=1), np.max(history_metric, axis=1), alpha=0.3)73 plt.xticks(fontsize=font_size)74 plt.yticks(fontsize=font_size)75 plt.ylabel(val_flag + metrics_name, fontsize=font_size)76 plt.xlabel('Epoch', fontsize=font_size)77def plot_history(history_list, task_name, val_flag=False):78 if task_name == 'relapse_risk':79 metric_list = ['loss', 'f1']80 else:81 metric_list = ['loss', 'r2']82 plt.figure(figsize=(12, 4))83 L = len(metric_list)84 for i, metric in enumerate(metric_list):85 plt.subplot(squrt(), L, i+1)86 show_train_history(history_list, metric)87 if val_flag:88 show_train_history(history_list, 'val_{}'.format(metric))89 plt.legend(labels=[metric, 'val_{}'.format(metric)], loc='upper left')90 plt.title('{} {}'.format(task_name, metric))91def history_save(history_list, history_name):92 history_all = pd.DataFrame([])93 for history in history_list:94 history_ = pd.DataFrame.from_dict(history.history, orient='index')95 history_all = pd.concat([history_all, history_], axis=0)96 history_all.to_csv('./hitory_{}.csv'.format(history_name))97def show_train_history(history_list, metrics_name):98 metrics_list = None99 for history in history_list:100 history_metric = pd.DataFrame(np.array(history.history[metrics_name]).reshape(1, -1))101 if metrics_list is None:102 metrics_list = history_metric103 else:104 metrics_list = pd.concat([metrics_list, history_metric], axis=0)105 # metrics = np.median(metrics_list, axis=0)106 metrics = np.mean(metrics_list, axis=0)107 plt.plot(metrics)108 plt.ylabel(metrics_name)...
07_most_recent_v4.py
Source:07_most_recent_v4.py
1"""Get data from user and store it in a list,2then display the most recent 3 entries3Final version based on trial #34Adds break loop and checks for empty list"""5# Set up empty list6history_list = []7# Get items of data and add to list8get_item = ''9while get_item != 'zz':10 get_item = input('Enter and item: ')11 if get_item == 'zz':12 break13 history_list.append(get_item)14print()15if len(history_list) == 0:16 print('History list is empty!')17else:18 # Show that everything made it to the list19 print()20 print('*** Full list ***')21 print(history_list)22 # Print items starting at the END of the list23 if len(history_list) >= 3:24 print('*** Most recent 3 ***')25 for item in range(3):26 print(history_list[len(history_list) - item - 1])27 else:28 print('*** Items from Newest to Oldest ***')29 for item in history_list:30 print(history_list[len(history_list) - history_list.index(item) -...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!