def auth(session, is_admin=False): """ Input: Session (SQLAlchemy), is_admin(role) Output: return True if auth is successcul else False. """ # Promt user for username username = input_dialog(title='Authentication', text='Please type your username:'******'Authentication', text='Please type your password:'******'admin' db_password = '******' else: pass except Exception as e: return False return (db_username == username) and (db_password == password)
def collect_credentials(self) -> Tuple[str, str, str]: instance_url = input_dialog( title="Instance URL", text= "Please enter your Jira instance URL (e.g. 'https://mycompany.jira.com/'):", ).run() if not instance_url: raise UserError("Cancelled") username = input_dialog( title="Username", text= ("Please enter your Jira username: \n\n(for Jira Cloud instances, you may need to generate a new API token to use as a password at https://id.atlassian.com/manage-profile/security/api-tokens)" ), ).run() if not username: raise UserError("Cancelled") password = input_dialog( title="Password", text=f"Please enter the password for {username}: ", password=True, ).run() if not password: raise UserError("Cancelled") return instance_url, username, password
def choose_category_synonym(item, hypernims, **kwargs): synonym = radiolist_dialog( values=make_labels(hypernims), title="Hypernims without category found", text= f"Which hypernim is synonymous with a category for the item '{item}'?", ).run() if not synonym: return known_categories = storage.get_known_categories() category = radiolist_dialog( values=make_labels(sorted(known_categories)), title=f"Choose category for '{synonym}'", text=f"Which category is '{synonym}' synonymous with?", ).run() if not category: category = input_dialog( title=f"Add a new category synonymous with '{synonym}'", ).run() if not category: category = input_dialog( title="Unknown category", text=f"What is the category for synonym '{item}'", ).run() if category: storage.add_category_synonym(synonym, category) return category
def main(): if len(sys.argv) < 2: while len(ApplicationState.current_path) < 1: filename = input_dialog( title='Open or create a file.', text='Please enter file name:', ).run() ApplicationState.current_path = format_filename(filename) else: ApplicationState.current_path = format_filename(sys.argv[1]) while len(ApplicationState.user) < 1: ApplicationState.user = input_dialog( title='User', text='Please type your user name:', ).run() while len(ApplicationState.password) < 8: ApplicationState.password = input_dialog( title='Password', text='Password must be longer than 8 characters\nPlease type your password:', password=True, ).run() do_open_file(ApplicationState.current_path) APPLICATION.run()
def update_items(args): if len(args) == 0: raise ArgumentError("No arguments given!") else: if args[0] == "clear": from dsres.resources import clear_mod_items clear_mod_items(DarkSouls.ITEM_CATEGORIES) nest_reset() elif args[0] == "remove": from dsres.resources import remove_mod_item try: remove_mod_item(args[1]) nest_remove(args[1]) except IndexError: raise ArgumentError("Item name not specified!") elif args[0] == "list": from dsres.resources import read_mod_items print(Fore.LIGHTBLUE_EX + "\n\tID\t\tName" + Fore.LIGHTYELLOW_EX) for item in read_mod_items(): item = item.split() if len(item) == 4: print("\t%s\t\t%s" % (item[0], DarkSouls.get_name_from_arg(item[3]))) print(Fore.RESET) elif args[0] == "add": from dsres.resources import create_mod_files create_mod_files(DarkSouls.ITEM_CATEGORIES) category = radiolist_dialog( title="Select item category", text="Category of the new item:", values=[(cat, cat.upper()) for cat in DarkSouls.ITEM_CATEGORIES.keys()] ).run() if category is None: return False item_id = input_dialog( title="Enter item ID", text="Item ID for the new %s:" % category ).run() if item_id is None or not item_id.strip(): return False item_name = input_dialog( title="Enter item name", text="Name of the new %s:" % category ).run() if not item_name.strip(): return False from dsres.resources import write_mod_item formatted_name = "-".join(item_name.lower().split()) try: if write_mod_item(category, formatted_name, int(item_id)): print(Fore.GREEN + ("%s '%s' (ID: %s) added successfully" % ( category.title(), item_name.title(), item_id)) + Fore.RESET) nest_add([formatted_name]) return True return False except ValueError: raise ArgumentError("Can't convert %s '%s' to int!" % (type(item_id).__name__, item_id)) else: raise ArgumentError("Unknown argument: %s" % args[0]) return True
def get_input_value(title, text): """ Handle input by user """ value = input_dialog(title, text) if not value: # if user decides to cancel if not quit_prompt(): # show the input dialogue again if user doesn't want to quit return input_dialog(title, text) # in case user wants to cancel raise SwiggyCliQuitError("No input provided by user") # raw value entered by user return value
def login(self, username=u'', password=u''): self._account['username'] = username or input_dialog( title=u"Account - Username", text=u"Input your username:"******"Account - Password", text=u"Input your password:", password=True) if not self._account['password']: return self._login(**self._account)
def start(): TERMINAL_SIZE = gts.get_terminal_size()[0] pwd = input_dialog(title='LOGIN', text='Please enter the password for the mail-client:', password=True) working = False if not pwd or len(pwd) <= 1: sys.exit() while not working: try: encryption.decrypt(pwd) working = True except: pwd = input_dialog( title='LOGIN', text='Your password was incorrect! Please try again:', password=True) working = False if not pwd or len(pwd) <= 1: sys.exit() os.system('clear') functions.makeMenu(TERMINAL_SIZE=TERMINAL_SIZE) select = input("> ") while select not in "qQ": if select in "sS": sendTUI(pwd=pwd) os.system('clear') elif select in "lL": showMails(pwd=pwd) os.system('clear') elif select in "uU": updateCredentials(pwd) os.system('clear') elif select in "rR": rainbow.main() os.system('clear') elif select in "aA": addressBookTUI() os.system('clear') else: functions.printInRed("I can't understand this") TERMINAL_SIZE = gts.get_terminal_size()[0] functions.makeMenu(TERMINAL_SIZE=TERMINAL_SIZE) select = input("> ") os.system('clear') functions.printInBlue("#" * TERMINAL_SIZE) functions.printInBlue("#{0:^{1}}#".format("Goodbye!", TERMINAL_SIZE - 2)) functions.printInBlue("#" * TERMINAL_SIZE)
def main(): result = input_dialog( title='Password dialog example', text='Please type your password:'******'Result = {}'.format(result))
def create_mode(self): """Create a mode.""" mode_name = input_dialog(title='Mode', text='Cool, got a name for your mode?', style=self.example_style).run() # create mode folder mode_path = os.path.join(self.machine_path, "modes", mode_name) if not os.path.exists(mode_path): self.create_mode_structure(mode_name, mode_path, self.machine_path) message_dialog( title='Mode', text=HTML( '''<style fg="green">Success:</style> Created mode {}. \nDon\'t forget to add it to your mode list.'''.format( mode_name)), style=self.example_style).run() else: message_dialog( title='Mode', text=HTML( '<style fg="red">Error:</style> A mode with this name exists already\nPlease pick another one' ), style=self.example_style).run() self.create_mode()
def create_machine_config(self): """Create a machine config.""" config_name = input_dialog( title='Machine Config', text='Please enter the name of your machine config:', style=self.example_style).run() if config_name is None: sys.exit() # create machine_config folder self.machine_path = os.path.join(self.current_path, config_name) if not os.path.exists(self.machine_path): self.create_machine_config_structure(config_name, self.machine_path) self.current_path = self.machine_path message_dialog( title='Mode', text=HTML( '''<style fg="green">Success:</style> Created machine config {}. \nYou can now create modes and shows.'''.format( config_name)), style=self.example_style).run() else: message_dialog( title='Mode', text=HTML( '''<style fg="red">Error:</style> A machine config with this name exists already \nPlease pick another one')'''), style=self.example_style).run() self._create_machine_config()
def create_show(self): """Create a show.""" show_name = input_dialog(title='Mode', text='Cool, got a name for your show?', style=self.example_style).run() # create shows folder show_path = os.path.normpath( os.path.join(self.machine_path, "shows", show_name)) shows_dir = os.path.normpath(os.path.join(self.machine_path, "shows")) if not os.path.exists(show_path): if self.in_machine_folder(): self.create_show_structure(show_name, shows_dir, self.machine_path) message_dialog( title='Shows', text=HTML( '<style fg="green">Success:</style> Created show {}.'. format(show_name)), # text='Success: Created machine config {}.'.format(config_name), style=self.example_style).run() else: self.show_not_in_machine_folder_dialog() else: message_dialog( title='Mode', text=HTML( '<style fg="red">Error:</style> A show with this name already exists\nPlease pick another one!' ), style=self.example_style).run() self._create_machine_config()
def login_prompt(secrets_manager_cls: Type[BaseSecretsManager], style: Style): err_msg = None secrets_manager = None if Security.new_password_required() and legacy_confs_exist(): secrets_manager = migrate_configs_prompt(secrets_manager_cls, style) if Security.new_password_required(): show_welcome(style) password = input_dialog(title="Set Password", text=""" Create a password to protect your sensitive data. This password is not shared with us nor with anyone else, so please store it securely. If you have used hummingbot before and already have secure configs stored, input your previous password in this prompt. The next step will automatically migrate your existing configs. Enter your new password:""", password=True, style=style).run() if password is None: return None re_password = input_dialog(title="Set Password", text="Please re-enter your password:"******"Passwords entered do not match, please try again." else: secrets_manager = secrets_manager_cls(password) store_password_verification(secrets_manager) migrate_non_secure_only_prompt(style) else: password = input_dialog(title="Welcome back to Hummingbot", text="Enter your password:"******"Invalid password - please try again." if err_msg is not None: message_dialog(title='Error', text=err_msg, style=style).run() return login_prompt(secrets_manager_cls, style) return secrets_manager
def pwd_dialog(title='', text=''): return input_dialog( title=title, text=text, password=True, ok_text='Ok', cancel_text='Annuler', )
def main(): result = input_dialog( title="Password dialog example", text="Please type your password:"******"Result = {}".format(result))
def gui() -> Tuple[str, int, str, str, str, str, str]: ip = input_dialog(title='Catalog IP', text='Please type catalog IP:').run() port = int( input_dialog(title='Catalog PORT', text='Please type catalog PORT:').run()) user_id = input_dialog(title='UserID', text='Please type UserID:', password=True).run() name = input_dialog( title='Name', text='Please type user Name:', ).run() surname = input_dialog( title='Surname', text='Please type user Surname:', ).run() work_email = input_dialog( title='Work Email', text='Please type Work email:', ).run() personal_email = input_dialog( title='Personal Email', text='Please type Personal email:', ).run() return ip, port, user_id, name, surname, work_email, personal_email
def prompt_pixel_size(): from prompt_toolkit.shortcuts import input_dialog value = input_dialog( title="Invalid pixel size", text="Please provide the effective pixel size (um):").run() dx = float(value) return dx
def login_prompt(): from hummingbot.client.config.security import Security err_msg = None if Security.new_password_required(): show_welcome() password = input_dialog( title="Set Password", text="Create a password to protect your sensitive data. " "This password is not shared with us nor with anyone else, so please store it securely." "\n\nEnter your new password:"******"Set Password", text="Please re-enter your password:"******"Passwords entered do not match, please try again." else: Security.login(password) else: password = input_dialog( title="Welcome back to Hummingbot", text="Enter your password:"******"Invalid password - please try again." if err_msg is not None: message_dialog( title='Error', text=err_msg, style=dialog_style).run() return login_prompt() return True
def _run (): with patch_stdout(): application = input_dialog( title = title, text = text, completer = PathCompleter() ) with application.input.raw_mode(): application.input.read_keys() application.layout.current_control.buffer.insert_text(default_value or "") return application.run_async()
def path_dialog() -> input_dialog: """ Displays a dialog for the user to input the directory containing the thermal images :return: @author Conor Brosnan <*****@*****.**> """ return input_dialog( title="File or Directory Path", text="Input file or directory path: ", ).run()
def stu_auth(session, is_stu=False): """ Input: Session (SQLAlchemy), is_stu(role) Output: return True if auth is successcul else False. """ # Promt user for username username = input_dialog( title='Authentication', text='Please type your username(Roll Number):').run() # Promt user for password password = input_dialog(title='Authentication', text='Please type your password:', password=True).run() status = (Auth.is_auth_successful(session, username, password), username) return status
def get_input(msg, title=None): if not title: _title = "Please provide input." else: _title = title in_dialog = input_dialog(title=_title, text=msg).run() return in_dialog
def main(): setup_method = radiolist_dialog( values=[ (0, 'Quick Setup (recommended)'), # automatic setup (1, 'Ultra Setup (no questions)'), # automatic setup, file mode (2, 'Manual (not recommended)') # classic setup ], title='Welcome to JMK OS', text='How would you like to setup JMK OS?') if setup_method == 0: # UINFO variables new_password = "" new_2_password = "" pass_loop = True new_username = "" # ask for username and password new_username = input_dialog(title='Welcome to JMK OS', text='Please type a username to continue:') while pass_loop: new_password = input_dialog(title='Welcome to JMK OS', text='Please type a password:'******'Welcome to JMK OS', text='Confirm the password:'******'JMK OS 2.0', text='Invalid passwords given.', buttons=[('Retype', True)], ) elif setup_method == 1: os.system('cls' if os.name == 'nt' else 'clear') elif setup_method == 2: os.system('cls' if os.name == 'nt' else 'clear') else: os.system('cls' if os.name == 'nt' else 'clear') print("Error loading JMK Setup. You must reinstall JMK OS.")
def login_prompt(): from hummingbot.client.config.security import Security import time err_msg = None if Security.new_password_required(): show_welcome() password = input_dialog( title="Set Password", text="Create a password to protect your sensitive data. " "This password is not shared with us nor with anyone else, so please store it securely." "\n\nEnter your new password:"******"Set Password", text="Please re-enter your password:"******"Passwords entered do not match, please try again." else: Security.login(password) # encrypt current timestamp as a dummy to prevent promping for password if bot exits without connecting an exchange dummy = f"{time.time()}" Security.update_secure_config("default", dummy) else: password = input_dialog(title="Welcome back to Hummingbot", text="Enter your password:"******"Invalid password - please try again." if err_msg is not None: message_dialog(title='Error', text=err_msg, style=dialog_style).run() return login_prompt() return True
def select_keys_directory(network): # Prompt the user for a directory that contains keys he generated already for the selected # network valid_keys_directory = False entered_directory = None input_canceled = False while not valid_keys_directory: not_valid_msg = '' if entered_directory is not None: not_valid_msg = (''' <style bg="red" fg="black">Your last input was <b>not a valid keys directory</b>. Please make sure to enter a valid keys directory.</style>''') entered_directory = input_dialog(title='Keys directory', text=(HTML(f''' Please enter the directory in which we can find the keys you generated. It should include all the files that the eth2.0-deposit-cli tool created including: - deposit_data(...).json - keystore-(...).json When creating your keys offline or elsewhere, make sure you select the correct network: {network.capitalize()} * Press the tab key to switch between the controls below{not_valid_msg} '''))).run() if not entered_directory: input_canceled = True break tilde_index = entered_directory.find('~') if tilde_index != -1: entered_directory = entered_directory.replace( '~', str(Path.home()), 1) entered_directory = Path(entered_directory) if not entered_directory.is_dir(): continue generated_keys = search_for_generated_keys(entered_directory) if (generated_keys['deposit_data_path'] is not None and len(generated_keys['keystore_paths']) > 0): valid_keys_directory = True if input_canceled: return '' return entered_directory
def promote_input_dialog(text: str, default='', validator: Validator = None): try: text = input_dialog(title=TITLE, text=text, cancel_text="取消", ok_text="确定", validator=validator).run() print(text) if text == '' or text is None: text = default return text except: return default
def ask_flag(): flag_id = input_dialog(title="Enter a flag ID", text="Event flag to listen to:").run() if flag_id is None or not flag_id.strip(): raise ArgumentError("No flag ID specified!") if not flag_id.isnumeric(): raise ArgumentError("Can't convert %s '%s' to int!" % (type(flag_id).__name__, flag_id)) state = radiolist_dialog(title="Select flag state", text="Desired state of event flag %s" % flag_id, values=[(True, "ON"), (False, "OFF")]).run() if state is None: raise ArgumentError("No state specified!") return int(flag_id), state
def main(): client = Client(client_id="SHELL/UTILITY") client.connect(host=SERVICE_BROKER_PORT["ip"], port=SERVICE_BROKER_PORT["port"]) client.loop_start() chat_id = int( input_dialog( title='Chat ID', text='Please activate the bot on your phone:' ' https://t.me/SmartHome_IoTbot and type here your' ' telegram chat id .. to obtain it go to ' 'https://telegram.me/get_id_bot:').run() ) client.publish(topic=SERVICE_TOPIC, payload=json.dumps({"chat_id": chat_id})) client.loop_stop() client.disconnect()
def get_upgrade_value_armor_or_unique(item: DSRItem): is_unique = item.get_upgrade_type() == DSRItem.Upgrade.UNIQUE max_upgrade = 5 if is_unique else 10 upgrade = input_dialog( title="Enter upgrade value for %s" % DarkSouls.get_name_from_arg(item.get_name()), text="Item type: %s" % "Unique" if is_unique else "Armor" ).run() try: if int(upgrade) > max_upgrade or int(upgrade) < 0: print(Fore.RED + ("Can't upgrade %s to +%s" % ( "Unique" if is_unique else "Armor", upgrade)) + Fore.RESET) return None except ValueError: raise ArgumentError("Can't convert %s '%s' to int!" % (type(upgrade).__name__, upgrade)) return upgrade
def get_upgrade_value_pyro_flame(item: DSRItem): is_pyro_asc = item.get_upgrade_type() == DSRItem.Upgrade.PYRO_FLAME_ASCENDED max_upgrade = 5 if is_pyro_asc else 15 upgrade = input_dialog( title="Enter upgrade value for %s" % DarkSouls.get_name_from_arg(item.get_name()), text="Item type: %sPyromancy Flame" % "Ascended " if is_pyro_asc else "" ).run() try: if int(upgrade) > max_upgrade or int(upgrade) < 0: print(Fore.RED + ("Can't upgrade %sPyromancy Flame to +%s" % ( "Ascended " if is_pyro_asc else "", upgrade)) + Fore.RESET) return None except ValueError: raise ArgumentError("Can't convert %s '%s' to int!" % (type(upgrade).__name__, upgrade)) return upgrade
def __alert_stock_selecting(self): """输入需要告警的股票代码及价位(600685:价1,价n),多个股票代码以;间隔""" for se in self.__se_info: alert = '' while alert.strip() == '': alert = input_dialog( title="请输入需要告警的股票代码及价位,格式:600685:价1[,价n][;600685:价1[,价n]]", text=se.split(':')[0], ok_text="确认", cancel_text="返回", style=Style.from_dict({ "dialog.body": "bg:#a9cfd0", "dialog.body label": "#fd8bb6" })).run() else: self.__alert_price[se.split(':')[0]] = alert
def main(): lat = input_dialog(title='Latitude', text='Type latitude of library') lon = input_dialog(title='Longitude', text='Type longitude of library') city = input_dialog(title='Library City', text='Which city is the library in?') street = input_dialog(title='Address:Street', text='Street Name') doornumber = input_dialog(title='Address:Doornumber', text='Door number') postcode = input_dialog(title='Address:Postcode', text='PIN/Postcode') name = input_dialog(title='Library Name', text='What is the name of the library?') opening_hours = input_dialog(title='Library Timings', text='What are the library timings?') _library = Library( name=name, lat=lat, lon=lon, opening_hours=opening_hours, city=city, street=street, doornumber=doornumber, postcode=postcode, country='IN' ) _feature = _library.make_feature() FILE_EMPTY = True if os.stat(GEODATAFILE).st_size == 0 else False if not FILE_EMPTY: with open(GEODATAFILE, 'r') as _data: current = load(_data) _featureCollection = current['features'] _featureCollection.append(_feature) print("Total libraries: %d" % len(_featureCollection)) libraries = FeatureCollection(_featureCollection) else: libraries = FeatureCollection([_feature]) # Write data to file with open(GEODATAFILE, 'w+') as data: dump(libraries, data, indent=4, sort_keys=True)
def main(): result = input_dialog( title='Input dialog example', text='Please type your name:').run() print('Result = {}'.format(result))