def ask_for_site_data() -> Dict: questions = [ inquirer.text('url', message='Enter your Zendesk site_url.', validate=text_is_not_blank), inquirer.text('locale', message='What is the default locale (lang code) for the site?\nDefault is en-us', default='en-us', validate=is_valid_lang_code) ] return inquirer.prompt(questions)
def hillCipher_cipher_get_key() -> str: # Set up cipher key key_source = inquirer.list_input("Choose key source", choices=["Manual Input", "File"]) if key_source == "Manual Input": key_size = int(inquirer.text(message="key size (N x N)")) key_string = inquirer.text(message="key") key_list = [int(x) for x in key_string.split()] if len(key_list) != key_size**2: raise Exception("key length not valid") key = [] for i in range(0, key_size): key_row = [] for j in range(0, key_size): key_row.append(key_list[key_size * i + j]) key.append(key_row) return key elif key_source == "File": question = [ inquirer.Path( "file_path", message="path to key file", path_type=inquirer.Path.FILE, ), ] key_file_path = inquirer.prompt(question) key_string_list = hf.read_file_as_string_list_stripped( key_file_path['file_path']) key_size = int(key_string_list[0]) key_list = [int(x) for x in key_string_list[1].split()] if len(key_list) != key_size**2: raise Exception("key length not valid") key = [] for i in range(0, key_size): key_row = [] for j in range(0, key_size): key_row.append(key_list[key_size * i + j]) key.append(key_row) return key else: raise NotImplementedError
def ask_for_credentials(): """Use the CLI to get the zendesk credentials """ questions = [ inquirer.text(name='zendesk_email', message='Enter your Zendesk email.'), inquirer.text(name='zendesk_email', message='Enter your Zendesk email.'), ] return inquirer.prompt(questions)
def aStcWrap(pth): """Advanced mode is pretty trash """ print('\nAdvanced Stitch\n---------------') print('Leaving fields blank will result in defaults being used') print('WARNING: The entry fields are finicky, and capture ALL input. ' + 'If you try to use backspace, the value will be rejected.') print(f'Drawing from {pth}\n') cF = text('Desired Crop Factor (num 0.01 - 1, def 0.75)') if not cF: cF = 0.75 try: cF = float(cF) except ValueError: print('Value entered is not a number, using default') cF = 0.75 if cF > 1 or cF < 0.01: print('Value entered is outside acceptable range, using default') cF = 0.75 print(f'Crop Factor is {cF}\n') fF = text('Desired Feather Radius (num 0.01 - 1, def 0.15)') if not fF: fF = 0.15 try: fF = float(fF) except ValueError: print('Value entered is not a number, using default') fF = 0.15 if fF > 1 or fF < 0.01: print('Value entered is outside acceptable range, using default') fF = 0.15 print(f'Feather Radius is {fF}\n') icon = confirm('Mark player position?', default=True) print(f'Mark Player = {icon}\n') try: return stitch.stitch2(pth, '', cF, fF, icon) except FileNotFoundError: print(errstr) print(f'Bad Path: {pth}\n') return 0
def sub_interactive_loop_make_a_guess(self, name): guess = "" while len(guess) == 0 or len(guess) > 1: guess = inquirer.text(message="Type a letter to guess...") link = self.send_post_message(name, "guess", guess) if link: status = "PENDING" counter = 0 while status == "PENDING": ret_json = self.send_get_message(link) status = ret_json["data"][0]["status"] counter += 1 sleep(1) if counter >= 10: break state = self.send_get_message( VALIDATOR_ENDPOINT_STATE.format(_make_hm_address(name))) decoded_state = self.decode(state["data"]) game = loads(decoded_state) current_game = game[-1] self.print_game(current_game) if current_game["state"] == 1: again = inquirer.confirm("Guess again?", default=True) if again: self.sub_interactive_loop_make_a_guess(name)
def get_book_from_goodreads(auth, search_term=None): search_term = inquirer.text( "Give me your best Goodreads search terms – or a URL, if you have one!", default=None, ) if "goodreads.com" in search_term: return get_book_data(url=search_term.strip() + ".xml", auth=auth) response = requests.get( f"{GOODREADS_URL}search/index.xml", {"key": auth["goodreads_developer_key"], "q": search_term}, ) to_root = ET.fromstring(response.content.decode()) results = to_root.find("search").find("results") options = [] for index, work in enumerate(results): title = work.find("best_book").find("title").text author = work.find("best_book").find("author").find("name").text options.append( ( (f"{index + 1}. {title} by {author}"), work.find("best_book").find("id").text, ) ) click.echo( click.style(f"Found {len(options)} possible books:", fg="green", bold=True) ) book = inquirer.list_input(message="Which one did you mean?", choices=options) return get_book_data(url=f"{GOODREADS_URL}book/show/{book}.xml", auth=auth)
def _change_cover(review, push_to_goodreads, auth): old_cover_url = review.metadata["book"]["cover_image_url"] source = inquirer.list_input( message="Where do you want to retrieve the cover image from?", choices=[ ("Goodreads", "goodreads"), ("Goodreads web scraping", "goodreads_scrape"), ("Google APIs", "google"), ("OpenLibrary", "openlibrary"), ("Custom URL", "manually"), ], carousel=True, ) if source == "manually": url = inquirer.text(message="Cover image URL") review.download_cover(url, force_new=True) else: review.find_cover(source, force_new=True) if review.metadata["book"]["cover_image_url"] != old_cover_url: click.echo( click.style("Successfully downloaded new cover image!", fg="green")) review.save() subprocess.check_call([ "xdg-open", Path("src/covers") / review.metadata["book"]["cover_image"] ]) else: click.echo(click.style("Couldn't find a new cover, sorry!", fg="red"))
def __refresh_token(url, username, password, config_dir, headless=True, spinner=True): spinner = Halo(enabled=spinner) try: spinner.start(SPINNER_MSGS['token_refresh']) driver = SSODriver(url, username, headless=headless, cookie_dir=config_dir) try: return driver.refresh_token(username, password) except MFACodeNeeded as e: spinner.stop() mfacode = inquirer.text(message='MFA Code') spinner.start(SPINNER_MSGS['mfa_send']) driver.send_mfa(e.mfa_form, mfacode) spinner.start(SPINNER_MSGS['token_refresh']) return driver.get_token() except AlertMessage as e: sys.exit(e) finally: spinner.stop() except KeyboardInterrupt as e: spinner.stop() raise e finally: driver.close()
def simple_key_read_prompt() -> str: # Set up cipher key key_source = inquirer.list_input("Choose key source", choices=["Manual Input", "File"]) if key_source == "Manual Input": key_string = inquirer.text(message="key") return key_string elif key_source == "File": question = [ inquirer.Path( "file_path", message="path to key file", path_type=inquirer.Path.FILE, ), ] key_file_path = inquirer.prompt(question) return hf.read_file_as_string_single_stripped( key_file_path['file_path']) else: raise NotImplementedError
def ciphertext_read_prompt() -> str: # Ask for ciphertext source ciphertext_source = inquirer.list_input("Choose ciphertext source", choices=["Manual Input", "File"]) if ciphertext_source == "Manual Input": ciphertext_string = inquirer.text(message="ciphertext") return ciphertext_string elif ciphertext_source == "File": question = [ inquirer.Path( "file_path", message="path to ciphertext file", path_type=inquirer.Path.FILE, ), ] ciphertext_file_path = inquirer.prompt(question) return hf.read_file_as_string_single_stripped( ciphertext_file_path['file_path']) else: raise NotImplementedError
def _get_search_results(search_term, auth=None): auth = auth or get_auth() search_term = inquirer.text( "Give me your best Goodreads search terms – or a URL, if you have one!", default=search_term, ) if "goodreads.com" in search_term: return get_book_data(url=search_term.strip() + ".xml") response = requests.get( f"{GOODREADS_URL}search/index.xml", { "key": auth["goodreads_developer_key"], "q": search_term }, ) to_root = ET.fromstring(response.content.decode()) results = to_root.find("search").find("results") options = [] for index, work in enumerate(results): title = work.find("best_book").find("title").text author = work.find("best_book").find("author").find("name").text options.append(( (f"{index + 1}. {title} by {author}"), work.find("best_book").find("id").text, )) return options
def extended_vignere_cipher_get_key() -> bytearray: # Set up cipher key key_source = inquirer.list_input("Choose key source", choices=["Manual Input", "File"]) if key_source == "Manual Input": key_string = inquirer.text(message="key") return key_string.encode('UTF-8') elif key_source == "File": question = [ inquirer.Path( "file_path", message="path to key file", path_type=inquirer.Path.FILE, ), ] key_file_path = inquirer.prompt(question) return hf.read_file_as_bytearray(key_file_path['file_path']) else: raise NotImplementedError
def get_date(prompt, default): choices = ["today", "yesterday", "another day"] if default: choices.append(default) date = inquirer.list_input(message=prompt, choices=choices, carousel=True, default=default) today = dt.datetime.now() if date == "today": return today.date() if date == "yesterday": yesterday = today - dt.timedelta(days=1) return yesterday.date() if date == default: return default date = None while True: date = inquirer.text(message="Which other day?") if re.match(r"^\d{4}-\d{2}-\d{2}$", date.strip()): return dt.datetime.strptime(date, "%Y-%m-%d").date() elif re.match(r"^\d{1,2} [A-Z][a-z]+ \d{4}$", date.strip()): return dt.datetime.strptime(date, "%d %B %Y").date() else: click.echo(click.style(f"Unrecognised date: {date}", fg="red"))
def interactive_loop_add_point_of_interest(self): CHOICE_CANCEL = "CANCEL" choice = "" while choice != "Back": point_of_interest = inquirer.text( message="Enter the name of the point of interest to add") # Query for the point of interest gm_results = self.gm.places(query=point_of_interest, type="point_of_interest") # Let user choose which point of interest to add choice = inquirer.list_input( "Please choose which point of interest to add", choices=[(result["name"], result["place_id"]) for result in gm_results["results"]] + [("Cancel", CHOICE_CANCEL)]) if choice == CHOICE_CANCEL: break # Build Google Maps URL url = "https://www.google.com/maps/search/?{}" params = { "api": "1", "query": point_of_interest, "query_place_id": choice, } self.logger.debug(u" > Google Maps URL: {}".format( url.format(urllib.urlencode(params)))) # Navigate with Firefox and try to add self.marionette.add_feature_2(url.format(urllib.urlencode(params)), self.list_add) # Wait for user input choice = inquirer.list_input( "Please choose an action", choices=["Add another point of interest", "Back"])
def interactive_loop_add_city(self): CHOICE_CANCEL = "CANCEL" choice = "" while choice != "Back": city = inquirer.text(message="Enter the name of the city to add") # Query for city gm_results = self.gm.places_autocomplete(input_text=city, types="(cities)") # Let user choose which city to add choice = inquirer.list_input( "Please choose which city to add", choices=[(result["description"], result["place_id"]) for result in gm_results] + [("Cancel", CHOICE_CANCEL)]) if choice == CHOICE_CANCEL: break # Build Google Maps URL url = "https://www.google.com/maps/search/?{}" params = { "api": "1", "query": city, "query_place_id": choice, } self.logger.debug(u" > Google Maps URL: {}".format( url.format(urllib.urlencode(params)))) # Navigate with Firefox and try to add self.marionette.add_feature_2(url.format(urllib.urlencode(params)), self.list_add) # Wait for user input choice = inquirer.list_input("Please choose an action", choices=["Add another city", "Back"])
def setup(): username = inquirer.text(message="What's your username") password = inquirer.password(message="What's your password") otc_secret = inquirer.password(message="What's your 2FA secret?") session = get_session(username, password, otc_secret) if session is None: print("Invalid login credentials") return config_file = inquirer.shortcuts.path(message="Specify config file", path_type=Path.FILE) output_directory = inquirer.shortcuts.path( message="Specify output directory", path_type=Path.DIRECTORY) brightspace_api = BrightspaceAPI(username, password) courses = get_courses_list(brightspace_api) selected_courses = inquirer.checkbox( message="Select courses to sync (press enter when ready)", choices=courses) course_ids = [courses[course] for course in selected_courses] with open(config_file, "w+") as f: f.write( json.dumps( { "output_directory": output_directory, "courses": course_ids, "credentials": { "username": username, "password": password, "otc_secret": otc_secret } }, indent=4)) print("Setup complete!")
def get_book_from_input(): questions = [ inquirer.Text("title", message="What’s the title of the book?"), inquirer.Text("author", message="Who’s the author?"), inquirer.Text("publication_year", message="When was it published?"), inquirer.Text("cover_image_url", message="What’s the cover URL?"), inquirer.Text("isbn10", message="Do you know the ISBN-10?"), inquirer.Text("isbn13", message="Do you know the ISBN-13?"), inquirer.Text("source", message="Do you have a source link?"), inquirer.List( "series", message="Is this book part of a series?", choices=[("Yes", True), ("No", False)], default=False, carousel=True, ), ] answers = inquirer.prompt(questions) if answers["series"]: series_questions = [ inquirer.Text("series", message="Which series does this book belong to?"), inquirer.Text( "series_position", message="Which position does the book have in its series?", ), ] answers = {**answers, **inquirer.prompt(series_questions)} else: answers.pop("series") page_method = inquirer.list_input( message="Do you know the length in pages or in words?", choices=[("Pages", "pages"), ("Words", "words")], default="words" if answers.get("source") else "pages", carousel=True, ) if page_method == "pages": answers["pages"] = inquirer.text(message="Page count") else: answers["pages"] = int(int(inquirer.text(message="Word count")) / 300) return answers
def ask_time(): return inquirer.text( message="Register Time 24hr (format: 13:10:10)", validate=lambda _, time_: int(time_.split(':')[0]) > 0 and int(time_.split(':')[0]) < 24\ and int(time_.split(':')[1]) >= 0 and int(time_.split(':')[1]) < 60\ and int(time_.split(':')[2]) >= 0 and int(time_.split(':')[2]) < 60\ and (datetime(datetime.now().year, datetime.now().month, datetime.now().day, int(time_.split(':')[0]), int(time_.split(':')[1]), int(time_.split(':')[2], 0)) - datetime.now()).seconds > 0 )
def create_label(existing_labels: Set[str]) -> Optional[str]: new_label = inquirer.text( message="New label name (enter CANCEL to select an existing label)", render=INQUIRER_RENDER) if new_label == 'CANCEL': # Return nothing to cancel return None if not new_label or new_label in existing_labels or new_label == CREATE_LABEL: print(f'Error: new label "{new_label}" is invalid, ' f'it may already exist or be reserved, please try again') return create_label(existing_labels) return new_label
def menu(con, foundUser, password): """ The internal menu after the user logs in. The user can choose to see, add or delete passwords. :param con, foundUser, password: db connection, the logged in user, their password :return: None """ q = [ inquirer.List( 'commands', message='What are you interested in?', choices=[ 'see all passwords', 'add a new password', 'delete a password', 'quit' ], ) ] while (True): print("\n") a = inquirer.prompt(q) if a['commands'] == 'see all passwords': dal.get_all_passwords(con, foundUser['id'], password) elif a['commands'] == 'add a new password': site = inquirer.text(message="Enter the name of the website") foundSite = dal.get_site(con, foundUser['id'], site) if (foundSite != None): print("You have already created a password for this website") else: user = inquirer.text(message="Enter username/email") new = dal.add_password(con, site, user, foundUser['id'], password) print("\n", new) elif a['commands'] == 'delete a password': dal.get_all_passwords(con, foundUser['id'], password) to_delete = inquirer.text(message="Enter password id") dal.delete_pass(con, to_delete) elif a['commands'] == 'quit': break
def send_email(cls, current_user, contacts_dict, groups_dict): to = ManageContacts.select_contact(contacts_dict) subject = inquirer.text(message="Enter email subject") message_text = FollowUp.get_email_contents() os.system('clear') print(f"\nSubject: {subject}\n\n{message_text}\n") message = "Are you sure you want to send?" send = inquirer.confirm(message, default=False) if send: EmailSetup.send_message( EmailSetup.create_message(to['email'], subject, message_text), current_user) FollowUp.set_dates(to, groups_dict) else: print("Message deleted.")
def get_review_from_user(auth=None): review = None while not review: original_search = inquirer.text(message="What's the book called?") search = original_search.strip().lower().replace(" ", "-") files = list(glob.glob(f"src/**/*{search}*.md")) + list( glob.glob(f"src/reviews/**/*{search}*.md")) if len(files) == 0: click.echo(click.style("No book like that was found.", fg="red")) progress = inquirer.list_input( "Do you want to add it as new book instead, or continue searching?", choices=[("New book", "new"), ("Continue", "continue")], ) if progress == "new": return create_book(auth=auth, search_term=original_search) continue reviews = [Review(path=path) for path in files] options = [( f"{review.metadata['book']['title']} by {review.metadata['book']['author']} ({review.entry_type})", review, ) for review in reviews] options += [ ("Try a different search", "again"), ("Add a new book instead", "new"), ] choice = inquirer.list_input( f"Found {len(reviews)} books. Which one's yours?", choices=options, carousel=True, ) if choice == "new": return create_book(auth=auth, search_term=original_search) if choice == "again": continue return choice return get_review_from_user(auth=auth)
import inquirer from inquirer import errors """ Creates a database connection if it does not exist """ database = "./database.db" con = setup.create_connection(database) """ Checks if the user has an account, if not it promts them to create one """ login = inquirer.confirm(message= "Do you have an account", default=True) if (login): pass else: username = inquirer.text(message="Enter your username") foundUsername = dal.get_user(con,username) if(foundUsername != None): print("The username is already taken") else: email = inquirer.text( message="Enter your email") pwd = getpass.getpass() dal.add_user(con,username,email,pwd.encode()) """ Login into user's account and display the internal menu """ print("Login") username = inquirer.text(message="Enter your username") foundUser = dal.get_user(con,username) password = getpass.getpass()
def ask_filename(): return inquirer.text( message="File name", default="pcc_semester.html", )
def new(ctx): while True: taskname = inquirer.text(message='task') taskobj = ctx.obj['API'].new_task({'name': taskname}) print(taskobj.export())
def interactive_loop_make_a_guess(self): name = inquirer.text(message="Enter game name") self.sub_interactive_loop_make_a_guess(name)
import os import sys sys.path.append(os.path.realpath('.')) import inquirer # flake8: noqa text = inquirer.text(message="Enter your username") print(text) password = inquirer.password(message='Please enter your password'), print(password) checkbox = inquirer.checkbox(message='Please define your type of project?', choices=['common', 'backend', 'frontend']) print(checkbox) choice = inquirer.list_input("Public or private?", choices=['public', 'private']) print(choice) correct = inquirer.confirm("This will delete all your current labels and " "create a new ones. Continue?", default=False) print(correct)
def ask_crn(): return inquirer.text(message="CRNs up to 10 (format: 12345 23456 34567)", validate=lambda _, crns: len(crns.split(',')) <= 10 and\ all(True == y for y in [len(x.strip()) == 5 for x in crns.split()]) )
] answers = inquirer.prompt(questions) predict = [] for i in data["data"]: if (answers["college"].lower() in i["college"].lower() and i["quota"] in answers["quota"] and i["category"] in answers["category"] and i["seat_pool"] in answers["seat_pool"] and answers["streams"].lower() in i["stream"].lower() and i["closing_rank"] >= int(answers["rank"])): predict.append(i) if not predict: inquirer.text(message="Done. Press Enter to exit. ") exit() predict.sort(key=lambda x: x["closing_rank"]) for i in predict: print(f"""---------------------------------------------------------- Name: {i["college"]} Stream: {i["stream"]} Round: {i["round"]} Quota: {i["quota"]} Category: {i["category"]} Seat Pool: {i["seat_pool"]} Opening Rank: {i["opening_rank"]} Closing Rank: {i["closing_rank"]} """)
import os import sys sys.path.append(os.path.realpath(".")) import inquirer # noqa text = inquirer.text(message="Enter your username") print(text) password = (inquirer.password(message="Please enter your password"),) print(password) checkbox = inquirer.checkbox(message="Please define your type of project?", choices=["common", "backend", "frontend"]) print(checkbox) choice = inquirer.list_input("Public or private?", choices=["public", "private"]) print(choice) correct = inquirer.confirm( "This will delete all your current labels and " "create a new ones. Continue?", default=False ) print(correct)
] answers = inquirer.prompt(questions) predict = [] for i in data["data"]: if (answers["college"].lower() in i["college"].lower() and i["quota"] in answers["quota"] and i["category"] in answers["category"] and i["seat_pool"] in answers["seat_pool"] and answers["streams"].lower() in i["stream"].lower() and i["closing_rank"] >= int(answers["rank"])): predict.append(i) if not predict: inquirer.text( message="No college found as per your details. Press enter to exit. ") exit() predict.sort(key=lambda x: x["closing_rank"]) text = "" for i in predict: text += f"""---------------------------------------------------------- Name: {i["college"]} Stream: {i["stream"]} Round: {i["round"]} Quota: {i["quota"]} Category: {i["category"]} Seat Pool: {i["seat_pool"]} Opening Rank: {i["opening_rank"]} Closing Rank: {i["closing_rank"]}