def handle(self) -> None: instance_url = "" username = "" password = "" verify: Union[bool, str] = True while True: instance_url, username, password = self.collect_credentials() if self.options.disable_certificate_verification: verify = False disable_warnings() elif self.options.certificate: verify = self.options.certificate options: Dict[str, Any] = { "agile_rest_path": "agile", "server": instance_url, "verify": verify, } try: JIRA( options, basic_auth=(username, password), max_retries=0, ) break except JIRAError: result = yes_no_dialog( title="Error connecting to Jira", text=( "A connection to Jira could not be established using " "the credentials you provided; try again?"), ).run() if not result: raise UserError("Aborted; configuration not saved.") self.config.instances[self.options.instance_name] = InstanceDefinition( url=instance_url, username=username, verify=verify, ) self.save_config() store_password = yes_no_dialog( title="Save password?", text="Would you like to save this password to your system keyring?", ).run() if store_password: keyring.set_password(APP_NAME, instance_url + username, password)
def update_components(self, result): if super().update_components(result): return if result == "delete": if yes_no_dialog( "Confirm", "Are you sure you want to delete vm {}".format( self.vm["name"])): self.shell.client.delete_vm_by_id(self.vm['id']) super().update_components("..") elif result in ["start", "reboot", "pause", "resume", "stop"]: self.shell.client.vm_action(result, self.vm['id']) self.vm = self.shell.client.vm_action('get', self.vm['id']) elif result.startswith("createforward"): segments = result.split() if len(segments) not in [2, 3]: print( "Invalid call, usages:\n createforward [publicport] privateport" ) return for port in segments[1:]: if not port.isdigit(): print("Ports should be numbers") return if len(segments) == 2: privateport = int(segments[1]) publicport = None else: privateport = int(segments[2]) publicport = int(segments[1]) self.shell.client.create_forward( self.shell.components[3].cloudspace, self.vm['name'], publicport, privateport) elif result == "print": self.vm = self.shell.client.vm_action('get', self.vm['id']) print(yaml.safe_dump(self.vm, default_flow_style=False))
def prompt_write_archive(self): """ prompts to write the archive file """ result = yes_no_dialog( title='Action confirmation', text='Do you want to write the archive file?').run() if result: self.write_archive()
def exit(self): confirm = yes_no_dialog(title=u"Confirm Exit", text=u"Are you sure you want to exit?") if confirm: self._cleanup() sys.exit(_NO_ERROR)
def repl(self) -> None: while True: answer = self.eval() if answer == 'QUIT' and yes_no_dialog( title="Confirm exit", text="Are you sure you want to quit?", ): break
def load(self): if self.verbose: if self.colored: self.print_timestamp(f"{c.bold}Loading config...{c.end}") else: self.print_timestamp(f"Loading config...") try: self.config = json.load(open(self.CONFIG, encoding="utf-8")) type(self.config.keys()) except: if self.verbose: if self.colored: self.print_timestamp( f"{c.warning}Config is unavailable or protected.{c.end} {c.bold}Loading fallback...{c.end}" ) else: self.print_timestamp( f"Config is unavailable or protected. Loading fallback..." ) self.config = self.fallback if self.verbose: if self.colored: self.print_timestamp(f"{c.bold}Fallback loaded{c.end}") else: self.print_timestamp(f"Fallback loaded") try: result = yes_no_dialog( title="No config found !!!", text="Do you want to save new config ?").run() if result: if self.verbose: if self.colored: self.print_timestamp( f"{c.bold}Creating new config file:{c.end} {c.green}{self.CONFIG}{c.end}" ) else: self.print_timestamp( f"Creating new config file: {self.CONFIG}") self.save() except Exception as e: self.print_timestamp(traceback.format_exc()) if self.verbose: if self.colored: self.print_timestamp( f"{c.fail}Error writing config file, please check if you have permission to write in this location:{c.end} {c.bold}{self.CONFIG}{c.end}" ) else: self.print_timestamp( f"Error writing config file, please check if you have permission to write in this location: {self.CONFIG}" ) return if self.verbose: if self.colored: self.print_timestamp(f"{c.bold}Config loaded{c.end}") else: self.print_timestamp(f"Config loaded")
def write_archive(self): """ writes out the stripped archive """ self.archive_written = True if self.filetype == 'tar': destination_file = self.get_stripped_filename() if os.path.exists(destination_file): result = yes_no_dialog( title="Action confirmation", text= f"File exists: {destination_file}\nDo you want to overwrite it?" ).run() if not result: return False archive_command = [ 'tar', '--options', 'gzip:compression-level=9', '-czf', destination_file, # --exclude='*wp-content/uploads/2*' \ # --exclude '*backup*.tar.gz' \ # --exclude '*public_html/video/*' \ # --exclude '*.wpress' ] for filename in self.file_filters: archive_command += [ '--exclude', f"'{filename}'", ] archive_command.append(f"@{self.filename}") string_command = " ".join(archive_command) logger.warning(f"I'm running this:") logger.warning(string_command) start_time = time() old_file_size = self.get_file_size() logger.info("Running tar command...") subprocess.run(" ".join(archive_command), shell=True) #logger.info("Done!") new_file_size = human_file_size(os.path.getsize(destination_file)) total_time = round(time() - start_time, 2) logger.info(f"") message_dialog( title='Archive munging complete', text= f"It took: {total_time} seconds.\nOld file size: {old_file_size}\nNew file size: {new_file_size}" ).run() else: raise NotImplementedError("Uh, not done yet!") self.move_stripped_over_original()
def yes_no_dialog(title, text): from prompt_toolkit.shortcuts import yes_no_dialog from prompt_toolkit.styles import Style example_style = Style.from_dict({ 'dialog': 'bg:#88ff88', 'dialog frame-label': 'bg:#ffffff #000000', 'dialog.body': 'bg:#000000 #00ff00', 'dialog shadow': 'bg:#00aa00', }) return yes_no_dialog(title=title, text=text, style=example_style)
def metadata_dialog() -> yes_no_dialog: """ Displays a dialog for the user to specify whether they would like metadata from the original images copied to the new ones :return: @author Conor Brosnan <*****@*****.**> """ return yes_no_dialog( title="Metadata", text= "Do you want all of the metadata from the original images copied to the new ones?", ).run()
def main(): parser = argparse.ArgumentParser() parser.add_argument("--db", default="data/grocery.db") args = parser.parse_args() conn = sqlite3.connect(args.db) for item in get_all(conn): buy = yes_no_dialog(title="Are u gonna buy it? 🎶", text=f"{item[1]} {item[2]} of {item[3]}?").run() if buy: buy_item(conn, item[0]) else: skip_item(conn, item[0])
def get_checklist(): # TODO: get user's trello card matching ID card = get_card() card_prompt_result = yes_no_dialog( title="Card found", text=f"Is '{card.name}' (from {card.dateLastActivity}) the right card?", ).run() if not card_prompt_result: return items = get_checklist_items(card) print(*items, sep="\n") return items
def emptyline(self): try: if self.xlk == None: try: from pyocd.probe import aggregator from pyocd.coresight import dap, ap, cortex_m daplinks = aggregator.DebugProbeAggregator.get_all_connected_probes( ) except Exception as e: daplinks = [] if daplinks and os.path.isfile(self.dllpath): use_dap = yes_no_dialog( title='J-Link or DAPLink', text=f'Do you want to use {daplinks[0].product_name}?' ).run() elif os.path.isfile(self.dllpath): use_dap = False elif daplinks: use_dap = True else: raise Exception('No link found') if use_dap: daplink = daplinks[0] daplink.open() _dp = dap.DebugPort(daplink, None) _dp.init() _dp.power_up_debug() _ap = ap.AHB_AP(_dp, 0) _ap.init() self.xlk = xlink.XLink(cortex_m.CortexM(None, _ap)) else: self.xlk = xlink.XLink( jlink.JLink(self.dllpath, self.mcucore)) else: self.xlk.close() self.xlk.open(self.mcucore) print(f'CPU core is {self.xlk.read_core_type()}\n') except Exception as e: print('connection fail\n') self.xlk = None
def cli(): try: wn.synsets("test") except LookupError: if not yes_no_dialog( title="NLTK WordNet dataset is missing", text="Would you like to download it?", ).run(): click.echo("NLTK Wordnet is required to run Hyper Shopping") return import nltk nltk.download("wordnet")
def update_components(self, result): if super().update_components(result): return if result == "print": self.forwards = self.shell.client.list_forwards(self.cloudspace) self.shell.client.print_forwards(self.cloudspace, self.forwards) elif result.startswith("delete "): pubport = result.split()[-1] if pubport.isdigit(): if yes_no_dialog( "Confirm", "Are you sure you want to delete forward {}".format( pubport)): self.shell.client.delete_forward(self.cloudspace, int(pubport))
def update_components(self, result): if super().update_components(result): return if result == "delete": if yes_no_dialog( "Confirm", "Are you sure you want to delete cloudspace {}".format( self.cloudspace["name"])): self.shell.client.delete_cloudspace(self.cloudspace) super().update_components("..") elif result == "vm": vmcom = VMListComponent(self.shell, self.cloudspace) self.shell.components.append(vmcom) elif result == "forwards": fwcom = ForwardListCompontent(self.shell, self.cloudspace) self.shell.components.append(fwcom)
def _delete_handler(self, event): if row := self._focused_row(): def handler(sure): if sure: with self.context.get_client() as c: c.call(f"{self.service}.delete", row[self.primary_key]) return self.__class__(self.context) event.app.exit( AppResult( app=yes_no_dialog( f"Delete {self.item_name}", f"Are you sure want to delete {self.item_name} {row[self.item_title_key]!r}?" ), app_result_handler=handler, ))
def load_configuration(): """ Load or load and configure BetaLibrary's project directory """ if not cli_configured(CONFIG_FILE): configuration = yes_no_dialog( title='Configuration', text="BetaLibrary's path is not configured. Configure now?") text = input_dialog(title='Configuration', text="Please enter BetaLibrary's path: ") if text: with open("config.txt", 'w', encoding='utf-8') as f: f.write(text) return text else: with open("config.txt", 'r', encoding='utf-8') as f: return f.read()
def __se_is_selected(self): """判断交易所是否已选择""" if self.__se_info: # 非空 selected_se = '' for el in self.__se_info: selected_se += el.split(':')[0] + ' ' self.__se_selected = yes_no_dialog(title="确认", text="你选中了: " + selected_se, yes_text="确认", no_text="返回").run() if not self.__se_selected: # 选择了返回,则回到交易所选择界面 self.interactive_start() else: self.__alert_stock_selecting() else: # 空 message_dialog(title='提示', text='尚未选中交易所信息!').run() self.interactive_start()
def get_items_from_checklists(): """ Fetch shopping card checklists and try to place the items in their related shopping categories, using a combination of nltk wordnet search as well manual choices to disambiguate. """ checklist = get_checklist() if checklist: print(*checklist, sep="\n") return should_create_card = yes_no_dialog( title="Card not found", text=f"Shall we create a new shopping card?", ).run() print(should_create_card) if not should_create_card: return create_shopping_card()
def create_shopping_card(): items = [] result = "" while result is not None: result = input_dialog( title="Add shopping item", ok_text="Add more", cancel_text="Finished", ).run() if result: items.append(result) print(items) item_list = "\n".join(items) response = yes_no_dialog( title="Done?", text=(f"You've entered the following items: " f"\n{item_list}\n would you like to " f"create the card?"), ).run()
def move_stripped_over_original(self): """ moves the *-stripped* file over the original """ if os.path.exists(self.get_stripped_filename()): stripped_size = human_file_size( os.path.getsize(self.get_stripped_filename())) original_size = human_file_size(os.path.getsize(self.filename)) result = yes_no_dialog( title='Action confirmation', text=f"""Do you want to move the stripped file over the original? Stripped: ({stripped_size}) {self.get_stripped_filename()} Original: ({original_size}) {self.filename} """).run() if not result: return False logger.debug( f"Moving {self.get_stripped_filename()} to {self.filename}") os.rename(self.get_stripped_filename(), self.filename) self.__init__(self.filename) return True return False
def getInput(): print(Fore.YELLOW + " --- MAIN MENU ---") prompt = input( " Please Select: \n Trade (t)\n Position Report (p)\n Quote (q)\n Balance Report (b)\n View Working Orders (o)\n " ) ######### trading ############ if prompt == "t": os.system('cls') title() print(Fore.YELLOW + " --- Order Type Selection ---") type = input( " Please Select: \n Market Order (m)\n Limit Order (l) \n Stop (s) \n Cancel (c). " ) ######### stop ######### if type == "s": cmd = input( " Enter LIMIT trade command (ex: 's 1000 fb 210.5') or (c) to cancel: " ) if len(cmd.split()) != 4 and cmd != "c": print(" Invalid format, starting over...") getInput() if cmd == "c": os.system('cls') title() getInput() else: side, qty, symbol, stopPrice = cmd.split() if side == "b": printSide = "Buy" if side == "s": printSide = "Sell" confirmTrade = input( f" Confirm trade? [{printSide} {qty} shares of {symbol} at STOP PRICE: {stopPrice}] YES (y) or NO (n)" ) if confirmTrade == "y": if side == "b": cleanSide = "BUY" else: cleanSide = "SELL" cleanPrice = stopPrice # actually place the trade placeStopLimitTradeShares(symbol, cleanSide, cleanPrice, qty) getInput() else: os.system('cls') title() getInput() ######### limit type ######### if type == "l": print(Fore.YELLOW + " --- Quantity Options ---") whichType = input( " Please Select:\n Notional Quantity (n)\n Shares Quantity (s)\n Cancel (c) \n " ) if whichType == "n": print(Fore.YELLOW + " --- Trade Script ---") cmd = input( " Enter trade command, use $ notional value (ex: 'b 100000 fb 210.5') or (c) to cancel: " ) if len(cmd.split()) != 4 and cmd != "c": print(" Invalid format, starting over...") getInput() if cmd == "c": os.system('cls') title() getInput() else: side, qty, symbol, price = cmd.split() if side == "b": printSide = "Buying" if side == "s": printSide = "Selling" print(Fore.YELLOW + " --- Confirm ---") confirmTrade = yes_no_dialog( title='Confirm Trade', style=dialog_style, text= f" Confirm {printSide} {qty} $ worth of {symbol} at {price}" ).run() if confirmTrade == True: if side == "b": cleanSide = "BUY" else: cleanSide = "SELL" cleanOrderType = "LIMIT" cleanPrice = price # actually place the trade placeLimitTradeNotional(cleanOrderType, symbol, cleanSide, cleanPrice, qty) getInput() else: os.system('cls') title() getInput() if whichType == "s": cmd = input( " Enter trade command (ex: 'b 1000 fb 210.5') or (c) to cancel: " ) if len(cmd.split()) != 4 and cmd != "c": print(" Invalid format, starting over...") getInput() if cmd == "c": os.system('cls') title() getInput() else: side, qty, symbol, price = cmd.split() if side == "b": printSide = "Buying" if side == "s": printSide = "Selling" confirmTrade = yes_no_dialog( title='Confirm Trade', style=dialog_style, text= f" Confirm {printSide} {qty} shares of {symbol} at {price}" ).run() if confirmTrade == True: if side == "b": cleanSide = "BUY" else: cleanSide = "SELL" cleanOrderType = "LIMIT" cleanPrice = price # actually place the trade placeLimitTradeShares(cleanOrderType, symbol, cleanSide, cleanPrice, qty) getInput() else: os.system('cls') title() getInput() if whichType == "c": ######### cancel ############# os.system('cls') title() getInput() else: os.system('cls') title() print(" Unknown entry...") getInput() ######### market type ########### if type == "m": print(Fore.YELLOW + " --- Quantity Options ---") whichType = input( " Please Select:\n Notional Quantity (n)\n Shares Quantity (s)\n (c) Cancel\n " ) if whichType == "n": print(Fore.YELLOW + " --- Trade Script ---") cmd = input( " Enter trade command, use $ notional value (ex: 'b 100000 fb') or (c) to cancel: " ) if len(cmd.split()) != 3 and cmd != "c": print(" Invalid format, starting over...") getInput() if cmd == "c": os.system('cls') title() getInput() else: side, qty, symbol = cmd.split() if side == "b": printSide = "Buying" if side == "s": printSide = "Selling" confirmTrade = yes_no_dialog( title='Confirm Trade', style=dialog_style, text= f"Confirm {printSide} {qty} $ worth of {symbol} at the market?" ).run() if confirmTrade == True: if side == "b": cleanSide = "BUY" else: cleanSide = "SELL" cleanOrderType = "MARKET" # actually place the trade placeMarketTradeNotional(cleanOrderType, symbol, cleanSide, qty) getInput() else: os.system('cls') title() getInput() if cmd == "c": os.system('cls') title() getInput() if whichType == "s": print(Fore.YELLOW + " --- Trade Script ---") cmd = input( " Enter trade command (ex: 'b 1000 fb') or (c) to cancel: " ) if len(cmd.split()) != 3 and cmd != "c": print(" Invalid format, starting over...") getInput() if cmd == "c": os.system('cls') title() getInput() else: side, qty, symbol = cmd.split() if side == "b": printSide = "Buying" if side == "s": printSide = "Selling" confirmTrade = yes_no_dialog( title='Confirm Trade', style=dialog_style, text= f" Confirm {printSide} {qty} shares of {symbol} at the market" ).run() if confirmTrade == True: if side == "b": cleanSide = "BUY" else: cleanSide = "SELL" cleanOrderType = "MARKET" # actually place the trade placeMarketTradeShares(cleanOrderType, symbol, cleanSide, qty) getInput() else: os.system('cls') title() getInput() if cmd == "c": os.system('cls') title() getInput() if whichType == "c": ######### cancel ############# os.system('cls') title() getInput() else: print(" Unknown entry...") getInput() ######### cancel ############# if type == "c": os.system('cls') title() getInput() ######### view working orders ####### if prompt == "o": getOrders() ######### position report ######## if prompt == "p": positionReport() getInput() ######### quote ######## if prompt == "q": symbol = input(" Please enter symbol: ") getQuote(symbol) ######### balances report ######## if prompt == "b": balancesReport() else: os.system('cls') print("Unrecognized command. Try again..") getInput()
def main(): result = yes_no_dialog(title="Yes/No dialog example", text="Do you want to confirm?").run() print("Result = {}".format(result))
def yes_no(self, title, message) -> bool: ret = yes_no_dialog(title=title, text=message) print("User has chosen:", ret) return ret
from prompt_toolkit.shortcuts import message_dialog, yes_no_dialog response = yes_no_dialog( title='Tento program provedl neplatnou operaci', text= 'Nevíme, co se stalo, známe jen kód chyby:\n#12345678.ABCDEFFF\n\nProvést restart?', yes_text='Ano', no_text='Ne') message_dialog(title='Zadali jste volbu', text='Ano' if response else 'Ne')
from prompt_toolkit.shortcuts import message_dialog, input_dialog, yes_no_dialog message_dialog( title='Example dialog window', text='Do you want to continue?\nPress ENTER to quit.').run() text = input_dialog( title='Input dialog example', text='Please type your name:').run() print(text) result = yes_no_dialog( title='Yes/No dialog example', text='Do you want to confirm?').run() print(result)
from prompt_toolkit.shortcuts import message_dialog, yes_no_dialog response = yes_no_dialog( title="Software failure", text="Guru Meditation #12345678.ABCDEFFF\nRestart system?") message_dialog(title="Your choice", text="Yes" if response else "No")
def main(): result = yes_no_dialog( title='Yes/No dialog example', text='Do you want to confirm?').run() print('Result = {}'.format(result))
def main(): result = yes_no_dialog( title='Yes/No dialog example', text='Do you want to confirm?') print('Result = {}'.format(result))
def __call__(self): print_formatted_text( HTML('<seagreen>[*] Starting setup now...</seagreen>')) sleep(1) while True: message_dialog( title="Password Selection", text= "Create a strong password.\nAt least 1 number and 1 special character with a length of 16." ) passwd_1 = input_dialog(title='Password Selection', text='Enter Master Password', password=True) if passwd_1 == None: sys.exit() passwd_2 = input_dialog(title='Password Confirmation', text='Confirm Password', password=True) if passwd_2 == None: sys.exit() if passwd_1 == passwd_2: check = valid_pass(passwd_1) if check == True: break else: result = yes_no_dialog( title="Error!", text= "Your password was not strong enough.\nDo you want to try again?" ) if result == True: continue else: sys.exit() else: result = yes_no_dialog( title="Error!", text= "Your passwords didn't match.\n Do you want to try again?") if result == True: continue else: sys.exit() self.hash_pass(passwd_1) self.setup(passwd_1)
def warn_disable_npc(): return yes_no_dialog( title="Warning", text="This command will kill all NPCs in the area. Do you want to proceed?" ).run()