index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
58,105
klgentle/lc_python
refs/heads/master
/leet_code/easy_case/longestCommonPrefix_answ.py
class Solution: def longestCommonPrefix(self, strs: "List[str]") -> "str": if len(strs) == 0: return "" if len(strs) == 1: return strs[0] prefix, chars = "", zip(*strs) print("zip(*strs):", chars) print("enumerate(chars):", enumerate(chars)) for i, group in enumerate(chars): ch = group[0] for j in range(1, len(group)): if group[j] != ch: return prefix print("prefix:", prefix) prefix += strs[0][i] return prefix if __name__ == "__main__": a = Solution() s = ["flower", "flow", "flight"] s1 = ["a"] s2 = ["aaa", "aa", "aaa"] a.longestCommonPrefix(s)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,106
klgentle/lc_python
refs/heads/master
/leet_code/A_LeetCode_Grinding_Guide/Greedy/P0455_Assign_Cookies.py
""" 455. Assign Cookies Easy Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number. Example 1: Input: g = [1,2,3], s = [1,1] Output: 1 Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. """ class Solution: def findContentChildren(self, g: List[int], s: List[int]) -> int: # sort two lists g.sort() s.sort() content_num = 0 cookie = 0 while content_num < len(g) and cookie < len(s): if s[cookie] >= g[content_num]: content_num += 1 cookie += 1 return content_num
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,107
klgentle/lc_python
refs/heads/master
/base_practice/RenameFileAndContent.py
import os import sys class RenameFileAndContent(object): def __init__(self, from_pattern, to_pattern, file_path): self.__from_pattern = from_pattern self.__to_pattern = to_pattern self.__file_path = file_path def getNewFilename(self, filename: str) -> str: return filename.replace(self.__from_pattern, self.__to_pattern) def renameFile(self, filename: str): newFilename = self.getNewFilename(filename) os.rename(filename, newFilename) def renameContent(self, filename: str): content = "" with open(filename, "r") as fr: content = fr.read() with open(filename, "w") as fw: fw.write(content.replace(self.__from_pattern, self.__to_pattern)) def renameAllFile(self): for filename in os.listdir(self.__file_path): oldFileNameAndPath = os.path.join(self.__file_path, filename) self.renameFile(oldFileNameAndPath) newFilename = self.getNewFilename(oldFileNameAndPath) #self.renameContent(newFilename) if __name__ == "__main__": # from_pattern = "MAC510_D" # to_pattern = "CIF360E" # file_path = "/mnt/c/Users/pactera/Downloads/Documents" # print(sys.argv) o = RenameFileAndContent(sys.argv[1], sys.argv[2], sys.argv[3]) o.renameAllFile()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,108
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/tree/P0098_Validate_Binary_Search_Tree.py
""" Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: Input: root = [2,1,3] Output: true """ class Solution: def isValidBST(self, root: TreeNode) -> bool: return self.isValidBSTSub(root, -2 ** 32, 2 ** 32 - 1) def isValidBSTSub(self, root, minVal, maxVal) -> bool: # 大树化成左右子树 if not root: return True if root.val <= minVal or root.val >= maxVal: return False return self.isValidBSTSub(root.left, minVal, root.val) and self.isValidBSTSub( root.right, root.val, maxVal )
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,109
klgentle/lc_python
refs/heads/master
/vs_code/copy_excel.py
import shutil, os import openpyxl class CopyExcel(object): def __init__(self): self.from_path = "/mnt/e/yx_walk/report_develop/report_dept" self.from_file = "ods_reports_out.xlsx" self.to_file = "ods_reports_out.xlsx" #self.sheet_name = sheet_name def readData(self): wb = openpyxl.load_workbook(os.path.join(self.from_path, self.from_file)) #sheet = wb.active sheets = wb.get_sheet_names() print(f"sheets:{sheets}") # range from index to change for i, v in enumerate(sheets): sheet = wb.get_sheet_by_name(v) self.data_list = [] for row in range(1, sheet.max_row + 1): name = sheet["A" + str(row)].value if not name: continue data_row = [sheet[chr(ord("A")+i) + str(row)].value for i in range(0,2)] self.data_list.append(data_row) # write self.saveData() def saveData(self): file_path_name = os.path.join(self.from_path, self.to_file) wb = openpyxl.load_workbook(file_path_name) #sheet = wb.active #sheet = wb.create_sheet("ALL") sheet = wb.get_sheet_by_name("ALL") for row in self.data_list: #print(f"row:{row}") sheet.append(row) wb.save(filename=file_path_name) if __name__ == "__main__": #sheet_name = "PMO Report-Recipient Mapping" a = CopyExcel() a.readData() #a.saveData() print(f"All done!")
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,110
klgentle/lc_python
refs/heads/master
/base_practice/year.py
modelYear = 1998 if ((modelYear >= 1995 and modelYear <= 1998) or (modelYear >=2004 and modelYear<=2006)): #System.out.println("RECALL") print(True) else: print(False) print((modelYear >= 1995 and modelYear <= 1998) or (modelYear >=2004 and modelYear<=2006))
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,111
klgentle/lc_python
refs/heads/master
/shell_test/send_table_mail/server3.py
import sqlite3 from flask import Flask, request def save_data(site_name): # 若不存在则创建 con = sqlite3.connect("ifrs9.db") # 游标对象 cur = con.cursor() # 新建表 cur.execute( "create table if not exists ifrs9_data \ (site_name text primary key not null, data text)" ) cur.execute( "delete from ifrs9_data where site_name=?", (site_name,) ) # insert data cur.execute( "INSERT INTO ifrs9_data(site_name, data) VALUES(?,?)", ("HASE", "1,HASE,12312,Oct,22,22:46,123\n2,HSCN,12312,Oct,22,22:46,123\n3,HMO,12312,Oct,22,22:46,123"), ) cur.execute("select * from ifrs9_data") print(cur.fetchall()) con.commit() con.close() pass if __name__ == "__main__": save_data("HASE")
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,112
klgentle/lc_python
refs/heads/master
/vs_code/spiralDraw.py
import pyautogui, time time.sleep(5) pyautogui.click() # click to put drawing program in focus distance = 200 while distance > 0: pyautogui.dragRel(distance, 0, duration=0.2) # move right distance = distance - 5 pyautogui.dragRel(0,distance,duration=0.2) # move down pyautogui.dragRel(-distance,0,duration=0.2) # move left distance = distance -5 pyautogui.dragRel(0,-distance,duration=0.2) # move up
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,113
klgentle/lc_python
refs/heads/master
/stock_pandas/lab_5_adv.py
import pandas as pd loan = pd.read_csv("loan.csv") keepgoing = "Y" while keepgoing == "Y": variable = input("Enter variable:") comparison = input("Enter comparison >,<,= : ") value = input("Enter value of cutoff:") # value format if value.isdigit(): value = int(value) if comparison == ">": loan = loan[loan[variable] > value] elif comparison == "<": loan = loan[loan[variable] < value] elif comparison == "=": loan = loan[loan[variable] = value] keepgoing = input("Do you want to slice by another variable (Y for yes?):") print(loan.head(10)) print(loan.describe(include="all"))
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,114
klgentle/lc_python
refs/heads/master
/tests/__init__.py
import os import sys from os.path import dirname # 项目根目录 BASE_DIR = dirname(dirname(os.path.abspath(__file__))) # 添加系统环境变量 sys.path.append(BASE_DIR)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,115
klgentle/lc_python
refs/heads/master
/encode/decrypt.py
from Crypto.Cipher import DES key = b'abcdefgh' # 密钥 8位或16位,必须为bytes def get_passwd(): des = DES.new(key, DES.MODE_ECB) # 创建一个DES实例 f = open("pactera_passwd_encrpt.txt","rb") # str 转二进制通过encode() encrypted_text = f.read() #encrypted_text = "" # rstrip(' ')返回从字符串末尾删除所有字符串的字符串(默认空白字符)的副本 s = des.decrypt(encrypted_text).decode().rstrip(' ') print(s) return s # 解密 if __name__ == '__main__': get_passwd()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,116
klgentle/lc_python
refs/heads/master
/leet_code/top_interview_questions/Medium_Case/P0036_Valid_Sudoku.py
class Solution: @staticmethod def isValidSudokuRow(grid) -> bool: for lst in grid: data = [i for i in lst if i != '.'] # check duplicate if len(data) != len(set(data)): return False return True def isValidSudoku(self, board: List[List[str]]) -> bool: # check row if not self.isValidSudokuRow(board): return False # check column if not self.isValidSudokuRow(zip(*board)): return False # get block 3*3 block = [[] for i in range(9)] for i in range(0,9): for j in range(0,9): block[(i//3)*3+j//3].append(board[i][j]) print(block) # check block 3*3 if not self.isValidSudokuRow(block): return False return True
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,117
klgentle/lc_python
refs/heads/master
/leet_code/medium_case/p537_Complex_Number_Multiplication.py
class Solution: def complexNumberMultiply(self, a: str, b: str) -> str: # display complex as a list t, t[0] is the real, t[1] is imaginary """ (at[0] + at[1]*i) * (bt[0] + bt[1]*i) = at[0]*bt[0] + at[0]*bt[1]*i + at[1]*i*bt[0] - at[1]*bt[1] = at[0]*bt[0] - at[1]*bt[1] + (at[0]*bt[1] + at[1]*bt[0]) * i """ at = [int(i) for i in a[:-1].split('+')] bt = [int(i) for i in b[:-1].split('+')] return "{0}+{1}i".format(at[0]*bt[0] - at[1]*bt[1], at[0]*bt[1] + at[1]*bt[0])
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,118
klgentle/lc_python
refs/heads/master
/wechat/VisitRecord.py
class VisitRecord: """旅游记录 """ def __init__(self, first_name, last_name, phone_number, date_visited): self.first_name = first_name self.last_name = last_name self.phone_number = phone_number self.date_visited = date_visited def __hash__(self): return hash((self.first_name, self.last_name, self.phone_number)) def __eq__(self, other): # 当两条访问记录的名字与电话号相等时,判定二者相等。 if isinstance(other, VisitRecord) and hash(other) == hash(self): return True return False def find_potential_customers_v3(): return set(VisitRecord(**r) for r in users_visited_puket) - set( VisitRecord(**r) for r in users_visited_nz )
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,119
klgentle/lc_python
refs/heads/master
/app_spider/Red_Wars.py
#!/usr/bin/env python # encoding: utf-8 """ @version: v1.0 @author: xag @license: Apache Licence @contact: xinganguo@gmail.com @site: http://www.xingag.top @software: PyCharm @file: Red_Wars.py @time: 2/5/19 09:59 @description:抢红包 """ # -*- encoding=utf8 -*- __author__ = "xingag" from airtest.core.api import * from poco.drivers.android.uiautomation import AndroidUiautomationPoco poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False) auto_setup(__file__) # 1.打开微信 poco(text='微信').click() # 2.输入要抢的群 # target = input('要抢哪个群:') target = '③抢票❤ 加速群(禁止广告,)' # 3.获取消息列表名称 item_elements = poco(name='com.tencent.mm:id/b4m').offspring('com.tencent.mm:id/b4o') names = list(map(lambda x: x.get_text(), item_elements)) def get_red_package(): """ 发现红包,就立马执行点击操作 :return: """ # 1.获取消息列表元素 msg_list_elements_pre = poco("android.widget.ListView").children() # 1.1 由于msg_list_elements属于UIObjectProxy对象,不能使用reverse进行反转 # 利用For把消息取反 msg_list_elements = [] for item in msg_list_elements_pre: msg_list_elements.insert(0, item) # 2.从后面的消息开始遍历 for msg_element in msg_list_elements: # 2.1 微信红包标识元素 red_key_element = msg_element.offspring('com.tencent.mm:id/apf') # 2.2 是否已经领取元素 has_click_element = msg_element.offspring('com.tencent.mm:id/ape') # 2.3 红包【包含:收到的红包和自己发出去的红包】 if red_key_element: print('发现一个红包') if has_click_element.exists() and ( has_click_element.get_text() == '已领取' or has_click_element.get_text() == '已被领完'): print('已经领取过了,略过~') continue else: # 抢这个红包 print('新红包,抢抢抢~') msg_element.click() click_element = poco("com.tencent.mm:id/cv0") if click_element.exists(): click_element.click() keyevent('BACK') else: print('红包元素不存在') continue if target in names: index = names.index(target) # 点击进入群聊 item_elements[index].click() while True: get_red_package() print('休眠1秒钟,继续刷新页面,开始抢红包。') sleep(1) else: print('找到这个群')
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,120
klgentle/lc_python
refs/heads/master
/Intermediate_Python/myclass__slots__.py
class MyClass(object): __slots__ = ['name', 'identifier'] def __init__(self, name, identifier): self.name = name self.identifier = identifier # self.set_up() ... if __name__ == "__main__": #a = MyClass("Cqy","<F7>7890-") #print(a.name) num = 1024*256 x = [MyClass(1,1) for i in range(num)]
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,121
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/tree/p0988_Smallest_String_Starting_From_Leaf.py
""" 988. Smallest String Starting From Leaf Medium Given the root of a binary tree, each node has a value from 0 to 25 representing the letters 'a' to 'z': a value of 0 represents 'a', a value of 1 represents 'b', and so on. Find the lexicographically smallest string that starts at a leaf of this tree and ends at the root. (As a reminder, any shorter prefix of a string is lexicographically smaller: for example, "ab" is lexicographically smaller than "aba". A leaf of a node is a node that has no children.) Example 1: Input: [0,1,2,3,4,3,4] Output: "dba" Example 2: Input: [25,1,3,1,3,0,2] Output: "adz" """ class Solution: def smallestFromLeaf(self, root: TreeNode) -> str: self.res = [] self.dfs(root, []) self.res.sort() #print(f"self.res:{self.res}") return self.res[0] def dfs(self, root, ls=[]): if root: if not root.left and not root.right: ls.append(root.val) # chr(97) = 'a' s = [chr(97+i) for i in ls[::-1]] self.res.append("".join(s)) self.dfs(root.left, ls+[root.val]) self.dfs(root.right, ls+[root.val])
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,122
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/sliding_window/p0438_Find_All_Anagrams_in_a_String.py
""" 438. Find All Anagrams in a String Medium Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. The order of output does not matter. Example 1: Input: s: "cbaebabacd" p: "abc" Output: [0, 6] """ class Solution: def findAnagrams(self, s: str, t: str) -> List[int]: """ 套用滑动窗口的框架,提前收缩窗口,这样可以保证进来的是目标字符的排列 """ need = {} wind = {} for c in t: if c in need: need[c] += 1 else: need[c] = 1 left, right = 0, 0 valid = 0 res = [] while right < len(s): c = s[right] right += 1 if c in need: if c in wind: wind[c] += 1 else: wind[c] = 1 if wind[c] == need[c]: valid += 1 # 提前收缩窗口,保证窗口中全为想要的字符串 while right - left >= len(t): if valid == len(need.keys()): res.append(left) d = s[left] left += 1 if d in need: #print(f"wind:{wind}, need:{need}") if wind[d] == need[d]: valid -= 1 wind[d] -= 1 return res
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,123
klgentle/lc_python
refs/heads/master
/leet_code/easy_case/removeDuplicates.py
class Solution: def removeAll(self, nums, a): times = nums.count(a) while times > 1: nums.remove(a) times -= 1 def removeDuplicates(self, nums): i = 0 while i < len(nums) - 1: a = nums[i] if nums[i] == nums[i + 1]: # print('i==j,i:{},j:{}'.format(i,i+1)) # nums.remove(a) self.removeAll(nums, a) i += 1 l = len(nums) print(l) return l
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,124
klgentle/lc_python
refs/heads/master
/leet_code/easy_case/findContentChildren.py
import logging logging.basicConfig( level=logging.DEBUG, format=" %(asctime)s - %(levelname)s - %(message)s" ) class Solution: def findContentChildren(self, g, s) -> int: # : List[int] # sort the list, small cookie for small greed factor g.sort() s.sort() logging.debug("g: %s" % g) logging.debug("s: %s" % s) child = 0 cookie = 0 cookie_amount = len(s) child_amount = len(g) while child < child_amount and cookie < cookie_amount: if s[cookie] >= g[child]: child += 1 cookie += 1 return child
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,125
klgentle/lc_python
refs/heads/master
/stock_pandas/stock_analysis_and_view.py
""" 数据可视化:股票数据分析 """ import pandas as pd from pandas_datareader import data ''' 获取国内股票数据的方式是:“股票代码”+“对应股市”(港股为.hk,A股为.ss) 例如腾讯是港股是:0700.hk ''' #字典:6家公司的股票 gafataDict={'谷歌':'GOOG','亚马逊':'AMZN','Facebook':'FB', '苹果':'AAPL','阿里巴巴':'BABA','腾讯':'0700.hk'} ''' get_data_yahoo表示从雅虎数据源获取股票数据,官网使用操作文档: http://pandas-datareader.readthedocs.io/en/latest/remote_data.html 可能存在的问题: 1)由于是从国外获取股票数据,会由于网络不稳定,获取数据失败,多运行几次这个cell就好了 2)如果多运行几次还是无法获的股票数据,使用这个链接里的方法:https://pypi.org/project/fix-yahoo-finance/0.0.21/ 3)如果经过上面2个方法还不行,打开这个官网使用文档(http://pandas-datareader.readthedocs.io/en/latest/remote_data.html), 换其他的财经数据源试试 ''' # 获取哪段时间范围的股票数据 start_date = '2017-01-01' end_date = '2018-01-01' #从雅虎财经数据源(get_data_yahoo)获取阿里巴巴股票数据 babaDf=data.get_data_yahoo(gafataDict['阿里巴巴'],start_date, end_date) #或者从Morningstar数据源获取阿里巴巴数据 #babaDf=data.DataReader(gafataDict['阿里巴巴'],'morningstar',start_date, end_date) #查看前5行数据 babaDf.head()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,126
klgentle/lc_python
refs/heads/master
/cs61a/remove_eg.py
def remove_digit(n, digit): """n >= 0, 0 <= digit <= 9 ruturn a number that remove digit from n >>> remove_digit(180, 1) 80 >>> remove_digit(1111, 1) 0 >>> remove_digit(8883, 8) 3 """ if n == 0: return 0 if n % 10 == digit: return remove_digit(n // 10, digit) return n % 10 + remove_digit(n // 10, digit) * 10 if __name__ == "__main__": import doctest doctest.testmod()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,127
klgentle/lc_python
refs/heads/master
/base_practice/PrimeNumbers.py
n=int(input("Enter an integer:")) def is_prime(n): if n<2: return False elif n==2: return True else: i=2 while i<n: if((n%i)==0): return False else: i+=1 return True print(is_prime(n))
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,128
klgentle/lc_python
refs/heads/master
/frequency_model/clock.py
# todo a clock import time import os import sys def sleepClock(m: str): """input a number of minute, time up play a song""" file = r"D:\\music\\music_good\\澤野弘之-Aliez_end.mp3" m = float(m) if m < 0 or m > 60: print("请输入分钟数:0<m<60") time.sleep(m * 60) os.system(file) # use windows to play music if __name__ == "__main__": #print(sys.argv) sleepClock(sys.argv[1])
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,129
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/sliding_window/p0003_Longest_Substring_Without_Repeating_Characters.py
""" 3. Longest Substring Without Repeating Characters Medium Given a string s, find the length of the longest substring without repeating characters. Example 1: Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: s = "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. """ class Solution: def lengthOfLongestSubstring(self, s: str) -> int: window = {} valid = 0 left, right = 0, 0 max_valid = 0 while right < len(s): c = s[right] right += 1 if c not in window: valid += 1 max_valid = max(max_valid, valid) window[c] = 1 else: window[c] += 1 while window[c] > 1: d = s[left] #print(f"right:{right}, left:{left}, d:{d}") left += 1 if window[d] == 1: valid -= 1 # del 字典中删除key del window[d] else: window[d] -= 1 return max_valid
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,130
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/dynamic_programming/p0072_Edit_Distance.py
""" 72. Edit Distance Hard Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. You have the following three operations permitted on a word: Insert a character Delete a character Replace a character Example 1: Input: word1 = "horse", word2 = "ros" Output: 3 Explanation: horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e') """ class Solution: """""" def minDistance(self, word1: str, word2: str) -> int: self.memo = {} def dp(i, j): if (i, j) in self.memo: return self.memo[(i, j)] # base case if i == -1: return j + 1 if j == -1: return i + 1 if word1[i] == word2[j]: self.memo[(i, j)] = dp(i-1, j-1) else: self.memo[(i, j)] = min( dp(i, j-1) + 1, # insert dp(i-1, j) + 1, # delete dp(i-1, j-1) + 1 # replace ) return self.memo[(i, j)] return dp(len(word1)-1, len(word2)-1)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,131
klgentle/lc_python
refs/heads/master
/leet_code/easy_case/rob.py
#!/usr/bin/env python3 # coding:utf8 import pysnooper import pdb class Solution: """ # 198 You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. """ # @pysnooper.snoop() def rob(self, nums: list) -> int: print(f"nums:{nums}") s = max(nums) ind = nums.index(s) l = len(nums) add_ind = ind for i in range(ind - 2, -1, -2): if i - 1 >= 0: if nums[i] >= nums[i - 1] and abs(i - add_ind) > 1: s += nums[i] add_ind = i else: s += nums[i - 1] add_ind = i - 1 # number after ind for i in range(ind + 2, l, 2): if i + 1 < l: print(f"i+1:{i+1}") if nums[i] >= nums[i + 1] and i - add_ind > 1: s += nums[i] add_ind = i else: s += nums[i + 1] add_ind = i + 1 print(f"s:{s}") return s if __name__ == "__main__": a = Solution() lst1 = [1, 2, 3, 1] lst2 = [2, 1, 1, 2] # a.rob(lst1) try: _ = a.rob(lst2) except (Exception, e): pdb.set_trace()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,132
klgentle/lc_python
refs/heads/master
/tests/re_simple_test.py
import re def test_re_search(test_str: str): if re.search( r"(\w*.)?M\s*=\s*(')?1(')?\s*AND\s+(\w*.)?S\s*=\s*(')?1(')?", test_str, flags=re.IGNORECASE, ): print("find") else: print("not find") if __name__ == "__main__": # test_re_search(" AND C.M = 1 AND C.S = 1") test_re_search(" AND M = '1' AND S = '1'")
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,133
klgentle/lc_python
refs/heads/master
/leet_code/easy_case/siglenumber.py
import logging from pprint import pprint logging.basicConfig( level=logging.DEBUG, format=" %(asctime)s - %(levelname)s - %(message)s" ) class Solution: def isDul(self, i, nums): for j in range(i + 1, len(nums)): if nums[i] == nums[j]: return True return False def singleNumber(self, nums) -> int: # if target in the last half: use index to find index != i # else if targe in the first half: find l[j] where l[i] = l[j] and i!= j continue logging.debug("nums:%s " % nums) # pprint(nums) nums_len = len(nums) logging.debug("nums_len:%s " % nums_len) for i in range(0, nums_len): logging.debug("nums[%s]:%s" % (i, nums[i])) if self.isDul(i, nums): continue print("nums[i]; ", nums[i]) return
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,134
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/tree/p0104_Maximum_Depth_of_Binary_Tree_2.py
""" 104. Maximum Depth of Binary Tree Easy Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Example 1: Input: root = [3,9,20,null,null,15,7] Output: 3 Example 2: Input: root = [1,null,2] Output: 2 Example 3: Input: root = [] Output: 0 Example 4: Input: root = [0] Output: 1 """ class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,135
klgentle/lc_python
refs/heads/master
/leet_code/medium_case/p0034_Find_First_and_Last_Position_of_Element_in_Sorted_Array.py
class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: if target not in nums: return [-1,-1] return [nums.index(target), self.searchEnding(nums, target)] def searchEnding(self, nums: List[int], target: int) -> int: ind = nums.index(target) for num in nums[nums.index(target)+1:]: if num == target: ind += 1 else: break return ind
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,136
klgentle/lc_python
refs/heads/master
/svn_operate/CheckProcedure.py
import re import os import platform from config_default import configs class CheckProcedure(object): def __init__(self): # 不需要检查的程序清单 self.white_list = [ "p_rpt_cif089_1.sql", "P_RPT_CIF089KN.sql", "P_RPT_CIF089KP.sql", "p_rpt_cif330d.sql", "p_rpt_fxd344rp.sql", "P_RPT_SAV_CUR_FLOAT.sql", "p_rpt_tu_error_mid.sql", ] self.setProcedurePath() def setProcedurePath(self): if platform.uname().system == "Windows": self.procedure_path = configs.get("path").get("win_svn_procedure_path") else: self.procedure_path = configs.get("path").get("svn_procedure_path") def getSvnStList(self): os.chdir(self.procedure_path) svn_st_list = os.popen("svn st").read().strip("\n").split("\n") return svn_st_list def findProcedureModifyList(self): svn_st_list = self.getSvnStList() # 取 add svn_add_filter = filter(lambda x: x.startswith("? "), svn_st_list) # 取 modify svn_modify_filter = filter(lambda x: x.startswith("M "), svn_st_list) svn_list = list( map( lambda x: x.strip("? ").strip("M "), list(svn_add_filter) + list(svn_modify_filter), ) ) return svn_list def isAllProcedureCorrect(self) -> bool: procedure_list = self.findProcedureModifyList() check_pass = True for procedure in procedure_list: if procedure not in self.white_list and not self.isOneProcedureCorrect( procedure ): check_pass = False return check_pass def isOneProcedureCorrect(self, procedure: str) -> bool: if self.isDateHardCode(procedure): print( "Warning: {} date is hard code, please check! __________________".format( procedure ) ) return False return True def isDateHardCode(self, procedure: str) -> bool: """ 检查是否有将日期写死,如将v_deal_date 写date'20...' """ with open( os.path.join(self.procedure_path, procedure), "r", encoding="utf-8" ) as f: proc_cont = f.read() if re.search("date'20", proc_cont, flags=re.IGNORECASE): return True return False if __name__ == "__main__": a = CheckProcedure() # tests # assert a.isDateHardCode("p_rpt_lon800_2.sql") is False # a.isOneProcedureCorrect("p_rpt_lon800_2.sql") # a.findProcedureModifyList() a.isProcedureCorrects()
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,137
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/divide_and_conquer/p0395_Longest_Substring_with_At_Least_K_Repeating_Characters.py
""" 395. Longest Substring with At Least K Repeating Characters Medium Given a string s and an integer k, return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k. Example 1: Input: s = "aaabb", k = 3 Output: 3 Explanation: The longest substring is "aaa", as 'a' is repeated 3 times. Example 2: Input: s = "ababbc", k = 2 Output: 5 Explanation: The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times. """ from collections import Counter class Solution: def longestSubstring(self, s: str, k: int) -> int: if len(s) < k: return 0 counter = Counter(s) #print(f"counter:{counter}") for p, v in enumerate(s): if counter[v] < k: # jump over p return max(self.longestSubstring(s[:p],k), self.longestSubstring(s[p+1:],k)) return len(s)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,138
klgentle/lc_python
refs/heads/master
/database/replace_view_and_log.py
import os import sys import logging logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s") # 绝对路径的import sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../") # from database.FindViewOriginalTable import FindViewOriginalTable # from database.Procedure import Procedure from database.ProcedureLogModify import ProcedureLogModify from database.AutoViewReplace import AutoViewReplace def run_replace_view(proc_name: str): # modify view name, data_area proc_view = AutoViewReplace() proc_view.main(proc_name) def run_modify_log(proc_name: str): # modify log proc_log = ProcedureLogModify(proc_name) proc_log.main() if __name__ == "__main__": action = "" if len(sys.argv) <= 1: logging.info("Please input procedure_name") sys.exit(1) if len(sys.argv) >= 3: action = sys.argv[2] proc_name = sys.argv[1] if action.lower().startswith("v"): run_replace_view(proc_name) elif action.lower().startswith("l"): run_modify_log(proc_name) else: run_replace_view(proc_name) run_modify_log(proc_name)
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,139
klgentle/lc_python
refs/heads/master
/leet_code/labuladong/backtracking/p0077_Combinations.py
""" 77. Combinations Medium Given two integers n and k, return all possible combinations of k numbers out of the range [1, n]. You may return the answer in any order. Example 1: Input: n = 4, k = 2 Output: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] Example 2: Input: n = 1, k = 1 Output: [[1]] """ from itertools import combinations class Solution: def combine(self, n: int, k: int) -> List[List[int]]: if k == 1: return [[i] for i in range(1,n+1)] elif k == n: return [[i for i in range(1, n+1)]] else: res = [] res += self.combine(n-1, k) part = self.combine(n-1, k-1) for ls in part: ls.append(n) res += part return res
{"/tests/testCreateWeekReport.py": ["/automatic_office/CreateWeekReport.py"], "/tests/re_test.py": ["/database/Procedure.py"], "/tests/test_procedure.py": ["/database/Procedure.py"], "/tests/test_proc_log_modify.py": ["/database/ProcedureLogModify.py"], "/database/batch_replace.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"], "/database/Procedure.py": ["/string_code/StringFunctions.py", "/decorator_test/logging_decorator.py"], "/tests/testDealInterval.py": ["/automatic_office/DealInterval.py"], "/automatic_office/CreateWeekReport.py": ["/automatic_office/CheckInForm.py", "/automatic_office/DealInterval.py"], "/database/AutoViewReplace.py": ["/database/Procedure.py", "/database/FindViewOriginalTable.py"], "/automatic_office/CheckInForm.py": ["/automatic_office/Holiday.py"], "/database/ProcedureLogModify.py": ["/database/Procedure.py"], "/tests/test_string.py": ["/string_code/StringFunctions.py"], "/database/replace_view_and_log.py": ["/database/ProcedureLogModify.py", "/database/AutoViewReplace.py"]}
58,152
mechbear14/mysterious-forest
refs/heads/master
/world.py
from core import ForestGraph from player import Player from blocks import Block, NormalBlock, PassBlock from pygame import Surface class Forest: def __init__(self, width: int, height: int, player_info: Player): self.width, self.height = width, height self.graph = ForestGraph(width, height) self.player = player_info px, py = self.player.position.x, self.player.position.y self.approachables = self.graph.get_direct_accessible(px, py) self.blocks = [] for block_index in range(width * height): y, x = divmod(block_index, width) block = PassBlock( x, y) if x == px and y == py else NormalBlock(x, y) self.blocks.append(block) block.on_create(self) def get_player(self) -> Player: return self.player def go_to(self, x: int, y: int): block = self.blocks[self.xy_2_index(x, y)] player_position = self.player.position if self.graph.check_accessible(player_position[0], player_position[1], x, y): block.on_enter(self) elif (x, y) in self.approachables: if block.state == Block.UNKNOWN: block.on_reveal(self) elif block.state == Block.REVEALED: block.on_open(self) def make_accessible(self, x: int, y: int): src_x, src_y = self.player.position.x, self.player.position.y self.graph.make_accessible(src_x, src_y, x, y) def make_inaccessible(self, x: int, y: int): self.graph.clear_accessible(x, y) def move_player_to(self, x: int, y: int): prev_block = self.blocks[self.xy_2_index(*self.player.position)] prev_block.on_leave(self) self.player.update_position(x, y) self.approachables = self.graph.get_direct_accessible(x, y) def render(self, area: Surface): for block in self.blocks: block.draw(area) def xy_2_index(self, x: int, y: int) -> int: return int(y * self.width + x)
{"/world.py": ["/core.py", "/player.py", "/blocks.py"], "/blocks.py": ["/player.py"], "/game.py": ["/world.py", "/player.py"], "/main.py": ["/world.py"]}
58,153
mechbear14/mysterious-forest
refs/heads/master
/core.py
import numpy from collections import namedtuple, deque class ForestGraph: def __init__(self, width: int, height: int): self.width = width self.height = height self.size = width * height self.graph = numpy.zeros([self.size, self.size], dtype=bool) for cell in range(self.size): self.graph[cell][cell] = True def check_accessible(self, src_x: int, src_y: int, dest_x: int, dest_y: int) -> bool: row_allowed = -1 < dest_x < self.width column_allowed = -1 < dest_y < self.height if all([row_allowed, column_allowed]): accessed = numpy.zeros([self.size, 1], dtype=int) queue = deque([]) src = self.rowcol_2_index(src_y, src_x) dest = self.rowcol_2_index(dest_y, dest_x) accessible = False queue.append(src) while True: try: current = queue.popleft() except IndexError: break else: if not accessed[current]: accessed[current] = True for possible_dest, is_possible in enumerate(self.graph[current][:]): if is_possible: if possible_dest == dest: accessible = True break else: queue.append(possible_dest) else: accessible = False return accessible def get_direct_accessible(self, src_x: int, src_y: int) -> list: direct_accessibles = [] if -1 < src_x + 1 < self.width: direct_accessibles.append((src_x + 1, src_y)) if -1 < src_x - 1 < self.width: direct_accessibles.append((src_x - 1, src_y)) if -1 < src_y + 1 < self.height: direct_accessibles.append((src_x, src_y + 1)) if -1 < src_y - 1 < self.height: direct_accessibles.append((src_x, src_y - 1)) return direct_accessibles def make_accessible(self, src_x: int, src_y: int, dest_x: int, dest_y: int): row_allowed = -1 < dest_x < self.width column_allowed = -1 < dest_y < self.height if all([row_allowed, column_allowed]): src = self.rowcol_2_index(src_y, src_x) dest = self.rowcol_2_index(dest_y, dest_x) self.graph[src][dest] = True self.graph[dest][src] = True def clear_accessible(self, src_x: int, src_y: int): src = self.rowcol_2_index(src_y, src_x) self.graph[src][:] = False self.graph[:][src] def rowcol_2_index(self, row: int, col: int) -> int: return int(self.width * row + col)
{"/world.py": ["/core.py", "/player.py", "/blocks.py"], "/blocks.py": ["/player.py"], "/game.py": ["/world.py", "/player.py"], "/main.py": ["/world.py"]}
58,154
mechbear14/mysterious-forest
refs/heads/master
/blocks.py
from player import Player import pygame from pygame.locals import * from pygame.sprite import Sprite from pygame import Vector2, Rect, Surface from random import randint class Block(Sprite): UNKNOWN = 0 REVEALED = 1 PASSED = 2 def __init__(self, x: int, y: int): Sprite.__init__(self) self.position = Vector2(x, y) self.size = Vector2(50, 50) self.canvas_position = Vector2(50 * x, 50 * y) self.image = Surface(self.size).convert_alpha() self.rect = Rect(self.canvas_position, self.size) self.state = Block.UNKNOWN def on_create(self, forest): pass def on_reveal(self, forest): pass def on_open(self, forest): pass def on_enter(self, forest): pass def on_leave(self, forest): pass def set_state(self, state): self.state = state def draw(self, area: Surface): area.blit(self.image, self.rect) class PassBlock(Block): def __init__(self, x: int, y: int): Block.__init__(self, x, y) self.primaryColour = Color(0, 0, 0, 0) self.state = Block.PASSED def on_create(self, forest): pygame.draw.rect(self.image, self.primaryColour, Rect( Vector2(2, 2), self.size - Vector2(4, 4))) def on_enter(self, forest): x, y = self.position.x, self.position.y forest.move_player_to(self.position.x, self.position.y) print(f"You've entered block ({x}, {y})") def on_leave(self, forest): x, y = self.position.x, self.position.y print(f"You've left block ({x}, {y})") class NormalBlock(Block): def __init__(self, x: int, y: int): Block.__init__(self, x, y) self.primaryColour = Color(128, 128, 128) self.revealColour = Color(255, 200, 0) def on_create(self, forest): pygame.draw.rect(self.image, self.primaryColour, Rect( Vector2(2, 2), self.size - Vector2(4, 4))) def on_reveal(self, forest): x, y = self.position.x, self.position.y pygame.draw.rect(self.image, self.revealColour, Rect( Vector2(2, 2), self.size - Vector2(4, 4))) print(f"You've revealed block ({x}, {y})") self.state = Block.REVEALED def on_open(self, forest): x, y = self.position.x, self.position.y print(f"You've opened block ({x}, {y})") a, b = randint(0, 100), randint(0, 100) answer = input(f"Here's a question: what is {a} + {b}?") if int(answer) == a + b: pygame.draw.rect(self.image, Color(0, 0, 0, 0), Rect( Vector2(0, 0), self.size)) print(f"Good. You can now pass block ({x}, {y})") self.state = Block.PASSED forest.make_accessible(x, y) forest.move_player_to(self.position.x, self.position.y) else: print("Roar! You can't pass") def on_leave(self, forest): x, y = self.position.x, self.position.y print(f"You've left block ({x}, {y})") def on_enter(self, forest): x, y = self.position.x, self.position.y forest.move_player_to(self.position.x, self.position.y) print(f"You've entered block ({x}, {y})")
{"/world.py": ["/core.py", "/player.py", "/blocks.py"], "/blocks.py": ["/player.py"], "/game.py": ["/world.py", "/player.py"], "/main.py": ["/world.py"]}
58,155
mechbear14/mysterious-forest
refs/heads/master
/game.py
import pygame from pygame.locals import * from pygame import Vector2 from world import Forest from player import Player pygame.init() screen = pygame.display.set_mode((640, 360)) player = Player(0, 0) world = Forest(6, 5, player) while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() raise SystemExit elif event.type == MOUSEBUTTONUP: mouse_position = Vector2(pygame.mouse.get_pos()) x = mouse_position.x // 50 y = mouse_position.y // 50 if -1 < x < world.width and -1 < y < world.height: world.go_to(x, y) screen.fill((0, 0, 0)) world.render(screen) player.draw(screen) pygame.display.update()
{"/world.py": ["/core.py", "/player.py", "/blocks.py"], "/blocks.py": ["/player.py"], "/game.py": ["/world.py", "/player.py"], "/main.py": ["/world.py"]}
58,156
mechbear14/mysterious-forest
refs/heads/master
/main.py
from world import Forest forest = Forest(6, 5) if __name__ == "__main__": forest.go_to(0, 1) forest.go_to(0, 2) forest.go_to(0, 3) forest.go_to(1, 1) forest.go_to(0, 0) forest.go_to(1, 0) forest.go_to(1, 1) forest.go_to(0, 2) forest.go_to(0, 3) forest.go_to(0, 4) forest.go_to(0, 5) forest.go_to(1, 0) forest.go_to(2, 0) forest.go_to(2, 1) forest.go_to(2, 0) forest.go_to(3, 0) forest.go_to(4, 0) forest.go_to(5, 0) forest.go_to(6, 0)
{"/world.py": ["/core.py", "/player.py", "/blocks.py"], "/blocks.py": ["/player.py"], "/game.py": ["/world.py", "/player.py"], "/main.py": ["/world.py"]}
58,157
mechbear14/mysterious-forest
refs/heads/master
/player.py
import pygame from pygame.sprite import Sprite from pygame import Vector2, Surface, Rect, Color class BasePlayer(Sprite): NORMAL = 0 def __init__(self, x: int, y: int): self.position = Vector2(x, y) self.size = Vector2(50, 50) self.canvas_position = Vector2(x * 50, y * 50) self.state = Player.NORMAL self.image = Surface(self.size).convert_alpha() self.rect = Rect(self.canvas_position, self.size) def update_position(self, x: int, y: int): self.position = Vector2(x, y) sx, sy = self.size.x, self.size.y self.canvas_position = Vector2(x * sx, y * sy) self.rect = Rect(self.canvas_position, self.size) def on_create(self): pass def on_move(self): pass def draw(self, area: Surface): area.blit(self.image, self.rect) class Player(BasePlayer): def __init__(self, x: int, y: int): BasePlayer.__init__(self, x, y) self.on_create() def on_create(self): pygame.draw.circle(self.image, Color(255, 128, 0), self.canvas_position + self.size / 2, self.size.x / 2)
{"/world.py": ["/core.py", "/player.py", "/blocks.py"], "/blocks.py": ["/player.py"], "/game.py": ["/world.py", "/player.py"], "/main.py": ["/world.py"]}
58,161
tejaswinigsl/crud_t
refs/heads/master
/app/models.py
# Create your models here. from django.db import models class Employee1(models.Model): empid=models.IntegerField() name=models.CharField(max_length=100) phone =models.IntegerField() age=models.IntegerField() email=models.EmailField()
{"/app/views.py": ["/app/models.py", "/app/forms.py"], "/app/forms.py": ["/app/models.py"]}
58,162
tejaswinigsl/crud_t
refs/heads/master
/app/views.py
from django.shortcuts import render from django.contrib import messages # Create your views here. from django.shortcuts import render,redirect from app.models import Employee1 from app.forms import EmployeeForm1 # Create your views here. def show(request): employees=Employee1.objects.all() return render(request,'app/index.html',{'employees':employees}) def display(request): #form=EmployeeForm() if request.method=='POST': employeeid=request.POST['id'] name=request.POST['name'] phone=request.POST['phone'] age=request.POST['age'] email=request.POST['email'] if employeeid=='' or name=='' or phone=='' or email=='' or age=='': messages.info(request,'fill all details') return redirect('/') else: form=Employee1.objects.create(empid=employeeid,name=name,phone=phone,email=email,age=age) form.save(); return redirect('/') return render(request,'app/index.html') def delete(request,id): employee=Employee1.objects.get(id=id) employee.delete() employees=Employee1.objects.all() return render(request,'app/index.html',{'employees':employees, 'res':'true', 'msg':'Deleted ', 'classStyle':"alert "}) def update(request,id): employee=Employee1.objects.get(id=id) if request.method=='POST': form=EmployeeForm1(request.POST ,instance=employee) if form.is_valid(): form.save() return render(request,'app/update.html',{'employee':employee,'res':'true','msg':' values updated ', 'classStyle':"alert alert-dark"}) else: return render(request,'app/update.html',{'employee':employee,'res':'false', 'msg':'Invalid', 'classStyle':'alert alert-dark'}) else: return render(request,'app/update.html',{'employee':employee,'res':'false'})
{"/app/views.py": ["/app/models.py", "/app/forms.py"], "/app/forms.py": ["/app/models.py"]}
58,163
tejaswinigsl/crud_t
refs/heads/master
/app/forms.py
from django import forms from app.models import Employee1 class EmployeeForm1(forms.ModelForm): class Meta: model=Employee1 fields='__all__'
{"/app/views.py": ["/app/models.py", "/app/forms.py"], "/app/forms.py": ["/app/models.py"]}
58,173
philipp-kurz/PoolFlow-Skarfify-Data_Engineering
refs/heads/main
/data_mappings.py
country_mapping = { 582: 'MEXICO Air Sea, and Not Reported (I-94, no land arrivals)', 236: 'AFGHANISTAN', 101: 'ALBANIA', 316: 'ALGERIA', 102: 'ANDORRA', 324: 'ANGOLA', 529: 'ANGUILLA', 518: 'ANTIGUA-BARBUDA', 687: 'ARGENTINA ', 151: 'ARMENIA', 532: 'ARUBA', 438: 'AUSTRALIA', 103: 'AUSTRIA', 152: 'AZERBAIJAN', 512: 'BAHAMAS', 298: 'BAHRAIN', 274: 'BANGLADESH', 513: 'BARBADOS', 104: 'BELGIUM', 581: 'BELIZE', 386: 'BENIN', 509: 'BERMUDA', 153: 'BELARUS', 242: 'BHUTAN', 688: 'BOLIVIA', 717: 'BONAIRE, ST EUSTATIUS, SABA', 164: 'BOSNIA-HERZEGOVINA', 336: 'BOTSWANA', 689: 'BRAZIL', 525: 'BRITISH VIRGIN ISLANDS', 217: 'BRUNEI', 105: 'BULGARIA', 393: 'BURKINA FASO', 243: 'BURMA', 375: 'BURUNDI', 310: 'CAMEROON', 326: 'CAPE VERDE', 526: 'CAYMAN ISLANDS', 383: 'CENTRAL AFRICAN REPUBLIC', 384: 'CHAD', 690: 'CHILE', 245: 'CHINA, PRC', 721: 'CURACAO', 270: 'CHRISTMAS ISLAND', 271: 'COCOS ISLANDS', 691: 'COLOMBIA', 317: 'COMOROS', 385: 'CONGO', 467: 'COOK ISLANDS', 575: 'COSTA RICA', 165: 'CROATIA', 584: 'CUBA', 218: 'CYPRUS', 140: 'CZECH REPUBLIC', 723: 'FAROE ISLANDS (PART OF DENMARK)', 108: 'DENMARK', 322: 'DJIBOUTI', 519: 'DOMINICA', 585: 'DOMINICAN REPUBLIC', 240: 'EAST TIMOR', 692: 'ECUADOR', 368: 'EGYPT', 576: 'EL SALVADOR', 399: 'EQUATORIAL GUINEA', 372: 'ERITREA', 109: 'ESTONIA', 369: 'ETHIOPIA', 604: 'FALKLAND ISLANDS', 413: 'FIJI', 110: 'FINLAND', 111: 'FRANCE', 601: 'FRENCH GUIANA', 411: 'FRENCH POLYNESIA', 387: 'GABON', 338: 'GAMBIA', 758: 'GAZA STRIP', 154: 'GEORGIA', 112: 'GERMANY', 339: 'GHANA', 143: 'GIBRALTAR', 113: 'GREECE', 520: 'GRENADA', 507: 'GUADELOUPE', 577: 'GUATEMALA', 382: 'GUINEA', 327: 'GUINEA-BISSAU', 603: 'GUYANA', 586: 'HAITI', 726: 'HEARD AND MCDONALD IS.', 149: 'HOLY SEE/VATICAN', 528: 'HONDURAS', 206: 'HONG KONG', 114: 'HUNGARY', 115: 'ICELAND', 213: 'INDIA', 759: 'INDIAN OCEAN AREAS (FRENCH)', 729: 'INDIAN OCEAN TERRITORY', 204: 'INDONESIA', 249: 'IRAN', 250: 'IRAQ', 116: 'IRELAND', 251: 'ISRAEL', 117: 'ITALY', 388: 'IVORY COAST', 514: 'JAMAICA', 209: 'JAPAN', 253: 'JORDAN', 201: 'KAMPUCHEA', 155: 'KAZAKHSTAN', 340: 'KENYA', 414: 'KIRIBATI', 732: 'KOSOVO', 272: 'KUWAIT', 156: 'KYRGYZSTAN', 203: 'LAOS', 118: 'LATVIA', 255: 'LEBANON', 335: 'LESOTHO', 370: 'LIBERIA', 381: 'LIBYA', 119: 'LIECHTENSTEIN', 120: 'LITHUANIA', 121: 'LUXEMBOURG', 214: 'MACAU', 167: 'MACEDONIA', 320: 'MADAGASCAR', 345: 'MALAWI', 273: 'MALAYSIA', 220: 'MALDIVES', 392: 'MALI', 145: 'MALTA', 472: 'MARSHALL ISLANDS', 511: 'MARTINIQUE', 389: 'MAURITANIA', 342: 'MAURITIUS', 760: 'MAYOTTE (AFRICA - FRENCH)', 473: 'MICRONESIA, FED. STATES OF', 157: 'MOLDOVA', 122: 'MONACO', 299: 'MONGOLIA', 735: 'MONTENEGRO', 521: 'MONTSERRAT', 332: 'MOROCCO', 329: 'MOZAMBIQUE', 371: 'NAMIBIA', 440: 'NAURU', 257: 'NEPAL', 123: 'NETHERLANDS', 508: 'NETHERLANDS ANTILLES', 409: 'NEW CALEDONIA', 464: 'NEW ZEALAND', 579: 'NICARAGUA', 390: 'NIGER', 343: 'NIGERIA', 470: 'NIUE', 275: 'NORTH KOREA', 124: 'NORWAY', 256: 'OMAN', 258: 'PAKISTAN', 474: 'PALAU', 743: 'PALESTINE', 504: 'PANAMA', 441: 'PAPUA NEW GUINEA', 693: 'PARAGUAY', 694: 'PERU', 260: 'PHILIPPINES', 416: 'PITCAIRN ISLANDS', 107: 'POLAND', 126: 'PORTUGAL', 297: 'QATAR', 748: 'REPUBLIC OF SOUTH SUDAN', 321: 'REUNION', 127: 'ROMANIA', 158: 'RUSSIA', 376: 'RWANDA', 128: 'SAN MARINO', 330: 'SAO TOME AND PRINCIPE', 261: 'SAUDI ARABIA', 391: 'SENEGAL', 142: 'SERBIA AND MONTENEGRO', 745: 'SERBIA', 347: 'SEYCHELLES', 348: 'SIERRA LEONE', 207: 'SINGAPORE', 141: 'SLOVAKIA', 166: 'SLOVENIA', 412: 'SOLOMON ISLANDS', 397: 'SOMALIA', 373: 'SOUTH AFRICA', 276: 'SOUTH KOREA', 129: 'SPAIN', 244: 'SRI LANKA', 346: 'ST. HELENA', 522: 'ST. KITTS-NEVIS', 523: 'ST. LUCIA', 502: 'ST. PIERRE AND MIQUELON', 524: 'ST. VINCENT-GRENADINES', 716: 'SAINT BARTHELEMY', 736: 'SAINT MARTIN', 749: 'SAINT MAARTEN', 350: 'SUDAN', 602: 'SURINAME', 351: 'SWAZILAND', 130: 'SWEDEN', 131: 'SWITZERLAND', 262: 'SYRIA', 268: 'TAIWAN', 159: 'TAJIKISTAN', 353: 'TANZANIA', 263: 'THAILAND', 304: 'TOGO', 417: 'TONGA', 516: 'TRINIDAD AND TOBAGO', 323: 'TUNISIA', 264: 'TURKEY', 161: 'TURKMENISTAN', 527: 'TURKS AND CAICOS ISLANDS', 420: 'TUVALU', 352: 'UGANDA', 162: 'UKRAINE', 296: 'UNITED ARAB EMIRATES', 135: 'UNITED KINGDOM', 695: 'URUGUAY', 163: 'UZBEKISTAN', 410: 'VANUATU', 696: 'VENEZUELA', 266: 'VIETNAM', 469: 'WALLIS AND FUTUNA ISLANDS', 757: 'WEST INDIES (FRENCH)', 333: 'WESTERN SAHARA', 465: 'WESTERN SAMOA', 216: 'YEMEN', 139: 'YUGOSLAVIA', 301: 'ZAIRE', 344: 'ZAMBIA', 315: 'ZIMBABWE', 403: 'INVALID: AMERICAN SAMOA', 712: 'INVALID: ANTARCTICA', 700: 'INVALID: BORN ON BOARD SHIP', 719: 'INVALID: BOUVET ISLAND (ANTARCTICA/NORWAY TERR.)', 574: 'INVALID: CANADA', 720: 'INVALID: CANTON AND ENDERBURY ISLS', 106: 'INVALID: CZECHOSLOVAKIA', 739: 'INVALID: DRONNING MAUD LAND (ANTARCTICA-NORWAY)', 394: 'INVALID: FRENCH SOUTHERN AND ANTARCTIC', 501: 'INVALID: GREENLAND', 404: 'INVALID: GUAM', 730: 'INVALID: INTERNATIONAL WATERS', 731: 'INVALID: JOHNSON ISLAND', 471: 'INVALID: MARIANA ISLANDS, NORTHERN', 737: 'INVALID: MIDWAY ISLANDS', 753: 'INVALID: MINOR OUTLYING ISLANDS - USA', 740: 'INVALID: NEUTRAL ZONE (S. ARABIA/IRAQ)', 710: 'INVALID: NON-QUOTA IMMIGRANT', 505: 'INVALID: PUERTO RICO', 0 : 'INVALID: STATELESS', 705: 'INVALID: STATELESS', 583: 'INVALID: UNITED STATES', 407: 'INVALID: UNITED STATES', 999: 'INVALID: UNKNOWN', 239: 'INVALID: UNKNOWN COUNTRY', 134: 'INVALID: USSR', 506: 'INVALID: U.S. VIRGIN ISLANDS', 755: 'INVALID: WAKE ISLAND', 311: 'Collapsed Tanzania (should not show)', 741: 'Collapsed Curacao (should not show)', 54: 'No Country Code (54)', 100: 'No Country Code (100)', 187: 'No Country Code (187)', 190: 'No Country Code (190)', 200: 'No Country Code (200)', 219: 'No Country Code (219)', 238: 'No Country Code (238)', 277: 'No Country Code (277)', 293: 'No Country Code (293)', 300: 'No Country Code (300)', 319: 'No Country Code (319)', 365: 'No Country Code (365)', 395: 'No Country Code (395)', 400: 'No Country Code (400)', 485: 'No Country Code (485)', 503: 'No Country Code (503)', 589: 'No Country Code (589)', 592: 'No Country Code (592)', 791: 'No Country Code (791)', 849: 'No Country Code (849)', 914: 'No Country Code (914)', 944: 'No Country Code (944)', 996: 'No Country Code (996)' } transportation_mapping = { 1: 'Air', 2: 'Sea', 3: 'Land', 9: 'Not reported' } state_mapping = { 'AL': 'ALABAMA', 'AK': 'ALASKA', 'AZ': 'ARIZONA', 'AR': 'ARKANSAS', 'CA': 'CALIFORNIA', 'CO': 'COLORADO', 'CT': 'CONNECTICUT', 'DE': 'DELAWARE', 'DC': 'DIST. OF COLUMBIA', 'FL': 'FLORIDA', 'GA': 'GEORGIA', 'GU': 'GUAM', 'HI': 'HAWAII', 'ID': 'IDAHO', 'IL': 'ILLINOIS', 'IN': 'INDIANA', 'IA': 'IOWA', 'KS': 'KANSAS', 'KY': 'KENTUCKY', 'LA': 'LOUISIANA', 'ME': 'MAINE', 'MD': 'MARYLAND', 'MA': 'MASSACHUSETTS', 'MI': 'MICHIGAN', 'MN': 'MINNESOTA', 'MS': 'MISSISSIPPI', 'MO': 'MISSOURI', 'MT': 'MONTANA', 'NC': 'N. CAROLINA', 'ND': 'N. DAKOTA', 'NE': 'NEBRASKA', 'NV': 'NEVADA', 'NH': 'NEW HAMPSHIRE', 'NJ': 'NEW JERSEY', 'NM': 'NEW MEXICO', 'NY': 'NEW YORK', 'OH': 'OHIO', 'OK': 'OKLAHOMA', 'OR': 'OREGON', 'PA': 'PENNSYLVANIA', 'PR': 'PUERTO RICO', 'RI': 'RHODE ISLAND', 'SC': 'S. CAROLINA', 'SD': 'S. DAKOTA', 'TN': 'TENNESSEE', 'TX': 'TEXAS', 'UT': 'UTAH', 'VT': 'VERMONT', 'VI': 'VIRGIN ISLANDS', 'VA': 'VIRGINIA', 'WV': 'W. VIRGINIA', 'WA': 'WASHINGTON', 'WI': 'WISCONSON', 'WY': 'WYOMING', '99': 'All Other Codes' } visa_type_mapping = { 1: "Business", 2: "Pleasure", 3: "Student" }
{"/etl.py": ["/data_mappings.py"]}
58,174
philipp-kurz/PoolFlow-Skarfify-Data_Engineering
refs/heads/main
/etl.py
import configparser import os from pyspark.sql import SparkSession from data_mappings import * import pyspark.sql.functions as F import pyspark.sql.types as T from itertools import chain import datetime def create_spark_session(): ''' Returns a Spark session for the ETL job. Returns: spark: Spark session object ''' os.environ["JAVA_HOME"] = "/usr/lib/jvm/java-8-openjdk-amd64" os.environ["PATH"] = "/opt/conda/bin:/opt/spark-2.4.3-bin-hadoop2.7/bin:/opt/conda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/lib/jvm/java-8-openjdk-amd64/bin" os.environ["SPARK_HOME"] = "/opt/spark-2.4.3-bin-hadoop2.7" os.environ["HADOOP_HOME"] = "/opt/spark-2.4.3-bin-hadoop2.7" return SparkSession.builder.getOrCreate() def process_immigration_data(spark, input_data): ''' Processes I94 immigration data SAS files and returns a Spark data frame of the resulting immigration table Parameters: spark (object): A Spark session object input_data (str): Input path to the data Returns: A spark dataframe for the resulting immigration table ''' print('Processing immigration data') df_immigration_data = spark.read.load(input_data) immigration_columns = { 'cicid': ('immigration_id', 'int'), 'i94port': ('airport_id', 'string'), 'i94res': ('residency_unmapped', 'int'), 'i94addr': ('destination_state', 'string'), 'arrdate': ('arrival_date_unmapped', 'int'), 'i94bir': ('age', 'int'), 'gender': ('gender', 'string'), 'airline': ('airline', 'string'), 'i94visa': ('visa_type_unmapped', 'int') } drop_columns = [value[0] for value in immigration_columns.values() if 'unmapped' in value[0]] # https://stackoverflow.com/questions/42980704/pyspark-create-new-column-with-mapping-from-a-dict # Accessed: 18/05/2021 country_mapping_expr = F.create_map([F.initcap(F.lit(x)) for x in chain(*country_mapping.items())]) visa_type_mapping_expr = F.create_map([F.lit(x) for x in chain(*visa_type_mapping.items())]) # https://stackoverflow.com/questions/26923564/convert-sas-numeric-to-python-datetime # Accessed: 18/05/2021 epoch_start = datetime.datetime(1960, 1, 1) sas_date_udf = F.udf(lambda sas_date_int: epoch_start + datetime.timedelta(days=sas_date_int), T.TimestampType()) selectExpressions = [f'cast({old} as {new[1]}) as {new[0]}' for old, new in immigration_columns.items()] df_immigration_table = df_immigration_data.selectExpr(*selectExpressions)\ .withColumn('residency', country_mapping_expr.getItem(F.col("residency_unmapped")))\ .withColumn('visa_type', visa_type_mapping_expr.getItem(F.col("visa_type_unmapped")))\ .withColumn('arrival_date', sas_date_udf(F.col('arrival_date_unmapped')))\ .drop(*drop_columns) return df_immigration_table def process_airport_data(spark, input_data): ''' Processes the airport data set and returns a Spark data frame of the resulting airports table Parameters: spark (object): A Spark session object input_data (str): Input path to the data Returns: A spark dataframe for the resulting airports table ''' print('Processing airport data') df_airports_data = spark.read.option("header",True).csv(input_data) airport_columns = { 'iata_code': ('airport_id', 'string'), 'name': ('airport_name', 'string'), 'municipality': ('city', 'string'), 'iso_region': ('state_unmapped', 'string'), 'elevation_ft': ('elevation_ft', 'string') } selectExpressions = [f'cast({old} as {new[1]}) as {new[0]}' for old, new in airport_columns.items()] drop_columns = [value[0] for value in airport_columns.values() if 'unmapped' in value[0]] state_mapping_udf = F.udf(lambda state_code: state_code[3:]) df_airports_table = df_airports_data.filter(F.col('iata_code').isNotNull())\ .filter(F.col('iso_country') == 'US')\ .filter(F.col('type') != 'closed')\ .selectExpr(*selectExpressions)\ .withColumn('state', state_mapping_udf(F.col('state_unmapped')))\ .drop(*drop_columns) return df_airports_table def process_temperature_data(spark, input_data): ''' Processes temperature data files and returns a Spark data frame of the resulting temperatures table Parameters: spark (object): A Spark session object input_data (str): Input path to the data Returns: A spark dataframe for the resulting temperatures table ''' print('Processing temperature data') df_temperature_data = spark.read.option("header",True).csv(input_data) temperature_columns = { 'dt': ('date', 'date'), 'City': ('city', 'string'), 'Country': ('country', 'string'), 'AverageTemperature': ('temperature', 'float') } selectExpressions = [f'cast({old} as {new[1]}) as {new[0]}' for old, new in temperature_columns.items()] df_temperature_table = df_temperature_data.filter(F.col('AverageTemperature').isNotNull())\ .filter(F.col('dt') >= '2010-01-01')\ .selectExpr(*selectExpressions)\ .withColumn('temperature_id', F.monotonically_increasing_id()) return df_temperature_table def process_demographics_data(spark, input_data): ''' Processes US demographics data set and returns a Spark data frame of the resulting demographics table Parameters: spark (object): A Spark session object input_data (str): Input path to the data Returns: A spark dataframe for the resulting demographics table ''' print('Processing demographics data') df_us_demographics_data = spark.read.option("header",True).option("delimiter",';').csv(input_data) us_demographics_columns = { 'City': ('us_city', 'string'), '`State Code`': ('state', 'string'), '`Total Population`': ('total_pop', 'int'), '`Median Age`': ('median_age', 'int'), '`Foreign-born`': ('foreign_born_pop', 'int') } selectExpressions = [f'cast({old} as {new[1]}) as {new[0]}' for old, new in us_demographics_columns.items()] df_us_demographics_table = df_us_demographics_data.selectExpr(*selectExpressions)\ .withColumn('fraction_foreign_born', F.col('foreign_born_pop') / F.col('total_pop')) return df_us_demographics_table def check_immigration_data(spark, df_immigration_table): ''' Runs quality checks on immigration data and prints results Parameters: spark (object): A Spark session object df_immigration_table (object): A spark data frame with the immigration table ''' print('Checking immigration table.') num_rows = df_immigration_table.count() print(f"{num_rows} of new immigration entries were found! Should be > 0.") num_negative_age = df_immigration_table.filter(F.col('age') < 0).count() print(f"{num_negative_age} records with negative age found! Should be 0.") min_date = '2000-01-01' # Retrieve date from Airflow DAG run instead num_old_date = df_immigration_table.filter(F.col('arrival_date') < min_date).count() print(f"{num_old_date} records with too old date found! Should be 0.") def check_airports_data(spark, df_airports_table): ''' Runs quality checks on airports data and prints results Parameters: spark (object): A Spark session object df_airports_table (object): A spark data frame with the airports table ''' print('Checking airports table.') # https://stackoverflow.com/questions/48229043/python-pyspark-count-null-empty-and-nan # Accessed: 24/05/2021 num_empty_rows = df_airports_table.filter((F.col("airport_id") == "") | F.col("airport_id").isNull() | F.isnan(F.col("airport_id"))).count() print(f"{num_empty_rows} records empty airport ID! Should be 0.") def check_temperature_data(spark, df_temperature_table): ''' Runs quality checks on temperature data and prints results Parameters: spark (object): A Spark session object df_temperature_table (object): A spark data frame with the temperature table ''' print('Checking temperature table.') num_null_rows = df_temperature_table.filter(F.col("temperature").isNull()).count() print(f"{num_null_rows} records with empty temperature found! Should be 0.") def check_demographics_data(spark, df_us_demographics_table): ''' Runs quality checks on demographics data and prints results Parameters: spark (object): A Spark session object df_us_demographics_table (object): A spark data frame with the US demographics table ''' print('Checking demographics table.') num_negative_rows = df_us_demographics_table.filter(F.col("total_pop") <= 0).count() print(f"{num_negative_rows} records with negative total population found! Should be 0.") def store_df_as_parquet(input_df, output_path): ''' Stores given Spark dataframes as Parquet files Parameters: input_df (object): A spark data frame output_path (str): Path where the parquet files should be stored ''' print(f'Writing Spark dataframe to {output_path}') input_df.write.parquet(output_path) def main(): config = configparser.ConfigParser() config.read('configs.ini') spark = create_spark_session() df_immigration_table = process_immigration_data(spark, config['input']['immigration']) df_airports_table = process_airport_data(spark, config['input']['airports']) df_temperature_table = process_temperature_data(spark, config['input']['temperatures']) df_us_demographics_table = process_demographics_data(spark, config['input']['demographics']) check_immigration_data(spark, df_immigration_table) check_airports_data(spark, df_airports_table) check_temperature_data(spark, df_temperature_table) check_demographics_data(spark, df_us_demographics_table) store_df_as_parquet(df_immigration_table, config['output']['folder_path'] + 'immigrants') store_df_as_parquet(df_airports_table, config['output']['folder_path'] + 'airports') store_df_as_parquet(df_temperature_table, config['output']['folder_path'] + 'temperatures') store_df_as_parquet(df_us_demographics_table, config['output']['folder_path'] + 'demographics') if __name__ == "__main__": main()
{"/etl.py": ["/data_mappings.py"]}
58,180
lin54241930/monkey_tcloud
refs/heads/master
/auto_install.py
import os import time from multiprocessing import Pool import uiautomator2 as u2 import subprocess def conndevice(device): d = u2.connect(device) return d def getDevicesAll(): # 获取devices数量和名称 devices = [] try: for dName_ in os.popen("adb devices"): if "\t" in dName_: if dName_.find("emulator") < 0: devices.append(dName_.split("\t")[0]) devices.sort(cmp=None, key=None, reverse=False) print(devices) except: pass print(u"\n设备名称: %s \n总数量:%s台" % (devices, len(devices))) return devices def check_screen_locked(device, d, times=1): try: if times >= 3: return False print('({}) <尝试{}次> 检查设备是否锁屏'.format(device, times)) if d.info.get('screenOn') == True: print('({}) 设备是亮屏状态!'.format(device)) d.press("power") print('({}) 关闭屏幕一次!'.format(device)) time.sleep(2) d.unlock() print('({}) 执行一次解锁'.format(device)) d.press("home") print('({}) 按一次home回到桌面'.format(device)) return True else: print('({}) 设备是黑屏状态!'.format(device)) d.unlock() print('({}) 直接执行解锁'.format(device)) d.press("home") print('({}) 按一次home回到桌面'.format(device)) return True except Exception as e: print(e) return check_screen_locked(times=times + 1) def input_autoinstall(device, d): try: devices_v = d.device_info["version"] devices_version = devices_v[0:3] display = d.device_info["display"] my_display = '{}*{}'.format(display["width"], display["height"]) print('当前手机系统版本为 {}'.format(devices_version)) print('检测是否是vivo或者OPPO手机 {}'.format(device)) print('当前屏幕分辨率为 {}'.format(my_display)) if d.device_info["brand"] == 'vivo': print('检测到vivo手机 {}'.format(device)) if float(devices_version) > 5 and float(devices_version) < 9: d(resourceId="vivo:id/vivo_adb_install_ok_button").click() else: print('开始输入密码 {}'.format(device)) d.xpath( '//*[@resource-id="com.bbk.account:id/dialog_pwd"]/android.widget.LinearLayout[1]/android.widget.RelativeLayout[1]').set_text( "Pokercity2019") print('点击确认按钮 {}'.format(device)) d(resourceId="android:id/button1").click() print('等待10s检测应用安全性 {}'.format(device)) d(resourceId="com.sohu.inputmethod.sogou.vivo:id/imeview_keyboard").wait(timeout=10.0) print('点击安装按钮 {}'.format(device)) d.click(0.497, 0.858) return True elif d.device_info["brand"] == 'OPPO': print('检测到OPPO手机 {}'.format(device)) print('开始输入密码 {}'.format(device)) d(resourceId="com.coloros.safecenter:id/et_login_passwd_edit").set_text("Pokercity2019") print('点击确认按钮 {}'.format(device)) d(resourceId="android:id/button1").click() print('等待8s检测应用安全性 {}'.format(device)) time.sleep(8) if d(text="发现广告插件").exists: d.click(0.686, 0.929) time.sleep(2) d.click(0.482, 0.84) return True else: if float(devices_version) > 5 and float(devices_version) < 7: d.click(0.718, 0.957) return True elif float(devices_version) > 8 and float(devices_version) < 11: d.click(0.495, 0.954) return True elif float(devices_version) < 5.3 and float(devices_version) >= 5: d.click(0.498, 0.793) return True else: return True else: return True except Exception as e: print(e) return False def quickinstall(device): packagename = "com.saiyun.vtmjzz" i = "/Users/boke/Downloads/apk/mjzz_release_1.07_0727-appetizer.apk" cmd = '{} -s {} {} {}'.format("adb", device, "install", i) print(cmd) # 卸载原有apk d = u2.connect(device) try: os.system('adb -s ' + device + ' uninstall %s' % packagename) print(device + " 卸载成功\n") except: print(device + " 卸载失败\n") check_screen_locked(device, d) subprocess.Popen(cmd, shell=True) time.sleep(10) input_autoinstall(device, d) def qainstall(devices): starting = time.time() pool = Pool() # 创建8个任务池 result = pool.map(quickinstall, devices) entire = time.time() pool.close() print(entire - starting) # 打印时间 if __name__ == "__main__": try: devices = getDevicesAll() except: print("获取设备出错") try: qainstall(devices) except: print("进程出错")
{"/automonkey/device.py": ["/automonkey/adb.py", "/automonkey/exception.py"], "/automonkey/utils.py": ["/automonkey/config.py", "/automonkey/exception.py"], "/automonkey/runner.py": ["/automonkey/config.py", "/automonkey/case.py", "/automonkey/exception.py", "/automonkey/monkey_runner.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py", "/automonkey/performance_runner.py"], "/automonkey/performance_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/monkey_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/tcloud_update.py": ["/automonkey/config.py"], "/automonkey/main.py": ["/automonkey/program.py"], "/automonkey/adb.py": ["/automonkey/exception.py", "/automonkey/utils.py"], "/automonkey/program.py": ["/automonkey/config.py", "/automonkey/loader.py", "/automonkey/recorder.py", "/automonkey/runner.py", "/automonkey/utils.py"], "/automonkey/performance.py": ["/automonkey/result.py", "/automonkey/device.py", "/automonkey/config.py"], "/automonkey/result.py": ["/automonkey/config.py"], "/automonkey/logcat.py": ["/automonkey/adb.py", "/automonkey/config.py", "/automonkey/utils.py"], "/automonkey/case.py": ["/automonkey/performance.py", "/automonkey/device.py", "/automonkey/monkey.py", "/automonkey/result.py"], "/automonkey/monkey.py": ["/automonkey/config.py", "/automonkey/device.py", "/automonkey/result.py"], "/automonkey/loader.py": ["/automonkey/case.py"]}
58,181
lin54241930/monkey_tcloud
refs/heads/master
/automonkey/device.py
import logging import traceback from .adb import AdbTool from .exception import DeviceNotConnectedException logger = logging.getLogger(__name__) """ # 设备操作 # 包括 连接设备, 断开设备 # 其他 """ class Device(object): def __init__(self): self.device_id = '' self.system_device = True self.adb_tool = None def constructor(self, config, ): self.device_id = config.get('device_id') self.system_device = config.get('system_device') self.adb_tool = AdbTool(self.device_id) @property def info(self): return { 'device_id': self.device_id, 'system_device': self.system_device, } def connect(self): try: # connect stuff logger.info('开始连接设备 {}'.format(self.device_id)) adb_version = self.adb_tool.get_adb_version() logger.info('Adb Version is : {}'.format(adb_version)) all_devices = self.adb_tool.get_device_list() logger.info('all devices : {} '.format(all_devices)) if self.adb_tool.check_device_connected(self.device_id): logger.info('设备 {} 连接成功!'.format(self.device_id)) return True else: logger.info('设备 {} 不在设备列表中!'.format(self.device_id)) raise DeviceNotConnectedException except DeviceNotConnectedException as device_error: logger.error(device_error) return device_error except Exception as e: logger.error(e) logger.error(traceback.format_exc()) return False def disconnect(self): try: # connect stuff # TODO: need disconnect or not??? pass except Exception as e: logger.error(e) logger.error(traceback.format_exc())
{"/automonkey/device.py": ["/automonkey/adb.py", "/automonkey/exception.py"], "/automonkey/utils.py": ["/automonkey/config.py", "/automonkey/exception.py"], "/automonkey/runner.py": ["/automonkey/config.py", "/automonkey/case.py", "/automonkey/exception.py", "/automonkey/monkey_runner.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py", "/automonkey/performance_runner.py"], "/automonkey/performance_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/monkey_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/tcloud_update.py": ["/automonkey/config.py"], "/automonkey/main.py": ["/automonkey/program.py"], "/automonkey/adb.py": ["/automonkey/exception.py", "/automonkey/utils.py"], "/automonkey/program.py": ["/automonkey/config.py", "/automonkey/loader.py", "/automonkey/recorder.py", "/automonkey/runner.py", "/automonkey/utils.py"], "/automonkey/performance.py": ["/automonkey/result.py", "/automonkey/device.py", "/automonkey/config.py"], "/automonkey/result.py": ["/automonkey/config.py"], "/automonkey/logcat.py": ["/automonkey/adb.py", "/automonkey/config.py", "/automonkey/utils.py"], "/automonkey/case.py": ["/automonkey/performance.py", "/automonkey/device.py", "/automonkey/monkey.py", "/automonkey/result.py"], "/automonkey/monkey.py": ["/automonkey/config.py", "/automonkey/device.py", "/automonkey/result.py"], "/automonkey/loader.py": ["/automonkey/case.py"]}
58,182
lin54241930/monkey_tcloud
refs/heads/master
/automonkey/utils.py
import logging import os import subprocess import sys import traceback from datetime import datetime import oss2 import prettytable import requests from automonkey.config import DefaultConfig from automonkey.exception import FileDownloadErrorException logger = logging.getLogger(__name__) """ # 工具类 """ class Utils(object): @classmethod def command_execute(cls, cmd): try: if not cmd: return False logger.info(cmd) command_process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, executable="/bin/bash") return command_process except Exception as e: logger.error(e) traceback.print_exc() @classmethod def bug_report_tool(cls, log_path): try: if not os.path.exists(log_path): return None local_path = os.getcwd() chk_path = os.path.abspath(os.path.join(local_path, "./tools/check_bug_report/chkbugreport")) jar_path = os.path.abspath(os.path.join(local_path, "./tools/check_bug_report")) if not os.path.exists(chk_path): logger.error('tool path not found at {}'.format(chk_path)) return None os.system('chmod +x {}'.format(chk_path)) cmd = '{} {} {}'.format(chk_path, log_path, jar_path) p = cls.command_execute(cmd) return p.stdout.readlines() except Exception as e: logger.error(e) logger.error(traceback.format_exc()) @classmethod def show_info_as_table(cls, keys, values): # keys list; values list(dict) or dict table = prettytable.PrettyTable() if isinstance(values, list): table.field_names = keys for v in values: if isinstance(v, list): row = v elif isinstance(v, dict): row = v.values() table.add_row(row) elif isinstance(values, dict): table.field_names = ['key', 'value'] for v in keys: row = [v, values.get(v)] table.add_row(row) logger.info('\n{}'.format(table)) # 下载 apk 文件 @classmethod def download_apk_from_url(cls, url, target_path, target_name): try: if not os.path.exists(target_path): os.mkdir(target_path) if target_name is None: date_time_now = datetime.now().strftime('%Y%m%d-%H.%M.%S') target_name = '{}.apk'.format(date_time_now) elif not target_name.endswith('.apk'): target_name = '{}.apk'.format(target_name) download_apk_name = os.path.join(target_path, target_name) logger.info('开始从 {} 下载到 {}'.format(url, download_apk_name)) response = requests.get(url=url, verify=False) with open(download_apk_name, 'wb') as f: f.write(response.content) # 下载失败 if not os.path.exists(download_apk_name): logger.error('{} 下载失败!'.format(url)) raise FileDownloadErrorException logger.info('下载成功,保存地址 {}'.format(download_apk_name)) return download_apk_name except Exception as e: print(e) traceback.print_exc() raise e @classmethod def upload_bug_report_log_to_oss(cls, log_path): endpoint = DefaultConfig.OSS_URL auth = DefaultConfig.OSS_AUTH bucket = oss2.Bucket(auth, endpoint, DefaultConfig.OSS_BUCKET_NAME) cls.upload_dir(log_path, bucket) @classmethod def upload_file_to_oss(cls, local_path, bucket): if not bucket: endpoint = DefaultConfig.OSS_URL auth = DefaultConfig.OSS_AUTH bucket = oss2.Bucket(auth, endpoint, DefaultConfig.OSS_BUCKET_NAME) now = datetime.now().strftime("%Y-%m-%d") build_number = os.environ.get('BUILD_NUMBER') remote_file_path = 'monkey/{}/{}/{}'.format(now, build_number, local_path) bucket.put_object_from_file('{}'.format(remote_file_path), local_path) @classmethod def upload_dir(cls, dir_path, bucket): if not bucket: endpoint = DefaultConfig.OSS_URL auth = DefaultConfig.OSS_AUTH bucket = oss2.Bucket(auth, endpoint, DefaultConfig.OSS_BUCKET_NAME) fs = os.listdir(dir_path) dir_path_new = dir_path for f in fs: file = dir_path_new + "/" + f if os.path.isdir(file): cls.upload_dir(file, bucket) else: if 'DS_Store' not in file: print(file) cls.upload_file_to_oss(file, bucket) @classmethod def deal_with_python_version(cls, data): if str(sys.version_info.major) == '3': if isinstance(data, list): return [d.decode('utf-8') for d in data] else: return data.decode('utf-8') else: return data
{"/automonkey/device.py": ["/automonkey/adb.py", "/automonkey/exception.py"], "/automonkey/utils.py": ["/automonkey/config.py", "/automonkey/exception.py"], "/automonkey/runner.py": ["/automonkey/config.py", "/automonkey/case.py", "/automonkey/exception.py", "/automonkey/monkey_runner.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py", "/automonkey/performance_runner.py"], "/automonkey/performance_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/monkey_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/tcloud_update.py": ["/automonkey/config.py"], "/automonkey/main.py": ["/automonkey/program.py"], "/automonkey/adb.py": ["/automonkey/exception.py", "/automonkey/utils.py"], "/automonkey/program.py": ["/automonkey/config.py", "/automonkey/loader.py", "/automonkey/recorder.py", "/automonkey/runner.py", "/automonkey/utils.py"], "/automonkey/performance.py": ["/automonkey/result.py", "/automonkey/device.py", "/automonkey/config.py"], "/automonkey/result.py": ["/automonkey/config.py"], "/automonkey/logcat.py": ["/automonkey/adb.py", "/automonkey/config.py", "/automonkey/utils.py"], "/automonkey/case.py": ["/automonkey/performance.py", "/automonkey/device.py", "/automonkey/monkey.py", "/automonkey/result.py"], "/automonkey/monkey.py": ["/automonkey/config.py", "/automonkey/device.py", "/automonkey/result.py"], "/automonkey/loader.py": ["/automonkey/case.py"]}
58,183
lin54241930/monkey_tcloud
refs/heads/master
/automonkey/runner.py
import logging import os import traceback from multiprocessing import Queue, Lock import prettytable from automonkey.config import DefaultConfig from .case import Case from .exception import CaseTypeErrorException, FileDownloadErrorException from .monkey_runner import MonkeyRunner from .tcloud_update import TCloud from .utils import Utils from .performance_runner import PerformanceRunner logger = logging.getLogger(__name__) """ # Runer # 运行 Case """ class Runner(object): def __init__(self): self.queue = None self.lock = None self.tcloud = None pass def show_system_information(self): pass def run(self, case): try: if not isinstance(case, Case): logger.error('Need Case Here, not {}'.format(type(case))) raise CaseTypeErrorException self.show_system_information() # 测试开始时间 case.result.on_case_begin() self.setup(case) if case.case_type == 1: self.run_monkeys(case.cases) elif case.case_type == 2: self.run_performance(case.cases) except Exception as e: logger.error(e) traceback.print_exc() def run_monkeys(self, monkeys): try: if not isinstance(monkeys, list): logger.error('Need list Here, not {}'.format(type(monkeys))) raise TypeError self.tcloud.on_monkey_begin(os.environ.get('BUILD_URL')) process_list = [] for monkey in monkeys: process = MonkeyRunner(self.queue, self.lock, monkey) process_list.append(process) for process in process_list: process.start() table_process = prettytable.PrettyTable() table_process.field_names = ["process id", "device id"] for process in process_list: row = [process.pid, process.monkey.device.device_id] table_process.add_row(row) logger.info('\n{}'.format(table_process)) results = [] while True: if len(results) == len(process_list): break if not self.queue.empty(): results.append(self.queue.get()) for result in results: print(result.info) except FileDownloadErrorException as f_e: logger.error(f_e) logger.error(traceback.format_exc()) self.tcloud.on_download_app(False) except Exception as e: logger.error(e) traceback.print_exc() finally: self.tcloud.on_monkey_end() def run_performance(self, performances): try: if not isinstance(performances, list): logger.error('Need list Here, not {}'.format(type(performances))) raise TypeError self.tcloud.on_monkey_begin(os.environ.get('BUILD_URL')) process_list = [] for performance in performances: process = PerformanceRunner(self.queue, self.lock, performance) process_list.append(process) for process in process_list: process.start() table_process = prettytable.PrettyTable() table_process.field_names = ["process id", "device id"] for process in process_list: row = [process.pid, process.performance.device.device_id] table_process.add_row(row) logger.info('\n{}'.format(table_process)) results = [] while True: if len(results) == len(process_list): break if not self.queue.empty(): results.append(self.queue.get()) for result in results: print(result.info) except FileDownloadErrorException as f_e: logger.error(f_e) logger.error(traceback.format_exc()) self.tcloud.on_download_app(False) except Exception as e: logger.error(e) traceback.print_exc() finally: self.tcloud.on_monkey_end() # 初始化 def setup(self, case): try: if not isinstance(case, Case): logger.error('Need Case Here, not {}'.format(type(case))) raise CaseTypeErrorException self.tcloud = TCloud(0, 0, monkey_id=case.monkey_id, tcloud_url=case.tcloud_url) # 下载文件 download_package = Utils.download_apk_from_url(case.app_download_url, DefaultConfig.LOCAL_APP_PATH, None) self.tcloud.on_download_app(True) case.bind_local_package_to_monkey(download_package) # 初始化 queue 用于多进程通信 self.queue = Queue(-1) # 初始化 lock 用于 多进程 self.lock = Lock() return download_package except Exception as e: logger.error(e) traceback.print_exc() raise e
{"/automonkey/device.py": ["/automonkey/adb.py", "/automonkey/exception.py"], "/automonkey/utils.py": ["/automonkey/config.py", "/automonkey/exception.py"], "/automonkey/runner.py": ["/automonkey/config.py", "/automonkey/case.py", "/automonkey/exception.py", "/automonkey/monkey_runner.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py", "/automonkey/performance_runner.py"], "/automonkey/performance_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/monkey_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/tcloud_update.py": ["/automonkey/config.py"], "/automonkey/main.py": ["/automonkey/program.py"], "/automonkey/adb.py": ["/automonkey/exception.py", "/automonkey/utils.py"], "/automonkey/program.py": ["/automonkey/config.py", "/automonkey/loader.py", "/automonkey/recorder.py", "/automonkey/runner.py", "/automonkey/utils.py"], "/automonkey/performance.py": ["/automonkey/result.py", "/automonkey/device.py", "/automonkey/config.py"], "/automonkey/result.py": ["/automonkey/config.py"], "/automonkey/logcat.py": ["/automonkey/adb.py", "/automonkey/config.py", "/automonkey/utils.py"], "/automonkey/case.py": ["/automonkey/performance.py", "/automonkey/device.py", "/automonkey/monkey.py", "/automonkey/result.py"], "/automonkey/monkey.py": ["/automonkey/config.py", "/automonkey/device.py", "/automonkey/result.py"], "/automonkey/loader.py": ["/automonkey/case.py"]}
58,184
lin54241930/monkey_tcloud
refs/heads/master
/automonkey/performance_runner.py
#!/usr/bin/python # -*- coding: utf-8 -*- import json import logging import os import time import traceback from datetime import datetime from multiprocessing import Process from automonkey.config import DefaultConfig from .adb import AdbTool from .exception import DeviceNotConnectedException, InstallAppException, CheckScreenLockedFailed from .logcat import LogCat from .tcloud_update import TCloud from .utils import Utils logger = logging.getLogger(__name__) """ # MonkeyRunner , 多进程 """ class PerformanceRunner(Process): def __init__(self, queue, lock, performance): super(PerformanceRunner, self).__init__() self.queue = queue self.performance = performance self.lock = lock self.daemon = True self.logcat = None self.adb_tool = None self.tcloud = None self.process = 0 def run(self): try: self.init_tools() # 开始测试 self.tcloud.on_task_begin() # 测试准备 self.setup() # 测试内容 self.run_performances() # 测试结束 self.teardown() except DeviceNotConnectedException as d_e: logger.error(d_e) self.performance.result.on_device_connect_failed() self.tcloud.on_device_connect(False) except CheckScreenLockedFailed as c_e: logger.error(c_e) self.performance.result.on_check_screen_lock_failed() self.tcloud.on_screen_lock(False) except InstallAppException as i_e: logger.error(i_e) self.performance.result.on_app_install_failed() self.tcloud.on_setup_install_app(False) except CheckScreenLockedFailed as s_e: logger.error(s_e) self.performance.result.on_check_screen_lock_failed() self.tcloud.on_screen_lock(False) except Exception as e: logger.error(e) traceback.print_exc() finally: logger.info('{} 结束测试 设备 {}'.format(self.pid, self.performance.device.device_id)) # 测试结束 self.teardown() self.publish_result() def get_performance_airtest_scripts(self): try: # os.system('rm -rf ./performancetest') # os.system('git clone http://mengwei@git.innotechx.com/scm/~mengwei/performancetest.git ./performancetest') os.system('cp -rf ./performancetest/* ./') except Exception as e: logger.error(e) def run_performances(self): try: if os.path.exists(self.performance.config.test_envs): if not os.path.exists(self.performance.config.test_envs): logger.error('config {} not found at local!'.format(self.performance.config.test_envs)) with open(self.performance.config.test_envs, 'r') as f: self.performance.config.test_envs = json.load(f) logger.info(self.performance.config.test_envs) tests_count = len(self.performance.config.test_envs.get('tests')) run_count = 0 for test_env in self.performance.config.test_envs.get('tests'): if self.on_user_cancel(): break self.adb_tool.clear_package_cache_data(self.performance.config.package_name) self.setup_air_test() self.run_performance(test_env, self.performance.config.test_envs.get('root'), tests_count, run_count) run_count += 1 # user cancel here if self.on_user_cancel(): self.tcloud.on_user_cancel_stask_success() except Exception as e: logger.error(e) logger.error(traceback.format_exc()) def run_performance(self, test_env, root_path, tests_count, run_count): try: test_name = test_env.get('name') test_path = '{}/{}'.format(root_path, test_env.get('path')) self.performance_test_id = self.tcloud.create_performance_test(test_name, self.performance.config.run_time) performance_progress = self.run_performance_cmd(test_path, test_name) time_begin = datetime.now() running_status = 1 running_error_reason = '' cancel_flag = False time.sleep(60) while True: time_temp = (datetime.now() - time_begin).seconds # 检测 performance progress 是否 if performance_progress.poll() is not None: logger.warning('[{}] performance stopped early !'.format(self.performance.device.device_id)) logger.info('[{}] try to rerun the performance!'.format(self.performance.device.device_id)) mins = self.performance.config.run_time - time_temp // 60 if mins <= 0: break performance_progress = self.run_performance_cmd(test_path, test_name) # 检测是否 进行了 中断操作 cancel_flag = self.on_user_cancel() if cancel_flag: break # 检测 设备连接和锁屏状态 if isinstance(self.performance.device.connect(), DeviceNotConnectedException): running_error_reason = 'device {} dis connect'.format(self.performance.device.device_id) running_status = 2 self.tcloud.on_device_disconnect_on_running() break self.adb_tool.check_screen_locked() self.get_cpu_rss_heap() self.on_process_changed(time_temp, tests_count, run_count) # 当 process == 100 , break if self.process == 100: break # time.sleep(1) time.sleep(30) # 此处的需要等待 log 写入 monkey_logs = [] # 等待 monkey 结束 while performance_progress.poll() is None: logger.info('waiting for monkey end...') time_temp = (datetime.now() - time_begin).seconds // 60 if time_temp > 1: if performance_progress.poll() is None: performance_progress.kill() break time.sleep(10) # user cancel here if cancel_flag: self.tcloud.on_user_cancel_stask_success() elif running_status == 2: self.tcloud.on_running_status(running_status, running_error_reason) self.performance.result.log_path = self.logcat.get_logcat_log(monkey_logs) # calculate every test's average and top self.tcloud.calculate_performance_test(self.performance_test_id) # 重复上传,删除 # self.get_gen_bug_report() # self.upload_other_report() time.sleep(10) except Exception as e: logger.error(e) logger.error(traceback.format_exc()) # finally: # self.teardown() def get_cpu_rss_heap(self): cpu, rss = self.adb_tool.get_cpu(self.performance.config.package_name) heap_size, heap_alloc = self.adb_tool.get_memory_info(self.performance.config.package_name) logger.info([cpu, rss, heap_size, heap_alloc]) self.tcloud.upload_realtime_log(self.performance_test_id, cpu, rss, heap_size, heap_alloc) def on_user_cancel(self): cancel_status = self.tcloud.get_monkey_cancel_status(self.performance.task_id) logger.info(cancel_status) if cancel_status in ['0', 0]: logger.warning('[{}] here find the cancel from the tcloud, stop the performance now!'. format(self.performance.device.device_id)) running_error_reason = 'cancel by user!' # on user cancel self.tcloud.on_user_cancel_task() cancel_flag = True else: cancel_flag = False return cancel_flag def run_performance_cmd(self, case_path, test_name): # 开始执行 logger.info('({}) 开始运行 performance 测试'.format(self.performance.device.device_id)) command = 'python3 -m airtest run {} --device Android://127.0.0.1:5037/{} ' \ '> {}_{}.log'.format(case_path, self.performance.device.device_id, self.local_performance_path, test_name) logger.info('({}) 开始运行 性能 测试'.format(self.performance.device.device_id)) monkey_progress = self.adb_tool.run_performance(command) return monkey_progress def setup_air_test(self): if self.performance.config.test_envs.get('setup') is not None: logger.info('({}) 开始运行 性能 测试 init'.format(self.performance.device.device_id)) case_path = '{}/{}'.format(self.performance.config.test_envs.get('root'), self.performance.config.test_envs.get('setup').get('path')) command = 'python3 -m airtest run {} --device Android://127.0.0.1:5037/{} ' \ ''.format(case_path, self.performance.device.device_id) p = self.adb_tool.run_performance(command) result = self.adb_tool.output(p) logger.info("\n".join(result)) self.adb_tool.set_system_default_input(key=self.performance.config.test_envs.get('setup').get('input')) # 获取并生成 bug report(adb bug report) def get_gen_bug_report(self): try: self.logcat.get_bug_report_log() self.logcat.generate_bug_report() self.logcat.upload_bug_report_log() now = datetime.now().strftime("%Y-%m-%d") build_number = os.environ.get('BUILD_NUMBER') report_url = '{}/monkey/{}/{}/logcat/{}/bug_report_out/index.html'.format(DefaultConfig.OSS_MONKEY_URL, now, build_number, self.pid) report_type = 1 self.tcloud.on_report_upload(report_url, report_type) except Exception as e: logger.error(e) logger.error(traceback.format_exc()) def upload_other_report(self): try: now = datetime.now().strftime("%Y-%m-%d") build_number = os.environ.get('BUILD_NUMBER') # monkey.log report_url_pre = '{}/monkey/{}/{}/logcat/{}'.format(DefaultConfig.OSS_MONKEY_URL, now, build_number, self.pid) self.tcloud.on_report_upload(report_url='{}/monkey.log'.format(report_url_pre), report_type=2) except Exception as e: logger.error(e) logger.error(traceback.format_exc()) def publish_result(self): self.lock.acquire() self.queue.put(self.performance) self.lock.release() def init_tools(self): self.adb_tool = AdbTool(self.performance.device.device_id) self.tcloud = TCloud(self.performance.task_id, self.performance.device.device_id, self.performance.monkey_id, self.performance.tcloud_url) self.local_performance_path = '{}/{}/{}'.format(DefaultConfig.LOCAL_LOGCAT_PATH, self.pid, 'performance') self.local_logcat_path = '{}/{}/{}'.format(DefaultConfig.LOCAL_LOGCAT_PATH, self.pid, 'logcat.log') def on_process_changed(self, time_temp, test_count, run_count): logger.info('({}) time now ... {}'.format(self.performance.device.device_id, time_temp)) self.process = int(time_temp / (self.performance.config.run_time * 60.00) * 100.00) logger.info('({}) process now : {}'.format(self.performance.device.device_id, self.process)) if self.process <= 0: self.process = 0 if self.process >= 100: self.process = 100 logger.info( '''current information <{}> {}'''.format(datetime.now().strftime('%Y.%m.%d %H:%M:%S'), self.process)) self.tcloud.on_anr_crash_changed((run_count * 100 + self.process)//test_count, 0, 0) def setup(self): try: logger.info('{} 开始测试 设备 {}'.format(self.pid, self.performance.device.device_id)) # 清除 重建 logs self.clear_local_logs() self.creat_local_log_path() # 连接设备 self.performance.result.device_connect_result = self.performance.device.connect() if isinstance(self.performance.result.device_connect_result, DeviceNotConnectedException): raise DeviceNotConnectedException self.tcloud.on_device_connect(True) # 锁定机器 self.tcloud.using_monkey_device(self.performance.device.device_id) # 开启日志 self.logcat = LogCat(self.performance.device.device_id, self.pid) # 测试开始时间 self.performance.result.on_case_begin() if self.performance.config.uninstall_app_required: # 卸载 self.performance.result.setup_uninstall_result = self.adb_tool.uninstall_package( self.performance.config.package_name) self.tcloud.on_setup_uninstall_app(self.performance.result.setup_uninstall_result) if self.performance.config.install_app_required: # 安装 package self.performance.result.setup_install_result = self.adb_tool.install_package( self.performance.config.local_package_path, self.performance.config.package_name) else: self.performance.result.setup_install_result = True self.tcloud.on_setup_install_app(self.performance.result.setup_install_result) if not self.performance.result.setup_install_result: raise InstallAppException # 获取 app 版本 self.performance.result.app_version = self.adb_tool.get_package_version( self.performance.config.package_name) self.tcloud.on_get_app_version(self.performance.result.app_version) # 检查 设备锁屏状态 self.performance.result.check_screen_locked = self.adb_tool.check_screen_locked() self.tcloud.on_screen_lock(self.performance.result.check_screen_locked) if not self.performance.result.check_screen_locked: raise CheckScreenLockedFailed self.clear_log_on_device() time.sleep(5) # 回到桌面 logger.info('({}) 回到桌面'.format(self.performance.device.device_id)) self.adb_tool.back_to_home() self.get_performance_airtest_scripts() time.sleep(5) # 热启动 app logger.info('({}) 尝试热启动 app'.format(self.performance.device.device_id)) self.performance.result.start_app_status = True self.tcloud.on_start_app(self.performance.result.start_app_status) # 登陆 app 没有用到! self.performance.result.login_app_status = self.try_to_login_app() self.tcloud.on_login_app(self.performance.result.login_app_status) except Exception as e: logger.error(e) traceback.print_exc() raise e def teardown(self): try: # update task end info self.tcloud.on_task_end(process=self.process, run_time=self.performance.config.run_time) logger.info('{} 结束测试 设备 {}'.format(self.pid, self.performance.device.device_id)) # 测试结束时间 self.performance.result.on_case_end() if self.performance.config.uninstall_app_required: # 卸载 package self.performance.result.teardown_uninstall_result = self.adb_tool.uninstall_package( self.performance.config.package_name) else: self.performance.result.teardown_uninstall_result = True self.tcloud.on_teardown_uninstall_app(self.performance.result.teardown_uninstall_result) self.tcloud.release_monkey_device(self.performance.device.device_id) self.tcloud.on_running_status(status=1, error_msg='') # 断开连接设备 self.performance.device.disconnect() except Exception as e: logger.error(e) traceback.print_exc() finally: self.tcloud.release_monkey_device(self.performance.device.device_id) def clear_log_on_device(self): # 移除 设备中原有的 log /sdcard 下的log self.logcat.reset_bug_report_log() def clear_local_logs(self): # 移除本地logcat 目录 logger.info('移除 logcat 目录') Utils.command_execute('rm -rf ./logcat') def creat_local_log_path(self): logger.info('初始化 log 目录') Utils.command_execute('mkdir -p logcat') Utils.command_execute('mkdir -p logcat/{}'.format(self.pid)) def try_to_unlock_screen(self): logger.info('({}) 尝试 解锁屏幕'.format(self.performance.device.device_id)) # TODO def try_to_login_app(self): logger.info('({}) 尝试 登陆 app {}'.format(self.performance.device.device_id, self.performance.config.package_name)) # TODO try: if self.performance.config.login_required: logger.info('({}) 使用 [{} ,{}] 尝试登陆'.format(self.performance.device.device_id, self.performance.config.login_username, self.performance.config.login_password)) return True else: logger.info('({}) 不需要登陆'.format(self.performance.device.device_id)) return True except Exception as e: logger.error(e) logger.error(traceback.format_exc()) return False
{"/automonkey/device.py": ["/automonkey/adb.py", "/automonkey/exception.py"], "/automonkey/utils.py": ["/automonkey/config.py", "/automonkey/exception.py"], "/automonkey/runner.py": ["/automonkey/config.py", "/automonkey/case.py", "/automonkey/exception.py", "/automonkey/monkey_runner.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py", "/automonkey/performance_runner.py"], "/automonkey/performance_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/monkey_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/tcloud_update.py": ["/automonkey/config.py"], "/automonkey/main.py": ["/automonkey/program.py"], "/automonkey/adb.py": ["/automonkey/exception.py", "/automonkey/utils.py"], "/automonkey/program.py": ["/automonkey/config.py", "/automonkey/loader.py", "/automonkey/recorder.py", "/automonkey/runner.py", "/automonkey/utils.py"], "/automonkey/performance.py": ["/automonkey/result.py", "/automonkey/device.py", "/automonkey/config.py"], "/automonkey/result.py": ["/automonkey/config.py"], "/automonkey/logcat.py": ["/automonkey/adb.py", "/automonkey/config.py", "/automonkey/utils.py"], "/automonkey/case.py": ["/automonkey/performance.py", "/automonkey/device.py", "/automonkey/monkey.py", "/automonkey/result.py"], "/automonkey/monkey.py": ["/automonkey/config.py", "/automonkey/device.py", "/automonkey/result.py"], "/automonkey/loader.py": ["/automonkey/case.py"]}
58,185
lin54241930/monkey_tcloud
refs/heads/master
/automonkey/config.py
import oss2 """ # MonkeyConfig # 所有的配置信息, 是从 jenkins job 中读取过来的信息,在 loader 中进行 构建 """ class DefaultConfig(object): RUN_MODE_MIX = 1 RUN_MODE_DFS = 2 RUN_MODE_TROY = 3 RUN_MODE_OTHER = 4 MONKEY_MIX_MODE = ' --uiautomatormix ' MONKEY_DFS_MODE = ' --uiautomatordfs ' MONKEY_TROY_MODE = ' --uiautomatortroy ' MONKEY_MODE_KEY_MAP = { RUN_MODE_MIX: MONKEY_MIX_MODE, RUN_MODE_DFS: MONKEY_DFS_MODE, RUN_MODE_TROY: MONKEY_TROY_MODE } RUN_TIME_DEFAULT = 120 # minutes RUN_TIME_SPLIT = 5 LOCAL_APP_PATH = './packages' # 本地保存 apk 的路径 LOCAL_LOGCAT_PATH = './logcat' # logcat 路径 KEY_MAP = ['package_name', 'device_id', 'run_time', 'app_download_url', 'run_mode', 'build_belong', 'task_id', 'system_device', 'login_username', 'login_password', 'default_app_activity', 'monkey_id', 'login_required', 'install_app_required'] ACTIVITY_PATH = 'max.activity.statistics.log' TCLOUD_URL = 'http://192.168.14.214:8088/v1/monkey' # Tcloud 对应的地址,可以作为参数传入 OSS_URL = '' # OSS url OSS_MONKEY_URL = '' # monkey oss url 存储报告地址 OSS_AUTH = oss2.Auth('username', 'password') # oss auth OSS_BUCKET_NAME = '' # oss bucket name class MonkeyConfig(object): def __init__(self): self.run_mode = '' self.package_name = '' self.default_app_activity = '' self.run_time = '' self.local_package_path = '' self.login_required = '' self.login_username = '' self.login_password = '' self.install_app_required = '' self.uninstall_app_required = '' def constructor(self, config): if isinstance(config, dict): self.run_mode = config.get('run_mode') or DefaultConfig.RUN_MODE_MIX self.run_time = config.get('run_time') or DefaultConfig.RUN_TIME_DEFAULT self.default_app_activity = config.get('default_app_activity') self.package_name = config.get('package_name') self.login_required = config.get('login_required') self.login_username = config.get('login_username') self.login_password = config.get('login_password') self.install_app_required = config.get('install_app_required') self.uninstall_app_required = config.get('uninstall_app_required') @property def info(self): return { 'run_mode': self.run_mode, 'package_name': self.package_name, 'default_app_activity': self.default_app_activity, 'run_time': self.run_time, 'local_package_path': self.local_package_path, 'login_required': self.login_required, 'login_username': self.login_username, 'login_password': self.login_password, 'install_app_required': self.install_app_required, 'uninstall_app_required': self.uninstall_app_required } class PerformanceConfig(object): def __init__(self): self.run_mode = '' self.package_name = '' self.default_app_activity = '' self.run_time = '' self.local_package_path = '' self.login_required = '' self.login_username = '' self.login_password = '' self.install_app_required = '' self.uninstall_app_required = '' self.test_envs = {} def constructor(self, config): if isinstance(config, dict): self.run_mode = config.get('run_mode') or DefaultConfig.RUN_MODE_MIX self.run_time = config.get('run_time') or DefaultConfig.RUN_TIME_DEFAULT self.default_app_activity = config.get('default_app_activity') self.package_name = config.get('package_name') self.login_required = config.get('login_required') self.login_username = config.get('login_username') self.login_password = config.get('login_password') self.install_app_required = config.get('install_app_required') self.test_envs = config.get('test_config') self.uninstall_app_required = config.get('uninstall_app_required') @property def info(self): return { 'run_mode': self.run_mode, 'package_name': self.package_name, 'default_app_activity': self.default_app_activity, 'run_time': self.run_time, 'local_package_path': self.local_package_path, 'login_required': self.login_required, 'login_username': self.login_username, 'login_password': self.login_password, 'install_app_required': self.install_app_required, 'test_envs': self.test_envs, 'uninstall_app_required': self.uninstall_app_required }
{"/automonkey/device.py": ["/automonkey/adb.py", "/automonkey/exception.py"], "/automonkey/utils.py": ["/automonkey/config.py", "/automonkey/exception.py"], "/automonkey/runner.py": ["/automonkey/config.py", "/automonkey/case.py", "/automonkey/exception.py", "/automonkey/monkey_runner.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py", "/automonkey/performance_runner.py"], "/automonkey/performance_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/monkey_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/tcloud_update.py": ["/automonkey/config.py"], "/automonkey/main.py": ["/automonkey/program.py"], "/automonkey/adb.py": ["/automonkey/exception.py", "/automonkey/utils.py"], "/automonkey/program.py": ["/automonkey/config.py", "/automonkey/loader.py", "/automonkey/recorder.py", "/automonkey/runner.py", "/automonkey/utils.py"], "/automonkey/performance.py": ["/automonkey/result.py", "/automonkey/device.py", "/automonkey/config.py"], "/automonkey/result.py": ["/automonkey/config.py"], "/automonkey/logcat.py": ["/automonkey/adb.py", "/automonkey/config.py", "/automonkey/utils.py"], "/automonkey/case.py": ["/automonkey/performance.py", "/automonkey/device.py", "/automonkey/monkey.py", "/automonkey/result.py"], "/automonkey/monkey.py": ["/automonkey/config.py", "/automonkey/device.py", "/automonkey/result.py"], "/automonkey/loader.py": ["/automonkey/case.py"]}
58,186
lin54241930/monkey_tcloud
refs/heads/master
/automonkey/recorder.py
""" # 解析结果,发布数据 """ class Recorder(object): def __init__(self): pass def result_analysis(self): pass
{"/automonkey/device.py": ["/automonkey/adb.py", "/automonkey/exception.py"], "/automonkey/utils.py": ["/automonkey/config.py", "/automonkey/exception.py"], "/automonkey/runner.py": ["/automonkey/config.py", "/automonkey/case.py", "/automonkey/exception.py", "/automonkey/monkey_runner.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py", "/automonkey/performance_runner.py"], "/automonkey/performance_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/monkey_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/tcloud_update.py": ["/automonkey/config.py"], "/automonkey/main.py": ["/automonkey/program.py"], "/automonkey/adb.py": ["/automonkey/exception.py", "/automonkey/utils.py"], "/automonkey/program.py": ["/automonkey/config.py", "/automonkey/loader.py", "/automonkey/recorder.py", "/automonkey/runner.py", "/automonkey/utils.py"], "/automonkey/performance.py": ["/automonkey/result.py", "/automonkey/device.py", "/automonkey/config.py"], "/automonkey/result.py": ["/automonkey/config.py"], "/automonkey/logcat.py": ["/automonkey/adb.py", "/automonkey/config.py", "/automonkey/utils.py"], "/automonkey/case.py": ["/automonkey/performance.py", "/automonkey/device.py", "/automonkey/monkey.py", "/automonkey/result.py"], "/automonkey/monkey.py": ["/automonkey/config.py", "/automonkey/device.py", "/automonkey/result.py"], "/automonkey/loader.py": ["/automonkey/case.py"]}
58,187
lin54241930/monkey_tcloud
refs/heads/master
/automonkey/monkey_runner.py
import logging import os import time import traceback from datetime import datetime from multiprocessing import Process from automonkey.config import DefaultConfig from .adb import AdbTool from .exception import DeviceNotConnectedException, InstallAppException, CheckScreenLockedFailed from .logcat import LogCat from .tcloud_update import TCloud from .utils import Utils logger = logging.getLogger(__name__) """ # MonkeyRunner , 多进程 """ class MonkeyRunner(Process): def __init__(self, queue, lock, monkey): super(MonkeyRunner, self).__init__() self.queue = queue self.monkey = monkey self.lock = lock self.daemon = True self.logcat = None self.adb_tool = None self.tcloud = None self.anr = 0 self.crash = 0 self.local_monkey_path = None self.local_logcat_path = None self.local_crash_path = None self.process = 0 def run(self): try: self.init_tools() # 开始测试 self.tcloud.on_task_begin() # 测试准备 self.setup() # 测试内容 self.run_monkey() # 测试结束 self.teardown() except DeviceNotConnectedException as d_e: logger.error(d_e) self.monkey.result.on_device_connect_failed() self.tcloud.on_device_connect(False) except CheckScreenLockedFailed as c_e: logger.error(c_e) self.monkey.result.on_check_screen_lock_failed() self.tcloud.on_screen_lock(False) except InstallAppException as i_e: logger.error(i_e) self.monkey.result.on_app_install_failed() self.tcloud.on_setup_install_app(False) except CheckScreenLockedFailed as s_e: logger.error(s_e) self.monkey.result.on_check_screen_lock_failed() self.tcloud.on_screen_lock(False) except Exception as e: logger.error(e) traceback.print_exc() finally: logger.info('{} 结束测试 设备 {}'.format(self.pid, self.monkey.device.device_id)) # 测试结束 self.teardown() self.publish_result() def run_monkey(self): try: # 回到桌面 logger.info('({}) 回到桌面'.format(self.monkey.device.device_id)) self.adb_tool.back_to_home() # 热启动 app logger.info('({}) 尝试热启动 app'.format(self.monkey.device.device_id)) self.monkey.result.start_app_status = self.adb_tool.start_activity(self.monkey.config.package_name, self.monkey.config.default_app_activity) self.tcloud.on_start_app(self.monkey.result.start_app_status) # 登陆 app self.monkey.result.login_app_status = self.try_to_login_app() self.tcloud.on_login_app(self.monkey.result.login_app_status) monkey_progress = self.run_monkey_cmd(self.monkey.config.run_time) time_begin = datetime.now() current_anr = 0 current_crash = 0 running_status = 1 running_error_reason = '' cancel_flag = False while True: time_temp = (datetime.now() - time_begin).seconds # 检测 monkey_progress 是否 if monkey_progress.poll() is not None: logger.warning('[{}] monkey stoped early !'.format(self.monkey.device.device_id)) logger.info('[{}] try to rerun the monkey!'.format(self.monkey.device.device_id)) mins = self.monkey.config.run_time - time_temp // 60 if mins <= 0: current_anr, current_crash = self.on_process_crash_anr_changed(time_temp) self.tcloud.on_anr_crash_changed(100, current_anr, current_crash) break monkey_progress = self.run_monkey_cmd(mins) # 检测是否 进行了 中断操作 cancel_flag = self.on_user_cancel() if cancel_flag: break # 检测 设备连接和锁屏状态 if isinstance(self.monkey.device.connect(), DeviceNotConnectedException): running_error_reason = 'device {} dis connect'.format(self.monkey.device.device_id) running_status = 2 self.tcloud.on_device_disconnect_on_running() break # self.adb_tool.check_screen_locked() # process crash anr 改变 self.on_process_crash_anr_changed(time_temp) # 当 process == 100 , break if self.process == 100: break time.sleep(5) time.sleep(30) # 此处的需要等待 log 写入 monkey_logs = [] # 等待 monkey 结束 while monkey_progress.poll() is None: logger.info('waiting for monkey end...') time_temp = (datetime.now() - time_begin).seconds // 60 if time_temp > 1: # 这里暂时不获取 monkey log # monkey_logs = monkey_progress.stdout.readlines() if monkey_progress.poll() is None: monkey_progress.kill() break time.sleep(10) # user cancel here if cancel_flag: self.tcloud.on_user_cancel_stask_success() else: self.tcloud.on_running_status(running_status, running_error_reason) self.monkey.result.log_path = self.logcat.get_logcat_log(monkey_logs) activity_all, activity_tested, activity_info = self.get_activity_infos() self.monkey.result.activity_info = activity_info # update task end info self.tcloud.on_task_end(process=self.process, activity_count=len(activity_all), activity_tested_count=len(activity_tested), activity_all=str(activity_all), activity_tested=str(activity_tested), anr_count=current_anr, crash_count=current_crash, crash_rate=0, exception_count=0, exception_run_time=0, run_time=self.monkey.config.run_time) # 重复上传,删除 # self.analysis_upload_crash_logs() self.get_gen_bug_report() self.upload_other_report() time.sleep(10) except Exception as e: logger.error(e) logger.error(traceback.format_exc()) finally: self.teardown() def on_user_cancel(self): cancel_status = self.tcloud.get_monkey_cancel_status(self.monkey.task_id) logger.info(cancel_status) if cancel_status in ['0', 0]: logger.warning('[{}] here find the cancel from the tcloud, stop the monkey now!'. format(self.monkey.device.device_id)) running_error_reason = 'cancel by user!' # on user cancel self.tcloud.on_user_cancel_task() cancel_flag = True else: cancel_flag = False return cancel_flag def on_process_crash_anr_changed(self, time_temp): logger.info('({}) time now ... {}'.format(self.monkey.device.device_id, time_temp)) self.process = int(time_temp / (self.monkey.config.run_time * 60.00) * 100.00) logger.info('({}) process now : {}'.format(self.monkey.device.device_id, self.process)) if self.process <= 0: self.process = 0 if self.process >= 100: self.process = 100 current_activity = self.adb_tool.get_current_activity() current_battery_level = self.adb_tool.get_battery_level() current_anr, current_crash = self.logcat.get_anr_crash_count() logger.info( '''current information <{}> current activity : {} ; current battery : {}; anr count : {} ;''' '''crash count : {}'''.format(datetime.now().strftime('%Y.%m.%d %H:%M:%S'), current_activity, current_battery_level, current_anr, current_crash)) self.on_anr_crash_changed(current_anr, current_crash) # 这里防止 crash anr 变小,使用系统存储的 anr 和 crash current_crash = self.crash current_anr = self.anr self.tcloud.on_anr_crash_changed(self.process, current_anr, current_crash) return current_anr, current_crash def run_monkey_cmd(self, run_time=0): run_mode = DefaultConfig.MONKEY_MODE_KEY_MAP.get(int(self.monkey.config.run_mode)) logcat_process = self.logcat.set_logcat(self.local_logcat_path) # 开始执行 monkey logger.info('({}) 开始运行 monkey 测试'.format(self.monkey.device.device_id)) logger.info('({}) monkey mode : {}'.format(self.monkey.device.device_id, run_mode)) command = 'shell CLASSPATH=/sdcard/monkey.jar:/sdcard/framework.jar exec app_process ' \ ' /system/bin tv.panda.test.monkey.Monkey -p {} {} --throttle 500 ' \ ' --output-directory /sdcard/MonkeyLog --running-minutes {} -v -v > {}'.format( self.monkey.config.package_name, run_mode, run_time, self.local_monkey_path) logger.info('({}) 开始运行 monkey 测试 [{} 分钟], 日志输出到 {}'.format( self.monkey.device.device_id, run_time, self.local_monkey_path)) monkey_progress = self.adb_tool.run_monkey(command) return monkey_progress def get_activity_infos(self): activity_info = self.logcat.get_activity_test_info(show_in_cmd=True) activity_all = activity_info.get('TotalActivity') activity_tested = activity_info.get('TestedActivity') return activity_all, activity_tested, activity_info def analysis_upload_crash_logs(self): crash_logs = self.logcat.analysis_crash_anr_log(self.local_crash_path) self.tcloud.on_errorlog_upload(crash_logs) # 当 anr 或者 crash 改变的时候, 获取并上传 anr crash log,实时显示 def on_anr_crash_changed(self, anr, crash): try: if self.anr != anr or self.crash != crash: if self.anr < anr or self.crash < crash: logger.info('here anr or crash changed !') self.logcat.get_crash_dump_log() crash_logs = self.logcat.analysis_crash_anr_log(self.local_crash_temp_path, self.anr, self.crash) self.anr = anr self.crash = crash self.tcloud.on_errorlog_upload(crash_logs) return True return False except Exception as e: logger.error(e) logger.error(traceback.format_exc()) # 获取并生成 bug report(adb bug report) def get_gen_bug_report(self): try: self.logcat.get_bug_report_log() self.logcat.generate_bug_report() self.logcat.upload_bug_report_log() now = datetime.now().strftime("%Y-%m-%d") build_number = os.environ.get('BUILD_NUMBER') report_url = '{}/monkey/{}/{}/logcat/{}/bug_report_out/index.html'.format(DefaultConfig.OSS_MONKEY_URL, now, build_number, self.pid) report_type = 1 self.tcloud.on_report_upload(report_url, report_type) except Exception as e: logger.error(e) logger.error(traceback.format_exc()) def upload_other_report(self): try: now = datetime.now().strftime("%Y-%m-%d") build_number = os.environ.get('BUILD_NUMBER') # monkey.log report_url_pre = '{}/monkey/{}/{}/logcat/{}'.format(DefaultConfig.OSS_MONKEY_URL, now, build_number, self.pid) self.tcloud.on_report_upload(report_url='{}/monkey.log'.format(report_url_pre), report_type=2) if self.anr > 0 or self.crash > 0: self.tcloud.on_report_upload(report_url='{}/monkey/MonkeyLog/crash-dump.log'.format(report_url_pre), report_type=3) except Exception as e: logger.error(e) logger.error(traceback.format_exc()) def publish_result(self): self.lock.acquire() self.queue.put(self.monkey) self.lock.release() def init_tools(self): self.adb_tool = AdbTool(self.monkey.device.device_id) self.tcloud = TCloud(self.monkey.task_id, self.monkey.device.device_id, self.monkey.monkey_id, self.monkey.tcloud_url) self.local_monkey_path = '{}/{}/{}'.format(DefaultConfig.LOCAL_LOGCAT_PATH, self.pid, 'monkey.log') self.local_logcat_path = '{}/{}/{}'.format(DefaultConfig.LOCAL_LOGCAT_PATH, self.pid, 'logcat.log') self.local_crash_path = '{}/{}/monkey/MonkeyLog/crash-dump.log'.format(DefaultConfig.LOCAL_LOGCAT_PATH, self.pid) self.local_crash_temp_path = '{}/{}/crash-dump.log'.format(DefaultConfig.LOCAL_LOGCAT_PATH, self.pid) def setup(self): try: logger.info('{} 开始测试 设备 {}'.format(self.pid, self.monkey.device.device_id)) # 清除 重建 logs self.clear_local_logs() self.creat_local_log_path() # 连接设备 self.adb_tool.check_screen_locked() self.monkey.result.device_connect_result = self.monkey.device.connect() if isinstance(self.monkey.result.device_connect_result, DeviceNotConnectedException): raise DeviceNotConnectedException self.tcloud.on_device_connect(True) # self.adb_tool.u2helper.connect() # 锁定机器 self.tcloud.using_monkey_device(self.monkey.device.device_id) # 开启日志 self.logcat = LogCat(self.monkey.device.device_id, self.pid) # 测试开始时间 self.monkey.result.on_case_begin() # 将 monkey.jar 和 framework.jar push 到 /sdcard self.adb_tool.push_file('./tools/monkey.jar', '/sdcard/') self.adb_tool.push_file('./tools/framework.jar', '/sdcard/') self.adb_tool.push_file('./tools/max.config', '/sdcard/') if self.monkey.config.install_app_required: # 卸载 self.monkey.result.setup_uninstall_result = self.adb_tool.uninstall_package( self.monkey.config.package_name) self.tcloud.on_setup_uninstall_app(self.monkey.result.setup_uninstall_result) # 安装 package self.monkey.result.setup_install_result = self.adb_tool.install_package( self.monkey.config.local_package_path, self.monkey.config.package_name) else: self.monkey.result.setup_install_result = True self.tcloud.on_setup_install_app(self.monkey.result.setup_install_result) if not self.monkey.result.setup_install_result: raise InstallAppException # 获取 app 版本 self.monkey.result.app_version = self.adb_tool.get_package_version(self.monkey.config.package_name) self.tcloud.on_get_app_version(self.monkey.result.app_version) # 检查 设备锁屏状态 # self.monkey.result.check_screen_locked = self.adb_tool.check_screen_locked() # self.tcloud.on_screen_lock(self.monkey.result.check_screen_locked) # if not self.monkey.result.check_screen_locked: # raise CheckScreenLockedFailed self.clear_log_on_device() time.sleep(5) except Exception as e: logger.error(e) traceback.print_exc() raise e def teardown(self): try: logger.info('{} 结束测试 设备 {}'.format(self.pid, self.monkey.device.device_id)) # 测试结束时间 self.monkey.result.on_case_end() # 卸载 package self.monkey.result.teardown_uninstall_result = self.adb_tool.uninstall_package( self.monkey.config.package_name) self.tcloud.on_teardown_uninstall_app(self.monkey.result.teardown_uninstall_result) self.tcloud.release_monkey_device(self.monkey.device.device_id) # 断开连接设备 self.monkey.device.disconnect() except Exception as e: logger.error(e) traceback.print_exc() finally: self.tcloud.release_monkey_device(self.monkey.device.device_id) def clear_log_on_device(self): # 移除 设备中原有的 log /sdcard 下的log self.adb_tool.remove_file('/sdcard/crash-dump.log') self.adb_tool.remove_file('/sdcard/oom-traces.log') self.adb_tool.remove_file('/sdcard/MonkeyLog') self.logcat.reset_bug_report_log() def clear_local_logs(self): # 移除本地logcat 目录 logger.info('移除 logcat 目录') Utils.command_execute('rm -rf ./logcat') def creat_local_log_path(self): logger.info('初始化 log 目录') Utils.command_execute('mkdir -p logcat') Utils.command_execute('mkdir -p logcat/{}'.format(self.pid)) def try_to_unlock_screen(self): logger.info('({}) 尝试 解锁屏幕'.format(self.monkey.device.device_id)) # TODO def try_to_login_app(self): logger.info('({}) 尝试 登陆 app {}'.format(self.monkey.device.device_id, self.monkey.config.package_name)) # TODO try: if self.monkey.config.login_required: logger.info('({}) 使用 [{} ,{}] 尝试登陆'.format(self.monkey.device.device_id, self.monkey.config.login_username, self.monkey.config.login_password)) return True else: logger.info('({}) 不需要登陆'.format(self.monkey.device.device_id)) return True except Exception as e: logger.error(e) logger.error(traceback.format_exc()) return False
{"/automonkey/device.py": ["/automonkey/adb.py", "/automonkey/exception.py"], "/automonkey/utils.py": ["/automonkey/config.py", "/automonkey/exception.py"], "/automonkey/runner.py": ["/automonkey/config.py", "/automonkey/case.py", "/automonkey/exception.py", "/automonkey/monkey_runner.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py", "/automonkey/performance_runner.py"], "/automonkey/performance_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/monkey_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/tcloud_update.py": ["/automonkey/config.py"], "/automonkey/main.py": ["/automonkey/program.py"], "/automonkey/adb.py": ["/automonkey/exception.py", "/automonkey/utils.py"], "/automonkey/program.py": ["/automonkey/config.py", "/automonkey/loader.py", "/automonkey/recorder.py", "/automonkey/runner.py", "/automonkey/utils.py"], "/automonkey/performance.py": ["/automonkey/result.py", "/automonkey/device.py", "/automonkey/config.py"], "/automonkey/result.py": ["/automonkey/config.py"], "/automonkey/logcat.py": ["/automonkey/adb.py", "/automonkey/config.py", "/automonkey/utils.py"], "/automonkey/case.py": ["/automonkey/performance.py", "/automonkey/device.py", "/automonkey/monkey.py", "/automonkey/result.py"], "/automonkey/monkey.py": ["/automonkey/config.py", "/automonkey/device.py", "/automonkey/result.py"], "/automonkey/loader.py": ["/automonkey/case.py"]}
58,188
lin54241930/monkey_tcloud
refs/heads/master
/automonkey/tcloud_update.py
#!/usr/bin/python # -*- coding: utf-8 -*- import json import logging import traceback from datetime import datetime import requests from .config import DefaultConfig logger = logging.getLogger(__name__) class TCloud(object): def __init__(self, task_id, device_id, monkey_id, tcloud_url, process=0): self.task_id = task_id self.monkey_id = monkey_id self.device_id = device_id self.tcloud_url = tcloud_url if tcloud_url is not None else DefaultConfig.TCLOUD_URL self.anr = 0 self.crash = 0 self.process = process # monkey update def on_get_app_version(self, version): if version is not None: self.update_monkey(app_version=version) def on_download_app(self, status): if status: download_app_status = 1 self.update_monkey(download_app_status=download_app_status) else: download_app_status = 2 end_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.update_monkey(download_app_status=download_app_status) def on_monkey_end(self, ): end_time = datetime.now().strftime('%Y-%m-%d-%H:%M:%S') self.update_monkey(process=100, end_time=end_time) def on_monkey_begin(self, jenkins_url): self.update_monkey(jenkins_url=jenkins_url) # task update def on_task_begin(self): process = 0 begin_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.update_task(process=process, begin_time=begin_time) def on_task_end(self, process=None, activity_count=None, activity_tested_count=None, activity_all=None, activity_tested=None, anr_count=None, crash_count=None, crash_rate=None, exception_count=None, exception_run_time=None, run_time=None): end_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.update_task(process=process, end_time=end_time, activity_count=activity_count, anr_count=anr_count, activity_tested_count=activity_tested_count, activity_all=activity_all, crash_count=crash_count, activity_tested=activity_tested, crash_rate=crash_rate, exception_count=exception_count, exception_run_time=exception_run_time, run_time=run_time) def on_running_status(self, status, error_msg): self.update_task(running_error_reason=error_msg, running_status=status) def on_device_connect(self, status): if status: device_connect_status = 1 self.update_task(device_connect_status=device_connect_status) else: device_connect_status = 2 end_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.update_task(process=100, activity_count=0, activity_tested_count=0, activity_all='', activity_tested='', anr_count=0, crash_count=0, crash_rate=0, exception_count=0, exception_run_time=0, setup_install_app_status=0, setup_uninstall_app_status=0, start_app_status=0, login_app_status=0, teardown_uninstall_app_status=0, end_time=end_time, run_time=0, device_connect_status=device_connect_status, screen_lock_status=0) def on_screen_lock(self, status): if status: screen_lock_status = 1 self.update_task(screen_lock_status=screen_lock_status) else: screen_lock_status = 2 end_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.update_task(process=100, activity_count=0, activity_tested_count=0, activity_all='', activity_tested='', anr_count=0, crash_count=0, crash_rate=0, exception_count=0, exception_run_time=0, setup_install_app_status=0, setup_uninstall_app_status=0, start_app_status=0, login_app_status=0, teardown_uninstall_app_status=0, end_time=end_time, run_time=0, screen_lock_status=screen_lock_status) def on_setup_uninstall_app(self, status): if status: setup_uninstall_app_status = 1 self.update_task(setup_uninstall_app_status=setup_uninstall_app_status) else: setup_uninstall_app_status = 2 self.update_task(process=100, activity_count=0, activity_tested_count=0, activity_all='', activity_tested='', anr_count=0, crash_count=0, crash_rate=0, exception_count=0, exception_run_time=0, setup_uninstall_app_status=setup_uninstall_app_status, start_app_status=0, login_app_status=0, teardown_uninstall_app_status=0, run_time=0) def on_setup_install_app(self, status): if status: setup_install_app_status = 1 self.update_task(setup_install_app_status=setup_install_app_status) else: setup_install_app_status = 2 end_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.update_task(process=100, activity_count=0, activity_tested_count=0, activity_all='', activity_tested='', anr_count=0, crash_count=0, crash_rate=0, exception_count=0, exception_run_time=0, setup_install_app_status=setup_install_app_status, start_app_status=0, login_app_status=0, teardown_uninstall_app_status=0, end_time=end_time, run_time=0) def on_start_app(self, status): if status: start_app_status = 1 self.update_task(start_app_status=start_app_status) else: start_app_status = 2 end_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.update_task(process=100, activity_count=0, activity_tested_count=0, activity_all='', activity_tested='', anr_count=0, crash_count=0, crash_rate=0, exception_count=0, exception_run_time=0, start_app_status=start_app_status, login_app_status=0, teardown_uninstall_app_status=0, end_time=end_time, run_time=0) def on_login_app(self, status): if status: login_app_status = 1 self.update_task(login_app_status=login_app_status) else: login_app_status = 2 end_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.update_task(process=100, activity_count=0, activity_tested_count=0, activity_all='', activity_tested='', anr_count=0, crash_count=0, crash_rate=0, exception_count=0, exception_run_time=0, login_app_status=login_app_status, teardown_uninstall_app_status=0, end_time=end_time, run_time=0) def on_teardown_uninstall_app(self, status): if status: teardown_uninstall_app_status = 1 self.update_task(teardown_uninstall_app_status=teardown_uninstall_app_status) else: teardown_uninstall_app_status = 2 end_time = datetime.now().strftime('%Y-%m-%d-%H:%M:%S') self.update_task(process=100, activity_count=0, activity_tested_count=0, activity_all='', activity_tested='', anr_count=0, crash_count=0, crash_rate=0, exception_count=0, exception_run_time=0, teardown_uninstall_app_status=teardown_uninstall_app_status, run_time=0) # on user cancel def on_user_cancel_task(self): self.update_task(current_stage=1000) # on user cancel success def on_user_cancel_stask_success(self): self.update_task(current_stage=1001) # on device_not connect on running def on_device_disconnect_on_running(self): self.update_task(current_stage=1002) # 当 anr crash process 发生改变时 上传 def on_anr_crash_changed(self, process, anr, crash): if self.anr != anr or self.crash != crash or self.process != process: self.anr = anr self.crash = crash self.process = process self.update_task(process=process, anr_count=anr, crash_count=crash) # upload errorlog def on_errorlog_upload(self, logs): for key in logs.keys(): log = logs.get(key) self.upload_log(int(self.monkey_id), int(self.task_id), log.get('error_type'), json.dumps(log.get('error_message')), log.get('error_count')) # upload report def on_report_upload(self, report_url, report_type): self.upload_report(int(self.monkey_id), int(self.task_id), report_url, report_type) def update_monkey(self, end_time=None, process=None, jenkins_url=None, status=None, app_version=None, begin_time=None, report_url=None, run_time=None, actual_run_time=None, download_app_status=None): try: logger.info('({}) update monkey'.format(self.device_id)) request_data_template = { "begin_time": begin_time, "process": process, "jenkins_url": jenkins_url, "status": status, "app_version": app_version, "report_url": report_url, "end_time": end_time, "run_time": run_time, "actual_run_time": actual_run_time, "download_app_status": download_app_status } request_data = {} for key in request_data_template.keys(): value = request_data_template.get(key) if value is not None: request_data[key] = value logger.info(request_data) request_url = '{}/v1/monkey/{}'.format(self.tcloud_url, self.monkey_id) response = requests.request(method='POST', url=request_url, json=request_data) if response.ok: logger.info(response.text) logger.info('({}) update monkey <{}> success'.format(self.device_id, self.monkey_id)) return True return False except Exception as e: logger.error(e) logger.error(traceback.format_exc()) return False def update_task(self, process=None, begin_time=None, activity_count=None, activity_tested_count=None, activity_all=None, activity_tested=None, anr_count=None, crash_count=None, crash_rate=None, exception_count=None, exception_run_time=None, setup_install_app_status=None, setup_uninstall_app_status=None, start_app_status=None, login_app_status=None, teardown_uninstall_app_status=None, end_time=None, run_time=None, device_connect_status=None, screen_lock_status=None, running_status=None, running_error_reason=None, current_stage=None): try: logger.info('({}) update task'.format(self.device_id)) request_data_template = { "begin_time": begin_time, "process": process, "activity_count": activity_count, "activity_tested_count": activity_tested_count, "activity_all": activity_all, "activity_tested": activity_tested, "anr_count": anr_count, "crash_count": crash_count, "crash_rate": crash_rate, "exception_count": exception_count, "exception_run_time": exception_run_time, "device_connect_status": device_connect_status, "screen_lock_status": screen_lock_status, "setup_install_app_status": setup_install_app_status, "setup_uninstall_app_status": setup_uninstall_app_status, "start_app_status": start_app_status, "login_app_status": login_app_status, "teardown_uninstall_app_status": teardown_uninstall_app_status, "end_time": end_time, "run_time": run_time, "running_status": running_status, "running_error_reason": running_error_reason, "current_stage": current_stage, } request_data = {} for key in request_data_template.keys(): value = request_data_template.get(key) if value is not None: request_data[key] = value logger.info(request_data) request_url = '{}/v1/monkey/devicestatus/{}'.format(self.tcloud_url, self.task_id) response = requests.request(method='POST', url=request_url, json=request_data) if response.ok: logger.info(response.text) logger.info('({}) update task <{}> success'.format(self.device_id, self.task_id)) return True return False except Exception as e: logger.error(e) logger.error(traceback.format_exc()) return False def upload_log(self, monkey_id=None, task_id=None, error_type=None, error_message=None, error_count=None): try: logger.info('({}) upload log'.format(self.device_id)) request_data_template = { 'monkey_id': monkey_id, 'task_id': task_id, 'error_type': error_type, 'error_message': error_message, 'error_count': error_count } request_data = {} for key in request_data_template.keys(): value = request_data_template.get(key) if value is not None: request_data[key] = value logger.info(request_data) request_url = '{}/v1/monkey/errorlog'.format(self.tcloud_url) response = requests.request(method='POST', url=request_url, json=request_data) if response.ok: logger.info(response.text) logger.info('({}) upload log success'.format(self.device_id)) return True return False except Exception as e: logger.error(e) traceback.print_exc() return False def upload_report(self, monkey_id=None, task_id=None, report_url=None, report_type=None): try: logger.info('({}) upload report'.format(self.device_id)) request_data_template = { 'monkey_id': monkey_id, 'task_id': task_id, 'report_url': report_url, 'report_type': report_type } request_data = {} for key in request_data_template.keys(): value = request_data_template.get(key) if value is not None: request_data[key] = value logger.info(request_data) request_url = '{}/v1/monkey/report'.format(self.tcloud_url) response = requests.request(method='POST', url=request_url, json=request_data) if response.ok: logger.info(response.text) logger.info('({}) upload report success'.format(self.device_id)) return True return False except Exception as e: logger.error(e) traceback.print_exc() return False def get_monkey_cancel_status(self, task_id): try: logger.info('({}) get monkey cancel status {}'.format(self.device_id, task_id)) request_url = '{}/v1/monkey/cancel?task_id={}'.format(self.tcloud_url, task_id) response = requests.request(method='GET', url=request_url) if response.ok: logger.info(response.json()) return response.json().get('data').get('cancel_status') except Exception as e: logger.error(e) logger.error(traceback.format_exc()) def using_monkey_device(self, serial): try: logger.info('using monkey device now!') request_data = { 'serial': serial } request_url = '{}/v1/monkey/device/using'.format(self.tcloud_url) response = requests.request(method='POST', url=request_url, json=request_data) if response.ok: logger.info(response.json()) return True except Exception as e: logger.error(e) logger.error(traceback.format_exc()) def release_monkey_device(self, serial): try: logger.info('release monkey device now!') request_data = { 'serial': serial } request_url = '{}/v1/monkey/device/release'.format(self.tcloud_url) response = requests.request(method='POST', url=request_url, json=request_data) if response.ok: logger.info(response.json()) return True except Exception as e: logger.error(e) logger.error(traceback.format_exc()) def upload_realtime_log(self, performance_test_id, cpu, rss, heap_size, heap_alloc): try: logger.info('upload realtime log now!') request_data = { 'cpu': str(cpu), 'rss': str(rss), 'heap_size': str(heap_size), 'heap_alloc': str(heap_alloc), } request_url = '{}/v1/performance/realtime/{}'.format(self.tcloud_url, performance_test_id) response = requests.request(method='POST', url=request_url, json=request_data) if response.ok: logger.info(response.json()) return response.json() except Exception as e: logger.error(e) def create_performance_test(self, run_type, run_time): try: logger.info('create_performance_test now!') request_data = { 'performance_id': int(self.task_id), 'run_type': run_type, 'run_time': run_time } request_url = '{}/v1/performance/test'.format(self.tcloud_url) response = requests.request(method='POST', url=request_url, json=request_data) if response.ok: logger.info(response.json()) return response.json().get('data')[0].get('id') except Exception as e: logger.error(e) return 0 def calculate_performance_test(self, performance_test_id): try: logger.info('calculate performance test average and top now now!') request_url = '{}/v1/performance/test/calculate/{}'.format(self.tcloud_url, performance_test_id) response = requests.request(method='GET', url=request_url) if response.ok: logger.info(response.json()) return response.json() except Exception as e: logger.error(e) return 0
{"/automonkey/device.py": ["/automonkey/adb.py", "/automonkey/exception.py"], "/automonkey/utils.py": ["/automonkey/config.py", "/automonkey/exception.py"], "/automonkey/runner.py": ["/automonkey/config.py", "/automonkey/case.py", "/automonkey/exception.py", "/automonkey/monkey_runner.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py", "/automonkey/performance_runner.py"], "/automonkey/performance_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/monkey_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/tcloud_update.py": ["/automonkey/config.py"], "/automonkey/main.py": ["/automonkey/program.py"], "/automonkey/adb.py": ["/automonkey/exception.py", "/automonkey/utils.py"], "/automonkey/program.py": ["/automonkey/config.py", "/automonkey/loader.py", "/automonkey/recorder.py", "/automonkey/runner.py", "/automonkey/utils.py"], "/automonkey/performance.py": ["/automonkey/result.py", "/automonkey/device.py", "/automonkey/config.py"], "/automonkey/result.py": ["/automonkey/config.py"], "/automonkey/logcat.py": ["/automonkey/adb.py", "/automonkey/config.py", "/automonkey/utils.py"], "/automonkey/case.py": ["/automonkey/performance.py", "/automonkey/device.py", "/automonkey/monkey.py", "/automonkey/result.py"], "/automonkey/monkey.py": ["/automonkey/config.py", "/automonkey/device.py", "/automonkey/result.py"], "/automonkey/loader.py": ["/automonkey/case.py"]}
58,189
lin54241930/monkey_tcloud
refs/heads/master
/automonkey/__init__.py
import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s <%(process)d> [%(filename)s (%(lineno)d)] %(levelname)s %(message)s')
{"/automonkey/device.py": ["/automonkey/adb.py", "/automonkey/exception.py"], "/automonkey/utils.py": ["/automonkey/config.py", "/automonkey/exception.py"], "/automonkey/runner.py": ["/automonkey/config.py", "/automonkey/case.py", "/automonkey/exception.py", "/automonkey/monkey_runner.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py", "/automonkey/performance_runner.py"], "/automonkey/performance_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/monkey_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/tcloud_update.py": ["/automonkey/config.py"], "/automonkey/main.py": ["/automonkey/program.py"], "/automonkey/adb.py": ["/automonkey/exception.py", "/automonkey/utils.py"], "/automonkey/program.py": ["/automonkey/config.py", "/automonkey/loader.py", "/automonkey/recorder.py", "/automonkey/runner.py", "/automonkey/utils.py"], "/automonkey/performance.py": ["/automonkey/result.py", "/automonkey/device.py", "/automonkey/config.py"], "/automonkey/result.py": ["/automonkey/config.py"], "/automonkey/logcat.py": ["/automonkey/adb.py", "/automonkey/config.py", "/automonkey/utils.py"], "/automonkey/case.py": ["/automonkey/performance.py", "/automonkey/device.py", "/automonkey/monkey.py", "/automonkey/result.py"], "/automonkey/monkey.py": ["/automonkey/config.py", "/automonkey/device.py", "/automonkey/result.py"], "/automonkey/loader.py": ["/automonkey/case.py"]}
58,190
lin54241930/monkey_tcloud
refs/heads/master
/automonkey/main.py
#!/usr/bin/python # -*- coding: utf-8 -*- import argparse import logging import traceback from .program import ProgramMain logger = logging.getLogger(__name__) """ # main """ def main(): arg_program = argparse.ArgumentParser(prog='python -m automonkey', add_help=True) sub_all_arg_program = arg_program.add_subparsers(dest='all') sub_run_arg_program = sub_all_arg_program.add_parser( 'run', help='run monkey with args' ) sub_run_arg_program.add_argument('--package-name', '-pn', dest='package_name', type=str) sub_run_arg_program.add_argument('--device-name', '-dn', dest='device_id', type=str) sub_run_arg_program.add_argument('--run-time', '-rt', dest='run_time', type=int) sub_run_arg_program.add_argument('--app-download-url', '-adu', dest='app_download_url', type=str) sub_run_arg_program.add_argument('--run-mode', '-rm', dest='run_mode', type=str) sub_run_arg_program.add_argument('--build-belong', '-bb', dest='build_belong', type=str) sub_run_arg_program.add_argument('--install-app-required', '-iar', dest='install_app_required', type=str) sub_run_arg_program.add_argument('--uninstall-app-required', '-uiar', dest='uninstall_app_required', type=str) sub_run_arg_program.add_argument('--system-device', '-sd', dest='system_device', type=str) sub_run_arg_program.add_argument('--login-required', '-lr', dest='login_required', type=str) sub_run_arg_program.add_argument('--login-username', '-lu', dest='login_username', type=str) sub_run_arg_program.add_argument('--login-password', '-lp', dest='login_password', type=str) sub_run_arg_program.add_argument('--default-app-activity', '-daa', dest='default_app_activity', type=str) sub_run_arg_program.add_argument('--task-id', '-tid', dest='task_id', type=str) sub_run_arg_program.add_argument('--monkey-id', '-mid', dest='monkey_id', type=str) sub_run_arg_program.add_argument('--tcloud-url', '-turl', dest='tcloud_url', type=str) sub_run_arg_program.add_argument('--test-type', '-ttype', dest='test_type', type=str) sub_run_arg_program.add_argument('--test-config', '-tconfig', dest='test_config', type=str) try: args = arg_program.parse_args() if hasattr(args, 'device_id') and args.device_id: devices = args.device_id.split(',') args.device_id = devices else: logger.error('missing device_id !') if hasattr(args, 'task_id') and args.task_id: task_ids = args.task_id.split(',') args.task_id = {} for i, device in enumerate(args.device_id): args.task_id[device] = task_ids[i] else: logger.error('missing task_id !') if hasattr(args, 'install_app_required'): args.install_app_required = args.install_app_required in ["true", "True"] if hasattr(args, 'system_device'): args.system_device = args.system_device in ["true", "True"] if hasattr(args, 'login_required'): args.login_required = args.login_required in ["true", "True"] if hasattr(args, 'uninstall_app_required'): args.login_required = args.login_required in ["true", "True"] logger.info(args) program = ProgramMain() program.run(args) except Exception as e: logger.error(e) traceback.print_exc()
{"/automonkey/device.py": ["/automonkey/adb.py", "/automonkey/exception.py"], "/automonkey/utils.py": ["/automonkey/config.py", "/automonkey/exception.py"], "/automonkey/runner.py": ["/automonkey/config.py", "/automonkey/case.py", "/automonkey/exception.py", "/automonkey/monkey_runner.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py", "/automonkey/performance_runner.py"], "/automonkey/performance_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/monkey_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/tcloud_update.py": ["/automonkey/config.py"], "/automonkey/main.py": ["/automonkey/program.py"], "/automonkey/adb.py": ["/automonkey/exception.py", "/automonkey/utils.py"], "/automonkey/program.py": ["/automonkey/config.py", "/automonkey/loader.py", "/automonkey/recorder.py", "/automonkey/runner.py", "/automonkey/utils.py"], "/automonkey/performance.py": ["/automonkey/result.py", "/automonkey/device.py", "/automonkey/config.py"], "/automonkey/result.py": ["/automonkey/config.py"], "/automonkey/logcat.py": ["/automonkey/adb.py", "/automonkey/config.py", "/automonkey/utils.py"], "/automonkey/case.py": ["/automonkey/performance.py", "/automonkey/device.py", "/automonkey/monkey.py", "/automonkey/result.py"], "/automonkey/monkey.py": ["/automonkey/config.py", "/automonkey/device.py", "/automonkey/result.py"], "/automonkey/loader.py": ["/automonkey/case.py"]}
58,191
lin54241930/monkey_tcloud
refs/heads/master
/automonkey/uiautomator_helper.py
# import logging # # logger = logging.getLogger(__name__) # # # class U2Helper(object): # def __init__(self, device_id): # self.device_id = device_id # self.server = None # # def connect(self): # import uiautomator2 as u2 # self.server = u2.connect(self.device_id) # # def try_to_install_app(self): # may_ok_list = '允许' # self.server(may_ok_list).click()
{"/automonkey/device.py": ["/automonkey/adb.py", "/automonkey/exception.py"], "/automonkey/utils.py": ["/automonkey/config.py", "/automonkey/exception.py"], "/automonkey/runner.py": ["/automonkey/config.py", "/automonkey/case.py", "/automonkey/exception.py", "/automonkey/monkey_runner.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py", "/automonkey/performance_runner.py"], "/automonkey/performance_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/monkey_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/tcloud_update.py": ["/automonkey/config.py"], "/automonkey/main.py": ["/automonkey/program.py"], "/automonkey/adb.py": ["/automonkey/exception.py", "/automonkey/utils.py"], "/automonkey/program.py": ["/automonkey/config.py", "/automonkey/loader.py", "/automonkey/recorder.py", "/automonkey/runner.py", "/automonkey/utils.py"], "/automonkey/performance.py": ["/automonkey/result.py", "/automonkey/device.py", "/automonkey/config.py"], "/automonkey/result.py": ["/automonkey/config.py"], "/automonkey/logcat.py": ["/automonkey/adb.py", "/automonkey/config.py", "/automonkey/utils.py"], "/automonkey/case.py": ["/automonkey/performance.py", "/automonkey/device.py", "/automonkey/monkey.py", "/automonkey/result.py"], "/automonkey/monkey.py": ["/automonkey/config.py", "/automonkey/device.py", "/automonkey/result.py"], "/automonkey/loader.py": ["/automonkey/case.py"]}
58,192
lin54241930/monkey_tcloud
refs/heads/master
/automonkey/adb.py
import logging import os import platform import re import time import traceback import uiautomator2 as u2 import prettytable from .exception import LocalPackageNotFoundException # from .uiautomator_helper import U2Helper # no use here from .utils import Utils logger = logging.getLogger(__name__) class AdbTool(object): def __init__(self, device_name): self.device_name = device_name self.command_path = 'adb' self.command_args = '-s {}'.format(device_name) # self.u2helper = U2Helper(self.device_name) pass @property def system(self): return platform.system() def output(self, p): if p.stdout: return Utils.deal_with_python_version(p.stdout.readlines()) else: return Utils.deal_with_python_version(p.stderr.readlines()) @property def adb_command(self): return '{} {} '.format(self.command_path, self.command_args) def check_screen_locked(self, times=1): try: if times >= 10: return False logger.info('({}) <尝试{}> 检查设备是否锁屏'.format(self.device_name, times)) d = u2.connect(self.device_name) if d.info.get('screenOn') == True: logger.info('({}) 设备是亮屏状态!'.format(self.device_name)) d.press("power") logger.info('({}) 关闭屏幕一次!'.format(self.device_name)) time.sleep(2) d.unlock() logger.info('({}) 执行一次解锁'.format(self.device_name)) d.press("home") logger.info('({}) 按一次home回到桌面'.format(self.device_name)) return True else: logger.info('({}) 设备是黑屏状态!'.format(self.device_name)) d.unlock() logger.info('({}) 直接执行解锁'.format(self.device_name)) d.press("home") logger.info('({}) 按一次home回到桌面'.format(self.device_name)) return True except Exception as e: logger.error(e) logger.error(traceback.format_exc()) return self.check_screen_locked(times=times + 1) def push_file(self, source, target): logger.info('({}) 将文件 {} 发送到 {}'.format(self.device_name, source, target)) cmd = '{} push {} {}'.format(self.adb_command, source, target) p = Utils.command_execute(cmd) return self.output(p) def remove_file(self, file_name): logger.info('({}) 开始删除文件 <{}>'.format(self.device_name, file_name)) if file_name in ['/', '/sdcard'] or not file_name.startswith('/sdcard/'): logger.error('({}) 文件名类型不对,无法删除!'.format(self.device_name)) return False cmd = '{} shell rm -rf {}'.format(self.adb_command, file_name) p = Utils.command_execute(cmd) r = self.output(p) if len(r) > 0: logger.info(r) return True def connect_remote_device(self, remote_device_id): cmd = '{} connect {}'.format(self.adb_command, remote_device_id) p = Utils.command_execute(cmd) return self.output(p) def pull_file(self, source, target): logger.info('({}) 将文件 {} 下载到 {}'.format(self.device_name, source, target)) cmd = '{} pull {} {}'.format(self.adb_command, source, target) p = Utils.command_execute(cmd) return self.output(p) def start_activity(self, package_name, activity_name): try: activity_name = '{}/{}'.format(package_name, activity_name) logger.info('({}) 启动 activity : {}'.format(self.device_name, activity_name)) cmd = '{} shell am start -W -n {}'.format(self.adb_command, activity_name) p = Utils.command_execute(cmd) result = self.output(p) logger.info(result) time.sleep(10) current_activity = self.get_current_activity() if current_activity == activity_name: logger.info('({}) activity 已经启动成功'.format(self.device_name)) return True return result except Exception as e: logger.error(e) logger.error(traceback.format_exc()) def clear_logcat(self): logger.info('({}) 清除 logcat log'.format(self.device_name)) cmd = '{} logcat -c'.format(self.adb_command) p = Utils.command_execute(cmd) return p def start_logcat(self, target): logger.info('({}) 打开 logcat log'.format(self.device_name)) # cmd = '{} logcat -v time > {}'.format(self.adb_command, target) # p = Utils.command_execute(cmd) return None def back_to_home(self): cmd = '{} shell input keyevent 3'.format(self.adb_command) p = Utils.command_execute(cmd) return self.output(p) # 运行随机测试命令 def run_monkey(self, monkey_command): try: cmd = '{} {}'.format(self.adb_command, monkey_command) p = Utils.command_execute(cmd) return p except Exception as e: logger.error(e) logger.error(traceback.format_exc()) #运行性能测试命令 # def run_performance(self, performance_command): # try: # cmd = '{}'.format(performance_command) # p = Utils.command_execute(cmd) # return p # except Exception as e: # logger.error(e) # logger.error(traceback.format_exc()) def input_autoinstall(self): #分辨率种类 display_class = "720*1080","720*1440","1080*1920","1080*2160","1080*2340" try: d = u2.connect(self.device_name) devices_v = d.device_info["version"] devices_version = devices_v[0:3] display = d.device_info["display"] my_display = '{}*{}'.format(display["width"], display["height"]) logger.info('当前手机系统版本为 {}'.format(devices_version)) logger.info('检测是否是vivo或者OPPO手机 {}'.format(self.device_name)) logger.info('当前屏幕分辨率为 {}'.format(my_display)) if d.device_info["brand"] == 'vivo': logger.info('检测到vivo手机 {}'.format(self.device_name)) if float(devices_version) > 5 and float(devices_version) < 9: d(resourceId="vivo:id/vivo_adb_install_ok_button").click() else: logger.info('开始输入密码 {}'.format(self.device_name)) d.xpath('//*[@resource-id="com.bbk.account:id/dialog_pwd"]/android.widget.LinearLayout[1]/android.widget.RelativeLayout[1]').set_text("Pokercity2019") logger.info('点击确认按钮 {}'.format(self.device_name)) d(resourceId="android:id/button1").click() logger.info('等待10s检测应用安全性 {}'.format(self.device_name)) d(resourceId="com.sohu.inputmethod.sogou.vivo:id/imeview_keyboard").wait(timeout=10.0) logger.info('点击安装按钮 {}'.format(self.device_name)) d.click(0.497, 0.858) return True elif d.device_info["brand"] == 'OPPO': logger.info('检测到OPPO手机 {}'.format(self.device_name)) logger.info('开始输入密码 {}'.format(self.device_name)) d(resourceId="com.coloros.safecenter:id/et_login_passwd_edit").set_text("Pokercity2019") logger.info('点击确认按钮 {}'.format(self.device_name)) d(resourceId="android:id/button1").click() logger.info('等待8s检测应用安全性 {}'.format(self.device_name)) time.sleep(8) if d(text="发现广告插件").exists: d.click(0.686, 0.929) time.sleep(2) d.click(0.482, 0.84) return True else: if float(devices_version) > 5 and float(devices_version) < 7: d.click(0.718, 0.957) return True elif float(devices_version) > 8 and float(devices_version) < 11: d.click(0.495, 0.954) return True elif float(devices_version) < 5.3 and float(devices_version) >= 5: d.click(0.498, 0.793) return True else: return True else: return False except Exception as e: logger.error(e) logger.error(traceback.format_exc()) return False def install_package(self, local_package_path, package_name, force_install=False): logger.info('({}) 开始安装包 : {}'.format(self.device_name, local_package_path)) try: if not os.path.exists(local_package_path): raise LocalPackageNotFoundException if force_install: cmd = '{} install -r {} > install_log.log'.format(self.adb_command, local_package_path) else: cmd = '{} install {} > install_log.log'.format(self.adb_command, local_package_path) p = Utils.command_execute(cmd) self.input_autoinstall() result = self.output(p) logger.info('({}) {}'.format(self.device_name, result)) if self.check_package_installed(package_name): # for r in result: # if 'Success' in r: # logger.info('({}) 安装 {} 成功'.format(self.device_name, local_package_path)) # return True return True logger.error('({}) 安装 {} 失败'.format(self.device_name, local_package_path)) return False except Exception as e: logger.error('({}) 安装 {} 失败'.format(self.device_name, local_package_path)) logger.error(e) return e def uninstall_package(self, package_name): logger.info('({}) 开始卸载 :{}'.format(self.device_name, package_name)) try: if self.check_package_installed(package_name): cmd = '{} uninstall {}'.format(self.adb_command, package_name) p = Utils.command_execute(cmd) result = self.output(p) logger.info('({}) {}'.format(self.device_name, result)) for r in result: if 'Success' in r: logger.info('({}) 卸载 {} 成功'.format(self.device_name, package_name)) return True logger.error('({}) 卸载 {} 失败 : '.format(self.device_name, package_name)) return False else: logger.info('({}) 设备没有安装 {}, 不需要卸载'.format(self.device_name, package_name)) return True except Exception as e: logger.error('({}) 卸载 {} 失败 : '.format(self.device_name, package_name)) return e def get_installed_packages(self, show_table=False): try: cmd = '{} shell pm list packages'.format(self.adb_command) p = Utils.command_execute(cmd) package_list = self.output(p) if show_table: logger.info('({}) 获取所有的已安装的包'.format(self.device_name)) table_packages = prettytable.PrettyTable() table_packages.field_names = ["id", "package name"] for i, package in enumerate(package_list): row = [i, package] table_packages.add_row(row) logger.info('({}) \n {}'.format(self.device_name, table_packages)) return package_list except Exception as e: logger.error(e) return e def check_package_installed(self, package_name): for package in self.get_installed_packages(): if package_name in package: return True return False #检测ADB环境变量是否正常 # def check_adb(self): # if "ANDROID_HOME" in os.environ: # if self.system == "Windows": # path = os.path.join(os.environ["ANDROID_HOME"], "platform-tools", "adb.exe") # if os.path.exists(path): # self.command_path = path # else: # raise EnvironmentError("Adb not found in $ANDROID_HOME path: {}".format(os.environ["ANDROID_HOME"])) # else: # path = os.path.join(os.environ["ANDROID_HOME"], "platform-tools", "adb") # if os.path.exists(path): # self.command_path = path # else: # raise EnvironmentError( # "Adb not found in $ANDROID_HOME path: {}.".format(os.environ["ANDROID_HOME"])) # else: # raise EnvironmentError("Adb not found in $ANDROID_HOME path: {}".format(os.environ["ANDROID_HOME"])) #获取当前界面正在运行的APP def get_current_application(self): return Utils.command_execute( '{} shell dumpsys window w | grep mCurrentFocus'.format(self.adb_command)) def get_current_package(self): p = self.get_current_application() result = self.output(p) if len(result) > 0: return result[0].split(' ')[-1].split('/')[0] return None def get_package_version(self, package_name): logger.info('({}) 获取 安装包 版本信息'.format(self.device_name)) if self.check_package_installed(package_name): cmd = '{} shell dumpsys package {} | grep versionName'.format(self.adb_command, package_name) p = Utils.command_execute(cmd) r = self.output(p) if len(r) > 0: temp = r[0].split('=') if len(temp) > 0: version = temp[1].strip() logger.info('({}) 版本是 [{}] '.format(self.device_name, version)) return version return '' else: logger.info('({}) {} 没有安装!'.format(self.device_name, package_name)) return None def get_current_activity(self): p = self.get_current_application() result = self.output(p) if len(result) > 0: names = result[0].split(' ') if len(names) > 1: activity_name = names[-1] if '/' in activity_name: activity = activity_name.split('/') return activity[1].strip() if len(activity) > 1 else activity return None def get_process(self, package_name): if self.system is "Windows": pid_command = Utils.command_execute( "{} shell ps | grep {}$".format(self.adb_command, package_name)).stdout.readlines() else: pid_command = Utils.command_execute( "{} shell ps | grep -w {}".format(self.adb_command, package_name)).stdout.readlines() return Utils.deal_with_python_version(pid_command) def process_exists(self, package_name): process = self.get_process(package_name) return package_name in process def get_pid(self, package_name): pid_command = self.get_process(package_name) if pid_command == '': logger.info("The process doesn't exist.") return pid_command req = re.compile(r"\d+") result = str(pid_command).split() result.remove(result[0]) return req.findall(" ".join(result))[0] def get_uid(self, pid): result = Utils.command_execute("{} shell cat /proc/{}/status".format(self.adb_command, pid)).stdout.readlines() result = Utils.deal_with_python_version(result) for i in result: if 'uid' in i.lower(): return i.split()[1] #获取电池电量 def get_battery_level(self): result = Utils.command_execute('{} shell dumpsys battery'.format(self.adb_command)).stdout.readlines() result = Utils.deal_with_python_version(result) for r in result: if 'level' in r: return int(r.split(':')[1]) return 0 def get_flow_data_tcp(self, uid): tcp_rcv = Utils.command_execute("{} shell cat proc/uid_stat/{}/tcp_rcv".format(self.adb_command, uid)).read().split()[0] tcp_snd = Utils.command_execute("{} shell cat proc/uid_stat/{}/tcp_snd".format(self.adb_command, uid)).read().split()[0] return tcp_rcv, tcp_snd #获取adb版本号 def get_adb_version(self): cmd = '{} version'.format(self.adb_command) p = Utils.command_execute(cmd) return self.output(p) #列出所有设备 def get_device_list(self): try: cmd = '{} devices'.format(self.command_path) p = Utils.command_execute(cmd) result = self.output(p) devices = [] if len(result) > 0 and result[0].startswith('List'): for line in result[1:]: if line in ['\n'] or 'un' in line: continue try: device = line.strip().replace('\t', '').split('device')[0] except Exception as e: device = None logger.error(e) if device not in [None, '\n', '\t']: devices.append(device) return devices except Exception as e: logger.info(e) logger.info(traceback.format_exc()) return [] #获取连接正常的设备 def check_device_connected(self, device): return device in self.get_device_list() #获取报错日志 def get_crash_dump_log(self): try: cmd = '{} shell cat /sdcard/MonkeyLog/crash-dump.log'.format(self.adb_command) p = Utils.command_execute(cmd) return self.output(p) except Exception as e: logger.error(e) logger.error(traceback.format_exc()) #解锁屏幕(此处滑动X轴坐标应为1500左右,有些手机滑动解锁需要滑动的距离较大) def unlock_screen(self): try: cmd = '{} shell input swipe 100 1500 100 20'.format(self.adb_command) Utils.command_execute(cmd) return True except Exception as e: logger.error(e) logger.error(traceback.format_exc()) #唤醒屏幕(此处是直接执行的电源键按钮,所以需要检测手机是否在亮屏状态下) def wakeup_screen(self): try: cmd = '{} shell input keyevent 26'.format(self.adb_command) Utils.command_execute(cmd) return True except Exception as e: logger.error(e) logger.error(traceback.format_exc()) #获取bug_report_log def get_bug_report_log(self, log_path): try: cmd = '{} shell bugreport > {}'.format(self.adb_command, log_path) p = Utils.command_execute(cmd) while p.poll() is None: time.sleep(1) for file_name in os.listdir("./"): if file_name.startswith('bugreport-') and file_name.endswith('.zip'): return file_name return log_path except Exception as e: logger.error(e) logger.error(traceback.format_exc()) #重置bug_report_log def reset_bug_report_log(self): try: logger.info('reset battery stats log now...') cmd = '{} shell dumpsys batterystats --reset'.format(self.adb_command) p = Utils.command_execute(cmd) return self.output(p) except Exception as e: logger.error(e) logger.error(traceback.format_exc()) #设置系统的默认输出 def set_system_default_input(self, key): try: if key: logger.info('try to set system default input to qjp') key_of_qjp = key cmd = '{} shell ime enable {}'.format(self.adb_command, key_of_qjp) p = Utils.command_execute(cmd) logger.info(self.output(p)) time.sleep(5) cmd = '{} shell ime set {}'.format(self.adb_command, key_of_qjp) p = Utils.command_execute(cmd) logger.info(self.output(p)) time.sleep(5) return True except Exception as e: logger.error(e) #获取内存信息 def get_memory_info(self, package_name): try: logger.info('try to get memory information') cmd = '{} shell dumpsys meminfo {}'.format(self.adb_command, package_name) p = Utils.command_execute(cmd) lines = self.output(p) # lines = Utils.deal_with_python_version(lines) heap_size, heap_alloc = 0, 0 for line in lines: if 'Native Heap' in line: temp = line.split() if len(temp) == 9: heap_size = temp[-3] heap_alloc = temp[-2] break heap_size = int(heap_size) if heap_size != '' else 0 heap_alloc = int(heap_alloc) if heap_alloc != '' else 0 return heap_size, heap_alloc except Exception as e: logger.error(e) return 0, 0 #获取CPU信息 def get_cpu(self, package_name): try: logger.info('try to get cpu information') cmd = '{} shell top -n 1 | grep {} '.format(self.adb_command, package_name) p = Utils.command_execute(cmd) lines = self.output(p) # lines = Utils.deal_with_python_version(lines) cpu = rss = 0 for line in lines: logger.info(line) if package_name in line and f'{package_name}:' not in line: temp = re.findall(r'.* (\w+)% .* (\w+)K (\w+)K .* {}'.format(package_name), line) cpu = temp[0][0] rss = temp[0][2] break cpu = int(cpu) if cpu != '' else 0 rss = int(rss) if rss != '' else 0 return cpu, rss except Exception as e: logger.error(e) return 0, 0 #清除包的缓存数据 def clear_package_cache_data(self, package_name): try: logger.info('try to clear cache data information') cmd = '{} shell pm clear {}'.format(self.adb_command, package_name) lines = Utils.command_execute(cmd) return lines except Exception as e: logger.error(e)
{"/automonkey/device.py": ["/automonkey/adb.py", "/automonkey/exception.py"], "/automonkey/utils.py": ["/automonkey/config.py", "/automonkey/exception.py"], "/automonkey/runner.py": ["/automonkey/config.py", "/automonkey/case.py", "/automonkey/exception.py", "/automonkey/monkey_runner.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py", "/automonkey/performance_runner.py"], "/automonkey/performance_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/monkey_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/tcloud_update.py": ["/automonkey/config.py"], "/automonkey/main.py": ["/automonkey/program.py"], "/automonkey/adb.py": ["/automonkey/exception.py", "/automonkey/utils.py"], "/automonkey/program.py": ["/automonkey/config.py", "/automonkey/loader.py", "/automonkey/recorder.py", "/automonkey/runner.py", "/automonkey/utils.py"], "/automonkey/performance.py": ["/automonkey/result.py", "/automonkey/device.py", "/automonkey/config.py"], "/automonkey/result.py": ["/automonkey/config.py"], "/automonkey/logcat.py": ["/automonkey/adb.py", "/automonkey/config.py", "/automonkey/utils.py"], "/automonkey/case.py": ["/automonkey/performance.py", "/automonkey/device.py", "/automonkey/monkey.py", "/automonkey/result.py"], "/automonkey/monkey.py": ["/automonkey/config.py", "/automonkey/device.py", "/automonkey/result.py"], "/automonkey/loader.py": ["/automonkey/case.py"]}
58,193
lin54241930/monkey_tcloud
refs/heads/master
/automonkey/exception.py
class MonkeyBaseException(Exception): pass class MonkeyTypeErrorException(MonkeyBaseException): pass class FileDownloadErrorException(MonkeyBaseException): pass class CaseBaseException(Exception): pass class CaseTypeErrorException(CaseBaseException): pass class DeviceNotConnectedException(Exception): pass class LocalPackageNotFoundException(Exception): pass class SetUpErrorException(Exception): pass class InstallAppException(Exception): pass class CheckScreenLockedFailed(Exception): pass
{"/automonkey/device.py": ["/automonkey/adb.py", "/automonkey/exception.py"], "/automonkey/utils.py": ["/automonkey/config.py", "/automonkey/exception.py"], "/automonkey/runner.py": ["/automonkey/config.py", "/automonkey/case.py", "/automonkey/exception.py", "/automonkey/monkey_runner.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py", "/automonkey/performance_runner.py"], "/automonkey/performance_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/monkey_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/tcloud_update.py": ["/automonkey/config.py"], "/automonkey/main.py": ["/automonkey/program.py"], "/automonkey/adb.py": ["/automonkey/exception.py", "/automonkey/utils.py"], "/automonkey/program.py": ["/automonkey/config.py", "/automonkey/loader.py", "/automonkey/recorder.py", "/automonkey/runner.py", "/automonkey/utils.py"], "/automonkey/performance.py": ["/automonkey/result.py", "/automonkey/device.py", "/automonkey/config.py"], "/automonkey/result.py": ["/automonkey/config.py"], "/automonkey/logcat.py": ["/automonkey/adb.py", "/automonkey/config.py", "/automonkey/utils.py"], "/automonkey/case.py": ["/automonkey/performance.py", "/automonkey/device.py", "/automonkey/monkey.py", "/automonkey/result.py"], "/automonkey/monkey.py": ["/automonkey/config.py", "/automonkey/device.py", "/automonkey/result.py"], "/automonkey/loader.py": ["/automonkey/case.py"]}
58,194
lin54241930/monkey_tcloud
refs/heads/master
/automonkey/program.py
import logging from .config import DefaultConfig from .loader import Loader from .recorder import Recorder from .runner import Runner from .utils import Utils logger = logging.getLogger(__name__) """ # ProgramMain 主程序 # 通过 Loader 解析参数 构建 CaseConfig 和 MonkeyConfig # 通过 Config 构建 Case 和 # 启动和控制 runner 的运行 # 通过 Recorder 解析 CaseResult # 通过 ... """ class ProgramMain(object): def __init__(self): self.loader = Loader() self.runner = Runner() self.recorder = Recorder() def run(self, args): self.show_args_info(args) case = self.loader.run(args) logger.info(case.info) self.runner.run(case) def show_args_info(self, args): keys = ["parameters id", "key", "Value"] values = [] for i, arg in enumerate(DefaultConfig.KEY_MAP): row = [i, arg, getattr(args, arg)] values.append(row) Utils.show_info_as_table(keys, values)
{"/automonkey/device.py": ["/automonkey/adb.py", "/automonkey/exception.py"], "/automonkey/utils.py": ["/automonkey/config.py", "/automonkey/exception.py"], "/automonkey/runner.py": ["/automonkey/config.py", "/automonkey/case.py", "/automonkey/exception.py", "/automonkey/monkey_runner.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py", "/automonkey/performance_runner.py"], "/automonkey/performance_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/monkey_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/tcloud_update.py": ["/automonkey/config.py"], "/automonkey/main.py": ["/automonkey/program.py"], "/automonkey/adb.py": ["/automonkey/exception.py", "/automonkey/utils.py"], "/automonkey/program.py": ["/automonkey/config.py", "/automonkey/loader.py", "/automonkey/recorder.py", "/automonkey/runner.py", "/automonkey/utils.py"], "/automonkey/performance.py": ["/automonkey/result.py", "/automonkey/device.py", "/automonkey/config.py"], "/automonkey/result.py": ["/automonkey/config.py"], "/automonkey/logcat.py": ["/automonkey/adb.py", "/automonkey/config.py", "/automonkey/utils.py"], "/automonkey/case.py": ["/automonkey/performance.py", "/automonkey/device.py", "/automonkey/monkey.py", "/automonkey/result.py"], "/automonkey/monkey.py": ["/automonkey/config.py", "/automonkey/device.py", "/automonkey/result.py"], "/automonkey/loader.py": ["/automonkey/case.py"]}
58,195
lin54241930/monkey_tcloud
refs/heads/master
/automonkey/ExeInstall.py
import os import sys import time import traceback import re from multiprocessing import Pool import multiprocessing import prettytable import requests import datetime import uiautomator2 as u2 import subprocess import logging logger = logging.getLogger(__name__) def getDevicesAll(): # 获取devices数量和名称 devices = ["emulator-5560"] try: for dName_ in os.popen("adb devices"): if "\t" in dName_: if dName_.find("emulator") < 0: devices.append(dName_.split("\t")[0]) devices.sort(cmp=None, key=None, reverse=False) print(devices) except Exception as e: print(e) print(u"\n设备名称: %s \n总数量:%s台" % (devices, len(devices))) return devices def check_screen_locked(device, d, times=1): devices_v = d.device_info["version"] devices_version = devices_v[0:3] try: if times >= 3: return False if d.device_info["brand"] == 'Honor' and float(devices_version) == 4.4: right_slide_unlock(device, d) elif d.device_info["brand"] == 'OPPO' and (float(devices_version) == 7.1 or float(devices_version) == 5.1): coordinate_unlock(device, d) elif d.device_info["brand"] == 'HUAWEI': coordinate_unlock(device, d) else: up_slide_unlock(device, d) except Exception as e: print(e) print("({}) 解锁失败,第{}次尝试".format(device, times)) return check_screen_locked(times=times + 1) def up_slide_unlock(device, d): print('({}) 关闭屏幕!'.format(device)) d.screen_off() print('({}) 开启屏幕!'.format(device)) d.screen_on() time.sleep(2) print('({}) 上滑动执行解锁'.format(device)) d.swipe_ext("up") time.sleep(2) print('({}) 回到桌面'.format(device)) d.press("home") def right_slide_unlock(device, d): print('({}) 关闭屏幕!'.format(device)) d.screen_off() print('({}) 开启屏幕!'.format(device)) d.screen_on() time.sleep(2) print('({}) 右滑动执行解锁'.format(device)) d.swipe_ext("right") time.sleep(2) print('({}) 回到桌面'.format(device)) d.press("home") def check_ordinary(device, d): print('({}) 关闭屏幕!'.format(device)) d.screen_off() print('({}) 开启屏幕!'.format(device)) d.screen_on() time.sleep(2) print('({}) 直接执行解锁'.format(device)) d.unlock() time.sleep(2) print('({}) 回到桌面'.format(device)) d.press("home") def coordinate_unlock(device, d): cmd = '{} -s {} shell input swipe 350 991 379 277'.format("adb", device) print(cmd) print('({}) 关闭屏幕!'.format(device)) d.screen_off() print('({}) 开启屏幕!'.format(device)) d.screen_on() time.sleep(2) print('({}) adb命令执行滑动解锁'.format(device)) subprocess.Popen(cmd, shell=True) time.sleep(2) print('({}) 回到桌面'.format(device)) d.press("home") def input_autoinstall(device, d): try: devices_v = d.device_info["version"] devices_version = devices_v[0:3] display = d.device_info["display"] my_display = '{}*{}'.format(display["width"], display["height"]) print('({}) 当前手机系统版本为 {}'.format(device, devices_version)) print('({}) 检测手机厂商 {}'.format(device, d.device_info["brand"])) print('({}) 屏幕分辨率为 {}'.format(device, my_display)) if d.device_info["brand"] == 'vivo': print('({}) 检测到vivo手机'.format(device)) if float(devices_version) < 8: try: d(resourceId="vivo:id/vivo_adb_install_ok_button").click() print("({}) 成功点击安装按钮".format(device)) except Exception as e: print(e) print("({}) 未找到安装按钮".format(device)) return False elif d(resourceId="android:id/button1").exists: print('({}) 开始输入密码'.format(device)) d.xpath( '//*[@resource-id="com.bbk.account:id/dialog_pwd"]/android.widget.LinearLayout[1]/android.widget.RelativeLayout[1]').set_text( "Pokercity2019") print('({}) 点击确认按钮'.format(device)) d(resourceId="android:id/button1").click() print('({}) 等待10s检测应用安全性'.format(device)) d(resourceId="com.sohu.inputmethod.sogou.vivo:id/imeview_keyboard").wait(timeout=10.0) print('({}) 点击安装按钮'.format(device)) d.click(0.497, 0.858) return True else: d.click(0.493, 0.885) time.sleep(2) d.click(0.493, 0.885) elif d.device_info["brand"] == 'OPPO' and float(devices_version) > 4.4: print('({}) 检测到OPPO手机'.format(device)) print('({}) 开始输入密码'.format(device)) time.sleep(2) d(resourceId="com.coloros.safecenter:id/et_login_passwd_edit").set_text("*****") print('({}) 点击确认按钮'.format(device)) d(resourceId="android:id/button1").click() print('({}) 等待8s检测应用安全性'.format(device)) time.sleep(8) if d(text="发现广告插件").exists: d.click(0.686, 0.929) time.sleep(2) d.click(0.482, 0.84) return True else: if float(devices_version) > 5 and float(devices_version) < 7: print("({}) 点击确认按钮".format(device)) d.click(0.718, 0.957) return True elif float(devices_version) == 7.1: print("({}) 点击确认按钮".format(device)) d.click(0.495, 0.841) elif float(devices_version) > 8 and float(devices_version) < 11: print("({}) 点击确认按钮".format(device)) d.click(0.495, 0.954) return True elif float(devices_version) < 5.3 and float(devices_version) >= 5: print("({}) 点击确认按钮".format(device)) d.click(0.498, 0.793) return True else: return True elif d.device_info["brand"] == "xiaomi": print('({}) 检测到小米手机'.format(device)) print('({}) 手机系统版本为{}'.format(device, devices_version)) if d(text="USB安装提示").exists: print('({}) 检测到弹出窗口,点击继续安装按钮'.format(device)) d.click(0.26, 0.953) else: print('({}) 没有检测到弹出窗口,静默安装'.format(device)) elif d.device_info["brand"] == "DOOV": print('({}) 检测到康佳手机'.format(device)) print('({}) 手机系统版本为{}'.format(devices_version)) cmd = '{} -s {} shell input tap 502 774'.format("adb", device) time.sleep(8) if d(text="权限提醒").exists: print('({}) 检测到弹出窗口,点击允许按钮'.format(device)) time.sleep(2) print(cmd) subprocess.Popen(cmd, shell=True) else: print('({}) 没有检测到弹出窗口,静默安装'.format(device)) else: return True # d.service("uiautomator").stop() # print("结束当前手机的uiautomator服务") except Exception as e: print(e) return False def deal_with_python_version(data): if str(sys.version_info.major) == '3': if isinstance(data, list): return [d.decode('utf-8') for d in data] else: return data.decode('utf-8') else: return data def output(p): if p.stdout: return deal_with_python_version(p.stdout.readlines()) else: return deal_with_python_version(p.stderr.readlines()) def command_execute(cmd): try: if not cmd: return False command_process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, executable="/bin/bash") return command_process except Exception as e: print(e) traceback.print_exc() def get_package_version(packagename, device): print('({}) 获取 安装包 版本信息'.format(device)) if check_package_installed(packagename, device): cmd = '{} -s {} shell dumpsys package {} | grep versionName'.format("adb",device, packagename) p = command_execute(cmd) r = output(p) if len(r) > 0: temp = r[0].split('=') if len(temp) > 0: version = temp[1].strip() print('({}) 版本是 [{}] '.format(device, version)) return version return '' else: print('({}) {} 没有安装!'.format(device, packagename)) return None def get_installed_packages(device, show_table=False): try: cmd = '{} -s {} shell pm list packages'.format("adb", device) p = command_execute(cmd) package_list = output(p) if show_table: print('({}) 获取所有的已安装的包'.format(device)) table_packages = prettytable.PrettyTable() table_packages.field_names = ["id", "package name"] for i, package in enumerate(package_list): row = [i, package] table_packages.add_row(row) print('({}) \n {}'.format(device, table_packages)) return package_list except Exception as e: print(e) return e def check_package_installed(packagename, device): for package in get_installed_packages(device): if packagename in package: return True return False def uninstall_package(device, packagename): print('({}) 开始卸载 :{}'.format(device, packagename)) try: if check_package_installed(packagename, device): cmd = '{} -s {} uninstall {}'.format("adb",device, packagename) p = command_execute(cmd) result = output(p) for r in result: if 'Success' in r: print('({}) 卸载 {} 成功'.format(device, packagename)) return True print('({}) 卸载 {} 失败 : '.format(device, packagename)) return False else: print('({}) 设备没有安装 {}, 不需要卸载'.format(device, packagename)) return True except Exception as e: print('({}) 卸载 {} 失败 : '.format(device, packagename)) return e #获取当前界面正在运行的APP def get_current_application(device): return command_execute('{} -s {} shell dumpsys activity activities | findstr "Run"'.format("adb", device)) def get_current_activity(device): p = get_current_application(device) result = output(p) if len(result) > 0: names = result[0].split(' ') if len(names) > 1: activity_name = names[-1] if '/' in activity_name: activity = activity_name.split('/') return activity[1].strip() if len(activity) > 1 else activity return None def whether_start_activity(packagename, d): pid = d.app_wait(packagename) # 等待应用运行, return pid(int) if not pid: print("应用没有启动成功") return "启动成功" else: print("应用启动成功,pid为 %d" % pid) return "启动失败" def start_activity(packagename, device, activity_name): try: activity_name = '{}/{}'.format(packagename, activity_name) print('({}) 启动 activity : {}'.format(device, activity_name)) cmd = '{} -s {} shell am start -W -n {}'.format("adb", device, activity_name) p = command_execute(cmd) result = output(p) print(result) time.sleep(10) current_activity = get_current_activity(device) if current_activity == activity_name: print('({}) activity 已经启动成功'.format(device)) return True return "启动失败" except Exception as e: print(e) print(traceback.format_exc()) def analysis_app_info(d, packagename): appinfo = d.app_info(packagename) print(appinfo) def apk_analysis(download_apk_name): try: print('开始分析包') package_info_re = re.compile(r"package: name='(.*)' versionCode='(.*)' versionName='(.*?)'.*", re.I) label_icon_re = re.compile(r"application: label='(.+)'.*icon='(.+)'", re.I) launchable_activity_re = re.compile(r"launchable-activity: name='(.+)'.*label.*", re.I) apk_info = {} cmd = '/Users/lin/Library/Android/sdk/build-tools/30.0.2/aapt dump badging {}'.format(download_apk_name) command_process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) infos = command_process.stdout.readlines() for info in infos: info = info.decode('utf-8') if info.startswith('package:'): temp = package_info_re.search(info) apk_info['package_name'] = temp.group(1) apk_info['version_code'] = temp.group(2) or 0 apk_info['version_name'] = temp.group(3) elif info.startswith('application:'): temp = label_icon_re.search(info) apk_info['label'] = temp.group(1) apk_info['icon'] = temp.group(2) elif info.startswith('launchable-activity:'): temp = launchable_activity_re.search(info) apk_info['default_activity'] = temp.group(1) try: size = round(os.path.getsize(download_apk_name) / float(1024 * 1024), 2) apk_info['size'] = str(size) except Exception as e: print(e) print(traceback.format_exc()) print(apk_info) if type == 1: pass elif type == 2: pass return apk_info except Exception as e: print(e) print(traceback.format_exc()) return {} def update_monkey(device_id=None, device_name=None, device_version=None, device_screen_size=None, begin_test_time=None, end_test_time=None, install_time=None, package_name=None, package_version=None, whether_install=None, whether_start=None, default_activity=None): tcloud_url = "http://192.168.31.214:8088" try: request_data_template = { "device_id": device_id, "device_name": device_name, "device_version": device_version, "device_screen_size": device_screen_size, "begin_test_time": begin_test_time, "end_test_time": end_test_time, "install_time": install_time, "package_name": package_name, "package_version": package_version, "whether_install": whether_install, "whether_start": whether_start, "default_activity": default_activity } request_data = {} for key in request_data_template.keys(): value = request_data_template.get(key) if value is not None: request_data[key] = value request_url = '{}/v1/monkey/test_install/{}'.format(tcloud_url, device_id) print("输出这个request_url看看") print(request_url) response = requests.request(method='POST', url=request_url, json=request_data) if response.ok: print(response.text) print('({}) update monkey success'.format(device_name)) return True return False except Exception as e: print(e) print(traceback.format_exc()) return False def quickinstall(device): i = "/Users/lin/Downloads/apk/app-debug.apk" packagename = apk_analysis(i)['package_name'] activity_name = apk_analysis(i)['default_activity'] device_id = 888 cmd = '{} -s {} {} {}'.format("adb", device, "install", i) name = multiprocessing.current_process().name print(name) # 卸载原有apk d = u2.connect(device) devices_v = d.device_info["version"] devices_version = devices_v[0:3] # analysis_app_info(d, packagename) get_package_version(packagename, device) uninstall_package(device, packagename) try: check_screen_locked(device, d) print("({}) 开始推送包,请耐心等待...".format((device))) starting = time.time() command_execute(cmd) time.sleep(6) input_autoinstall(device, d) time.sleep(5) if check_package_installed(packagename, device): print('({}) 安装 {} 成功'.format(device, packagename)) whether_install = "安装成功" entire = time.time() print('({}) 安装用时{}'.format(device, entire - starting)) start_activity(packagename, device, activity_name) whether_start = whether_start_activity(packagename, d) else: print('({}) 安装 {} 失败'.format(device, packagename)) whether_install = "安装失败" update_monkey(device_id=device_id, device_name=device, device_version=devices_version, device_screen_size=d.device_info["display"], begin_test_time=starting, end_test_time=entire, install_time=entire - starting, package_name=packagename, package_version=apk_analysis(i)['version_code'], whether_install=whether_install, whether_start=whether_start,default_activity=activity_name) except: print("程序异常") def qainstall(devices): starting = time.time() pool = Pool() # 创建8个任务池 pool.map(quickinstall, devices) entire = time.time() pool.close() pool.join() usetime ='本次安装总耗时为:{}'.format(entire - starting) print(usetime) # 打印时间 if __name__ == "__main__": try: devices = getDevicesAll() except: print("获取设备出错") try: qainstall(devices) except Exception as e: print(e)
{"/automonkey/device.py": ["/automonkey/adb.py", "/automonkey/exception.py"], "/automonkey/utils.py": ["/automonkey/config.py", "/automonkey/exception.py"], "/automonkey/runner.py": ["/automonkey/config.py", "/automonkey/case.py", "/automonkey/exception.py", "/automonkey/monkey_runner.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py", "/automonkey/performance_runner.py"], "/automonkey/performance_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/monkey_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/tcloud_update.py": ["/automonkey/config.py"], "/automonkey/main.py": ["/automonkey/program.py"], "/automonkey/adb.py": ["/automonkey/exception.py", "/automonkey/utils.py"], "/automonkey/program.py": ["/automonkey/config.py", "/automonkey/loader.py", "/automonkey/recorder.py", "/automonkey/runner.py", "/automonkey/utils.py"], "/automonkey/performance.py": ["/automonkey/result.py", "/automonkey/device.py", "/automonkey/config.py"], "/automonkey/result.py": ["/automonkey/config.py"], "/automonkey/logcat.py": ["/automonkey/adb.py", "/automonkey/config.py", "/automonkey/utils.py"], "/automonkey/case.py": ["/automonkey/performance.py", "/automonkey/device.py", "/automonkey/monkey.py", "/automonkey/result.py"], "/automonkey/monkey.py": ["/automonkey/config.py", "/automonkey/device.py", "/automonkey/result.py"], "/automonkey/loader.py": ["/automonkey/case.py"]}
58,196
lin54241930/monkey_tcloud
refs/heads/master
/automonkey/performance.py
#!/usr/bin/python # -*- coding: utf-8 -*- import traceback from .result import MonkeyCaseResult from .device import Device from .config import MonkeyConfig, PerformanceConfig """ # MonkeyCase, 每个 device 对应一个 MonkeyCase # monkey_runner 运行的基本单位 """ class PerformanceCase(object): def __init__(self): self.config = PerformanceConfig() self.device = Device() self.result = MonkeyCaseResult() self.task_id = '' # performance 的 device status id self.monkey_id = '' # 此次 performance 的 id self.tcloud_url = '' def constructor(self, config, device, monkey_id, task_id, tcloud_url): if isinstance(config, dict): config_dict = config.get('config') self.config.constructor(config_dict) if isinstance(device, Device): self.device = device self.task_id = task_id self.monkey_id = monkey_id self.tcloud_url = tcloud_url @property def info(self): return { 'config': self.config.info, 'device': self.device.info, 'result': self.result.info, 'task_id': self.task_id, 'monkey_id': self.monkey_id, 'tcloud_url': self.tcloud_url }
{"/automonkey/device.py": ["/automonkey/adb.py", "/automonkey/exception.py"], "/automonkey/utils.py": ["/automonkey/config.py", "/automonkey/exception.py"], "/automonkey/runner.py": ["/automonkey/config.py", "/automonkey/case.py", "/automonkey/exception.py", "/automonkey/monkey_runner.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py", "/automonkey/performance_runner.py"], "/automonkey/performance_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/monkey_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/tcloud_update.py": ["/automonkey/config.py"], "/automonkey/main.py": ["/automonkey/program.py"], "/automonkey/adb.py": ["/automonkey/exception.py", "/automonkey/utils.py"], "/automonkey/program.py": ["/automonkey/config.py", "/automonkey/loader.py", "/automonkey/recorder.py", "/automonkey/runner.py", "/automonkey/utils.py"], "/automonkey/performance.py": ["/automonkey/result.py", "/automonkey/device.py", "/automonkey/config.py"], "/automonkey/result.py": ["/automonkey/config.py"], "/automonkey/logcat.py": ["/automonkey/adb.py", "/automonkey/config.py", "/automonkey/utils.py"], "/automonkey/case.py": ["/automonkey/performance.py", "/automonkey/device.py", "/automonkey/monkey.py", "/automonkey/result.py"], "/automonkey/monkey.py": ["/automonkey/config.py", "/automonkey/device.py", "/automonkey/result.py"], "/automonkey/loader.py": ["/automonkey/case.py"]}
58,197
lin54241930/monkey_tcloud
refs/heads/master
/automonkey/result.py
#!/usr/bin/python # -*- coding: utf-8 -*- import traceback from datetime import datetime from .config import MonkeyConfig """ # 运行的 Case 的 结果 # 每个 Case 有多个 MonkeyCase # MonkeyCase 的结果 # 每个对应 一个 device """ class CaseResult(object): def __init__(self): self.begin_time = '' self.end_time = '' self.result = '' self.reason = '' self.crash = {} self.anr = {} @property def info(self): return { 'begin_time': self.begin_time, 'end_time': self.end_time, 'result': self.result, 'reason': self.reason, 'crash': self.crash, 'anr': self.anr } def on_case_begin(self): self.begin_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') def on_case_end(self): self.end_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') """ # monkey 运行结果 """ class MonkeyCaseResult(object): def __init__(self): self.begin_time = '' self.end_time = '' self.result = '' self.reason = '' self.device_connect_result = '' self.setup_install_result = '' self.setup_uninstall_result = '' self.screen_lock_result = '' self.start_app_status = '' self.login_app_status = '' self.teardown_uninstall_result = '' self.crash = {} self.anr = {} self.check_screen_locked = '' self.log_path = '' self.activity_info = {} self.app_version = '' @property def info(self): return { 'begin_time': self.begin_time, 'end_time': self.end_time, 'result': self.result, 'reason': self.reason, 'crash': self.crash, 'anr': self.anr, 'setup_install_result': self.setup_install_result, 'setup_uninstall_result': self.setup_uninstall_result, 'teardown_uninstall_result': self.teardown_uninstall_result, 'device_connect_result': self.device_connect_result, 'check_screen_locked': self.check_screen_locked, 'screen_lock_result': self.screen_lock_result, 'start_app_status': self.start_app_status, 'login_app_status': self.login_app_status, 'log_path': self.log_path, 'activity_info': self.activity_info, 'app_version': self.app_version } def on_case_begin(self): self.begin_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') def on_case_end(self): self.end_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') def on_app_install_failed(self): self.setup_install_result = False self.on_check_screen_lock_failed() def on_device_connect_failed(self): self.device_connect_result = False self.on_setup_app_uninstall_failed() def on_setup_app_uninstall_failed(self): self.setup_uninstall_result = False self.on_app_install_failed() def on_teardown_app_uninstall_failed(self): self.teardown_uninstall_result = False self.on_case_end() def on_check_screen_lock_failed(self): self.check_screen_locked = False self.on_teardown_app_uninstall_failed() class PerformanceCaseResult(object): def __init__(self): self.begin_time = '' self.end_time = '' self.result = '' self.reason = '' self.device_connect_result = '' self.setup_install_result = '' self.setup_uninstall_result = '' self.screen_lock_result = '' self.start_app_status = '' self.login_app_status = '' self.teardown_uninstall_result = '' self.check_screen_locked = '' self.log_path = '' self.app_version = '' @property def info(self): return { 'begin_time': self.begin_time, 'end_time': self.end_time, 'result': self.result, 'reason': self.reason, 'setup_install_result': self.setup_install_result, 'setup_uninstall_result': self.setup_uninstall_result, 'teardown_uninstall_result': self.teardown_uninstall_result, 'device_connect_result': self.device_connect_result, 'check_screen_locked': self.check_screen_locked, 'screen_lock_result': self.screen_lock_result, 'start_app_status': self.start_app_status, 'login_app_status': self.login_app_status, 'log_path': self.log_path, 'app_version': self.app_version } def on_case_begin(self): self.begin_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') def on_case_end(self): self.end_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') def on_app_install_failed(self): self.setup_install_result = False self.on_check_screen_lock_failed() def on_device_connect_failed(self): self.device_connect_result = False self.on_setup_app_uninstall_failed() def on_setup_app_uninstall_failed(self): self.setup_uninstall_result = False self.on_app_install_failed() def on_teardown_app_uninstall_failed(self): self.teardown_uninstall_result = False self.on_case_end() def on_check_screen_lock_failed(self): self.check_screen_locked = False self.on_teardown_app_uninstall_failed()
{"/automonkey/device.py": ["/automonkey/adb.py", "/automonkey/exception.py"], "/automonkey/utils.py": ["/automonkey/config.py", "/automonkey/exception.py"], "/automonkey/runner.py": ["/automonkey/config.py", "/automonkey/case.py", "/automonkey/exception.py", "/automonkey/monkey_runner.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py", "/automonkey/performance_runner.py"], "/automonkey/performance_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/monkey_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/tcloud_update.py": ["/automonkey/config.py"], "/automonkey/main.py": ["/automonkey/program.py"], "/automonkey/adb.py": ["/automonkey/exception.py", "/automonkey/utils.py"], "/automonkey/program.py": ["/automonkey/config.py", "/automonkey/loader.py", "/automonkey/recorder.py", "/automonkey/runner.py", "/automonkey/utils.py"], "/automonkey/performance.py": ["/automonkey/result.py", "/automonkey/device.py", "/automonkey/config.py"], "/automonkey/result.py": ["/automonkey/config.py"], "/automonkey/logcat.py": ["/automonkey/adb.py", "/automonkey/config.py", "/automonkey/utils.py"], "/automonkey/case.py": ["/automonkey/performance.py", "/automonkey/device.py", "/automonkey/monkey.py", "/automonkey/result.py"], "/automonkey/monkey.py": ["/automonkey/config.py", "/automonkey/device.py", "/automonkey/result.py"], "/automonkey/loader.py": ["/automonkey/case.py"]}
58,198
lin54241930/monkey_tcloud
refs/heads/master
/automonkey/logcat.py
import json import logging import os import traceback from .adb import AdbTool from .config import DefaultConfig from .utils import Utils logger = logging.getLogger(__name__) """ # LogCat """ class LogCat(object): def __init__(self, device_id, pid): super(LogCat, self).__init__() self.daemon = True self.device_id = device_id self.adb_tool = AdbTool(self.device_id) self.log_path = '{}/{}'.format(DefaultConfig.LOCAL_LOGCAT_PATH, pid) self.bug_report_path = '{}/bug_report'.format(self.log_path) # 清除logcat,开启重定向 def set_logcat(self, target): try: self.adb_tool.clear_logcat() p = self.adb_tool.start_logcat(target) return p except Exception as e: logger.error(e) logger.error(traceback.format_exc()) def get_logcat_log(self, log): try: logger.info('({}) 开始获取 logcat 日志'.format(self.device_id)) local_log_path = '{}'.format(self.log_path) monkey_log_path = '{}/monkey'.format(local_log_path) # p = self.adb_tool.start_logcat() # log = [] # step = 1 # for line in p.stdout.readlines(): # log.append(line) # if step == 10000: # break # step += 1 if not os.path.exists(DefaultConfig.LOCAL_LOGCAT_PATH): os.mkdir(DefaultConfig.LOCAL_LOGCAT_PATH) if not os.path.exists(self.log_path): os.mkdir(self.log_path) if not os.path.exists(local_log_path): os.mkdir(local_log_path) if not os.path.exists(monkey_log_path): os.mkdir(monkey_log_path) with open('{}/monkey_result_log.log'.format(local_log_path), 'w') as f: f.write(str(log)) # 获取 crash dump log self.adb_tool.pull_file('/sdcard/MonkeyLog/oom-traces.log', '{}/'.format(local_log_path)) self.adb_tool.pull_file('/sdcard/MonkeyLog/', '{}/'.format(monkey_log_path)) self.get_crash_dump_log() logger.info('({}) 成功获取日志'.format(self.device_id)) log_paths = ['{}/{}'.format(local_log_path, log_name) for log_name in os.listdir(local_log_path)] return log_paths except Exception as e: logger.error(e) logger.error(traceback.format_exc()) def get_crash_dump_log(self): logger.info('({}) 开始获取 crash-dump log 日志'.format(self.device_id)) self.adb_tool.pull_file('/sdcard/MonkeyLog/crash-dump.log', '{}/'.format(self.log_path)) def analysis_crash_anr_log(self, target, anr_count=-1, crash_count=-1): try: logger.info('({}) 开始分析 crash dump log {}'.format(self.device_id, target)) log_name = target crash_anr_logs = {} i = 0 anr_i = 0 crash_i = 0 if os.path.exists(log_name) and os.path.isfile(log_name): with open(log_name, 'r') as f: crash_flag = False oom_flag = False for line in f.readlines(): if 'crashend' in line: if crash_flag: i += 1 crash_flag = False elif 'crash:' in line: crash_i += 1 if crash_i > crash_count: crash_anr_logs[i] = { 'error_type': 'CRASH', 'error_count': 1, 'error_message': [] } crash_flag = True if crash_flag: crash_anr_logs[i]['error_message'].append(line) if 'oomend' in line: if oom_flag: i += 1 oom_flag = False elif 'oom:' in line: anr_i += 1 if anr_i > anr_count: crash_anr_logs[i] = { 'error_type': 'OOM', 'error_count': 1, 'error_message': [] } oom_flag = True if oom_flag: crash_anr_logs[i]['error_message'].append(line) logger.info('({}) debug log crash here : {}'.format(self.device_id, crash_anr_logs)) return crash_anr_logs except Exception as e: logger.error(e) logger.error(traceback.format_exc()) def get_oom_trace_logs(self, target): try: # TODO: 需要分析详情??? logger.info('({}) 开始分析 out of memory log {}'.format(self.device_id, target)) log_name = target crash_anr_logs = {} i = 0 if os.path.exists(log_name) and os.path.isfile(log_name): with open(log_name, 'r') as f: crash_flag = False for line in f.readlines(): if 'crashend' in line: crash_flag = False i += 1 elif 'crash:' in line: crash_anr_logs[i] = { 'error_type': 'CRASH', 'error_count': 1, 'error_message': [] } crash_flag = True if crash_flag: crash_anr_logs[i]['error_message'].append(line) return crash_anr_logs except Exception as e: logger.error(e) logger.error(traceback.format_exc()) def get_anr_crash_count(self): try: anr_count = 0 crash_count = 0 logs = self.adb_tool.get_crash_dump_log() for log in logs: if 'ANR' in log: anr_count += 1 if 'CRASH' in log: crash_count += 1 return anr_count, crash_count except Exception as e: logger.error(e) logger.error(traceback.format_exc()) def get_activity_test_info(self, show_in_cmd=False): try: activity_path = '{}/monkey/MonkeyLog/{}'.format(self.log_path, DefaultConfig.ACTIVITY_PATH) infos = { 'TotalActivity': [], 'TestedActivity': [], 'Coverage': 0, 'Sampling': [] } if os.path.exists(activity_path): with open(activity_path, 'r') as f: infos = json.load(f) else: logger.warning('{} not found in local!'.format(activity_path)) if show_in_cmd: keys = infos.keys() values = { 'TotalActivity': infos.get('TotalActivity', []), 'TestedActivity': infos.get('TestedActivity', []), 'Coverage': infos.get('Coverage'), 'Sampling': infos.get('Sampling') } Utils.show_info_as_table(keys, values) return infos except Exception as e: logger.error(e) logger.error(traceback.format_exc()) return {'error': e} def reset_bug_report_log(self): self.adb_tool.reset_bug_report_log() def get_bug_report_log(self): return self.adb_tool.get_bug_report_log(self.bug_report_path) def generate_bug_report(self): try: out = Utils.bug_report_tool(self.bug_report_path) print(out) except Exception as e: logger.error(e) logger.error(traceback.format_exc()) def upload_bug_report_log(self): if self.log_path.startswith("./"): log_path = self.log_path[2:] Utils.upload_bug_report_log_to_oss(log_path)
{"/automonkey/device.py": ["/automonkey/adb.py", "/automonkey/exception.py"], "/automonkey/utils.py": ["/automonkey/config.py", "/automonkey/exception.py"], "/automonkey/runner.py": ["/automonkey/config.py", "/automonkey/case.py", "/automonkey/exception.py", "/automonkey/monkey_runner.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py", "/automonkey/performance_runner.py"], "/automonkey/performance_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/monkey_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/tcloud_update.py": ["/automonkey/config.py"], "/automonkey/main.py": ["/automonkey/program.py"], "/automonkey/adb.py": ["/automonkey/exception.py", "/automonkey/utils.py"], "/automonkey/program.py": ["/automonkey/config.py", "/automonkey/loader.py", "/automonkey/recorder.py", "/automonkey/runner.py", "/automonkey/utils.py"], "/automonkey/performance.py": ["/automonkey/result.py", "/automonkey/device.py", "/automonkey/config.py"], "/automonkey/result.py": ["/automonkey/config.py"], "/automonkey/logcat.py": ["/automonkey/adb.py", "/automonkey/config.py", "/automonkey/utils.py"], "/automonkey/case.py": ["/automonkey/performance.py", "/automonkey/device.py", "/automonkey/monkey.py", "/automonkey/result.py"], "/automonkey/monkey.py": ["/automonkey/config.py", "/automonkey/device.py", "/automonkey/result.py"], "/automonkey/loader.py": ["/automonkey/case.py"]}
58,199
lin54241930/monkey_tcloud
refs/heads/master
/automonkey/case.py
from automonkey.performance import PerformanceCase from .device import Device from .monkey import MonkeyCase from .result import CaseResult """ # 运行的 Case # runner 运行的基本操作单位 """ class Case(object): def __init__(self): self.name = '' self.cases = [] self.case_type = 1 self.monkey_id = '' self.task_ids = '' self.app_download_url = '' self.tcloud_url = '' self.result = CaseResult() self.test_config = '' def constructor(self, inputs): self.monkey_id = inputs.get('monkey_id') self.task_ids = inputs.get('task_ids') self.app_download_url = inputs.get('app_download_url') self.tcloud_url = inputs.get('tcloud_url') for device_dict in inputs.get('devices'): device = Device() device.constructor(device_dict) if inputs.get('test_type') == 'monkey': self.case_type = 1 elif inputs.get('test_type') == 'performance': self.case_type = 2 if self.case_type == 1: case = MonkeyCase() elif self.case_type == 2: case = PerformanceCase() case.constructor(inputs.get('case'), device, self.monkey_id, self.task_ids.get(device.device_id), self.tcloud_url) self.cases.append(case) @property def info(self): return { 'cases': [monkey.info for monkey in self.cases], 'result': self.result.info, 'monkey_id': self.monkey_id, 'task_ids': self.task_ids, 'app_download_url': self.app_download_url, 'tcloud_url': self.tcloud_url, 'case_type': self.case_type } def bind_local_package_to_monkey(self, local_package_path): for monkey in self.cases: monkey.config.local_package_path = local_package_path
{"/automonkey/device.py": ["/automonkey/adb.py", "/automonkey/exception.py"], "/automonkey/utils.py": ["/automonkey/config.py", "/automonkey/exception.py"], "/automonkey/runner.py": ["/automonkey/config.py", "/automonkey/case.py", "/automonkey/exception.py", "/automonkey/monkey_runner.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py", "/automonkey/performance_runner.py"], "/automonkey/performance_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/monkey_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/tcloud_update.py": ["/automonkey/config.py"], "/automonkey/main.py": ["/automonkey/program.py"], "/automonkey/adb.py": ["/automonkey/exception.py", "/automonkey/utils.py"], "/automonkey/program.py": ["/automonkey/config.py", "/automonkey/loader.py", "/automonkey/recorder.py", "/automonkey/runner.py", "/automonkey/utils.py"], "/automonkey/performance.py": ["/automonkey/result.py", "/automonkey/device.py", "/automonkey/config.py"], "/automonkey/result.py": ["/automonkey/config.py"], "/automonkey/logcat.py": ["/automonkey/adb.py", "/automonkey/config.py", "/automonkey/utils.py"], "/automonkey/case.py": ["/automonkey/performance.py", "/automonkey/device.py", "/automonkey/monkey.py", "/automonkey/result.py"], "/automonkey/monkey.py": ["/automonkey/config.py", "/automonkey/device.py", "/automonkey/result.py"], "/automonkey/loader.py": ["/automonkey/case.py"]}
58,200
lin54241930/monkey_tcloud
refs/heads/master
/automonkey/monkey.py
from .config import MonkeyConfig from .device import Device from .result import MonkeyCaseResult """ # MonkeyCase, 每个 device 对应一个 MonkeyCase # monkey_runner 运行的基本单位 """ class MonkeyCase(object): def __init__(self): self.config = MonkeyConfig() self.device = Device() self.result = MonkeyCaseResult() self.task_id = '' # monkey 的 MonkeyDevice数据的 id self.monkey_id = '' # 此次 monkey 的 id self.tcloud_url = '' def constructor(self, config, device, monkey_id, task_id, tcloud_url): if isinstance(config, dict): config_dict = config.get('config') self.config.constructor(config_dict) if isinstance(device, Device): self.device = device self.task_id = task_id self.monkey_id = monkey_id self.tcloud_url = tcloud_url @property def info(self): return { 'config': self.config.info, 'device': self.device.info, 'result': self.result.info, 'task_id': self.task_id, 'monkey_id': self.monkey_id, 'tcloud_url': self.tcloud_url }
{"/automonkey/device.py": ["/automonkey/adb.py", "/automonkey/exception.py"], "/automonkey/utils.py": ["/automonkey/config.py", "/automonkey/exception.py"], "/automonkey/runner.py": ["/automonkey/config.py", "/automonkey/case.py", "/automonkey/exception.py", "/automonkey/monkey_runner.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py", "/automonkey/performance_runner.py"], "/automonkey/performance_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/monkey_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/tcloud_update.py": ["/automonkey/config.py"], "/automonkey/main.py": ["/automonkey/program.py"], "/automonkey/adb.py": ["/automonkey/exception.py", "/automonkey/utils.py"], "/automonkey/program.py": ["/automonkey/config.py", "/automonkey/loader.py", "/automonkey/recorder.py", "/automonkey/runner.py", "/automonkey/utils.py"], "/automonkey/performance.py": ["/automonkey/result.py", "/automonkey/device.py", "/automonkey/config.py"], "/automonkey/result.py": ["/automonkey/config.py"], "/automonkey/logcat.py": ["/automonkey/adb.py", "/automonkey/config.py", "/automonkey/utils.py"], "/automonkey/case.py": ["/automonkey/performance.py", "/automonkey/device.py", "/automonkey/monkey.py", "/automonkey/result.py"], "/automonkey/monkey.py": ["/automonkey/config.py", "/automonkey/device.py", "/automonkey/result.py"], "/automonkey/loader.py": ["/automonkey/case.py"]}
58,201
lin54241930/monkey_tcloud
refs/heads/master
/automonkey/loader.py
from argparse import Namespace from .case import Case """ # Loader : 将参数转化为 Config, 并构建 Case """ class Loader(object): def __init__(self): self.params = { 'monkey_id': '', 'device': [], 'monkey': { 'config': {} }, 'config': {} } def parse_args_to_dict(self, args): if isinstance(args, Namespace): self.params['monkey_id'] = args.monkey_id self.params['task_ids'] = args.task_id self.params['tcloud_url'] = args.tcloud_url self.params['build_belong'] = args.build_belong self.params['app_download_url'] = args.app_download_url self.params['test_type'] = args.test_type # 构建 case dict self.params['case'] = { 'config': { 'run_mode': args.run_mode, 'package_name': args.package_name, 'app_download_url': args.app_download_url, 'default_app_activity': args.default_app_activity, 'run_time': args.run_time, 'login_required': args.login_required, 'login_password': args.login_password, 'login_username': args.login_username, 'install_app_required': args.install_app_required, 'test_config': args.test_config } } self.params['devices'] = [ {'device_id': id, 'system_device': args.system_device} for id in args.device_id ] def constructor_case(self): case = Case() case.constructor(self.params) return case def run(self, args): self.parse_args_to_dict(args) return self.constructor_case()
{"/automonkey/device.py": ["/automonkey/adb.py", "/automonkey/exception.py"], "/automonkey/utils.py": ["/automonkey/config.py", "/automonkey/exception.py"], "/automonkey/runner.py": ["/automonkey/config.py", "/automonkey/case.py", "/automonkey/exception.py", "/automonkey/monkey_runner.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py", "/automonkey/performance_runner.py"], "/automonkey/performance_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/monkey_runner.py": ["/automonkey/config.py", "/automonkey/adb.py", "/automonkey/exception.py", "/automonkey/logcat.py", "/automonkey/tcloud_update.py", "/automonkey/utils.py"], "/automonkey/tcloud_update.py": ["/automonkey/config.py"], "/automonkey/main.py": ["/automonkey/program.py"], "/automonkey/adb.py": ["/automonkey/exception.py", "/automonkey/utils.py"], "/automonkey/program.py": ["/automonkey/config.py", "/automonkey/loader.py", "/automonkey/recorder.py", "/automonkey/runner.py", "/automonkey/utils.py"], "/automonkey/performance.py": ["/automonkey/result.py", "/automonkey/device.py", "/automonkey/config.py"], "/automonkey/result.py": ["/automonkey/config.py"], "/automonkey/logcat.py": ["/automonkey/adb.py", "/automonkey/config.py", "/automonkey/utils.py"], "/automonkey/case.py": ["/automonkey/performance.py", "/automonkey/device.py", "/automonkey/monkey.py", "/automonkey/result.py"], "/automonkey/monkey.py": ["/automonkey/config.py", "/automonkey/device.py", "/automonkey/result.py"], "/automonkey/loader.py": ["/automonkey/case.py"]}
58,210
tim-chow/common-object-pool
refs/heads/master
/test_dedicate_object_pool.py
from common_object_pool.dedicate_object_pool import DedicateObjectPool from test_shared_object_pool import test, Factory if __name__ == "__main__": thread_count = 20 sleep_time = 3 max_count = 3 object_pool = DedicateObjectPool( max_count, Factory ) timeout = 1.5 max_attempts = 5 test( thread_count, sleep_time, object_pool, timeout, max_attempts )
{"/test_dedicate_object_pool.py": ["/common_object_pool/dedicate_object_pool.py", "/test_shared_object_pool.py"], "/common_object_pool/dedicate_object_pool.py": ["/common_object_pool/abstract_object_pool.py"], "/common_object_pool/shared_object_pool.py": ["/common_object_pool/abstract_object_pool.py"], "/test_drop_object.py": ["/common_object_pool/dedicate_object_pool.py", "/common_object_pool/exceptions.py"], "/test_shared_object_pool.py": ["/common_object_pool/shared_object_pool.py", "/common_object_pool/__init__.py", "/common_object_pool/exceptions.py"]}
58,211
tim-chow/common-object-pool
refs/heads/master
/common_object_pool/exceptions.py
class ObjectPoolException(Exception): pass class MaxAttemptsReached(ObjectPoolException): pass class ObjectUnusable(ObjectPoolException): pass
{"/test_dedicate_object_pool.py": ["/common_object_pool/dedicate_object_pool.py", "/test_shared_object_pool.py"], "/common_object_pool/dedicate_object_pool.py": ["/common_object_pool/abstract_object_pool.py"], "/common_object_pool/shared_object_pool.py": ["/common_object_pool/abstract_object_pool.py"], "/test_drop_object.py": ["/common_object_pool/dedicate_object_pool.py", "/common_object_pool/exceptions.py"], "/test_shared_object_pool.py": ["/common_object_pool/shared_object_pool.py", "/common_object_pool/__init__.py", "/common_object_pool/exceptions.py"]}
58,212
tim-chow/common-object-pool
refs/heads/master
/common_object_pool/__init__.py
from contextlib import contextmanager import sys from .exceptions import ObjectUnusable @contextmanager def get_object( object_pool, *args, **kwargs): object_id, obj = object_pool.get_object(*args, **kwargs) exc_info = None try: yield obj except ObjectUnusable: object_pool.drop_object(object_id) raise except: exc_info = sys.exc_info() object_pool.release_object(object_id) if exc_info: raise exc_info[0], exc_info[1], exc_info[2]
{"/test_dedicate_object_pool.py": ["/common_object_pool/dedicate_object_pool.py", "/test_shared_object_pool.py"], "/common_object_pool/dedicate_object_pool.py": ["/common_object_pool/abstract_object_pool.py"], "/common_object_pool/shared_object_pool.py": ["/common_object_pool/abstract_object_pool.py"], "/test_drop_object.py": ["/common_object_pool/dedicate_object_pool.py", "/common_object_pool/exceptions.py"], "/test_shared_object_pool.py": ["/common_object_pool/shared_object_pool.py", "/common_object_pool/__init__.py", "/common_object_pool/exceptions.py"]}
58,213
tim-chow/common-object-pool
refs/heads/master
/common_object_pool/abstract_object_pool.py
# coding: utf8 import logging import abc import threading import sys from .exceptions import MaxAttemptsReached LOGGER = logging.getLogger(__name__) class AbstractObjectPool(object): __metaclass__ = abc.ABCMeta __LOCK = threading.Lock() __ID = 0 def __init__(self, max_count, factory=None): if factory is not None: assert callable(factory), "factory must be callable" self._creating_count = 0 self._created_count = 0 self._condition = threading.Condition() self._closing = False self._closed = False self._factory = factory self._max_count = max_count @abc.abstractmethod def has_free_object(self): pass @abc.abstractmethod def get_free_object(self): pass @abc.abstractmethod def store_newly_created_object(self, object_id, obj): pass def get_object( self, timeout=None, max_attempts=None, factory=None): """ 获取对象 @param timeout None、不小于0的数值 当对象池中没有空闲对象时,线程等待的时间, None 表示等待到其它线程释放或销毁对象。 线程的最大等待时间等于 timeout * (max_attempts or 1) @param max_attempts None、不小于0的整数 线程尝试获取对象的最大次数 @param factory None、可调用对象 对象池调用该可调用对象创建对象 @return (int, object) 由 ID 和对象组成的元组 @raise MaxRetriesReached 当线程尝试获取连接的次数达到指定的最大次数时,抛出该异常 @raise RuntimeError 当调用方既没有通过该方法的 factory 参数, 也没有通过构造方法指定 factory 时, 抛出该异常 @raise BaseException 调用 factory 时出现的异常,会被抛出 @raise RuntimeError 当对象池正在或已经关闭时,调用该方法将引发该异常 """ if factory is not None: assert callable(factory), "factory must be callable" cf = factory or self._factory if cf is None: raise RuntimeError("no factory specified") with self._condition: if self._closing or self._closed: raise RuntimeError("pool closed") loop_count = 1 max_attempts = max_attempts or 1 while loop_count <= max_attempts: if self._closing or self._closed: raise RuntimeError("pool closed") if self.has_free_object(): object_id, obj = self.get_free_object() LOGGER.debug("get object %d from pool", object_id) return object_id, obj if self._creating_count + self._created_count < self._max_count: LOGGER.debug("will create new object") self._creating_count = self._creating_count + 1 break if loop_count < max_attempts: LOGGER.debug("wait for idle objects") self._condition.wait(timeout) loop_count = loop_count + 1 else: raise MaxAttemptsReached("max attempts reached") obj = None exc_info = None try: obj = cf() except Exception: exc_info = sys.exc_info() with self._condition: if self._closing or self._closed: if obj is not None: try_close(obj) raise RuntimeError("pool closed") self._creating_count = self._creating_count - 1 if obj is not None: self._created_count = self._created_count + 1 object_id = self.get_id() LOGGER.debug("store newly created object %d", object_id) self.store_newly_created_object(object_id, obj) return object_id, obj LOGGER.error("fail to create object") raise exc_info[0], exc_info[1], exc_info[2] @abc.abstractmethod def is_using(self, object_id): pass @abc.abstractmethod def restore_object(self, object_id): pass def release_object(self, object_id): """ 将对象放回对象池 @param object_id int 对象ID @return None @raise RuntimeError 当对象池正在关闭时,调用该方法将引发该异常 """ with self._condition: if self._closing or self._closed: raise RuntimeError("pool closed") if not self.is_using(object_id): LOGGER.error("unknown object id %d", object_id) return LOGGER.debug("release using object %d to pool", object_id) self.restore_object(object_id) self._condition.notify_all() @abc.abstractmethod def remove_using_object_from_pool(self, object_id): pass @abc.abstractmethod def is_idle(self, object_id): pass @abc.abstractmethod def remove_idle_object_from_pool(self, object_id): pass def drop_object(self, object_id): """ 从对象池中移除对象 比如,当对象是一个网络连接时,如果调用方发现该连接不可用,则应该调用该方法移除该连接 @param object_id int 对象ID @return None @raise RuntimeError 当对象池正在关闭时,调用该方法将引发该异常 """ with self._condition: if self._closing or self._closed: raise RuntimeError("pool closed") if self.is_using(object_id): self._created_count = self._created_count - 1 LOGGER.debug("drop using object %d", object_id) self.remove_using_object_from_pool(object_id) elif self.is_idle(object_id): self._created_count = self._created_count - 1 LOGGER.debug("drop idle object %d", object_id) self.remove_idle_object_from_pool(object_id) else: LOGGER.debug("unknown object %d", object_id) self._condition.notify_all() @classmethod def get_id(cls): """ 获取唯一ID @return int """ with cls.__LOCK: cls.__ID = cls.__ID + 1 return cls.__ID @abc.abstractmethod def iter_created_objects(self): pass def close(self): if self._closing or self._closed: return with self._condition: if self._closing or self._closed: return self._closing = True self._condition.notify_all() for obj in self.iter_created_objects(): try_close(obj) self._closing = False self._closed = True def try_close(obj): attr = getattr(obj, 'close', None) if attr is not None and callable(attr): try: attr() except Exception: LOGGER.error("fail to call close", exc_info=True)
{"/test_dedicate_object_pool.py": ["/common_object_pool/dedicate_object_pool.py", "/test_shared_object_pool.py"], "/common_object_pool/dedicate_object_pool.py": ["/common_object_pool/abstract_object_pool.py"], "/common_object_pool/shared_object_pool.py": ["/common_object_pool/abstract_object_pool.py"], "/test_drop_object.py": ["/common_object_pool/dedicate_object_pool.py", "/common_object_pool/exceptions.py"], "/test_shared_object_pool.py": ["/common_object_pool/shared_object_pool.py", "/common_object_pool/__init__.py", "/common_object_pool/exceptions.py"]}
58,214
tim-chow/common-object-pool
refs/heads/master
/common_object_pool/dedicate_object_pool.py
from .abstract_object_pool import AbstractObjectPool class DedicateObjectPool(AbstractObjectPool): def __init__(self, max_count, factory=None): AbstractObjectPool.__init__(self, max_count, factory) self._idle_object_ids = [] self._idle_objects = {} self._using_objects = {} def has_free_object(self): return len(self._idle_object_ids) > 0 def get_free_object(self): object_id = self._idle_object_ids.pop(0) obj = self._idle_objects.pop(object_id) self._using_objects[object_id] = obj return object_id, obj def store_newly_created_object(self, object_id, obj): self._using_objects[object_id] = obj def is_using(self, object_id): return object_id in self._using_objects def is_idle(self, object_id): return object_id in self._idle_objects def restore_object(self, object_id): obj = self._using_objects.pop(object_id) self._idle_object_ids.append(object_id) self._idle_objects[object_id] = obj def remove_idle_object_from_pool(self, object_id): self._idle_objects.pop(object_id) self._idle_object_ids.remove(object_id) def remove_using_object_from_pool(self, object_id): self._using_objects.pop(object_id) def iter_created_objects(self): for obj in self._idle_objects.values(): yield obj for obj in self._using_objects.values(): yield obj
{"/test_dedicate_object_pool.py": ["/common_object_pool/dedicate_object_pool.py", "/test_shared_object_pool.py"], "/common_object_pool/dedicate_object_pool.py": ["/common_object_pool/abstract_object_pool.py"], "/common_object_pool/shared_object_pool.py": ["/common_object_pool/abstract_object_pool.py"], "/test_drop_object.py": ["/common_object_pool/dedicate_object_pool.py", "/common_object_pool/exceptions.py"], "/test_shared_object_pool.py": ["/common_object_pool/shared_object_pool.py", "/common_object_pool/__init__.py", "/common_object_pool/exceptions.py"]}
58,215
tim-chow/common-object-pool
refs/heads/master
/common_object_pool/shared_object_pool.py
from .abstract_object_pool import AbstractObjectPool class SharedObjectPool(AbstractObjectPool): def __init__(self, max_shared_count, max_count, factory=None): AbstractObjectPool.__init__(self, max_count, factory) self._max_shared_count = max_shared_count self._objects = {} self._id_to_shared_count = {} self._available_object_ids = [] def has_free_object(self): return len(self._available_object_ids) > 0 def get_free_object(self): object_id = self._available_object_ids[0] self._id_to_shared_count[object_id] = \ self._id_to_shared_count.get(object_id, 0) + 1 if self._id_to_shared_count[object_id] == self._max_shared_count: self._available_object_ids.pop(0) return object_id, self._objects[object_id] def store_newly_created_object(self, object_id, obj): self._objects[object_id] = obj self._id_to_shared_count[object_id] = 1 if self._max_shared_count > 1: self._available_object_ids.append(object_id) def is_using(self, object_id): if object_id not in self._objects: return False return self._id_to_shared_count[object_id] > 0 def is_idle(self, object_id): if object_id not in self._objects: return False return self._id_to_shared_count[object_id] == 0 def restore_object(self, object_id): self._id_to_shared_count[object_id] = \ self._id_to_shared_count[object_id] - 1 if self._id_to_shared_count[object_id] < self._max_shared_count: if object_id not in self._available_object_ids: self._available_object_ids.append(object_id) def remove_using_object_from_pool(self, object_id): self._objects.pop(object_id) self._id_to_shared_count.pop(object_id) try: self._available_object_ids.remove(object_id) except ValueError: pass remove_idle_object_from_pool = remove_using_object_from_pool def iter_created_objects(self): for obj in self._objects.itervalues(): yield obj
{"/test_dedicate_object_pool.py": ["/common_object_pool/dedicate_object_pool.py", "/test_shared_object_pool.py"], "/common_object_pool/dedicate_object_pool.py": ["/common_object_pool/abstract_object_pool.py"], "/common_object_pool/shared_object_pool.py": ["/common_object_pool/abstract_object_pool.py"], "/test_drop_object.py": ["/common_object_pool/dedicate_object_pool.py", "/common_object_pool/exceptions.py"], "/test_shared_object_pool.py": ["/common_object_pool/shared_object_pool.py", "/common_object_pool/__init__.py", "/common_object_pool/exceptions.py"]}
58,216
tim-chow/common-object-pool
refs/heads/master
/test_drop_object.py
import logging from common_object_pool.dedicate_object_pool import DedicateObjectPool from common_object_pool.exceptions import MaxAttemptsReached logging.basicConfig( level=logging.DEBUG, format="%(asctime)s %(message)s", ) LOGGER = logging.getLogger(__name__) def test(timeout=1, max_attempts=2): max_count = 2 pool = DedicateObjectPool(max_count, object) for _ in range(max_count): object_id, _ = pool.get_object(timeout, max_attempts) pool.drop_object(object_id) for _ in range(max_count): _, obj = pool.get_object(timeout, max_attempts) LOGGER.debug("object is %r", obj) try: _, obj = pool.get_object(timeout, max_attempts) except MaxAttemptsReached: LOGGER.debug("max attempts reached") pool.close() if __name__ == "__main__": test()
{"/test_dedicate_object_pool.py": ["/common_object_pool/dedicate_object_pool.py", "/test_shared_object_pool.py"], "/common_object_pool/dedicate_object_pool.py": ["/common_object_pool/abstract_object_pool.py"], "/common_object_pool/shared_object_pool.py": ["/common_object_pool/abstract_object_pool.py"], "/test_drop_object.py": ["/common_object_pool/dedicate_object_pool.py", "/common_object_pool/exceptions.py"], "/test_shared_object_pool.py": ["/common_object_pool/shared_object_pool.py", "/common_object_pool/__init__.py", "/common_object_pool/exceptions.py"]}
58,217
tim-chow/common-object-pool
refs/heads/master
/test_shared_object_pool.py
import logging import threading import time from common_object_pool.shared_object_pool import SharedObjectPool from common_object_pool import get_object from common_object_pool.exceptions import MaxAttemptsReached LOGGER = logging.getLogger(__name__) logging.basicConfig( level=logging.DEBUG, format="%(threadName)s %(asctime)s " "%(filename)s:%(lineno)d %(message)s", datefmt="%Y-%m-%d %H:%M:%S") def target(sleep_time, object_pool, *args, **kwargs): try: with get_object(object_pool, *args, **kwargs) as obj: LOGGER.info("object is %s", obj) time.sleep(sleep_time) except MaxAttemptsReached: LOGGER.error("max attempts reached") def test( thread_count, sleep_time, object_pool, timeout, max_attempts): threads = [] for ind in range(thread_count): t = threading.Thread( target=target, args=(sleep_time, object_pool, timeout, max_attempts)) t.setName("test-thread-%d" % ind) t.setDaemon(True) threads.append(t) t.start() for t in threads: t.join() object_pool.close() class Factory(object): def close(self): LOGGER.debug("object %r is closed", self) if __name__ == "__main__": thread_count = 20 sleep_time = 1 max_shared_count = 2 max_count = 3 object_pool = SharedObjectPool( max_shared_count, max_count, Factory ) timeout = 1.5 max_attempts = 5 test( thread_count, sleep_time, object_pool, timeout, max_attempts )
{"/test_dedicate_object_pool.py": ["/common_object_pool/dedicate_object_pool.py", "/test_shared_object_pool.py"], "/common_object_pool/dedicate_object_pool.py": ["/common_object_pool/abstract_object_pool.py"], "/common_object_pool/shared_object_pool.py": ["/common_object_pool/abstract_object_pool.py"], "/test_drop_object.py": ["/common_object_pool/dedicate_object_pool.py", "/common_object_pool/exceptions.py"], "/test_shared_object_pool.py": ["/common_object_pool/shared_object_pool.py", "/common_object_pool/__init__.py", "/common_object_pool/exceptions.py"]}
58,219
galenscovell/CommuteMap
refs/heads/master
/services/google_maps_client.py
""" Client for interacting with the Google Maps API. @Author GalenS <galen.scovell@gmail.com> """ import googlemaps from models.distance_matrix import DistanceMatrix from models.location import Location class MapClient: def __init__(self): self.client = googlemaps.Client(key='AIzaSyAoo39xmVMOA6K90WzGNF_se9eKpuw0VG8') def find_location_details(self, search_term): location = None try: result = self.client.geocode(search_term) location = Location(result[0]) except Exception as ex: print('Unable to get location details - {0}'.format(ex)) location = None finally: return location def get_distance_matrix(self, start, end, arrival_time): details = self.client.distance_matrix( origins=[s['address'] for s in start if 'address' in s], destinations=[e['address'] for e in end if 'address' in e], mode='transit', units='imperial', arrival_time=arrival_time, traffic_model='best_guess', transit_routing_preference='fewer_transfers' ) origins = details['origin_addresses'] destinations = details['destination_addresses'] result_rows = details['rows'] distances = [] if len(origins) > 1: # Multiple-to-destination for x in range(0, len(origins)): distances.append(DistanceMatrix(origins[x], destinations[0], result_rows[x])) elif len(destinations) > 1: # Multiple-from-origin for x in range(0, len(destinations)): distances.append(DistanceMatrix(origins[0], destinations[x], result_rows[x])) else: # Single origin to single destination distances.append(DistanceMatrix(origins[0], destinations[0], result_rows[0])) return distances
{"/services/google_maps_client.py": ["/models/distance_matrix.py", "/models/location.py"], "/run.py": ["/util/constants.py", "/graphics/visualizer.py", "/services/google_maps_client.py"], "/graphics/visualizer.py": ["/models/distance_matrix.py", "/models/location.py", "/graphics/cell.py", "/util/constants.py"]}
58,220
galenscovell/CommuteMap
refs/heads/master
/models/distance_matrix.py
""" Defines a Distance containing search terms and travel distance/time. @author GalenS <galen.scovell@gmail.com> """ class DistanceMatrix(dict): def __init__(self, origin, destination, row): super(DistanceMatrix, self).__init__() self['start'] = origin self['end'] = destination elements = row['elements'][0] self['distance'] = elements['distance']['text'] self['duration'] = int(elements['duration']['value'])
{"/services/google_maps_client.py": ["/models/distance_matrix.py", "/models/location.py"], "/run.py": ["/util/constants.py", "/graphics/visualizer.py", "/services/google_maps_client.py"], "/graphics/visualizer.py": ["/models/distance_matrix.py", "/models/location.py", "/graphics/cell.py", "/util/constants.py"]}
58,221
galenscovell/CommuteMap
refs/heads/master
/run.py
""" Entrypoint for commute map tool. Fill in `params.json` with desired values, then run `python run.py` @Author GalenS <galen.scovell@gmail.com> """ import json from datetime import datetime import util.constants as constants from graphics.visualizer import Visualizer from services.google_maps_client import MapClient def extract_params(): with open(constants.params_path, 'rb') as f: contents = f.read().strip() p = json.loads(contents) p['arrival_time'] = datetime.strptime(p['arrival_time'], '%m/%d/%y %H:%M') return p def fill_locations(location_list, client): locations = [] for l in location_list: locations.append(client.find_location_details(l)) return locations def create_google_maps_client(): client = None try: client = MapClient() except Exception as ex: print('Unable to generate map client - {0}'.format(ex)) client = None finally: return client if __name__ == '__main__': params = extract_params() print('Arrive by: {0}'.format(params['arrival_time'])) map_client = create_google_maps_client() # Fill in origins and destinations as detailed Locations origins = fill_locations(params['origins'], map_client) destinations = fill_locations(params['destinations'], map_client) # Calculate distance matrix between origins and destinations distance_matrix = map_client.get_distance_matrix(origins, destinations, params['arrival_time']) mapper = Visualizer(origins, destinations, distance_matrix)
{"/services/google_maps_client.py": ["/models/distance_matrix.py", "/models/location.py"], "/run.py": ["/util/constants.py", "/graphics/visualizer.py", "/services/google_maps_client.py"], "/graphics/visualizer.py": ["/models/distance_matrix.py", "/models/location.py", "/graphics/cell.py", "/util/constants.py"]}
58,222
galenscovell/CommuteMap
refs/heads/master
/models/location.py
""" Defines a Location containing name, central point, and region boundaries via NW and SW point. @author GalenS <galen.scovell@gmail.com> """ import math class Location(dict): def __init__(self, details): super(Location, self).__init__() if 'address' in details: self['label'] = details['address'] self['address'] = details['address'] else: self['label'] = details['address_components'][0]['long_name'] self['address'] = details['formatted_address'] if 'geometry' in details: geometry = details['geometry'] bounds = geometry['bounds'] self['center'] = [geometry['location']['lat'], geometry['location']['lng']] self['northeast'] = [bounds['northeast']['lat'], bounds['northeast']['lng']] self['southwest'] = [bounds['southwest']['lat'], bounds['southwest']['lng']] else: self['center'] = [details['center'][0], details['center'][1]] self['northeast'] = [details['northeast'][0], details['northeast'][1]] self['southwest'] = [details['southwest'][0], details['southwest'][1]] self['width'] = math.fabs(self['northeast'][0] - self['southwest'][0]) self['height'] = math.fabs(self['northeast'][1] - self['southwest'][1])
{"/services/google_maps_client.py": ["/models/distance_matrix.py", "/models/location.py"], "/run.py": ["/util/constants.py", "/graphics/visualizer.py", "/services/google_maps_client.py"], "/graphics/visualizer.py": ["/models/distance_matrix.py", "/models/location.py", "/graphics/cell.py", "/util/constants.py"]}
58,223
galenscovell/CommuteMap
refs/heads/master
/util/constants.py
""" Values used throughout tool. @author GalenS <galen.scovell@gmail.com> """ import os params_path = os.path.join(os.getcwd(), 'params.json') # Dimensions window_x = 640 window_y = 960 cell_size = 5 margin = 1 # Color setup c_background = (62, 70, 73) c_empty = (47, 47, 49) c_origin = (34, 168, 109) c_destination = (233, 110, 68) # Misc frame_rate = 60 empty_id = 0 origin_id = 1 destination_id = 2
{"/services/google_maps_client.py": ["/models/distance_matrix.py", "/models/location.py"], "/run.py": ["/util/constants.py", "/graphics/visualizer.py", "/services/google_maps_client.py"], "/graphics/visualizer.py": ["/models/distance_matrix.py", "/models/location.py", "/graphics/cell.py", "/util/constants.py"]}
58,224
galenscovell/CommuteMap
refs/heads/master
/graphics/cell.py
class Cell: def __init__(self, grid_x, grid_y, pixel_x, pixel_y): self.id = -1 self.grid_x = grid_x self.grid_y = grid_y self.pixel_x = pixel_x self.pixel_y = pixel_y self.address = None self.duration = 0.0 def set_address(self, address): self.address = address def set_duration(self, duration): self.duration = duration // 60 def get_duration_color(self): c = self.duration / (120 / 255) return c
{"/services/google_maps_client.py": ["/models/distance_matrix.py", "/models/location.py"], "/run.py": ["/util/constants.py", "/graphics/visualizer.py", "/services/google_maps_client.py"], "/graphics/visualizer.py": ["/models/distance_matrix.py", "/models/location.py", "/graphics/cell.py", "/util/constants.py"]}
58,225
galenscovell/CommuteMap
refs/heads/master
/graphics/visualizer.py
""" Takes in generated values and plots them into a graphical representation. @Author GalenS <galen.scovell@gmail.com> """ import math import pygame import sys from models.distance_matrix import DistanceMatrix from models.location import Location from graphics.cell import Cell import util.constants as constants class Visualizer: def __init__(self, origins, destinations, distance_matrix): self.rows, self.columns, self.x_offset, self.y_offset = self.find_map_bounds(origins, destinations) self.map_width = self.columns * (constants.cell_size + constants.margin) self.map_height = self.rows * (constants.cell_size + constants.margin) print('Map dimensions: [{0}, {1}], [{2}, {3}]'.format(self.columns, self.rows, self.map_width, self.map_height)) if self.map_width > 1280 or self.map_height > 960: print('Map dimensions too large -- tool isn\'t designed for cross country trips!') sys.exit() grid = self.create_grid(origins, destinations, distance_matrix) # Init screen pygame.init() self.font = pygame.font.SysFont("source code pro", 12) screen = pygame.display.set_mode((self.map_width, self.map_height)) pygame.display.set_caption("Commute Mapper") screen.fill(constants.c_background) clock = pygame.time.Clock() # Main loop running = True while running: clock.tick(constants.frame_rate) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.MOUSEBUTTONDOWN: None screen.fill(constants.c_background) self.update_grid(grid, screen) pygame.display.flip() pygame.quit() sys.exit() def create_grid(self, origins, destinations, distance_matrix): grid = [] for y in range(0, self.rows): grid.append([]) for x in range(0, self.columns): grid[y].append( Cell( x, y, x * (constants.cell_size + constants.margin), y * (constants.cell_size + constants.margin) ) ) for o in range(0, len(origins)): if len(origins) > 1: self.set_origin(origins[o], grid, distance_matrix[o]) else: self.set_origin(origins[o], grid) for d in range(0, len(destinations)): if len(destinations) > 1: self.set_destination(destinations[d], grid, distance_matrix[d]) else: self.set_destination(destinations[d], grid) return grid def update_grid(self, grid, screen): labels = [] for y in range(0, self.rows): for x in range(0, self.columns): cell = grid[y][x] if cell.id == constants.origin_id: color = (cell.get_duration_color(), 128, 128) label = [(cell.address, 1, (255, 255, 0)), (cell.pixel_x + 4, cell.pixel_y - 8)] labels.append(label) duration_label = [('{0}min'.format(cell.duration), 1, (255, 255, 255)), (cell.pixel_x + 4, cell.pixel_y + 14)] labels.append(duration_label) elif cell.id == constants.destination_id: color = constants.c_destination label = [(cell.address, 1, (255, 0, 255)), (cell.pixel_x + 4, cell.pixel_y - 8)] labels.append(label) else: color = constants.c_empty pygame.draw.rect( screen, color, [ (constants.margin + constants.cell_size) * cell.grid_x + constants.margin, (constants.margin + constants.cell_size) * cell.grid_y + constants.margin, constants.cell_size, constants.cell_size ] ) for l in labels: text = self.font.render(l[0][0], l[0][1], l[0][2]) screen.blit(text, (l[1][0] - text.get_width() / 2, l[1][1] - text.get_height() / 2)) labels.clear() def set_origin(self, location, grid, distance_entry=None): x, y = self.convert_geo_to_coords(location['center'][0], location['center'][1]) x -= self.x_offset y -= self.y_offset grid[x][y].set_address(location['label']) grid[x][y].id = constants.origin_id nex, ney = self.convert_geo_to_coords(location['northeast'][0], location['northeast'][1]) nex -= self.x_offset ney -= self.y_offset half_height = int(math.fabs((ney - y) / 2)) half_width = int(math.fabs((nex - x) / 2)) if distance_entry: grid[x][y].set_duration(distance_entry['duration']) def set_destination(self, location, grid, distance_entry=None): x, y = self.convert_geo_to_coords(location['center'][0], location['center'][1]) x -= self.x_offset y -= self.y_offset grid[x][y].set_address(location['label']) grid[x][y].id = constants.destination_id if distance_entry: grid[x][y].set_duration(distance_entry['duration']) @staticmethod def convert_geo_to_coords(lat, lng): x = int(6371 * math.cos(lat) * math.cos(lng) / (constants.cell_size + constants.margin)) y = int(6371 * math.cos(lat) * math.sin(lng) / (constants.cell_size + constants.margin)) return x, y def find_map_bounds(self, origins, destinations): most_north = -math.inf most_east = -math.inf most_south = math.inf most_west = math.inf for loc in (origins + destinations): x, y = self.convert_geo_to_coords(loc['center'][0], loc['center'][1]) if x > most_east: most_east = x if x < most_west: most_west = x if y > most_north: most_north = y if y < most_south: most_south = y width = int(math.fabs(most_east - most_west)) height = int(math.fabs(most_north - most_south)) return width + 20, height + 20, most_west - 10, most_south - 10
{"/services/google_maps_client.py": ["/models/distance_matrix.py", "/models/location.py"], "/run.py": ["/util/constants.py", "/graphics/visualizer.py", "/services/google_maps_client.py"], "/graphics/visualizer.py": ["/models/distance_matrix.py", "/models/location.py", "/graphics/cell.py", "/util/constants.py"]}
58,239
pythonpereira/goodreads-graphql
refs/heads/master
/init_database.py
from pymongo import MongoClient from mimesis import Text import pandas as pd from progress.bar import Bar client = MongoClient() text_faker = Text(locale='en') def connect_db(db_name, collection_name): db = client[db_name] collection = db[collection_name] return collection def store_books(): books_collection = connect_db('goodreads', 'books') df_books = pd.read_csv('./goodbooks-10k/books.csv', index_col=0) books_list = [] bar = Bar('Processing books', max=len(df_books)) for idx, book in df_books.iterrows(): data = { 'bookId': book['book_id'], 'workId': book['work_id'], 'originalTitle': book['original_title'], 'title': book['title'], 'isbn': book['isbn'], 'isbn13': book['isbn13'], 'authors': book['authors'].split(','), 'publicationYear': book['original_publication_year'], 'languageCode': book['language_code'], 'avgRating': book['average_rating'], 'ratingsCount': book['ratings_count'], 'workRatingsCount': book['work_ratings_count'], 'workTextReviewsCount': book['work_ratings_count'], 'ratings1': book['ratings_1'], 'ratings2': book['ratings_2'], 'ratings3': book['ratings_3'], 'ratings4': book['ratings_4'], 'ratings5': book['ratings_5'], 'coverURL': book['image_url'], 'smallCoverURL': book['small_image_url'], 'Description': text_faker.text(), } books_list.append(data) bar.next() bar.finish() result = books_collection.insert_many(books_list) print(f'{len(result.inserted_ids)} inserted books') def main(): store_books() if __name__ == '__main__': main()
{"/schema.py": ["/basic_types.py"]}
58,240
pythonpereira/goodreads-graphql
refs/heads/master
/basic_types.py
import graphene from graphene.types.resolver import dict_resolver from pymongo import MongoClient client = MongoClient() reviews_collection = client.goodreads.reviews class Review(graphene.ObjectType): class Meta: default_resolver = dict_resolver _id = graphene.ID() bookId = graphene.ID() rate = graphene.Float() text = graphene.String() likes = graphene.Int() class Book(graphene.ObjectType): class Meta: default_resolver = dict_resolver bookId = graphene.ID() workId = graphene.Int() title = graphene.String() originalTitle = graphene.String() isbn = graphene.String() isbn13 = graphene.Int() authors = graphene.List(graphene.String) publicationYear = graphene.Int() languageCode = graphene.String() avgRating = graphene.Float() ratingsCount = graphene.Int() workRatingsCount = graphene.Int() workTextReviewsCount = graphene.Int() ratings1 = graphene.Int() ratings2 = graphene.Int() ratings3 = graphene.Int() ratings4 = graphene.Int() ratings5 = graphene.Int() coverURL = graphene.String() smallCoverURL = graphene.String() description = graphene.String() reviews = graphene.List(Review) @classmethod def resolve_reviews(self, root, info, **kwargs): results = reviews_collection.find({'bookId': root['bookId']}) return results
{"/schema.py": ["/basic_types.py"]}
58,241
pythonpereira/goodreads-graphql
refs/heads/master
/schema.py
import graphene from pymongo import MongoClient from bson.objectid import ObjectId from basic_types import Book, Review client = MongoClient() books_collection = client.goodreads.books reviews_collection = client.goodreads.reviews class CreateReview(graphene.Mutation): class Arguments: bookId = graphene.Int(name='bookId', required=True) username = graphene.String(required=True) rate = graphene.Float(required=True) text = graphene.String(required=True) state = graphene.String() review = graphene.Field(Review) def mutate(self, info, bookId, username, rate, text): result = books_collection.find_one({'bookId': bookId}) if result == None: return CreateReview(state='Book id not found') new_review = { 'bookId': bookId, 'username': username, 'rate': rate, 'text': text, 'likes': 0, } result = reviews_collection.insert_one(new_review) if not result is None: return CreateReview(state='success', review=new_review) else: return {'state': 'Something went wrong on serverside'} class LikeReview(graphene.Mutation): class Arguments: id = graphene.ID() review = graphene.Field(Review) def mutate(self, info, id): reviews_collection.update_one({ '_id': ObjectId(id) }, {'$inc': { 'likes': 1 }}) review = reviews_collection.find_one(ObjectId(id)) return LikeReview(review=review) class Query(graphene.ObjectType): books = graphene.List(Book, pageSize=graphene.Int(), page=graphene.Int()) book = graphene.Field(Book, bookId=graphene.ID(required=True)) reviews = graphene.List(Review) def resolve_books(self, info, **kwargs): pageSize = kwargs.get('pageSize', None) page = kwargs.get('page', None) books = books_collection.find() if pageSize != None and page != None: start = page * pageSize end = start + pageSize return books[start:end] return books def resolve_book(self, info, bookId): result = books_collection.find_one({'bookId': int(bookId)}) if result == None: return {'message': 'Book not found'} else: return result def resolve_reviews(self, info): results = reviews_collection.find({}) return results class Mutations(graphene.ObjectType): create_review = CreateReview.Field() like_review = LikeReview.Field() schema = graphene.Schema(query=Query, mutation=Mutations)
{"/schema.py": ["/basic_types.py"]}
58,294
we-chatter/wechatter
refs/heads/main
/wechatter/shared/importers/importer.py
# -*- coding: utf-8 -*- """ @Author : Xu @Software: PyCharm @File : importer.py @Time : 2021/4/6 6:23 下午 @Desc : 数据加载 """ import asyncio from functools import reduce from typing import Text, Optional, List, Dict, Set, Any, Tuple import logging from wechatter.shared.dm.domain import Domain logger = logging.getLogger(__name__) class TrainingDataImporter: """ 加载训练数据实现 """ async def get_domain(self) -> Domain: """Retrieves the domain of the bot. Returns: Loaded `Domain`. """ raise NotImplementedError() async def get_stories( self, template_variables: Optional[Dict] = None, use_e2e: bool = False, exclusion_percentage: Optional[int] = None, ) -> StoryGraph: """Retrieves the stories that should be used for training. Args: template_variables: Values of templates that should be replaced while reading the story files. use_e2e: Specifies whether to parse end to end learning annotations. exclusion_percentage: Amount of training data that should be excluded. Returns: `StoryGraph` containing all loaded stories. """ # TODO: Drop `use_e2e` in Rasa Open Source 3.0.0 when removing Markdown support raise NotImplementedError() async def get_conversation_tests(self) -> StoryGraph: """Retrieves end-to-end conversation stories for testing. Returns: `StoryGraph` containing all loaded stories. """ return await self.get_stories(use_e2e=True) async def get_config(self) -> Dict: """Retrieves the configuration that should be used for the training. Returns: The configuration as dictionary. """ raise NotImplementedError() async def get_nlu_data(self, language: Optional[Text] = "en") -> TrainingData: """Retrieves the NLU training data that should be used for training. Args: language: Can be used to only load training data for a certain language. Returns: Loaded NLU `TrainingData`. """ raise NotImplementedError() @staticmethod def load_from_config( config_path: Text, domain_path: Optional[Text] = None, training_data_paths: Optional[List[Text]] = None, training_type: Optional[TrainingType] = TrainingType.BOTH, ) -> "TrainingDataImporter": """Loads a `TrainingDataImporter` instance from a configuration file.""" config = rasa.shared.utils.io.read_config_file(config_path) return TrainingDataImporter.load_from_dict( config, config_path, domain_path, training_data_paths, training_type ) @staticmethod def load_core_importer_from_config( config_path: Text, domain_path: Optional[Text] = None, training_data_paths: Optional[List[Text]] = None, ) -> "TrainingDataImporter": """Loads core `TrainingDataImporter` instance. Instance loaded from configuration file will only read Core training data. """ importer = TrainingDataImporter.load_from_config( config_path, domain_path, training_data_paths, TrainingType.CORE ) return importer @staticmethod def load_nlu_importer_from_config( config_path: Text, domain_path: Optional[Text] = None, training_data_paths: Optional[List[Text]] = None, ) -> "TrainingDataImporter": """Loads nlu `TrainingDataImporter` instance. Instance loaded from configuration file will only read NLU training data. """ importer = TrainingDataImporter.load_from_config( config_path, domain_path, training_data_paths, TrainingType.NLU ) if isinstance(importer, E2EImporter): # When we only train NLU then there is no need to enrich the data with # E2E data from Core training data. importer = importer.importer return NluDataImporter(importer) @staticmethod def load_from_dict( config: Optional[Dict] = None, config_path: Optional[Text] = None, domain_path: Optional[Text] = None, training_data_paths: Optional[List[Text]] = None, training_type: Optional[TrainingType] = TrainingType.BOTH, ) -> "TrainingDataImporter": """Loads a `TrainingDataImporter` instance from a dictionary.""" from rasa.shared.importers.rasa import RasaFileImporter config = config or {} importers = config.get("importers", []) importers = [ TrainingDataImporter._importer_from_dict( importer, config_path, domain_path, training_data_paths, training_type ) for importer in importers ] importers = [importer for importer in importers if importer] if not importers: importers = [ RasaFileImporter( config_path, domain_path, training_data_paths, training_type ) ] return E2EImporter(ResponsesSyncImporter(CombinedDataImporter(importers))) @staticmethod def _importer_from_dict( importer_config: Dict, config_path: Text, domain_path: Optional[Text] = None, training_data_paths: Optional[List[Text]] = None, training_type: Optional[TrainingType] = TrainingType.BOTH, ) -> Optional["TrainingDataImporter"]: from rasa.shared.importers.multi_project import MultiProjectImporter from rasa.shared.importers.rasa import RasaFileImporter module_path = importer_config.pop("name", None) if module_path == RasaFileImporter.__name__: importer_class = RasaFileImporter elif module_path == MultiProjectImporter.__name__: importer_class = MultiProjectImporter else: try: importer_class = rasa.shared.utils.common.class_from_module_path( module_path ) except (AttributeError, ImportError): logging.warning(f"Importer '{module_path}' not found.") return None importer_config = dict(training_type=training_type, **importer_config) constructor_arguments = rasa.shared.utils.common.minimal_kwargs( importer_config, importer_class ) return importer_class( config_path, domain_path, training_data_paths, **constructor_arguments )
{"/wechatter/shared/dm/slots.py": ["/wechatter/shared/utils/io.py"], "/wechatter/server/run_server.py": ["/wechatter/config/__init__.py", "/wechatter/__init__.py", "/wechatter/shared/utils/io.py", "/wechatter/model_training.py"], "/wechatter/model.py": ["/wechatter/shared/utils/io.py", "/wechatter/utils/io.py", "/wechatter/exceptions.py"], "/wechatter/dm/tracker_store.py": ["/wechatter/shared/dm/conversation.py"], "/wechatter/model_training.py": ["/wechatter/shared/importers/importer.py"], "/wechatter/shared/dm/trackers.py": ["/wechatter/shared/dm/slots.py"], "/wechatter/config/__init__.py": ["/wechatter/config/config.py"]}
58,295
we-chatter/wechatter
refs/heads/main
/wechatter/shared/dm/conversation.py
# -*- coding: utf-8 -*- """ @Author : Xu @Software: PyCharm @File : conversation.py @Time : 2021/4/2 3:33 下午 @Desc : """ from typing import Dict, List, Text, Any from wechatter.shared.dm.events import Event class Dialogue: """ 对话实例构造 """ def __init__(self, name: Text, events: List["Event"]) -> None: """ 初始化一个对话 :param name: :param events: """ self.name = name self.events = events def __str__(self) -> Text: """ This function returns the dialogue and turns. """ return "Dialogue with name '{}' and turns:\n{}".format( self.name, "\n\n".join([f"\t{t}" for t in self.events]) ) def as_dict(self) -> Dict: """ This function returns the dialogue as a dictionary to assist in serialization. :return: """ return {"events": [event.as_dict() for event in self.events]} @classmethod def from_parameters(cls, parameters: Dict[Text, Any]) -> "Dialogue": """Create `Dialogue` from parameters. Args: parameters: Serialised dialogue, should contain keys 'name' and 'events'. Returns: Deserialised `Dialogue`. """ return cls( parameters.get("name"), [Event.from_parameters(evt) for evt in parameters.get("events")], )
{"/wechatter/shared/dm/slots.py": ["/wechatter/shared/utils/io.py"], "/wechatter/server/run_server.py": ["/wechatter/config/__init__.py", "/wechatter/__init__.py", "/wechatter/shared/utils/io.py", "/wechatter/model_training.py"], "/wechatter/model.py": ["/wechatter/shared/utils/io.py", "/wechatter/utils/io.py", "/wechatter/exceptions.py"], "/wechatter/dm/tracker_store.py": ["/wechatter/shared/dm/conversation.py"], "/wechatter/model_training.py": ["/wechatter/shared/importers/importer.py"], "/wechatter/shared/dm/trackers.py": ["/wechatter/shared/dm/slots.py"], "/wechatter/config/__init__.py": ["/wechatter/config/config.py"]}
58,296
we-chatter/wechatter
refs/heads/main
/wechatter/__init__.py
# -*- coding: utf-8 -*- """ @Author : Xu @Software: PyCharm @File : __init__.py.py @Time : 2020/11/17 7:10 下午 @Desc : """ import logging from wechatter import version # define the version before the other imports since these need it __version__ = version.__version__
{"/wechatter/shared/dm/slots.py": ["/wechatter/shared/utils/io.py"], "/wechatter/server/run_server.py": ["/wechatter/config/__init__.py", "/wechatter/__init__.py", "/wechatter/shared/utils/io.py", "/wechatter/model_training.py"], "/wechatter/model.py": ["/wechatter/shared/utils/io.py", "/wechatter/utils/io.py", "/wechatter/exceptions.py"], "/wechatter/dm/tracker_store.py": ["/wechatter/shared/dm/conversation.py"], "/wechatter/model_training.py": ["/wechatter/shared/importers/importer.py"], "/wechatter/shared/dm/trackers.py": ["/wechatter/shared/dm/slots.py"], "/wechatter/config/__init__.py": ["/wechatter/config/config.py"]}
58,297
we-chatter/wechatter
refs/heads/main
/wechatter/shared/dm/slots.py
# -*- coding: utf-8 -*- """ @Author : Xu @Software: PyCharm @File : slots.py @Time : 2021/4/1 5:05 下午 @Desc : 槽位的处理逻辑 """ import logging from typing import Any, Dict, List, Optional, Text, Type import wechatter.shared.dm.dm_config from wechatter.shared.exceptions import WechatterException import wechatter.shared.utils.common import wechatter.shared.utils.io from wechatter.shared.dialogue_config import DOCS_URL_SLOTS logger = logging.getLogger(__name__) class InvalidSlotTypeException(WechatterException): """Raised if a slot type is invalid.""" class InvalidSlotConfigError(WechatterException, ValueError): """Raised if a slot's config is invalid.""" class Slot: """ Key-value store for storing information during a conversation. """ type_name = None def __init__( self, name: Text, initial_value: Any = None, value_reset_delay: Optional[int] = None, auto_fill: bool = True, influence_conversation: bool = True, ) -> None: """Create a Slot. Args: name: The name of the slot. initial_value: The initial value of the slot. value_reset_delay: After how many turns the slot should be reset to the initial_value. This is behavior is currently not implemented. auto_fill: `True` if the slot should be filled automatically by entities with the same name. influence_conversation: If `True` the slot will be featurized and hence influence the predictions of the dialogue polices. """ self.name = name self._value = initial_value self.initial_value = initial_value self._value_reset_delay = value_reset_delay self.auto_fill = auto_fill self.influence_conversation = influence_conversation self._has_been_set = False def feature_dimensionality(self) -> int: """How many features this single slot creates. Returns: The number of features. `0` if the slot is unfeaturized. The dimensionality of the array returned by `as_feature` needs to correspond to this value. """ if not self.influence_conversation: return 0 return self._feature_dimensionality() def _feature_dimensionality(self) -> int: """See the docstring for `feature_dimensionality`.""" return 1 def has_features(self) -> bool: """Indicate if the slot creates any features.""" return self.feature_dimensionality() != 0 def value_reset_delay(self) -> Optional[int]: """After how many turns the slot should be reset to the initial_value. If the delay is set to `None`, the slot will keep its value forever.""" # TODO: FUTURE this needs to be implemented - slots are not reset yet return self._value_reset_delay def as_feature(self) -> List[float]: if not self.influence_conversation: return [] return self._as_feature() def _as_feature(self) -> List[float]: raise NotImplementedError( "Each slot type needs to specify how its " "value can be converted to a feature. Slot " "'{}' is a generic slot that can not be used " "for predictions. Make sure you add this " "slot to your domain definition, specifying " "the type of the slot. If you implemented " "a custom slot type class, make sure to " "implement `.as_feature()`." "".format(self.name) ) def reset(self) -> None: """Resets the slot's value to the initial value.""" self.value = self.initial_value self._has_been_set = False @property def value(self) -> Any: """Gets the slot's value.""" return self._value @value.setter def value(self, value: Any) -> None: """Sets the slot's value.""" self._value = value self._has_been_set = True @property def has_been_set(self) -> bool: """Indicates if the slot's value has been set.""" return self._has_been_set def __str__(self) -> Text: return f"{self.__class__.__name__}({self.name}: {self.value})" def __repr__(self) -> Text: return f"<{self.__class__.__name__}({self.name}: {self.value})>" @staticmethod def resolve_by_type(type_name) -> Type["Slot"]: """Returns a slots class by its type name.""" for cls in wechatter.shared.utils.common.all_subclasses(Slot): if cls.type_name == type_name: return cls try: return wechatter.shared.utils.common.class_from_module_path(type_name) except (ImportError, AttributeError): raise InvalidSlotTypeException( f"Failed to find slot type, '{type_name}' is neither a known type nor " f"user-defined. If you are creating your own slot type, make " f"sure its module path is correct. " f"You can find all build in types at {DOCS_URL_SLOTS}" ) def persistence_info(self) -> Dict[str, Any]: return { "type": wechatter.shared.utils.common.module_path_from_instance(self), "initial_value": self.initial_value, "auto_fill": self.auto_fill, "influence_conversation": self.influence_conversation, } class FloatSlot: """ 数字类型slot """ type_name = "float" def __init__( self, name: Text, initial_value: Optional[float] = None, value_reset_delay: Optional[int] = None, auto_fill: bool = True, max_value: float = 1.0, min_value: float = 0.0, influence_conversation: bool = True, ) -> None: super().__init__( name, initial_value, value_reset_delay, auto_fill, influence_conversation ) self.max_value = max_value self.min_value = min_value if min_value >= max_value: raise InvalidSlotConfigError( "Float slot ('{}') created with an invalid range " "using min ({}) and max ({}) values. Make sure " "min is smaller than max." "".format(self.name, self.min_value, self.max_value) ) if initial_value is not None and not (min_value <= initial_value <= max_value): wechatter.shared.utils.io.raise_warning( f"Float slot ('{self.name}') created with an initial value " f"{self.value}. This value is outside of the configured min " f"({self.min_value}) and max ({self.max_value}) values." ) def _as_feature(self) -> List[float]: try: capped_value = max(self.min_value, min(self.max_value, float(self.value))) if abs(self.max_value - self.min_value) > 0: covered_range = abs(self.max_value - self.min_value) else: covered_range = 1 return [1.0, (capped_value - self.min_value) / covered_range] except (TypeError, ValueError): return [0.0, 0.0] def persistence_info(self) -> Dict[Text, Any]: """Returns relevant information to persist this slot.""" d = super().persistence_info() d["max_value"] = self.max_value d["min_value"] = self.min_value return d def _feature_dimensionality(self) -> int: return len(self.as_feature()) class BooleanSlot(Slot): type_name = "bool" def _as_feature(self) -> List[float]: try: if self.value is not None: return [1.0, float(bool_from_any(self.value))] else: return [0.0, 0.0] except (TypeError, ValueError): # we couldn't convert the value to float - using default value return [0.0, 0.0] def _feature_dimensionality(self) -> int: return len(self.as_feature()) class AnySlot: """ """ pass class TextSlot(Slot): """ """ type_name = "text" def _as_feature(self) -> List[float]: return [1.0 if self.value is not None else 0.0] class ListSlot(Slot): """ """ type_name = "list" def _as_feature(self) -> List[float]: try: if self.value is not None and len(self.value) > 0: return [1.0] else: return [0.0] except (TypeError, ValueError): # we couldn't convert the value to a list - using default value return [0.0] class CategoricalSlot: """ """ def bool_from_any(x: Any) -> bool: """ Converts bool/float/int/str to bool or raises error """ if isinstance(x, bool): return x elif isinstance(x, (float, int)): return x == 1.0 elif isinstance(x, str): if x.isnumeric(): return float(x) == 1.0 elif x.strip().lower() == "true": return True elif x.strip().lower() == "false": return False else: raise ValueError("Cannot convert string to bool") else: raise TypeError("Cannot convert to bool")
{"/wechatter/shared/dm/slots.py": ["/wechatter/shared/utils/io.py"], "/wechatter/server/run_server.py": ["/wechatter/config/__init__.py", "/wechatter/__init__.py", "/wechatter/shared/utils/io.py", "/wechatter/model_training.py"], "/wechatter/model.py": ["/wechatter/shared/utils/io.py", "/wechatter/utils/io.py", "/wechatter/exceptions.py"], "/wechatter/dm/tracker_store.py": ["/wechatter/shared/dm/conversation.py"], "/wechatter/model_training.py": ["/wechatter/shared/importers/importer.py"], "/wechatter/shared/dm/trackers.py": ["/wechatter/shared/dm/slots.py"], "/wechatter/config/__init__.py": ["/wechatter/config/config.py"]}
58,298
we-chatter/wechatter
refs/heads/main
/wechatter/shared/utils/io.py
# -*- coding: utf-8 -*- """ @Author : Xu @Software: PyCharm @File : io.py @Time : 2021/4/2 5:23 下午 @Desc : """ from collections import OrderedDict import errno import glob from hashlib import md5 from io import StringIO import json import os from pathlib import Path import re from typing import Any, Dict, List, Optional, Text, Type, Union, FrozenSet import warnings from ruamel import yaml from wechatter.shared.exceptions import ( FileIOException, FileNotFoundException, YamlSyntaxException ) DEFAULT_ENCODING = 'utf-8' # 默认用utf-8,打开文件时用 def read_file(filename: Union[Text, Path], encoding: Text = DEFAULT_ENCODING) -> Any: """Read text from a file.""" try: with open(filename, encoding=encoding) as f: return f.read() except FileNotFoundError: raise FileNotFoundException( f"Failed to read file, " f"'{os.path.abspath(filename)}' does not exist." ) except UnicodeDecodeError: raise FileIOException( f"Failed to read file '{os.path.abspath(filename)}', " f"could not read the file using {encoding} to decode " f"it. Please make sure the file is stored with this " f"encoding." ) def read_yaml(content: Text, reader_type: Union[Text, List[Text]] = "safe") -> Any: """ Parses yaml from a text. 解析yaml文件 Args: content: A text containing yaml content. reader_type: Reader type to use. By default "safe" will be used replace_env_vars: Specifies if environment variables need to be replaced Raises: ruamel.yaml.parser.ParserError: If there was an error when parsing the YAML. """ if _is_ascii(content): # Required to make sure emojis are correctly parsed content = ( content.encode("utf-8") .decode("raw_unicode_escape") .encode("utf-16", "surrogatepass") .decode("utf-16") ) yaml_parser = yaml.YAML(typ=reader_type) # yaml_parser.version = YAML_VERSION yaml_parser.preserve_quotes = True return yaml_parser.load(content) or {} def _is_ascii(text: Text) -> bool: return all(ord(character) < 128 for character in text) def write_text_file( content: Text, file_path: Union[Text, Path], encoding: Text = DEFAULT_ENCODING, append: bool = False, ) -> None: """ 写入文件 Args: content: The content to write. file_path: The path to which the content should be written. encoding: The encoding which should be used. append: Whether to append to the file or to truncate the file. """ mode = "a" if append else "w" with open(file_path, mode, encoding=encoding) as file: file.write(content)
{"/wechatter/shared/dm/slots.py": ["/wechatter/shared/utils/io.py"], "/wechatter/server/run_server.py": ["/wechatter/config/__init__.py", "/wechatter/__init__.py", "/wechatter/shared/utils/io.py", "/wechatter/model_training.py"], "/wechatter/model.py": ["/wechatter/shared/utils/io.py", "/wechatter/utils/io.py", "/wechatter/exceptions.py"], "/wechatter/dm/tracker_store.py": ["/wechatter/shared/dm/conversation.py"], "/wechatter/model_training.py": ["/wechatter/shared/importers/importer.py"], "/wechatter/shared/dm/trackers.py": ["/wechatter/shared/dm/slots.py"], "/wechatter/config/__init__.py": ["/wechatter/config/config.py"]}
58,299
we-chatter/wechatter
refs/heads/main
/wechatter/shared/nlu/interpreter.py
# -*- coding: utf-8 -*- """ @Author : Xu @Software: PyCharm @File : interpreter.py @Time : 2021/4/6 4:39 下午 @Desc : nlu解析器 """ import json import logging import re from json.decoder import JSONDecodeError from typing import Text, Optional, Dict, Any, Union, List, Tuple logger = logging.getLogger(__name__) class NatureLanguageInterpreter: async def parse( self, text: Text, message_id: Optional[Text] = None, tracker: Optional[DialogueStateTracker] = None, metadata: Optional[Dict] = None, ) -> Dict[Text, Any]: raise NotImplementedError( "Interpreter needs to be able to parse messages into structured output." ) def featurize_message(self, message: Message) -> Optional[Message]: pass
{"/wechatter/shared/dm/slots.py": ["/wechatter/shared/utils/io.py"], "/wechatter/server/run_server.py": ["/wechatter/config/__init__.py", "/wechatter/__init__.py", "/wechatter/shared/utils/io.py", "/wechatter/model_training.py"], "/wechatter/model.py": ["/wechatter/shared/utils/io.py", "/wechatter/utils/io.py", "/wechatter/exceptions.py"], "/wechatter/dm/tracker_store.py": ["/wechatter/shared/dm/conversation.py"], "/wechatter/model_training.py": ["/wechatter/shared/importers/importer.py"], "/wechatter/shared/dm/trackers.py": ["/wechatter/shared/dm/slots.py"], "/wechatter/config/__init__.py": ["/wechatter/config/config.py"]}
58,300
we-chatter/wechatter
refs/heads/main
/wechatter/server/run_server.py
# -*- coding: utf-8 -*- """ @Author : Xu @Software: PyCharm @File : run_server.py @Time : 2020/8/26 2:50 下午 @Desc : """ import asyncio import concurrent.futures import logging import multiprocessing import os import tempfile import traceback from collections import defaultdict from functools import reduce, wraps from inspect import isawaitable from pathlib import Path from http import HTTPStatus from typing import ( Any, Callable, List, Optional, Text, Union, Dict, TYPE_CHECKING, NoReturn ) from pathlib import Path # parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # sys.path.insert(0, parentdir) from wechatter.config import CONFIG import aiohttp from sanic import Sanic, response from sanic.response import text, HTTPResponse from sanic.request import Request from sanic_cors import CORS import wechatter import wechatter.utils import wechatter.shared import wechatter.utils.endpoints import wechatter.shared.utils import wechatter.shared.utils.io from wechatter.model_training import train_async from wechatter.shared.dialogue_config import ( DOCS_URL_TRAINING_DATA, DEFAULT_MODELS_PATH, DEFAULT_DOMAIN_PATH ) logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO) app = Sanic(__name__) logging.info('wechatter loading...') def configure_cors( app: Sanic, cors_origins: Union[Text, List[Text], None] = "" ) -> None: """Configure CORS origins for the given app.""" # Workaround so that socketio works with requests from other origins. # https://github.com/miguelgrinberg/python-socketio/issues/205#issuecomment-493769183 app.config.CORS_AUTOMATIC_OPTIONS = True app.config.CORS_SUPPORTS_CREDENTIALS = True app.config.CORS_EXPOSE_HEADERS = "filename" CORS( app, resources={r"/*": {"origins": cors_origins or ""}}, automatic_options=True ) # def create_app( # cors_origins: Union[Text, List[Text], None] = "*", # ): # app = Sanic(__name__) app.update_config(CONFIG) # 系统配置信息 # configure_cors(app, cors_origins) # 解决跨域问题 @app.route("/") async def test(request): return text('Welcome to wechatty dialogue engine,Current version is:' + wechatter.__version__) @app.get('/version') async def version(request: Request): """ Get version information :param request: :return: """ return response.text( "Hello from Wechatter:" + wechatter.__version__ ) @app.post("/model/train") async def train(request: Request) -> HTTPResponse: """ 训练模型 方式一:加载数据库,写入临时文件,训练模型 :param temporary_directory: :param request: :return: """ training_payload = _training_payload_from_json(request) try: # with app.active_training_processes.get_lock(): # app.active_training_processes.value += 1 training_result = await train_async(**training_payload) if training_result.model: filename = os.path.basename(training_result.model) return await response.file( training_result.model, filename=filename, ) else: raise ErrorResponse( HTTPStatus.INTERNAL_SERVER_ERROR, "TrainingError", "Ran training, but it finished without a trained model.", ) except ErrorResponse as e: raise e def _training_payload_from_json(request: Request) -> Dict[Text, Any]: """ 读取请求的json文件,同时写入一个临时文件夹 :param request: :param temp_dir: :return: """ logging.debug( "Extracting JSON payload with Markdown training data from request body." ) request_payload = request.json _validate_json_training_payload(request_payload) temp_dir= '' config_path = os.path.join(temp_dir, "config.yml") wechatter.shared.utils.io.write_text_file(request_payload["config"], config_path) if "nlu" in request_payload: nlu_path = os.path.join(temp_dir, "nlu.md") wechatter.shared.utils.io.write_text_file(request_payload["nlu"], nlu_path) if "stories" in request_payload: stories_path = os.path.join(temp_dir, "stories.md") wechatter.shared.utils.io.write_text_file(request_payload["stories"], stories_path) if "responses" in request_payload: responses_path = os.path.join(temp_dir, "responses.md") wechatter.shared.utils.io.write_text_file( request_payload["responses"], responses_path ) domain_path = DEFAULT_DOMAIN_PATH if "domain" in request_payload: domain_path = os.path.join(temp_dir, "domain.yml") wechatter.shared.utils.io.write_text_file(request_payload["domain"], domain_path) if "model_name" in request_payload: # 制定模型名称 model_name = request_payload["model_name"] model_output_directory = str(temp_dir) if request_payload.get( "save_to_default_model_directory", wechatter.utils.endpoints.bool_arg(request, "save_to_default_model_directory", True), ): # 如果参数里save_to_default_model_directory = True,则保存在默认的文件夹里 model_output_directory = DEFAULT_MODELS_PATH return dict( domain=domain_path, config=config_path, training_files=str(temp_dir), output=model_output_directory, force_training=request_payload.get( "force", wechatter.utils.endpoints.bool_arg(request, "force_training", False) ), dm_additional_arguments=_extract_dm_additional_arguments(request), nlu_additional_arguments=_extract_nlu_additional_arguments(request), ) def _validate_json_training_payload(rjs: Dict): if "config" not in rjs: raise ErrorResponse( HTTPStatus.BAD_REQUEST, "BadRequest", "The training request is missing the required key `config`.", {"parameter": "config", "in": "body"}, ) if "nlu" not in rjs and "stories" not in rjs: raise ErrorResponse( HTTPStatus.BAD_REQUEST, "BadRequest", "To train a Rasa model you need to specify at least one type of " "training data. Add `nlu` and/or `stories` to the request.", {"parameters": ["nlu", "stories"], "in": "body"}, ) if "stories" in rjs and "domain" not in rjs: raise ErrorResponse( HTTPStatus.BAD_REQUEST, "BadRequest", "To train a Rasa model with story training data, you also need to " "specify the `domain`.", {"parameter": "domain", "in": "body"}, ) # if "force" in rjs or "save_to_default_model_directory" in rjs: # wechatter.shared.utils.io.raise_deprecation_warning( # "Specifying 'force' and 'save_to_default_model_directory' as part of the " # "JSON payload is deprecated. Please use the header arguments " # "'force_training' and 'save_to_default_model_directory'.", # docs=_docs("/api/http-api"), # ) # if "model_name" in rjs class ErrorResponse(Exception): """Common exception to handle failing API requests.""" def __init__( self, status: Union[int, HTTPStatus], reason: Text, message: Text, details: Any = None, help_url: Optional[Text] = None, ) -> None: """Creates error. Args: status: The HTTP status code to return. reason: Short summary of the error. message: Detailed explanation of the error. details: Additional details which describe the error. Must be serializable. help_url: URL where users can get further help (e.g. docs). """ self.error_info = { "version": wechatter.__version__, "status": "failure", "message": message, "reason": reason, "details": details or {}, "help": help_url, "code": status, } self.status = status logging.error(message) super(ErrorResponse, self).__init__() if __name__ == '__main__': app.run(host='0.0.0.0', port=9015, auto_reload=True, workers=4)
{"/wechatter/shared/dm/slots.py": ["/wechatter/shared/utils/io.py"], "/wechatter/server/run_server.py": ["/wechatter/config/__init__.py", "/wechatter/__init__.py", "/wechatter/shared/utils/io.py", "/wechatter/model_training.py"], "/wechatter/model.py": ["/wechatter/shared/utils/io.py", "/wechatter/utils/io.py", "/wechatter/exceptions.py"], "/wechatter/dm/tracker_store.py": ["/wechatter/shared/dm/conversation.py"], "/wechatter/model_training.py": ["/wechatter/shared/importers/importer.py"], "/wechatter/shared/dm/trackers.py": ["/wechatter/shared/dm/slots.py"], "/wechatter/config/__init__.py": ["/wechatter/config/config.py"]}
58,301
we-chatter/wechatter
refs/heads/main
/wechatter/model.py
# -*- coding: utf-8 -*- """ @Author : Xu @Software: PyCharm @File : model.py @Time : 2021/4/14 6:26 下午 @Desc : 模型构建 """ import copy import glob import hashlib import logging import os import shutil from subprocess import CalledProcessError, DEVNULL, check_output # skipcq:BAN-B404 import tempfile import typing from pathlib import Path from typing import Any, Text, Tuple, Union, Optional, List, Dict, NamedTuple import wechatter.shared.utils.io import wechatter.utils.io from wechatter.shared.dialogue_config import ( CONFIG_KEYS_CORE, CONFIG_KEYS_NLU, CONFIG_KEYS, DEFAULT_MODELS_PATH, DEFAULT_DOMAIN_PATH, DEFAULT_CORE_SUBDIRECTORY_NAME, DEFAULT_NLU_SUBDIRECTORY_NAME ) from wechatter.exceptions import ModelNotFound logger = logging.getLogger(__name__)
{"/wechatter/shared/dm/slots.py": ["/wechatter/shared/utils/io.py"], "/wechatter/server/run_server.py": ["/wechatter/config/__init__.py", "/wechatter/__init__.py", "/wechatter/shared/utils/io.py", "/wechatter/model_training.py"], "/wechatter/model.py": ["/wechatter/shared/utils/io.py", "/wechatter/utils/io.py", "/wechatter/exceptions.py"], "/wechatter/dm/tracker_store.py": ["/wechatter/shared/dm/conversation.py"], "/wechatter/model_training.py": ["/wechatter/shared/importers/importer.py"], "/wechatter/shared/dm/trackers.py": ["/wechatter/shared/dm/slots.py"], "/wechatter/config/__init__.py": ["/wechatter/config/config.py"]}
58,302
we-chatter/wechatter
refs/heads/main
/wechatter/shared/importers/wechatter_data.py
# -*- coding: utf-8 -*- """ @Author : Xu @Software: PyCharm @File : wechatter_data.py @Time : 2021/4/12 10:40 上午 @Desc : """ import logging from typing import Dict, List, Optional, Text, Union
{"/wechatter/shared/dm/slots.py": ["/wechatter/shared/utils/io.py"], "/wechatter/server/run_server.py": ["/wechatter/config/__init__.py", "/wechatter/__init__.py", "/wechatter/shared/utils/io.py", "/wechatter/model_training.py"], "/wechatter/model.py": ["/wechatter/shared/utils/io.py", "/wechatter/utils/io.py", "/wechatter/exceptions.py"], "/wechatter/dm/tracker_store.py": ["/wechatter/shared/dm/conversation.py"], "/wechatter/model_training.py": ["/wechatter/shared/importers/importer.py"], "/wechatter/shared/dm/trackers.py": ["/wechatter/shared/dm/slots.py"], "/wechatter/config/__init__.py": ["/wechatter/config/config.py"]}
58,303
we-chatter/wechatter
refs/heads/main
/wechatter/dm/tracker_store.py
# -*- coding: utf-8 -*- """ @Author : Xu @Software: PyCharm @File : tracker_store.py @Time : 2021/4/1 3:32 下午 @Desc : 对话状态存储 """ import contextlib import itertools import json import logging import os import pickle from datetime import datetime, timezone from time import sleep from typing import ( Any, Callable, Dict, Iterable, Iterator, List, Optional, Text, Union, TYPE_CHECKING, ) from wechatter.shared.dm.conversation import Dialogue from wechatter.shared.dm.domain import Domain from wechatter.shared.dm.events import SessionStarted from wechatter.shared.exceptions import ConnectionException from wechatter.utils.endpoints import EndpointConfig logger = logging.getLogger(__name__) class TrackerStore: """ Represents common behavior and interface for all `TrackerStore`s. """ def __init__( self, domain: Optional[Domain], event_broker: Optional[EventBroker] = None, **kwargs: Dict[Text, Any], ) -> None: """Create a TrackerStore. Args: domain: The `Domain` to initialize the `DialogueStateTracker`. event_broker: An event broker to publish any new events to another destination. kwargs: Additional kwargs. """ self.domain = domain self.event_broker = event_broker self.max_event_history = None # TODO: Remove this in Rasa Open Source 3.0 self.retrieve_events_from_previous_conversation_sessions: Optional[bool] = None self._set_deprecated_kwargs_and_emit_warning(kwargs) def _set_deprecated_kwargs_and_emit_warning(self, kwargs: Dict[Text, Any]) -> None: retrieve_events_from_previous_conversation_sessions = kwargs.get( "retrieve_events_from_previous_conversation_sessions" ) if retrieve_events_from_previous_conversation_sessions is not None: rasa.shared.utils.io.raise_deprecation_warning( f"Specifying the `retrieve_events_from_previous_conversation_sessions` " f"kwarg for the `{self.__class__.__name__}` class is deprecated and " f"will be removed in Rasa Open Source 3.0. " f"Please use the `retrieve_full_tracker()` method instead." ) self.retrieve_events_from_previous_conversation_sessions = ( retrieve_events_from_previous_conversation_sessions ) @staticmethod def create( obj: Union["TrackerStore", EndpointConfig, None], domain: Optional[Domain] = None, event_broker: Optional[EventBroker] = None, ) -> "TrackerStore": """Factory to create a tracker store.""" if isinstance(obj, TrackerStore): return obj from botocore.exceptions import BotoCoreError import pymongo.errors import sqlalchemy.exc try: return _create_from_endpoint_config(obj, domain, event_broker) except ( BotoCoreError, pymongo.errors.ConnectionFailure, sqlalchemy.exc.OperationalError, ) as error: raise ConnectionException("Cannot connect to tracker store.") from error def get_or_create_tracker( self, sender_id: Text, max_event_history: Optional[int] = None, append_action_listen: bool = True, ) -> "DialogueStateTracker": """Returns tracker or creates one if the retrieval returns None. Args: sender_id: Conversation ID associated with the requested tracker. max_event_history: Value to update the tracker store's max event history to. append_action_listen: Whether or not to append an initial `action_listen`. """ self.max_event_history = max_event_history tracker = self.retrieve(sender_id) if tracker is None: tracker = self.create_tracker( sender_id, append_action_listen=append_action_listen ) return tracker def init_tracker(self, sender_id: Text) -> "DialogueStateTracker": """Returns a Dialogue State Tracker""" return DialogueStateTracker( sender_id, self.domain.slots if self.domain else None, max_event_history=self.max_event_history, ) def create_tracker( self, sender_id: Text, append_action_listen: bool = True ) -> DialogueStateTracker: """Creates a new tracker for `sender_id`. The tracker begins with a `SessionStarted` event and is initially listening. Args: sender_id: Conversation ID associated with the tracker. append_action_listen: Whether or not to append an initial `action_listen`. Returns: The newly created tracker for `sender_id`. """ tracker = self.init_tracker(sender_id) if append_action_listen: tracker.update(ActionExecuted(ACTION_LISTEN_NAME)) self.save(tracker) return tracker def save(self, tracker: DialogueStateTracker) -> None: """Save method that will be overridden by specific tracker.""" raise NotImplementedError() def exists(self, conversation_id: Text) -> bool: """Checks if tracker exists for the specified ID. This method may be overridden by the specific tracker store for faster implementations. Args: conversation_id: Conversation ID to check if the tracker exists. Returns: `True` if the tracker exists, `False` otherwise. """ return self.retrieve(conversation_id) is not None def retrieve(self, sender_id: Text) -> Optional[DialogueStateTracker]: """Retrieves tracker for the latest conversation session. This method will be overridden by the specific tracker store. Args: sender_id: Conversation ID to fetch the tracker for. Returns: Tracker containing events from the latest conversation sessions. """ raise NotImplementedError() def retrieve_full_tracker( self, conversation_id: Text ) -> Optional[DialogueStateTracker]: """Retrieve method for fetching all tracker events across conversation sessions that may be overridden by specific tracker. The default implementation uses `self.retrieve()`. Args: conversation_id: The conversation ID to retrieve the tracker for. Returns: The fetch tracker containing all events across session starts. """ return self.retrieve(conversation_id) def stream_events(self, tracker: DialogueStateTracker) -> None: """Streams events to a message broker""" offset = self.number_of_existing_events(tracker.sender_id) events = tracker.events for event in list(itertools.islice(events, offset, len(events))): body = {"sender_id": tracker.sender_id} body.update(event.as_dict()) self.event_broker.publish(body) def number_of_existing_events(self, sender_id: Text) -> int: """Return number of stored events for a given sender id.""" old_tracker = self.retrieve(sender_id) return len(old_tracker.events) if old_tracker else 0 def keys(self) -> Iterable[Text]: """Returns the set of values for the tracker store's primary key""" raise NotImplementedError() @staticmethod def serialise_tracker(tracker: DialogueStateTracker) -> Text: """Serializes the tracker, returns representation of the tracker.""" dialogue = tracker.as_dialogue() return json.dumps(dialogue.as_dict()) @staticmethod def _deserialize_dialogue_from_pickle( sender_id: Text, serialised_tracker: bytes ) -> Dialogue: # TODO: Remove in Rasa Open Source 3.0 rasa.shared.utils.io.raise_deprecation_warning( f"Found pickled tracker for " f"conversation ID '{sender_id}'. Deserialization of pickled " f"trackers is deprecated and will be removed in Rasa Open Source 3.0. Rasa " f"will perform any future save operations of this tracker using json " f"serialisation." ) return pickle.loads(serialised_tracker) def deserialise_tracker( self, sender_id: Text, serialised_tracker: Union[Text, bytes] ) -> Optional[DialogueStateTracker]: """Deserializes the tracker and returns it.""" tracker = self.init_tracker(sender_id) try: dialogue = Dialogue.from_parameters(json.loads(serialised_tracker)) except UnicodeDecodeError: dialogue = self._deserialize_dialogue_from_pickle( sender_id, serialised_tracker ) tracker.recreate_from_dialogue(dialogue) return tracker
{"/wechatter/shared/dm/slots.py": ["/wechatter/shared/utils/io.py"], "/wechatter/server/run_server.py": ["/wechatter/config/__init__.py", "/wechatter/__init__.py", "/wechatter/shared/utils/io.py", "/wechatter/model_training.py"], "/wechatter/model.py": ["/wechatter/shared/utils/io.py", "/wechatter/utils/io.py", "/wechatter/exceptions.py"], "/wechatter/dm/tracker_store.py": ["/wechatter/shared/dm/conversation.py"], "/wechatter/model_training.py": ["/wechatter/shared/importers/importer.py"], "/wechatter/shared/dm/trackers.py": ["/wechatter/shared/dm/slots.py"], "/wechatter/config/__init__.py": ["/wechatter/config/config.py"]}
58,304
we-chatter/wechatter
refs/heads/main
/wechatter/config/config.py
# -*- coding: utf-8 -*- """ @Author : Xu @Software: PyCharm @File : config.py @Time : 2020/11/10 9:04 上午 @Desc : """ import os class Config(): """ Basic config for demo02 """ # Application config TIMEZONE = 'Asia/Shanghai' # BASE_DIR = os.path.dirname(os.path.dirname(__file__)) DEBUG = True
{"/wechatter/shared/dm/slots.py": ["/wechatter/shared/utils/io.py"], "/wechatter/server/run_server.py": ["/wechatter/config/__init__.py", "/wechatter/__init__.py", "/wechatter/shared/utils/io.py", "/wechatter/model_training.py"], "/wechatter/model.py": ["/wechatter/shared/utils/io.py", "/wechatter/utils/io.py", "/wechatter/exceptions.py"], "/wechatter/dm/tracker_store.py": ["/wechatter/shared/dm/conversation.py"], "/wechatter/model_training.py": ["/wechatter/shared/importers/importer.py"], "/wechatter/shared/dm/trackers.py": ["/wechatter/shared/dm/slots.py"], "/wechatter/config/__init__.py": ["/wechatter/config/config.py"]}
58,305
we-chatter/wechatter
refs/heads/main
/wechatter/model_training.py
# -*- coding: utf-8 -*- """ @Author : Xu @Software: PyCharm @File : model_training.py @Time : 2020/11/17 8:56 下午 @Desc : train model """ import asyncio import os import tempfile from contextlib import ExitStack from typing import ( Text, NamedTuple, Tuple, Optional, List, Union, Dict, ) from wechatter.shared.dm.domain import Domain from wechatter.shared.importers.importer import TrainingDataImporter from wechatter.shared.dialogue_config import ( DEFAULT_MODELS_PATH ) class TrainingResult(NamedTuple): """Holds information about the results of training.""" model: Optional[Text] = None code: int = 0 async def train_async( domain: Union[Domain, Text], config: Text, training_files: Optional[Union[Text, List[Text]]], output: Text = DEFAULT_MODELS_PATH, dry_run: bool = False, force_training: bool = False, model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, core_additional_arguments: Optional[Dict] = None, nlu_additional_arguments: Optional[Dict] = None, model_to_finetune: Optional[Text] = None, finetuning_epoch_fraction: float = 1.0, ) -> TrainingResult: """ 进行异步训练 :param domain: :param config: :param training_files: :param output: :param dry_run: :param force_training: bool值,如果为True,则在数据没有变动的情况下也训练 :param model_name: 模型名称 :param persist_nlu_training_data: :param core_additional_arguments: :param nlu_additional_arguments: :param model_to_finetune: :param finetuning_epoch_fraction: :return: TrainingResult 的实例 """ file_importer = TrainingDataImporter.load_from_config( config, domain, training_files ) with TempDirectoryPath(tempfile.mkdtemp()) as train_path: domain = await file_importer.get_domain() if domain.is_empty(): nlu_model = await handle_domain_if_not_exists( file_importer, output, model_name ) return TrainingResult(model=nlu_model) return await _train_async_internal( file_importer, train_path, output, dry_run, force_training, model_name, persist_nlu_training_data, dm_additional_arguments=core_additional_arguments, nlu_additional_arguments=nlu_additional_arguments, model_to_finetune=model_to_finetune, finetuning_epoch_fraction=finetuning_epoch_fraction, ) async def handle_domain_if_not_exists( file_importer: TrainingDataImporter ): return None async def _train_async_internal( file_importer: TrainingDataImporter, train_path: Text, output_path: Text, dry_run: bool, force_training: bool, model_name: Optional[Text], persist_nlu_training_data: bool, dm_additional_arguments: Optional[Dict] = None, nlu_additional_arguments: Optional[Dict] = None, model_to_finetune: Optional[Text] = None, finetuning_epoch_fraction: float = 1.0, ) -> TrainingResult: """ 模型训练 :param file_importer: :param train_path: :param output_path: :param dry_run: :param force_training: :param model_name: :param persist_nlu_training_data: :param dm_additional_arguments: :param nlu_additional_arguments: :param model_to_finetune: :param finetuning_epoch_fraction: :return: """ return TrainingResult(model=old_model)
{"/wechatter/shared/dm/slots.py": ["/wechatter/shared/utils/io.py"], "/wechatter/server/run_server.py": ["/wechatter/config/__init__.py", "/wechatter/__init__.py", "/wechatter/shared/utils/io.py", "/wechatter/model_training.py"], "/wechatter/model.py": ["/wechatter/shared/utils/io.py", "/wechatter/utils/io.py", "/wechatter/exceptions.py"], "/wechatter/dm/tracker_store.py": ["/wechatter/shared/dm/conversation.py"], "/wechatter/model_training.py": ["/wechatter/shared/importers/importer.py"], "/wechatter/shared/dm/trackers.py": ["/wechatter/shared/dm/slots.py"], "/wechatter/config/__init__.py": ["/wechatter/config/config.py"]}
58,306
we-chatter/wechatter
refs/heads/main
/wechatter/exceptions.py
# -*- coding: utf-8 -*- """ @Author : Xu @Software: PyCharm @File : exceptions.py @Time : 2021/4/15 3:54 下午 @Desc : 异常处理 """ from typing import Text from wechatter.shared.exceptions import WechatterException class ModelNotFound(WechatterException): """Raised when a model is not found in the path provided by the user.""" class NoEventsToMigrateError(WechatterException): """Raised when no events to be migrated are found.""" class NoConversationsInTrackerStoreError(WechatterException): """Raised when a tracker store does not contain any conversations.""" class NoEventsInTimeRangeError(WechatterException): """Raised when a tracker store does not contain events within a given time range.""" class MissingDependencyException(WechatterException): """Raised if a python package dependency is needed, but not installed.""" class PublishingError(WechatterException): """Raised when publishing of an event fails. Attributes: timestamp -- Unix timestamp of the event during which publishing fails. """ def __init__(self, timestamp: float) -> None: self.timestamp = timestamp super(PublishingError, self).__init__() def __str__(self) -> Text: """Returns string representation of exception.""" return str(self.timestamp)
{"/wechatter/shared/dm/slots.py": ["/wechatter/shared/utils/io.py"], "/wechatter/server/run_server.py": ["/wechatter/config/__init__.py", "/wechatter/__init__.py", "/wechatter/shared/utils/io.py", "/wechatter/model_training.py"], "/wechatter/model.py": ["/wechatter/shared/utils/io.py", "/wechatter/utils/io.py", "/wechatter/exceptions.py"], "/wechatter/dm/tracker_store.py": ["/wechatter/shared/dm/conversation.py"], "/wechatter/model_training.py": ["/wechatter/shared/importers/importer.py"], "/wechatter/shared/dm/trackers.py": ["/wechatter/shared/dm/slots.py"], "/wechatter/config/__init__.py": ["/wechatter/config/config.py"]}
58,307
we-chatter/wechatter
refs/heads/main
/setup.py
# -*- coding: utf-8 -*- """ @Author : Xu @Software: PyCharm @File : setup.py @Time : 2020/9/17 7:20 下午 @Desc : version information """ from setuptools import setup packages = \ ['wechatter', ] package_data = \ {'': ['*'], 'wechatter.dm': ['schemas/*']} install_requires = [ 'tensorflow>=2.1'] extras_require = {} entry_points = \ {'console_scripts': ['wechatter = wechatter.__main__:main']} setup_kwargs = { 'name': 'wechatter', 'version': '1.0.0', 'description': 'Open source deep learning framework to automate text- and voice-based conversations', 'long_description': '# wechatter Open Source', 'author': 'wechatter community', 'author_email': 'charlesxu86@163.com', 'maintainer': 'wechatter', 'maintainer_email': 'charlesxu86@163.com', 'url': 'https://we-chatter.com', 'packages': packages, 'package_data': package_data, 'install_requires': install_requires, 'extras_require': extras_require, 'entry_points': entry_points, 'python_requires': '>=3.6', } setup(**setup_kwargs)
{"/wechatter/shared/dm/slots.py": ["/wechatter/shared/utils/io.py"], "/wechatter/server/run_server.py": ["/wechatter/config/__init__.py", "/wechatter/__init__.py", "/wechatter/shared/utils/io.py", "/wechatter/model_training.py"], "/wechatter/model.py": ["/wechatter/shared/utils/io.py", "/wechatter/utils/io.py", "/wechatter/exceptions.py"], "/wechatter/dm/tracker_store.py": ["/wechatter/shared/dm/conversation.py"], "/wechatter/model_training.py": ["/wechatter/shared/importers/importer.py"], "/wechatter/shared/dm/trackers.py": ["/wechatter/shared/dm/slots.py"], "/wechatter/config/__init__.py": ["/wechatter/config/config.py"]}