def _summary_table(labels, data, names=None, datafile=None, infofile=None): """ Summarize multiple parameters in a table. :returns: Table of summary statistics for particular parameters :rtype: string """ # Summarize all parameters by default if names is None: names = labels.values() # Make a string describing credible interval beta_percent = 100. * (1. - default("alpha")[1]) credible_name = "%.2g%% credible region" % beta_percent # Headings for a table headings = ["Name", "best-fit", "posterior mean", credible_name, "" ] param_table = pt(headings) param_table.align = "l" param_table.float_format = "4.2" # Make summary data and add it to table posterior = data[0] chi_sq = data[1] for key, name in labels.iteritems(): if name in names: param = data[key] param_table.add_row(_summary(name, param, posterior, chi_sq)) # Best-fit information and information about chain min_chi_sq = data[1].min() p_value = stats.p_value(data[1], default("dof")) bestfit_table = pt(header=False) bestfit_table.align = "l" bestfit_table.float_format = "4.2" bestfit_table.add_row(["File", datafile]) bestfit_table.add_row(["Info-file", infofile]) bestfit_table.add_row(["Minimum chi-squared", min_chi_sq]) bestfit_table.add_row(["p-value", p_value]) return bestfit_table.get_string() + "\n\n" + param_table.get_string()
def sta(): with open('data.json','r+') as f: x = f.readlines() l = re.findall(r'["]([0-9]*[\.]*[0-9]+)%["]',str(x)) print len(l),'data is valid for statistic.\n' counter_0 = 0 counter_1 = 0 counter_2 = 0 counter_3 = 0 counter_4 = 0 for i in range(0,len(l)): if float(l[i])<10: counter_0 = counter_0 + 1 if float(l[i])>=10 and float(l[i])<25: counter_1 = counter_1 + 1 if float(l[i])>=25 and float(l[i])<40: counter_2 = counter_2 + 1 if float(l[i])>=40 and float(l[i])<55: counter_3 = counter_3 + 1 if float(l[i])>55: counter_4 = counter_4 + 1 tb = pt(["COVERAGE RANGE","COUNT","PERCENTAGE",]) tb.align["COUNT"] = "r" tb.add_row(["x<10",counter_0,float(counter_0/len(l)*100)]) tb.add_row(["10<=x<25",counter_1,float(counter_1/len(l)*100)]) tb.add_row(["25<=x<40",counter_2,float(counter_2/len(l)*100)]) tb.add_row(["40<=x<55",counter_3,float(counter_3/len(l)*100)]) tb.add_row(["x>55",counter_4,float(counter_4/len(l)*100)]) print tb
def Euler (): TbE = pt() TbE.field_names = ["№", "x", "y", "y'=f(x,y)", "Delta(y)=y'h"] gotoxy(40, 2) SetColor(5, 15) print ('Задача: решить данное ДУ методом Эйлера') SetColor(0, 15) Form = Formula() x, y = CheckErrorFormula (Form) gotoxy(2, 7) print ('Введите шаг итерации h:') h = Enter_float (0, 2, '', 26, 7) gotoxy(2, 8) print ('Введите количество итераций:') k = Enter_int (1, 10, '', 31, 8) gotoxy(2, 9) SetColor(5, 15) print ('Решение будет производится на интервале [',x,', ',h*k+x,']') gotoxy(2, 10) print ('y(',h*k+x,') = ?\n') SetColor(0, 15) for i in range (k+1): #Цикл вычисления ДУ методом Эйлера fxy = eval (Form) dy = fxy*h TbE.add_row ([i, "%.2f" %x, "%.2f" %y, "%.5f" %fxy, "%.5f" %dy]) y += dy x += h print (TbE)
def show_movie_projections(self, *args): ''' show_movie_projections <movie_id> [<date>] - print all projections of a given movie for the given date (date is optional). ''' # print(args) tbl_headers = ['Projection_ifno'] tbl = pt(tbl_headers) tbl.align['Projection_ifno'] = 'l' cur = self.con.cursor() movie_id_sql = '''SELECT m.name, "["||p.id||"] - "||p.date||" "|| p.time||" ("||p.type||")" as p_info from movies m left join projections p on (m.id = p.movie_id) where m.id=?''' movie_and_date_sql = '''SELECT m.name, p.date, "["||p.id||"] - "|| p.time||" ("||p.type||")" as p_info from movies m left join projections p on (m.id = p.movie_id) where m.id=? and p.date =?''' try: if len(args[0]) == 1: cur.execute(movie_id_sql, (int(args[0][0]), )) result = cur.fetchall() for i in result: tbl.add_row([i[1], ]) return "\nProjections for movie '{}':\n".format(result[0][0]) + str(tbl) else: cur.execute(movie_and_date_sql, (int(args[0][0]), args[0][1])) result = cur.fetchall() for i in result: tbl.add_row([i[2], ]) return "\nProjections for movie '{}' on date {}:\n".format( result[0][0], result[0][1]) + str(tbl) except (IndexError, KeyError, ValueError): return '''
def main(): URL = "http://mail-archives.apache.org/mod_mbox/" try: fh=open('items.json') except: print "Generate items.json file first" foobar=json.loads(fh.read()) for item in foobar: if 'project' in item.keys(): print item['project'][0].upper() for list in item['list']: print list if 'ml' in item.keys(): x = pt(["Date","# Messages"," URL ", " Size"]) print item['ml'] for dt in item['datatime']: date = dt[0].split(' ')[0] url_mbox = URL + item['ml'] + date.split('-')[0] + date.split('-')[1] + ".mbox" ml_open = urllib.urlopen(url_mbox) meta = ml_open.info() ml_size = meta.getheaders("Content-Length")[0] x.add_row([date,dt[1], url_mbox, ml_size]) print x
def print_words(table): '''print words table using pretty table''' x = pt(['word', 'translation']) for line in table: x.add_row(line) print(x)
def ImprovedEuler (): TbImE = pt() TbImE.field_names = ["№", "x", "y", "f(x,y)", "x+h/2", "y+h/2*f(x,y)", "f(x+h/2, y+h/2*f(x,y))", "Delta(y)=f(x+h/2, y+h/2*f(x,y))*h"] gotoxy(35, 2) SetColor(5, 15) print ('Задача: решить данное ДУ усовершенствованным методом Эйлера') SetColor(0, 15) Form = Formula() x, y = CheckErrorFormula (Form) gotoxy(2, 7) print ('Введите шаг итерации h:') h = Enter_float (0, 2, '', 26, 7) t = len(str(h)) - str(h).index('.') - 1 Flag = False gotoxy(2, 8) print ('Введите X конечное:') while Flag == False: #Цикл проверки правильности вода x конечного ShowCursor(True) #и расчёта количества итераций k = Enter_float (x+h-0.0001, 20, '', 22, 8) sizecicle = (k - x) / h if round(k - h * round(sizecicle), t) == x: #Условие проверки правильности вода x конечного Flag = True else: ShowCursor(False) gotoxy(22, 8) print ('\t\t\t\t\t\t\t\t\t\t\t\t\t\t') gotoxy(33, 20) SetColor(4, 15) print ('Ошибка!!! Введите X конечное, соответствующее шагу итерации!') sleep(4) SetColor(0, 15) gotoxy(33, 20) print ('\t\t\t\t\t\t\t\t\t') gotoxy(2, 9) SetColor(5, 15) print ('Решение будет производится на интервале [',x,',',k,']') gotoxy(2, 10) print ('y(',k,') = ?\n') SetColor(0, 15) for i in range (round(sizecicle)+1): #Цикл вычисления ДУ усовершенствованным chx = x #методом Эйлера chy = y fxy = eval (Form) x = x+h*0.5 y = y+h*0.5*fxy xh = x yh = y fxhyh = eval (Form) x = chx y = chy dy = fxhyh*h TbImE.add_row ([i, round(x, t), round(y, t),"%.5f" %fxy, "%.5f" %xh, "%.5f" %yh, "%.5f" %fxhyh, "%.5f" %dy]) y += dy x += h print (TbImE)
def help(self): table = pt(['Command', 'Format']) table.add_row(["show_movies", 'List of Movies']) table.add_row(["show_movie_projections", "show_movie_projections <movie_id> [<date>]"]) table.add_row(["make_reservation", 'Interactive input']) table.add_row(["show_tickets", 'Interactive input <projection_id>']) table.add_row(["quit", ""]) return table
def show_movies(self): sql = "SELECT * FROM MOVIES ORDER BY `rating` DESC;" self.cur.execute(sql) table = pt(["N:", "Title", "Rating"]) for movie in self.cur.fetchall(): table.add_row([movie['id'], movie['name'], movie['rating']]) table.sortby = "N:" return table
def __init__(self, rounds): x, com_rounds, human_rounds, ties, flag = pt( ), 0, 0, 0, False # My field variables x.field_names = [ "Round number", "You played", "COM played", "Wins", "COM wins", "Ties" ] # Yhe header for my table self.flag, self.x, self.rounds, self.com_rounds, self.human_rounds, self.ties = flag, x, rounds, com_rounds, human_rounds, ties
def show_dic(sorted_dic): c = 1 product_table = pt(["s.no", "Product", "Location"]) for item in sorted_dic: #print("{}. {} {}".format(c,item[0],item[1])) product_table.add_row([c, item[0], item[1]]) c += 1 print(product_table)
def show_table(html): '''打印考试安排表。''' table = pt(["课程名称", "考试时间", "考试地点", "座位号"]) for tr in bs(html).find_all('tr')[1:]: td = tr.find_all('td') l = [x.get_text() for x in td[1:]] table.add_row([l[0], l[2], l[3], l[5]]) print(table.get_string(sortby="考试时间", reversesort=False))
def high_score(): print("\nHIGH SCORE") #buka file user_score hiscore_list = open("user_score.txt", "r") #membaca file user_score a = hiscore_list.read() #mengubah isi file user_score menjadi list, disimpan di variabel a1 a1 = a.split("\n") #menghapus isi file user_score yang mengandung spasi atau blank a1.remove("") #mengambil data username a2 = [i.split("#$", 1)[0] for i in a1] list_user = set(a2) #mengambil data score a3 = [i.split("#$", 1)[1] for i in a1] #BUAT DICTIONARY #kenapa dictionary, biar bisa memetakan score2 milik username siapa dic = {} #proses memetakan score2 yg ada ke username for x, y in zip(a2, a3): dic.setdefault(x, []).append(y) list_user = list() #proses mengambil data username utk dimasukkan ke list_user for i in dic.keys(): list_user.append(i) list_score = list() #AMBIL DATA SOCRE DIMASUKIN KE LIST_SCORE for i in dic.values(): for j in range(0, len(i)): i[j] = int(i[j]) list_score.append(max(i)) #membuat tabel high score hiscore_table = pt() #NAMBAH KOLOM USERNAME SAMA ISI USERNAME hiscore_table.add_column("Username", list_user) #NAMBAH KOLOM SKOR SAMA ISI KOLOM hiscore_table.add_column("Score", list_score) #URUTKAN TABEL DARI SKOR PALING TINGGI hiscore_table.sortby = "Score" hiscore_table.reversesort = True #TOP 10 HIGH SCORE print(hiscore_table.get_string(start=0, end=10)) hiscore_list.close()
def __init__(self, name: str, path: str) -> None: """ Initialization function for University class """ self.name: str = name os.chdir(path) # key = instructor CWID, value = respective instructor class object self.instructors: Dict[str, Instructor] = {} # key = student CWID, value = respective student class object self.students: Dict[str, Student] = {} self.p_instructors = pt() self.p_students = pt() # read in respective files self.read_students("students.txt") self.read_instructors("instructors.txt") self.read_grades("grades.txt") # have __init__ call pretty_print for students and instructors self._pretty_print_students() self._pretty_print_instructors()
def show_items(self): self.mycursor.execute("select prod_name from product_details;") avail_items=self.mycursor.fetchall() c=1 product_table=pt(["s.no","Product"]) for item in avail_items: #print("{}. {}".format(c,item[0]),end="\n") product_table.add_row([c,item[0]]) c+=1 print(product_table)
def printStudentScore(self, info, tb_name): print("".ljust(24) + tb_name.center(45, "*")) tb = pt(list(info.keys())) tb.border = False if tb_name in "总分" or tb_name in "平均分": tb.add_row(list(info.values())) else: tb.add_row([self.data["info"][str(val[1])]["姓名"] for val in info.values()]) # 先输出姓名,再输出成绩 tb.add_row([val[0] for val in info.values()]) for s in tb.get_string().splitlines(): print("".ljust(37) + s) input("".ljust(23) + ">按任意键继续<".center(43))
def show_movie_projections(self, movie_id, date=False): rows = self.set_movie_projections(movie_id, date) table = pt(["Projection ID", "Title", "Type", "Date", "Time", "Saets Available"]) i = 0 for projection in rows: table.add_row([projection['id'], projection['Title'], projection['Type'], projection['projection_date'], projection['projection_time'], "{} spots available".format( (self.col * self.row)-self.available_seats(projection['id']))]) i += 1 return table
def print_tickets(self): table = pt(["Registerd To", "Title", "Rating", "Date", "Time", "Seat Row", "Seat Col"]) for i in range(len(self.ticket["seats"])): table.add_row([self.ticket["username"], self.ticket["movie"]["Title"], self.ticket["movie"]["Rating"], self.ticket["projection_date"], self.ticket["projection_time"], self.ticket["seats"][i][0], self.ticket["seats"][i][1], ]) return table
def pprint_playlist(self): songs_tbl = pt(['Artist', 'Song', 'Length']) songs_tbl.align['Artist'] = 'l' songs_tbl.align['Song'] = 'l' for i in self.playlist1: row = [i.get_artist(), i.get_title(), i.get_length()] songs_tbl.add_row(row) songs_tbl.add_row(['', '', '']) songs_tbl.add_row(['', '', '']) songs_tbl.add_row(['', '---------------------------', '----------']) songs_tbl.add_row(['', ' Total Playlist Length ', self.total_lenght()]) return str(songs_tbl)
def print_info(): '''print date_info table''' new_info = list(date_info.keys()) new_info.sort() x = pt(['Date', 'Recite words', 'Add words', 'Del words', 'Mod words']) for key in new_info: x.add_row([ key, date_info[key]['recite_counts'], date_info[key]['add_counts'], date_info[key]['del_counts'], date_info[key]['mod_counts'] ]) print(x)
def main(url): html = urllib2.urlopen(url).read() soup = bs(html) title = soup.title.string.replace(' - YouTube','') encoded_links = re.findall(r"\"url_encoded_fmt_stream_map\":\"(.*?)\"",html)[0] encoded_links2 = re.findall(r"\"adaptive_fmts\":\"(.*?)\"",html)[0] link_list = encoded_links.split(',') ll2 = encoded_links2.split(',') for i in ll2: if '1920x1080' in i: link_list.append(i) break fin_list = [] for i in link_list: d = {'url':'','quality':'','type':''} if '1920x1080' in i: d['quality'] = '1080p' l = i.split('\u0026') for j in l: dct = j.split('=') d[dct[0]] = dct[1] fin_list.append(d) for i in fin_list: while '%25' in i['url']: i['url'] = urllib2.unquote(i['url']) i['url'] = urllib2.unquote(i['url']) # print fin_list print 'Found %d videos.' % (len(fin_list)) id = 0 table = pt(["id","quality","type","size"]) for i in fin_list: table.add_row([id,i['quality'],gettype(i['type']),prettify(getsize(i['url']))]) id += 1 print table print 'Select any one of the above videos using id:' a = int(raw_input()) # print fin_list[a] print "Preparing to download the video..." sz = getsize(fin_list[a]['url']) size = prettify(sz) dest = title+'.'+gettype(fin_list[a]['type']) dl = Thread(target=download, args=[fin_list[a]['url'],dest,sz]) dl.setDaemon(True) dl.start() progress = 0 while progress != 100: time.sleep(2) progress = 100 * os.path.getsize(dest)/float(sz) sys.stdout.write("\r [%s%s] %0.2f%% done of %s" % ("#"*int(progress/10), "-"*(10-int(progress/10)),progress,size)) sys.stdout.flush() dl.join() print '\nDownload Finished.\n'
def _print_seats(self, projection_id): sql = "SELECT * FROM Reservations WHERE projection_id = ?" self.cur.execute(sql, (projection_id,)) seats_taken = self.cur.fetchall() for place in seats_taken: self.seats[place["_row"]][place["_col"]] = 'x' t = pt([" ", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]) i = 1 for x in self.seats: t.add_row([i]+x) i += 1 return t
def cellChangeloca(oldLoca, newLoca, operator, date): with open('cell_info.json', 'r') as f: cellDic = json.load(f) tb = pt(['Cell Name', 'Old Location', 'New Location']) # 检查对应出库位置是否存在细胞 for i in range(len(oldLoca)): try: if cellDic[oldLoca[i]][0] is None: # 确认该位置是否存在细胞 print(f'{oldLoca[i]}无细胞,请检查输入信息') return elif cellDic[newLoca[i]][0]: # 确认该位置是否存在细胞 print( f'转移后位置“{newLoca[i]}”存在细胞{cellDic[newLoca[i]][0]},请检查输入信息') return else: tb.add_row([cellDic[oldLoca[i]][0], oldLoca[i], newLoca[i]]) except KeyError as key: # 确保保存位置的格式正确 print(f'{key}位置输入有误,请检查输入信息') return print(">>>>转移位置信息如下:") print(tb) # 确认是否执行操作 s = input(">>>请输入y确认操作,按任意键取消\n").lower() if s == 'y': flowInfo = [] # 细胞出库 for i in range(len(oldLoca)): # 生成流水记录信息['细胞名称','数量','位置','操作','操作日期','操作人'] flowInfo.append([ cellDic[oldLoca[i]][0], '1', oldLoca[i], '出库', date, operator ]) flowInfo.append([ cellDic[oldLoca[i]][0], '1', newLoca[i], '入库', date, operator ]) # 细胞出入库 cellDic[newLoca[i]] = cellDic[oldLoca[i]] cellDic[oldLoca[i]] = [None, None] # 记录流水信息 flowRecord(flowInfo) # 保存细胞库文件并保存一份副本 saveFile(cellDic) print('记录完成') else: print("出库已取消")
def show_movies(self): ''' print all movies ORDERED BY rating desc ''' tbl_header = ['ID', 'Name', 'Rating'] tbl = pt(tbl_header) tbl.align['Name'] = 'l' tbl.align['Rating'] = 'l' cur = self.con.cursor() cur.execute("select * from movies order by rating desc") for i in cur.fetchall(): tbl.add_row(i) return "\nCurrent movies:\n" + str(tbl)
def available_seats(self): self.gen_seats_matrix() tbl_headers = ['', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] tbl = pt(tbl_headers) tbl.align[''] = 'r' r_seats = self.return_reserved_seats(self.reservation_projection_id) for seat in r_seats: self.seats_matrix[seat[0] - 1][seat[1] - 1] = 'X' row_num = [1] for i in self.seats_matrix: tbl.add_row(row_num + i) row_num[0] += 1 return str(tbl)
def available_seats(self): self.gen_seats_matrix() tbl_headers = ['', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] tbl = pt(tbl_headers) tbl.align[''] = 'r' r_seats = self.return_reserved_seats(self.reservation_projection_id) for seat in r_seats: self.seats_matrix[seat[0]-1][seat[1]-1] = 'X' row_num = [1] for i in self.seats_matrix: tbl.add_row(row_num + i) row_num[0] += 1 return str(tbl)
def main(): input1 = '../data/input1.txt' #Original Test Case input2 = '../data/input2.txt' #Extra Test Case output1 = '../data/output1.txt' #Original Test Case output2 = '../data/output2.txt' #Extra Test Case correctfile1 = '../data/correct_output_1.txt' # correct output for test case 1 correctfile2 = '../data/correct_output_2.txt' # correct output for test case 2 correct_output = open(correctfile1, 'r', encoding="GBK") check_output = open(output1, 'r', encoding="GBK") py_input = open(input1, 'r', encoding="GBK") score = list() total_checks = 0 total_correct = 0 for correct, check, py in zip(correct_output, check_output, py_input): sentence = list() correct = correct.replace(" ", '').rstrip("\n") check = check.replace(" ", '').rstrip("\n") py = py.rstrip("\n") sentence.append(str(py)) sentence.append(str(correct)) sentence.append(str(check)) total_char_py = len(correct) total_checks += total_char_py num_correct = 0 for a, b in zip(correct, check): # print(a + " " + b) if a == b: num_correct += 1 total_correct += 1 sentence.append(str(num_correct) + "/" + str(total_score)) # print(str(num_correct)+"/"+ str(total_score)) score.append(sentence) x = pt(["Pinyin", "Correct", "Mine", "Score"]) x.align["Correct"] = "l" x.align["Mine"] = "l" x.align["Score"] = "l" x.align["Pinyin"] = "l" x.padding_width = 1 for a in score: x.add_row([a[0], a[1], a[2], a[3]]) with open('../src/score.txt', 'w', encoding="GBK") as score: score.write("Reading from " + input2 + "and compare to " + correctfile2 + "\n") score.write(str(x)) score.write("\nTotal Percentage Correct " + str(total_correct / total_checks))
def enter(self): print("\nThis is the total customers we've had in each store") cursor = db.cursor() sqlcommand =("SELECT Count(CUST_ID) as TotalCustomers, STORE FROM TRANSACT GROUP BY STORE ORDER BY TotalCustomers DESC;") cursor.execute(sqlcommand) col_names = [cn[0] for cn in cursor.description] rows = cursor.fetchall() y1 = pt() y1.padding_width = 1 y1.add_column(col_names[0],[row[0] for row in rows]) y1.add_column(col_names[1],[row[1] for row in rows]) print(y1) return 'central'
def printStudentInfoLine(self, suid, flag=False): table = pt(lt) table.align[lt[1]] = "l" row = [suid] + list(self.data["info"][suid].values()) + list(self.data["score"][suid].values()) + \ [self.data["tot_score"][suid]] table.add_row(row) # 去掉边框,因为边框存在布局错误,再转换为字符串逐行对齐输出 table.border = False # 通过多次调用逐行打印学生成绩达到打印整个表的效果,但是只能输出一次表头 for s in table.get_string().splitlines(): if flag: # 如果执行的是打印整个表,则不会打印表头 flag = not flag continue print("".ljust(19) + s)
def enter(self): print("\nOkay, you want to know how many customers spent more than $500") cursor = db.cursor() sqlcommand =("SELECT COUNT(CUST_ID) as TotalCustomers, TRAN_DATE as TransactionDate FROM TRANSACT WHERE TRAN_AMT > 500 GROUP BY TRAN_DATE ORDER BY TRAN_DATE desc") cursor.execute(sqlcommand) col_names = [cn[0] for cn in cursor.description] rows = cursor.fetchall() y1 = pt() y1.padding_width = 1 y1.add_column(col_names[0],[row[0] for row in rows]) y1.add_column(col_names[1],[row[1] for row in rows]) print(y1) return 'central'
def printvtable(data): """Generate a prettytable for output data. Table is generated vertically. Each row only consists of 2 columns and there is no "field data". Data should be passed as a list of tuples. The tuples represent each row.""" fields = ["0", "1"] table = pt() table.field_names = fields table.align = "l" table.padding_width = 1 table.header = False for row in data: table.add_row(row) print table
def printhtable(fields, data, sort=None): """Generate a prettytable for output data. Table is generated horizontally, much like mysql tables. Fields must be a list and data must be a list with the rows as tuples.""" table = pt() table.field_names = fields if sort != None: table.sortby = fields[int(sort)] else: table.sortby = fields[0] table.align = "c" table.padding_width = 1 for row in data: table.add_row(row) print table
def learn_s(self): data_student = pickle.load(open('%s/student.db' % settings.DB_DIR, 'rb')) data_course = pickle.load(open('%s/course.db' % settings.DB_DIR, 'rb')) filed = ['课程ID', '课程名', '课时费用', '主讲'] print_out = pt(filed) print_out.align['课程ID'] = '1' print_out.padding_width = 1 for i in data_student.keys(): print_out.add_row([i, data_student[i][0], data_student[i][1], data_student[i][2]]) print(print_out) while True: choose_input = input('请选择要学习的课程:').strip() if choose_input not in data_student: print("选择无效!") else: print(data_course[choose_input][3]) break
def choose(user_ID): data_student = pickle.load(open('%s/student.db' % settings.DB_DIR, 'rb')) data_course = pickle.load(open('%s/course.db' % settings.DB_DIR, 'rb')) filed = ['课程ID', '课程名', '课时费用', '主讲'] print_out = pt(filed) print_out.align['课程ID'] = '1' print_out.padding_width = 1 for i in data_course.keys(): print_out.add_row([i, data_course[i][0], data_course[i][1], data_course[i][2]]) print(print_out) choose = input('请选择:').strip() if choose not in data_course.keys(): print("选择无效!") else: if choose not in data_student: data = pickle.load(open('%s/student.db' % settings.DB_DIR, 'rb')) data[user_ID] = [choose, data[choose][0], data[choose][1], data[choose][2]] pickle.dump(data, open('%s/student.db' % settings.DB_DIR, 'wb')) print('选课成功!') else: print("该课程已添加!")
def show_movie_projections_and_seats(self, movie_id): tbl_headers = ['Projection info'] tbl = pt(tbl_headers) tbl.align['Projection info'] = 'l' cur = self.con.cursor() sql = '''SELECT m.name, "["||p.id||"] - "||p.date||" "|| p.time||" ("||p.type||")"||" - "||(100 - COUNT(R.PROJECTION_ID))|| ' available seats' as p_info from movies m left join projections p on (m.id = p.movie_id) left join reservations r on (p.id = r.projection_id) group by m.name, p.id, p.date, p.time, r.projection_id having m.id = ?''' cur.execute(sql, (movie_id, )) result = cur.fetchall() for i in result: tbl.add_row([i[1]]) return "\nProjections for movie '{}':\n".format( result[0][0]) + str(tbl)
def problem_10(): """ This function provides the solution to problem 10. We use the 4 data sets from problem 5 to generate moments regarding data filtered with an HP filter, BK filter, and first-difference filter. Inputs: None Outputs: the_tables: This is the tables containing mean, standard deviation, autocorrelation, and correlation with GDP for the following filters for each data set: HP(1600) BK(16, 6, 32) first difference. """ # Generate GDP filtered data first_diff_gdp = gdp[1:] - gdp[:-1] hp_gdp = hp.hp_filter(gdp)[1] bp_gdp = bpf.bandpass_filter(gdp, 16, 6, 32)[16:-16] all_gdp = np.array([first_diff_gdp, hp_gdp, bp_gdp]) # Generate cpi filtered data first_diff_cpi = cpi[1:] - cpi[:-1] hp_cpi = hp.hp_filter(cpi)[1] bp_cpi = bpf.bandpass_filter(cpi, 16, 6, 32)[16:-16] all_cpi = np.array([first_diff_cpi, hp_cpi, bp_cpi]) # Generate consumption filtered data first_diff_cons = cons[1:] - cons[:-1] hp_cons = hp.hp_filter(cons)[1] bp_cons = bpf.bandpass_filter(cons, 16, 6, 32)[16:-16] all_cons = np.array([first_diff_cons, hp_cons, bp_cons]) # Generate investment filtered data first_diff_inv = inv[1:] - inv[:-1] hp_inv = hp.hp_filter(inv)[1] bp_inv = bpf.bandpass_filter(inv, 16, 6, 32)[16:-16] all_inv = np.array([first_diff_inv, hp_inv, bp_inv]) all_data = np.vstack([all_gdp, all_cpi, all_cons, all_inv]) all_tables = np.empty((4, 4, 3)) data_titles = ['GDP', "CPI", 'Consumption', 'Investment'] filter_labels = ['First Diff', 'HP', 'BP'] for data_set in range(all_data.shape[0]): plt.figure() for filt in range(all_data.shape[1]): plt.plot( range(all_data[data_set, filt].size), all_data[data_set,filt], label = filter_labels[filt]) plt.title(data_titles[data_set]) plt.legend(loc=0) plt.show() for data_set in range(all_data.shape[0]): for i in range(all_data.shape[1]): all_tables[data_set, 0, i] = np.mean(all_data[data_set, i]) all_tables[data_set, 1, i] = np.std(all_data[data_set, i]) all_tables[data_set, 2, i] = np.corrcoef(all_data[data_set, i][:-1], all_data[data_set, i][1:])[0,1] all_tables[data_set, 3, i] = np.corrcoef(all_data[data_set, i], all_data[0, i])[0,1] titles = ['Parameters [GDP]', 'Parameters [CPI]', 'Parameters [cons]', 'Parameters [inv]'] col_names = ['First Diff', 'HP (1600)', 'BK (16)'] params = ['Mean', 'Std', 'Autocorrelation', 'Corr w/GDP'] pretty_gdp = pt() pretty_cpi = pt() pretty_cons = pt() pretty_inv = pt() pretty_all = [pretty_gdp, pretty_cpi, pretty_cons, pretty_inv] for tab in range(4): pretty_all[tab].add_column(titles[tab], params) for col in range(3): pretty_all[tab].add_column(col_names[col], all_tables[tab, :, col]) print pretty_all[tab] return pretty_all
#!/usr/bin/env python3 import numpy as np from datetime import datetime, timedelta, date from prettytable import PrettyTable as pt import sys import random import math import itertools # Output and date format #=============================================================================== table = pt(['Being', 'Birth', 'Death', 'Died at']) table.align['Being'] = 'l' def formDate(t): strFmt = '{year:4}-{month:02}-{day:02}' return strFmt.format(year=t.year, month=t.month, day=t.day) # Being list #=============================================================================== beings = [ # weight , being , mean , stdDev [ 1910 , 'worm' , 2000 , 150], [ 1110 , 'crab' , 1460 , 530], [ 9999 , 'insect' , 28 , 300], [ 490 , 'snail' , 4380 , 300], [ 1910 , 'fish' , 1700 , 700], [ 4610 , 'marineInv' , 800 , 910],
def main(): tt = pt(["Bin", "ID", "Text"]) tt.align["Bin"] tt.padding_with = 1 p = optparse.OptionParser() p.add_option('--duration', '-d', default = 300) p.add_option('--binsize', '-b', default = 1) p.add_option('--query', '-q', default = 'i am groot') options, arguments = p.parse_args() pp = partial(json.dumps, indent = 1) q = options.query #query phrase start_time = str(datetime.datetime.now())[:-7] ttf = open("tweet-table" + " " + q +".txt", 'w') f.write(start_time+"/"+start_time + "\n") def oauth_login(): CONSUMER_KEY = '' CONSUMER_SECRET ='' OAUTH_TOKEN = '-' OAUTH_TOKEN_SECRET = '' auth = twitter.oauth.OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET) twitter_api = twitter.Twitter(auth=auth) return twitter_api """ ---- DO THINGS ---- """ print >> sys.stderr, 'Filtering the public timeline for track="%s"' % (q,) twitter_api = oauth_login() print twitter_api twitter_stream = twitter.TwitterStream(auth=twitter_api.auth) stream = twitter_stream.statuses.filter(track=q) #CHANGE NEEDED VARIABLES HERE c = 0 tc = 0 alpha = 0.3 s_s = [] s_x = [] s_times = {} s_raw = {} gr = [] abs_tc = 0 sfreq = [0] freq = [] #change these two values to choose how long the program shall run, and also how large each bin will be lim = options.duration timeframe = options.binsize def find_smooth(c, depth = 0): #not called when c is 0 global sfreq global freq global alpha if c == 0: return sfreq[0] elif not c == 0 and depth > 500: return sfreq[c-501] else: return alpha * freq[c-1] + (1-alpha) * find_smooth(c-1, depth + 1) g = open("raw-tweets.txt", 'w') z = open("ema-tweet-freq.txt", 'w') rawh = open("raw_freq.txt", 'w') dt_i = int(time.time()) dt_t = str(datetime.datetime.now())[:-7] for tweet in stream: abs_tc += 1 #print "tweet" dt = int(time.time()) - dt_i #current time #print "current time: " + str(dt) + "\n" try: g.write(str(dt) + " " + tweet['text'].encode('ascii', 'ignore') + "\n") except: g.write("UNSUPPORTED TEXT \n") try: zz = s_times[(dt//timeframe)] zz = s_times[(dt//timeframe)] except KeyError: s_times[(dt//timeframe)] = [] s_raw[(dt//timeframe)] = 0 try: s_times[(dt//timeframe)].append(tweet['text'].encode('ascii', 'ignore')) except: s_times[(dt//timeframe)].append("nope") s_raw[(dt//timeframe)] += 1 try: tt.add_row([str(dt//timeframe), tweet['id'], tweet['text'].encode('ascii', 'ignore')]) except KeyError: pass try: dt == prev #is this tweet the same bin as the previous one? except NameError: #only happens for 1st tweet prev = dt continue if dt == prev: #if same bin # print "dt is " + str(dt) # print "prev is " + str(prev) + "\n" tc += 1 #increase number in bin else: #if not same bin c += 1 tc = 0 prev = dt if dt >= lim: ttf.write(str(tt)) print pp(s_raw) for a in s_raw: rawh.write(str(s_raw[a]) + "\n") _maxa = 0 #print "smoothed : " + str(s_s) for a in xrange(_maxa): if a not in [b for b in iter(s_raw)]: freq.append(0) else: freq.append(s_raw[a]) print pp(freq) print "length of freq is: " + str(len(freq)) + "\n" for a in xrange(len(freq)): if a == 0: sfreq.append(0) else: print "smoothing " + str(freq[a]) sfreq.append(find_smooth(a)) z.write(pp(sfreq)) print pp(sfreq) print "processed " + str(abs_tc) + " tweets" plt.plot([a for a in s_times], [len(s_times[a]) for a in s_times], '-r') plt.plot([a for a in xrange(len(sfreq))], [a for a in sfreq], '-b') plt.plot([a for a in xrange(len(sfreq))], [a for a in sfreq], '+') plt.title(q + ' ' + dt_t) plt.xlabel("Time frame of " + str(timeframe) + " second(s)") plt.ylabel("Bin size") plt.draw() fig1 = plt.gcf() fig1.savefig("plot" + ".svg") break
# <codecell> cpi_table # <codecell> cons_table # <codecell> inv_table # <codecell> gtab = pt() # <codecell> all_tables = np.array([gdp_table, cpi_table, cons_table, inv_table]) # <codecell> blank_tables = np.zeros((4,4,3)) # <codecell> # <codecell>