def main(args): screen = Screen("Bubble Sort") screen.display() n = 400 to_sort = np.random.randint(1, 10000, size=n, dtype=np.int64) print(f"[IN PROCESS] Processing input: {to_sort}") result, start_time = bubbleSort(to_sort) exec_time = time.perf_counter_ns() - start_time print(f"[INFO] Input successfully proccessed. Time spent: {exec_time}ns") print(f""" INPUT: {to_sort} OUTPUT: {result} """)
def __init__(self, args): """ args are parse as add, or delete""" self.url = "https://www.myfitnesspal.com/" self.screen = Screen("Meal manager", version='0.1') # order matters self.meals = { "Desayuno": 0, "Media Mañana": 1, "Almuerzo": 2, "Media tarde": 3, "Cena": 4 } self.translate(language="spanish") self.digest_args(args)
class Interface(object): def __init__(self, *args): self.log = Logger(path_log_file=LOG_FILE_PATH, level = "warning") self.sc = Screen("PW manager") self.sc.display() sleep(2) self.digest_args(*args) def __del__(self): print(f"[IN PROGRESS] Exciting ...") @staticmethod def usage(): print(f""" Usage: -> $pw --list | -l: List all the store password references -> $pw --save | -s [password | -cb]: If not password as argument, then store clipboard data as a pw and prompt for a password reference. -> $pw --change | -c [pw_ref]: if not pw_ref, then user is prompted for the reference as well as the new password -> $pw pw_ref: Verify user and copy pw to clipboard if matches, otherwise will prompt to select the underlying pw_ref based on better matches to the input ref. """) def digest_args(self, *args): try: self.sc.display() if not args: Interface.usage() return self.ctrl = Controller(screen=self.sc) if not self.ctrl.has_user(): return index = 0 while index < len(args): self.sc.display() arg = args[index] self.log.info(f"Reading arg {arg}") if arg and not "-" in arg: self.log.info(f"Calling search_pw") self.ctrl.search_pw(arg) elif arg == "--list" or arg == "-l": self.log.info(f"Calling list_pws") self.ctrl.list_pws() elif arg == "--save" or arg == "-s": cfc = "--clipboard" in args or "-cb" in args self.ctrl.save_pw(pw= Utils.check_next_arg(args, index), copy_from_clipboard=cfc) index += 1 elif arg == "--change" or arg == "-c": self.ctrl.change_pw(pw=Utils.check_next_arg(args, index)) sleep(2) index += 1 except Exception: traceback.print_exc(file=sys.stdout)
import sys import os import subprocess from Modules.Screen.Screen import Screen #!Python 3 # This script it shows the currently enviroment variables, and checks if a path is added or not. screen = Screen('System variables manager') screen.display() if len(sys.argv) < 2: print( "Usage: (path 'vars') print the current environment system variables") print(" (path 'path') check if the given path is added") sys.exit() arg = sys.argv[1] enviroment_vars = subprocess.check_output('echo %PATH%', shell=True) paths_list = enviroment_vars.decode('utf-8').split(';')[:-1] if arg == 'vars': for index, path in enumerate(paths_list, 1): print(f'[{index}] -> {path}') else: for path in paths_list: if path == arg: print('The path is added.') sys.exit()
try: task_list.show_task_list() num = int(input("Enter the num of the task: ")) task_list.remove_task(num) time.sleep(1) except ValueError: print("A integer value is expected.") elif choose == 3: task_list.show_task_list() time.sleep(1) except ValueError: print("A number is expected.") screen = Screen('Task manager') screen.display() task_list = Task_list() if len(sys.argv) < 2: print('Usage: (task_manager 1) add a new task ') print(' (task_manager 2) delete a task ') print(' (task_manager 3) show tasks ') print(' (task_manager 4) exit ') sys.exit() store_tasks(task_list) time.sleep(2) selector(sys.argv[1], task_list) while True:
def __init__(self, *args): self.log = Logger(path_log_file=LOG_FILE_PATH, level = "warning") self.sc = Screen("PW manager") self.sc.display() sleep(2) self.digest_args(*args)
def __init__(self, cedula): """ arg is either money or a date """ self.__id = cedula self.screen = Screen('Family handler', version='0.1') self.db = Database('tracker.db') self.valid_user()
class Logger(): def __init__(self, cedula): """ arg is either money or a date """ self.__id = cedula self.screen = Screen('Family handler', version='0.1') self.db = Database('tracker.db') self.valid_user() def valid_user(self): self.screen.display() if not self.db.check(self.__id): try: print(f"[INFO] {self.__id} is not registered yet.", end=' ') ans = pyip.inputYesNo('Do you want to register? (y/n) ', limit=3, yesVal='y', noVal='n') if ans == 'y': name = pyip.inputStr('Enter a name: ', limit=3) money = pyip.inputInt('Initial money (default 0): ', limit=3, default=None) response = self.db.register(self.__id, name, money) if response: self.add(money) print( f'[INFO] User: (id:{self.__id}, name:{name}, money:{money}$) was succesfully registered in the Database.' ) else: print('[ERROR] Something was wrong with the register.') print('Thanks for using the script!') sys.exit() else: sys.exit() except pyip.RetryLimitException: print(f'[ERROR] Limit of attempts exceeded.') def add(self, money): self.db.add_money(self.__id, money) def substract(self, money): self.db.add_money(self.__id, (-1) * money) def get_info(self, attribute): try: self.db.cursor.execute( f"""SELECT {attribute} FROM {TABLE_NAME} WHERE cc = {self.__id} """ ) response = self.db.cursor.fetchall()[0] logging.debug(f'Query: {attribute} and response: {response}') return response[0] except Exception as ex: print(f'[ERROR] Query failed. CAUSE: {ex}') def history(self, date=None): """ print history since a given date """ logs = self.db.history[self.__id] start = 0 #index to start printing the transactions if date: print(f'[IN PROGRESS] Getting historial since {date} ...') logging.debug(f'given date {date}') start = get_start(logs, date) if not start: #means get_start return None print(f'[INFO] No dates match with {date}') start = 0 #set it as by default name = self.get_info('name') title = f'{name} - {self.__id} History' print(f"[IN PROGRESS] Building historial table ... ") self.history_table(logs[start:], title=title) input('') #wait to read the history def history_table(self, logs, title='History'): table = PrettyTable() table.title = title table.field_names = ['Total', 'Transaction', 'Message', 'Date', 'Hour'] #fill in columns and rows for full_date, message, money, total in logs: date = full_date[:10] time = full_date[11:] table.add_row([total, money, message, date, time]) print(table)
for char in message: if not blanks: if char == " ": continue if char in special_chars: raw = char.encode('unicode_escape') parse = raw.decode('utf-8') chars.setdefault(parse, 0) chars[parse] += 1 continue chars.setdefault(char, 0) chars[char] += 1 return chars screen = Screen('Char Counter') screen.display() if len(sys.argv) < 2: print("Usage: (char 1) print the number of times a character appear") print( " (char 2) print the number of times a character appear (without blanks)" ) print(" (char 3) print only the length") sys.exit() arg = sys.argv[1] try: arg = int(arg) blanks = True string = pyperclip.paste().replace(' ', '') if arg == 3:
class myfitnesspal(): def __init__(self, args): """ args are parse as add, or delete""" self.url = "https://www.myfitnesspal.com/" self.screen = Screen("Meal manager", version='0.1') # order matters self.meals = { "Desayuno": 0, "Media Mañana": 1, "Almuerzo": 2, "Media tarde": 3, "Cena": 4 } self.translate(language="spanish") self.digest_args(args) def usage(self): usage = """ Usage: $meals add *meal-name *meal-name ...: (add the regular ingredients for each given meal) delete meal-name: (delete an existing meal ingredients) """ print(usage) def translate(self, language="spanish"): """ Handle the random modification of languages in myfitnesspal website """ config_path = PATH / "config.ini" assert os.path.exists(config_path) parser = configparser.ConfigParser() parser.read(config_path, encoding="utf-8") self.parser = parser[language] def digest_args(self, args): self.screen.display() if len(args) < 2: self.usage() task = args[1] if task in FEATURES: print("[IN PROGRESS] Loading page...") self.get_page() print("[INFO] Web page loaded succesfully.") time.sleep(1) self.LogIn() time.sleep(3) self.get_foods_page() time.sleep(3) args = [arg.lower().capitalize() for arg in args] if task == "add": meals = args[2:] self.add_meal(meals) elif task == "delete": # parse meals like 'media tarde' or 'media mañana' if args[2] == "Media": meal = " ".join([args[2], args[3].lower()]) else: meal = args[2] self.delete_meal(meal) else: self.usage() print(f"Thanks for using the script!") sys.exit() def add_meal(self, meals, regular=True): """ Handle the register of meals """ # parse each element in meals list temp_meals = [] for index, meal in enumerate(meals): if meal == "Media": meal += " " + meals[index + 1].lower() elif meal == "Tarde" or meal == "Mañana": continue temp_meals.append(meal) meals = temp_meals logging.debug(f"Meals {meals}") for meal in meals: if meal in self.meals.keys(): #new or regular if regular: regular_meal = self.get_regulars(meal) self.add_ingredients(meal, regular_meal) else: print(f"[INFO] {meal} is not a correct meal.") def delete_meal(self, meal): try: if not meal in self.meals.keys(): raise Exception("Meal not available.") amount_elements = len(self.get_regulars(meal)) meal_header = self.get_header(meal) # delete button button, name = self.get_ingredient_to_delete(meal_header) if not button: print(f"[INFO] No entries were found for {meal}.") return print("[IN PROGRESS] Removing ingredients ...") while button: button.click() print(f" [INFO] {name} Succesfully removed.") meal_header = self.get_header(meal) button, name = self.get_ingredient_to_delete(meal_header) print(f"[INFO] {meal} Ingredients removed succesfully.") except Exception as ex: print(f"[ERROR] {ex}") def get_header(self, meal): try: # wait for page to be scrapped food_page = EC.presence_of_element_located( (By.XPATH, "//tr[contains(@class,'meal_header')]")) WebDriverWait(self.driver, 10).until(food_page) except TimeoutException: print( f"[ERROR] {self.driver.current_url} took too much time to load" ) # TODO: Solve wrong parent element, two options: *Figure out how to access to the container element, *Split the header matching to divide access to external headers and matched header. headers = self.driver.find_elements_by_xpath( "//tr[@class = 'meal_header']") assert len(headers) == 6 for header in headers: try: if header.find_element_by_xpath(".//td[text() = '%s']" % meal): return header except NoSuchElementException: continue def get_ingredient_to_delete(self, node): """ Find nodes at the same level according to a certain conditions""" sibling = node.find_elements_by_xpath(".//following-sibling::tr") if not sibling: return [None, None] # avoid to unpack a unique None value element = sibling[0] # always select the top element try: delete_button = element.find_element_by_xpath( ".//td[@class = 'delete']") name = element.find_element_by_xpath( ".//td[@class = 'first alt']").text return [delete_button, name] except NoSuchElementException: return [None, None] # avoid to unpack a unique None value except Exception as ex: print(f"[ERROR] {ex}") def get_regulars(self, meal): # default meals for a breakfast BREAKFAST_REGULAR = [ "Latti - Leche Descremada-deslactosada", "Facundo - Champiñones Tajados", "Natri - Galletas Multicereal Tostadas", "Genereico - Pechuga De Pollo (Sin Piel Ni Hueso)", "Justo Y Bueno - Jamón Sanduche Ahumado", "mas por menos - queso bajo en grasa", "SUSANITA - Tostadas de Arroz Con Sal Marina", "Homemade - Huevo Frito", ] MIDDLE_MORNING_REGULAR = [] LUNCH_REGULAR = [ "Lentejas Schettino - Lentejas Cocidas", "Verdura - Papa Cocida", "mercaderia - Mostaza", "Arju - Ensalada Tomate-cebolla-lechuga-pepinos", "Fruco - Salsa De Tomate", "Mercadería - Mayonesa Baja en grasa", "Pechuga de pollo (sin hueso, sin piel)", "Arroz Blanco Daniba - Arroz Blanco Cocido", ] MIDDLE_AFTERNOON_REGULAR = [ "Nuthos - Mezcla Crunchy", "Mash - Creamy Peanut Buttet", ] DINNER_REGULAR = [ "Latti - Leche Entera", "Latti - Leche Descremada-deslactosada", "Servipan - Pan De Queso", "Coolechera - Queso Costeño", "mercaderia - Mostaza", "Fruco - Salsa De Tomate", "Arju - Ensalada Tomate-cebolla-lechuga-pepinos", "Genereico - Pechuga De Pollo (Sin Piel Ni Hueso)", ] index = self.meals[meal] if index == 0: return BREAKFAST_REGULAR elif index == 1: return MIDDLE_MORNING_REGULAR elif index == 2: return LUNCH_REGULAR elif index == 3: return MIDDLE_AFTERNOON_REGULAR elif index == 4: return DINNER_REGULAR def get_page(self): options = webdriver.ChromeOptions() options.add_argument("start-maximized") options.add_argument("disable-infobars") # options.add_argument('--headless') options.add_argument('--log-level=3') # options.add_argument("--disable-logging") self.driver = webdriver.Chrome(chrome_options=options) self.driver.get(self.url + "account/login") def LogIn(self): print("[IN PROGRESS] Log In account...") try: # let the page load time.sleep(3) # save the main window src_window = self.driver.window_handles[0] # wait the fb login button to load log_in_frame_xpath = "//div[contains(@class,'fb-login-button')]" log_in_iframe = EC.element_to_be_clickable( (By.XPATH, log_in_frame_xpath)) WebDriverWait(self.driver, 20).until(log_in_iframe).click() # pop-up page pop_up_fb_page = self.driver.window_handles[1] self.driver.switch_to_window(pop_up_fb_page) user_box = self.driver.find_element_by_id("email") user_box.send_keys("*****@*****.**") pw_box = self.driver.find_element_by_id("pass") pw_box.send_keys("Chivasregal123") time.sleep(3) self.driver.find_element_by_name("login").click() time.sleep(2) self.driver.switch_to_window(src_window) print("[INFO] Log In complete.") except Exception as ex: print(f"[ERROR] Log In proccess has failed. {ex}") def get_foods_page(self): # wait until iframe be clickeable logging.debug(f"Number of windows {len(self.driver.window_handles)}") while True: try: close_button = EC.visibility_of_element_located( (By.XPATH, "//a[@class = 'close-btn' and text() = '✕']")) popup_box = WebDriverWait(self.driver, 20).until(close_button) popup_box.click() break except ElementNotInteractableException: continue except TimeoutException: print( f"[ERROR] {self.driver.current_url} took too much time to load" ) continue except Exception as ex: print(f"[ERROR] Can't close the pop-up box. {ex}") break time.sleep(1) # get meals page FOOD_button = self.driver.find_element_by_xpath( "//a[text() = 'Alimento']") FOOD_button.click() def add_ingredients(self, meal, ingredients): try: # wait for page to be scrapped food_page = EC.presence_of_element_located( (By.XPATH, "//tr[contains(@class,'meal_header')]")) WebDriverWait(self.driver, 10).until(food_page) except TimeoutException: print( f"[ERROR] {self.driver.current_url} took too much time to load" ) buttons = self.driver.find_elements_by_xpath( "//a[contains(@href,'/food/add to diary?meal=') or text() = '%s']" % self.parser.get("FOOD_BUTTON")) # TODO: find all All Food buttons. assert len(buttons) == 6 buttons[self.meals[meal]].click() time.sleep(3) print(f"[IN PROGRESS] Adding ingredients for {meal}...") # get all the regular foods regular_ingredients_xpath = "//tr[@class = 'favorite']" regular_ingredients = self.driver.find_elements_by_xpath( regular_ingredients_xpath) for ingredient in ingredients: self.add_ingredient(ingredient, regular_ingredients) time.sleep(2) submit_button = self.driver.find_element_by_xpath( "//input[@id = '%s']" % self.parser.get("SUBMIT_BUTTON")) submit_button.click() print("[INFO] Added ingredients succesfully.") def add_ingredient(self, ingredient, iterator): target_xpath = ".//td[text() = '%s']" % ingredient for regular_ingredient in iterator: logging.debug(f"xpath = {target_xpath}") try: target_ingredient = regular_ingredient.find_element_by_xpath( target_xpath) if target_ingredient: # add it regular_ingredient.find_element_by_xpath( ".//input[@class = 'checkbox']").click() print( f" [INFO] Added {target_ingredient.text} succesfully.", ) break except NoSuchElementException: continue except ElementNotInteractableException: continue except Exception as ex: logging.debug(f"[ERROR] in {regular_ingredient} CAUSE: {ex}") print(f"[ERROR] Something was wrong - {type(ex)} {ex}") break logging.debug(f"target ingredient {target_ingredient.text}")