def run(): vi_mode_enabled = False # Create a set of key bindings that have Vi mode enabled if the # ``vi_mode_enabled`` is True.. manager = KeyBindingManager.for_prompt( enable_vi_mode=Condition(lambda cli: vi_mode_enabled)) # Add an additional key binding for toggling this flag. @manager.registry.add_binding(Keys.F4) def _(event): " Toggle between Emacs and Vi mode. " nonlocal vi_mode_enabled vi_mode_enabled = not vi_mode_enabled # Add a bottom toolbar to display the status. style = style_from_dict({ Token.Toolbar: 'reverse', }) def get_bottom_toolbar_tokens(cli): " Display the current input mode. " text = 'Vi' if vi_mode_enabled else 'Emacs' return [ (Token.Toolbar, ' [F4] %s ' % text) ] prompt('> ', key_bindings_registry=manager.registry, get_bottom_toolbar_tokens=get_bottom_toolbar_tokens, style=style)
def test_interactive(self, service_name): # get the contract contract = rpc.load_contract_file() interfaces = contract.interfaces log.info("Service has {} interface(s) - {}".format(len(interfaces), list(interfaces.keys()))) for i in contract.interfaces.values(): log.info("Interface '{}' has {} function(s):". format(i.name, len(i.functions))) for f in i.functions.values(): log.info("\t{}".format(rpc.render_signature(f))) while True: (iface, fname) = prompt('Enter Interface.Function to test: ').split('.') f = contract.interface(iface).function(fname) values = [prompt('Enter "{}" value for {}: '.format(p.type, p.name)) for p in f.params] eval_values = [json.loads(x) for x in values] if utils.VERBOSE: pp_values = highlight(json.dumps(eval_values, indent=4), JsonLexer(), Terminal256Formatter()) log.debug("Calling {} with {}".format(f.full_name, pp_values)) msg = { "service": service_name, "request": { "method": f.full_name, "params": eval_values } } self.call_service(msg)
def prompt_spec_exec_dict(run_dict: dict) -> dict: """ Prompt for the config of the spec exec runner. :param run_dict: run config dict (without the runner part) :return: runner config """ runner_dict = {} runner_dict["file"] = default_prompt("SPEC like result file to use: ", validator=TypeValidator(FileName()), completer=PathCompleter()) runner_dict["base_path"] = prompt("Property base path: ") runner_dict["path_regexp"] = prompt("Regexp matching the property path for each measured property: ", validator=NonEmptyValidator()) def get(sub_path: str = ""): # just a mock """ Get the value of the property with the given path. :param sub_path: given path relative to the base path :return: value of the property """ print("The python code is entered via a multiline input. ") print("Press [Meta+Enter] or [Esc] followed by [Enter] to accept input.") print("You can click with the mouse in order to select text.") print("Use the get(sub_path: str) -> str function to obtain a properties value.") locs = locals() runner_dict["code"] = prompt_python("The python is executed for each measured property: \n", lambda: {}, lambda: {"get": locs["get"]}) return runner_dict
def run(): # Create a `Registry` that contains the default key bindings. registry = load_key_bindings_for_prompt() # Add an additional key binding for toggling this flag. @registry.add_binding(Keys.F4) def _(event): " Toggle between Emacs and Vi mode. " if event.cli.editing_mode == EditingMode.VI: event.cli.editing_mode = EditingMode.EMACS else: event.cli.editing_mode = EditingMode.VI # Add a bottom toolbar to display the status. style = style_from_dict({ Token.Toolbar: 'reverse', }) def get_bottom_toolbar_tokens(cli): " Display the current input mode. " text = 'Vi' if cli.editing_mode == EditingMode.VI else 'Emacs' return [ (Token.Toolbar, ' [F4] %s ' % text) ] prompt('> ', key_bindings_registry=registry, get_bottom_toolbar_tokens=get_bottom_toolbar_tokens, style=style)
def start(self): print("PyBorg offline chat!") print("Type !quit to leave") default = getpass.getuser() print("[{}]".format(default)) self.name = prompt("What is your name? ") if self.name == "\n": self.name = default while 1: # body = prompt('> ', history=history, completer=self.completer) body = prompt('> ', history=history) if body == "": continue if body == "!quit": return # Pass message to borg if self.multiplexed: d = {"body": body, "reply_rate": 100, "learning": 1, "owner": 1} resp = requests.post("http://localhost:2001/process", data=d) if resp.status_code == requests.codes.ok: self.output(resp.text, None) else: logger.error(resp) else: self.pyborg.process_msg(self, body, 100, 1, (self.name), owner=1)
def main(): home = expanduser("~") git_history = FileHistory(home+'/.git-inter-cli-history') try: while True: text = prompt('$ git ', completer=cli_completer, style=cli_style,complete_while_typing=True, mouse_support=True,history=git_history, on_abort=AbortAction.RETRY) if text=='q': while True: text=prompt('$ ',style=cli_style) if text=='git': break status=subprocess.call(text, shell=True) elif text=='': currentBranchName=subprocess.check_output('git rev-parse --abbrev-ref HEAD', shell=True) currentPath=os.getcwd() print(currentPath.replace('\n','')+' ('+currentBranchName.replace('\n','')+')') continue else: status=subprocess.call("git " + text, shell=True) except EOFError: print('exit')
def select_service_and_operation(): service_names = Session().get_available_services() service_completer = WordCompleter(service_names) service_name = prompt(u'Select service: ', completer=service_completer) if service_name not in service_names: click.secho(u'{} is not valid service'.format(service_name), fg='red') raise click.Abort() moto_client = get_moto_implementation(service_name) real_client = boto3.client(service_name, region_name='us-east-1') implemented = [] not_implemented = [] operation_names = [xform_name(op) for op in real_client.meta.service_model.operation_names] for op in operation_names: if moto_client and op in dir(moto_client): implemented.append(op) else: not_implemented.append(op) operation_completer = WordCompleter(operation_names) click.echo('==Current Implementation Status==') for operation_name in operation_names: check = 'X' if operation_name in implemented else ' ' click.secho('[{}] {}'.format(check, operation_name)) click.echo('=================================') operation_name = prompt(u'Select Operation: ', completer=operation_completer) if operation_name not in operation_names: click.secho('{} is not valid operation'.format(operation_name), fg='red') raise click.Abort() if operation_name in implemented: click.secho('{} is already implemented'.format(operation_name), fg='red') raise click.Abort() return service_name, operation_name
def iter_nautilus(method): solution=None try: print("Preference elicitation options:") print("\t1 - Percentages") print("\t2 - Relative ranks") print("\t3 - Direct") pref_sel=int(prompt(u'Reference elicitation ',default=u"%s"%(1),validator=NumberValidator([1,3]))) except: pref_sel=1 PREFCLASSES=[PercentageSpecifictation,RelativeRanking,DirectSpecification] preference_class=PREFCLASSES[pref_sel-1] print("Nadir: %s"%method.problem.nadir) print("Ideal: %s"%method.problem.ideal) try: method.user_iters=method.current_iter=int(prompt(u'Ni: ',default=u"%s"%(method.current_iter),validator=NumberValidator())) except Exception,e: print e method.current_iter=method.user_iters=5
def iter_enautilus(method): try: method.user_iters=method.current_iter=int(prompt(u'Ni: ',default=u"%i"%method.current_iter,validator=NumberValidator())) method.Ns=int(prompt(u'Ns: ',default=u"5",validator=NumberValidator())) except: method.user_iters=5 method.Ns=5 print("Nadir: %s"%method.problem.nadir) print("Ideal: %s"%method.problem.ideal) method.nextIteration() points = None while method.current_iter: #method.printCurrentIteration() pref=select_iter(method,1) if pref in COMMANDS: break try: method.Ns=int(prompt(u'Ns: ',default=u"%s"%(method.Ns),validator=NumberValidator())) except: pass points=method.nextIteration(pref) if not method.current_iter: method.zh_prev=select_iter(method,1)[0] method.current_iter-=1 return points
def run(): # Create a set of key bindings that have Vi mode enabled if the # ``vi_mode_enabled`` is True.. manager = KeyBindingManager.for_prompt() # Add an additional key binding for toggling this flag. @manager.registry.add_binding(Keys.F4) def _(event): " Toggle between Emacs and Vi mode. " if event.cli.editing_mode == EditingMode.VI: event.cli.editing_mode = EditingMode.EMACS else: event.cli.editing_mode = EditingMode.VI # Add a bottom toolbar to display the status. style = style_from_dict({ Token.Toolbar: 'reverse', }) def get_bottom_toolbar_tokens(cli): " Display the current input mode. " text = 'Vi' if cli.editing_mode == EditingMode.VI else 'Emacs' return [ (Token.Toolbar, ' [F4] %s ' % text) ] prompt('> ', key_bindings_registry=manager.registry, get_bottom_toolbar_tokens=get_bottom_toolbar_tokens, style=style)
def prompt_generator(form_title, fields): if os.name == 'nt': os.system('cls') else: os.system('clear') print(form_title) data = {} for field in fields: if field['type'] == 'TitleSelectOne': print('{} : '.format(field['name'])) completer = WordCompleter(field['values'], ignore_case=True) for v in field['values']: print('- {}'.format(v)) text = None while text not in field['values']: text = prompt('Enter your choice : ', completer=completer) data[field['key']] = text elif field['type'] == 'TitleSelect': print('{} : '.format(field['name'])) completer = WordCompleter(field['values'], ignore_case=True) for v in field['values']: print('- {}'.format(v)) data[field['key']] = prompt( 'Enter your choice or create new : ', completer=completer) elif field['type'] == 'TitlePassword': data[field['key']] = prompt( '{} : '.format(field['name']), is_password=True) else: data[field['key']] = prompt('{} : '.format(field['name'])) print('------------------------------') return data
def _config(self): "Configure Pidgey" credentials = {} try: credentials = load_config('config/credentials.yaml') except: pass # Prompt for user credentials service = service_prompt() if service == 'ptc': service_name = 'Pokemon Trainer Club' else: service_name = 'Google' username = prompt('Please enter your %s username: '******'Please enter your %s password: '******'config/credentials.yaml', 'w') as yaml_file: yaml_file.write(yaml.dump(credentials, default_flow_style=False)) return credentials
def advanced_add_note(args): """ Add a new note by requesting user-defined creation date and tags interactively. """ # DATES dates = _last_days(1000) date_completer = WordCompleter(dates, sentence=True) try: date = prompt('date: ', completer=date_completer) except KeyboardInterrupt: print('poi: interrupted') return None # Next we'll check that the given date is in a right format: ok_format = False try: date = datetime.datetime.strptime(date, '%Y-%m-%d') except ValueError: pass except TypeError: pass else: ok_format = True try: date = datetime.datetime.strptime(date, '%Y-%m-%d %a') except ValueError: pass except TypeError: pass else: ok_format = True if not ok_format: print("poi: using today's date") date = datetime.date.today() # TAGS # TODO: generate the tag list below in a separate thread while the user # is working on data: tag_completer = WordCompleter(list(sorted(nm.count_tags().keys())), sentence=True) tags = [] while True: try: tag = prompt('tag {}: '.format(len(tags) + 1), completer=tag_completer) except KeyboardInterrupt: print('poi: interrupted') return None else: if tag: tags.append(tag) else: break # Create a note with the given date and tags: nm.add_note(date=date, tags=tags)
def main(): # Validate when pressing ENTER. text = prompt('Enter e-mail address: ', validator=validator, validate_while_typing=False) print('You said: %s' % text) # While typing text = prompt('Enter e-mail address: ', validator=validator, validate_while_typing=True) print('You said: %s' % text)
def do_export(self, arguments): item = get_arg(arguments) if item == 'wif': if not self.Wallet: return print("Please open a wallet") address = get_arg(arguments, 1) if not address: return print("Please specify an address") passwd = prompt("[wallet password]> ", is_password=True) if not self.Wallet.ValidatePassword(passwd): return print("Incorrect password") keys = self.Wallet.GetKeys() for key in keys: if key.GetAddress() == address: export = key.Export() print("WIF key export: %s" % export) return elif item == 'nep2': if not self.Wallet: return print("Please open a wallet") address = get_arg(arguments, 1) if not address: return print("Please specify an address") passwd = prompt("[wallet password]> ", is_password=True) if not self.Wallet.ValidatePassword(passwd): return print("Incorrect password") nep2_passwd1 = prompt("[key password]> ", is_password=True) if len(nep2_passwd1) < 10: return print("Please provide a password with at least 10 characters") nep2_passwd2 = prompt("[key password again]> ", is_password=True) if nep2_passwd1 != nep2_passwd2: return print("Passwords do not match") keys = self.Wallet.GetKeys() for key in keys: export = key.ExportNEP2(nep2_passwd1) print("NEP2 key export: %s" % export) return print("Command export %s not found" % item)
def file_upload(self, channel_name): os.system("clear") channel_id = self.find_channel_id(channel_name) fields = ["file", "content", "filename", "title", "initial_comment"] for i in fields: if i == "file": os.system("echo 'opening the file dialog. wait...' ") file = subprocess.check_output(['zenity', '--file-selection']) os.system("echo '\u001b[1m\u001b[31m file : \u001b[0m'" + file + "'") elif i == "content": content = raw_input("\u001b[1m\u001b[31m content : \u001b[0m") elif i == "filename": filename = raw_input("\u001b[1m\u001b[31m filename : \u001b[0m") elif i == "title": title = raw_input("\u001b[1m\u001b[31m title : \u001b[0m") else: initial_comment = prompt("add comment : ", completer=WordCompleter(users), style=DocumentStyle) url = "https://www.slack.com/api/files.upload?token={token}&content={content}&filename={filename}&channels={channel_id}&title={title}&initial_comment={initial_comment}".format( token=settings.token, content=content, filename=filename, channel_id=channel_id, title=title, initial_comment=initial_comment) response = requests.get(url).json() if response["ok"]: os.system("figlet 'Uploaded!'" + lString) time.sleep(2) os.system("clear") else: print "something goes wrong :( (\u001b[1m\u001b[31m " + response["error"] + "\u001b[0m)"
def test_invoke_contract(self, args): if not self.Wallet: print("Please open a wallet") return args, from_addr = get_from_addr(args) if args and len(args) > 0: tx, fee, results, num_ops = TestInvokeContract(self.Wallet, args, from_addr=from_addr) if tx is not None and results is not None: print( "\n-------------------------------------------------------------------------------------------------------------------------------------") print("Test invoke successful") print("Total operations: %s" % num_ops) print("Results %s" % [str(item) for item in results]) print("Invoke TX GAS cost: %s" % (tx.Gas.value / Fixed8.D)) print("Invoke TX fee: %s" % (fee.value / Fixed8.D)) print( "-------------------------------------------------------------------------------------------------------------------------------------\n") print("Enter your password to continue and invoke on the network\n") passwd = prompt("[password]> ", is_password=True) if not self.Wallet.ValidatePassword(passwd): return print("Incorrect password") result = InvokeContract(self.Wallet, tx, fee, from_addr=from_addr) return else: print("Error testing contract invoke") return print("Please specify a contract to invoke")
def manipulate_attachments(card): '''Give the user a CRUD interface for attachments on this card''' print('Enter a URL, "delete", "open", "print", or Enter to exit') user_input = 'Nothing really' attachment_completer = WordCompleter(['delete', 'print', 'open', 'http://', 'https://'], ignore_case=True) while user_input != '': user_input = prompt('attach > ', completer=attachment_completer).strip() if re.search(VALID_URL_REGEX, user_input): # attach this link card.attach(url=user_input) print('Attached {0}'.format(user_input)) elif user_input in ['delete', 'open']: attachment_opts = {a.name: a for a in card.get_attachments()} if not attachment_opts: print('No attachments') continue dest = single_select(attachment_opts.keys()) if dest is not None: target = attachment_opts[dest] if user_input == 'delete': card.remove_attachment(target.id) elif user_input == 'open': with DevNullRedirect(): webbrowser.open(target.url) elif user_input == 'print': existing_attachments = card.get_attachments() if existing_attachments: print('Attachments:') for a in existing_attachments: print(' ' + a.name)
def do_open(self, arguments): if self.Wallet: self.do_close_wallet() item = get_arg(arguments) if item and item == 'wallet': path = get_arg(arguments, 1) if path: if not os.path.exists(path): print("Wallet file not found") return passwd = prompt("[password]> ", is_password=True) password_key = to_aes_key(passwd) try: self.Wallet = UserWallet.Open(path, password_key) self.start_wallet_loop() print("Opened wallet at %s" % path) except Exception as e: print("Could not open wallet: %s" % e) else: print("Please specify a path") else: print("Please specify something to open")
def cli(url): click.echo('Version: %s' % __version__) # Override less options os.environ['LESS'] = '-RXF' url = fix_incomplete_url(url) context = Context(url) # For prompt-toolkit history = InMemoryHistory() lexer = PygmentsLexer(HttpPromptLexer) completer = HttpPromptCompleter(context) style = style_from_pygments(get_style_by_name('monokai')) while True: try: text = prompt('%s> ' % context.url, completer=completer, lexer=lexer, style=style, history=history) except EOFError: break # Control-D pressed else: if text.strip() == 'exit': break else: execute(text, context) click.echo("Goodbye!")
def cli(url, http_options): click.echo('Version: %s' % __version__) # Override less options os.environ['LESS'] = '-RXF' url = fix_incomplete_url(url) context = Context(url) load_context(context) # For prompt-toolkit history = InMemoryHistory() lexer = PygmentsLexer(HttpPromptLexer) completer = HttpPromptCompleter(context) style = style_from_pygments(get_style_by_name('monokai')) # Execute default http options. execute(' '.join(http_options), context) save_context(context) while True: try: text = prompt('%s> ' % context.url, completer=completer, lexer=lexer, style=style, history=history) except EOFError: break # Control-D pressed else: execute(text, context) save_context(context) if context.should_exit: break click.echo("Goodbye!")
def ask_pref(method,prev_pref): rank=prompt(u'Ranking: ',default=u",".join(map(str,prev_pref)),validator=VectorValidator(method)) if rank=="e": return rank pref=RelativeRanking(map(float,rank.split(","))) method.nextIteration(pref) method.printCurrentIteration()
def add_labels(card, label_choices=None): '''Give the user a way to toggle labels on this card by their name rather than by a numeric selection interface. Using prompt_toolkit, we have automatic completion which makes things substantially faster without having to do a visual lookup against numeric IDs :param trello.Card card: the card to modify :param dict label_choices: str->trello.Label, the names and objects of labels on this board ''' print('Enter a tag name to toggle it, <TAB> completes. Give "ls" to list tags, Enter to exit') label_choices = label_choices or BoardTool.label_lookup(card.board) label_completer = WordCompleter(label_choices.keys(), ignore_case=True) while True: userinput = prompt('tag > ', completer=label_completer).strip() if userinput == '': break elif userinput == 'ls': triple_column_print(label_choices.keys()) elif userinput not in label_choices.keys(): if prompt_for_confirmation('Unrecognized tag name {0}, would you like to create it?'.format(userinput), False): label = card.board.add_label(userinput, 'black') card.add_label(label) click.echo('Successfully added tag {0} to board {1} and card {2}!'.format(label.name, card.board.name, card.name)) label_choices = BoardTool.label_lookup(card.board) label_completer = WordCompleter(label_choices.keys(), ignore_case=True) else: label_obj = label_choices[userinput] try: card.add_label(label_obj) print('Added tag {0}'.format(Colors.green + userinput + Colors.reset)) except trello.exceptions.ResourceUnavailable: # This label already exists on the card so remove it card.remove_label(label_obj) print('Removed tag {0}'.format(Colors.red + userinput + Colors.reset))
def main(): swapped = [False] # Nonlocal bindings = KeyBindings() @bindings.add('c-t') def _(event): ' When ControlT has been pressed, toggle light/dark colors. ' swapped[0] = not swapped[0] def bottom_toolbar(): if swapped[0]: on = 'on=true' else: on = 'on=false' return HTML('Press <style bg="#222222" fg="#ff8888">[control-t]</style> ' 'to swap between dark/light colors. ' '<style bg="ansiblack" fg="ansiwhite">[%s]</style>') % on text = prompt(HTML('<style fg="#aaaaaa">Give some animals</style>: '), completer=html_completer, complete_while_typing=True, bottom_toolbar=bottom_toolbar, key_bindings=bindings, lexer=PygmentsLexer(HtmlLexer), swap_light_and_dark_colors=Condition(lambda: swapped[0])) print('You said: %s' % text)
def singleplayer_mainloop(self, player_connection: PlayerConnection) -> None: """Main event loop for the console I/O adapter for single player mode""" while not self.stop_main_loop: # Input a single line of text by the player. It is stored in the internal # command buffer of the player. The driver's main loop can look into that # to see if any input should be processed. self.input_not_paused.wait() try: # note that we don't print any prompt ">>", that needs to be done # by the main thread that handles screen *output* # (otherwise the prompt will often appear before any regular screen output) old_player = player_connection.player # do blocking console input call if prompt_toolkit and self.do_prompt_toolkit: # word completion for the names of things and people all_candidates = self.tab_complete_get_all_candidates(mud_context.driver) completer = WordCompleter(all_candidates) # unfortunately prompt_toolkit doesn't allow ansi style codes in the prompt so we use a plain one. cmd = prompt_toolkit.prompt("\n>> ", patch_stdout=True, completer=completer, complete_while_typing=False) else: cmd = input() player_connection.player.store_input_line(cmd) if old_player is not player_connection.player: # this situation occurs when a save game has been restored, # we also have to unblock the old_player old_player.store_input_line(cmd) except KeyboardInterrupt: self.break_pressed() except EOFError: pass
def run_repl(self): """Run the REPL loop.""" color_output(intro) load_namespace() while True: try: val = prompt( 'Mini Matlab >> ', lexer=MathematicaLexer, history=self.hist, completer=self.autocomplete(), display_completions_in_columns=True, mouse_support=True ) if val == 'exit': self.workspace() break elif val == 'help': color_output(intro) else: parser = Parser(val) parser.save_retrieve_args() except (KeyboardInterrupt, SystemExit, EOFError): self.workspace() break
def main(): parser = argparse.ArgumentParser() parser.add_argument('--host', default='localhost:8082', help="host:port to connect to (default='%(default)s')") parser.add_argument('--ssl', action="store_true", default=False, help="connect with SSL (default=%(default)s)") parser.add_argument('--user', default='', help="authenticate with user (default='%(default)s')") parser.add_argument('--password', default='', help="authenticate with password (default='%(default)s')") options = parser.parse_args() if options.ssl: APIClient.PROTOCOL = 'https' if options.host: APIClient.HOST = options.host if options.user and options.password: APIClient.USER = options.user APIClient.PASSWORD = options.password for p in APIClient().list(current_path): utils.COMPLETION_QUEUE.put(p) while True: try: action = prompt(get_prompt_tokens=get_prompt_tokens, history=history, completer=completer, style=PromptStyle) except (EOFError, KeyboardInterrupt): break try: action_list = action.split() cmd = getattr(commands, action_list[0]) args = action_list[1:] except IndexError: continue except AttributeError: print ("Command not found. Type help for all commands.") continue try: result = cmd(current_path, *args) except commands.CommandError: continue except APIError as e: print (e) continue else: if result is None: continue elif type(result) == list: output_paths = [] for p in result: output_paths.append(str(p.relative(current_path))) utils.COMPLETION_QUEUE.put(p) print("\n".join(output_paths)) elif type(result) == dict: print(pprint.pformat(result, indent=2)) else: print(result)
def main(): # We start with a `KeyBindingManager` instance, because this will already # nicely load all the default key bindings. key_bindings_manager = KeyBindingManager() # We add a custom key binding to space. @key_bindings_manager.registry.add_binding(' ') def _(event): """ When space is pressed, we check the word before the cursor, and autocorrect that. """ b = event.cli.current_buffer w = b.document.get_word_before_cursor() if w is not None: if w in corrections: b.delete_before_cursor(count=len(w)) b.insert_text(corrections[w]) b.insert_text(' ') # Read input. text = prompt('Say something: ', key_bindings_registry=key_bindings_manager.registry) print('You said: %s' % text)
def WithdrawOne(wallet, require_password=True): hold = wallet._holds[0] withdraw_tx = create_withdraw_tx(wallet, hold) if withdraw_tx is not None: if require_password: print("\n---------------------------------------------------------------") print("Will make withdrawal request for %s %s from %s to %s " % ( Fixed8(hold.Amount).ToString(), hold.AssetName, hold.InputAddr, hold.OutputAddr)) print("------------------------------------------------------------------\n") print("Enter your password to complete this request") passwd = prompt("[Password]> ", is_password=True) if not wallet.ValidatePassword(passwd): print("incorrect password") return return PerformWithdrawTx(wallet, withdraw_tx, hold.InputHash.ToString()) return False
def prompt_perf_stat_exec_dict(run_dict: dict) -> dict: """ Prompt for the config of the perf stat exec runner. :param run_dict: run config dict (without the runner part) :return: runner config """ runner_dict = {} default_repeat = PerfStatExecRunner.misc_options["repeat"].get_default() runner_dict["repeat"] = int(default_prompt("How many times should perf stat itself repeat the measurement? ", default=default_repeat, validator=TypeValidator(PositiveInt()))) default_props = ", ".join(PerfStatExecRunner.misc_options["properties"].get_default()) class PerfStatPropertiesValidator(Validator): def validate(self, document: Document): vals = [elem.strip() for elem in document.text.split(",")] cmd = "perf stat -x ';' -e {props} -- /bin/echo".format(props=",".join(vals)) proc = subprocess.Popen(["/bin/sh", "-c", cmd], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, universal_newlines=True) out, err = proc.communicate() if proc.poll() > 0: msg = str(err).split("\n")[0].strip() raise ValidationError(message=msg, cursor_position=len(document.text)) props = prompt("Which properties should perf stat measure? ", validator=PerfStatPropertiesValidator(), default=default_props, completer=WordCompleter(sorted(list(set(get_av_perf_stat_properties()))), ignore_case=False, WORD=True)) runner_dict["properties"] = [prop.strip() for prop in props.split(",")] return runner_dict
def start_repl(self, quiet: bool) -> None: """ Start the objection repl. """ banner = (""" _ _ _ _ ___| |_ |_|___ ___| |_|_|___ ___ | . | . | | | -_| _| _| | . | | |___|___|_| |___|___|_| |_|___|_|_| |___|(object)inject(ion) v{0} Runtime Mobile Exploration by: @leonjza from @sensepost """).format(__version__) if not quiet: click.secho(banner, bold=True) click.secho('[tab] for command suggestions', fg='white', dim=True) # the main application loop is here, reading inputs provided by # prompt_toolkit and sending it off the the needed handlers while True: try: document = prompt( get_prompt_tokens=self.get_prompt_tokens, completer=self.completer, style=PromptStyle().get_style(), history=FileHistory( os.path.expanduser('~/.objection/objection_history')), auto_suggest=AutoSuggestFromHistory(), on_abort=AbortAction.RETRY, reserve_space_for_menu=4) # check if this is an exit command if document.strip() in ('quit', 'exit', 'bye'): click.secho('Exiting...', dim=True) break # if we got the reconnect command, handle just that if self.handle_reconnect(document): continue # dispatch to the command handler. if something goes horribly # wrong, catch it instead of crashing the REPL try: # find something to run self.run_command(document) except Exception as e: click.secho(( '\n\nAn exception occurred while processing the command. If this ' 'looks like a code related error, please file a bug report!' ), fg='red') click.secho('Error: {0}'.format(e), fg='red', bold=True) except (KeyboardInterrupt, EOFError): click.secho('Exiting...', dim=True) break
#!/usr/bin/env python3 from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory #按向上的按键,可以查看输入的历史 from prompt_toolkit.auto_suggest import AutoSuggestFromHistory #输入内容时会提示之前的输过的内容 #from prompt_toolkit.contrib.completers import WordCompleter #SQLCompleter=WordCompleter(['select','from','insert','update','delete','drop'],ignore_case=True) while True: user_input = prompt( '>', history=FileHistory('history.txt'), auto_suggest=AutoSuggestFromHistory(), #completer=SQLCompleter, ) print(user_input)
'var1': SimpleLexer(Token.Number), 'var2': SimpleLexer(Token.Number), }) completer = GrammarCompleter( g, { 'operator1': WordCompleter(operators1), 'operator2': WordCompleter(operators2), }) try: # REPL loop. while True: # Read input and parse the result. text = prompt('Calculate: ', lexer=lexer, completer=completer, style=ExampleStyle) m = g.match(text) if m: vars = m.variables() else: print('Invalid command\n') continue print(vars) if vars.get('operator1') or vars.get('operator2'): try: var1 = float(vars.get('var1', 0)) var2 = float(vars.get('var2', 0)) except ValueError: print('Invalid command (2)\n')
def run(self): dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) dbloop.start(.1) Blockchain.Default().PersistBlocks() tokens = [(Token.Neo, 'NEO'), (Token.Default, ' cli. Type '), (Token.Command, "'help' "), (Token.Default, 'to get started')] print_tokens(tokens, self.token_style) print("\n") while self.go_on: try: result = prompt("neo> ", completer=self.get_completer(), history=self.history, get_bottom_toolbar_tokens=self.get_bottom_toolbar, style=self.token_style, refresh_interval=3 ) except EOFError: # Control-D pressed: quit return self.quit() except KeyboardInterrupt: # Control-C pressed: do nothing continue try: command, arguments = self.parse_result(result) if command is not None and len(command) > 0: command = command.lower() if command == 'quit' or command == 'exit': self.quit() elif command == 'help': self.help() elif command == 'create': self.do_create(arguments) elif command == 'open': self.do_open(arguments) elif command == 'build': self.do_build(arguments) elif command == 'load_run': self.do_load_n_run(arguments) elif command == 'import': self.do_import(arguments) elif command == 'export': self.do_export(arguments) elif command == 'wallet': self.show_wallet(arguments) elif command == 'send': self.do_send(arguments) elif command == 'sign': self.do_sign(arguments) elif command == 'block': self.show_block(arguments) elif command == 'tx': self.show_tx(arguments) elif command == 'header': self.show_header(arguments) elif command == 'account': self.show_account_state(arguments) elif command == 'asset': self.show_asset_state(arguments) elif command == 'contract': self.show_contract_state(arguments) elif command == 'testinvoke': self.test_invoke_contract(arguments) elif command == 'withdraw_request': self.do_request_withdraw(arguments) elif command == 'withdraw': self.do_withdraw_from(arguments) elif command == 'mem': self.show_mem() elif command == 'nodes' or command == 'node': self.show_nodes() elif command == 'state': self.show_state() elif command == 'config': self.configure(arguments) elif command is None: print('please specify a command') else: print("command %s not found" % command) except Exception as e: print("could not execute command: %s " % e) traceback.print_stack() traceback.print_exc()
def do_import(self, arguments): item = get_arg(arguments) if not item: print("please specify something to import") return if item == 'wif': if not self.Wallet: print("Please open a wallet before importing WIF") return wif = get_arg(arguments, 1) if not wif: print("Please supply a valid WIF key") return try: prikey = KeyPair.PrivateKeyFromWIF(wif) key = self.Wallet.CreateKey(prikey) print("Imported key %s " % wif) print("Pubkey: %s \n" % key.PublicKey.encode_point(True).hex()) print("Wallet: %s " % json.dumps(self.Wallet.ToJson(), indent=4)) except ValueError as e: print(str(e)) except Exception as e: print(str(e)) return elif item == 'nep2': if not self.Wallet: print("Please open a wallet before importing a NEP2 key") return nep2_key = get_arg(arguments, 1) if not nep2_key: print("Please supply a valid nep2 encrypted private key") return nep2_passwd = prompt("[Key Password]> ", is_password=True) try: prikey = KeyPair.PrivateKeyFromNEP2(nep2_key, nep2_passwd) key = self.Wallet.CreateKey(prikey) print("Imported nep2 key: %s " % nep2_key) print("Pubkey: %s \n" % key.PublicKey.encode_point(True).hex()) print("Wallet: %s " % json.dumps(self.Wallet.ToJson(), indent=4)) except ValueError as e: print(str(e)) except Exception as e: print(str(e)) return elif item == 'contract': return self.load_smart_contract(arguments) elif item == 'contract_addr': return ImportContractAddr(self.Wallet, arguments[1:]) elif item == 'watch_addr': return ImportWatchAddr(self.Wallet, get_arg(arguments, 1)) elif item == 'multisig_addr': return ImportMultiSigContractAddr(self.Wallet, arguments[1:]) elif item == 'token': return ImportToken(self.Wallet, get_arg(arguments, 1)) else: print("Import of '%s' not implemented" % item)
from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.completion import Completer, Completion import click from fuzzyfinder import fuzzyfinder from pygments.lexers.sql import SqlLexer SQLKeywords = ['select', 'from', 'insert', 'update', 'delete', 'drop'] class SQLCompleter(Completer): def get_completions(self, document, complete_event): word_before_cursor = document.get_word_before_cursor(WORD=True) matches = fuzzyfinder(word_before_cursor, SQLKeywords) for m in matches: yield Completion(m, start_position=-len(word_before_cursor)) while 1: user_input = prompt(u'SQL>', history=FileHistory('history.txt'), auto_suggest=AutoSuggestFromHistory(), completer=SQLCompleter(), lexer=SqlLexer, ) click.echo_via_pager(user_input)
def ClaimGas(wallet, require_password=True, args=None): """ Args: wallet: require_password: args: Returns: (claim transaction, relayed status) if successful: (tx, True) if unsuccessful: (None, False) """ if args: params, from_addr_str = get_from_addr(args) else: params = None from_addr_str = None unclaimed_coins = wallet.GetUnclaimedCoins() unclaimed_count = len(unclaimed_coins) if unclaimed_count == 0: print("no claims to process") return None, False max_coins_per_claim = None if params: max_coins_per_claim = get_arg(params, 0, convert_to_int=True) if not max_coins_per_claim: print("max_coins_to_claim must be an integer") return None, False if max_coins_per_claim <= 0: print("max_coins_to_claim must be greater than zero") return None, False if max_coins_per_claim and unclaimed_count > max_coins_per_claim: unclaimed_coins = unclaimed_coins[:max_coins_per_claim] unclaimed_coin_refs = [coin.Reference for coin in unclaimed_coins] available_bonus = Blockchain.Default().CalculateBonusIgnoreClaimed( unclaimed_coin_refs) if available_bonus == Fixed8.Zero(): print("No gas to claim") return None, False claim_tx = ClaimTransaction() claim_tx.Claims = unclaimed_coin_refs claim_tx.Attributes = [] claim_tx.inputs = [] script_hash = wallet.GetChangeAddress() # the following can be used to claim gas that is in an imported contract_addr # example, wallet claim --from-addr={smart contract addr} if from_addr_str: script_hash = wallet.ToScriptHash(from_addr_str) standard_contract = wallet.GetStandardAddress() claim_tx.Attributes = [ TransactionAttribute(usage=TransactionAttributeUsage.Script, data=standard_contract.Data) ] claim_tx.outputs = [ TransactionOutput(AssetId=Blockchain.SystemCoin().Hash, Value=available_bonus, script_hash=script_hash) ] context = ContractParametersContext(claim_tx) wallet.Sign(context) print("\n---------------------------------------------------------------") print("Will make claim for %s GAS" % available_bonus.ToString()) if max_coins_per_claim and unclaimed_count > max_coins_per_claim: print( "NOTE: You are claiming GAS on %s unclaimed coins. %s additional claim transactions will be required to claim all available GAS." % (max_coins_per_claim, math.floor(unclaimed_count / max_coins_per_claim))) print( "------------------------------------------------------------------\n") if require_password: print("Enter your password to complete this claim") passwd = prompt("[Password]> ", is_password=True) if not wallet.ValidatePassword(passwd): print("incorrect password") return None, False if context.Completed: claim_tx.scripts = context.GetScripts() print("claim tx: %s " % json.dumps(claim_tx.ToJson(), indent=4)) relayed = NodeLeader.Instance().Relay(claim_tx) if relayed: print("Relayed Tx: %s " % claim_tx.Hash.ToString()) wallet.SaveTransaction(claim_tx) else: print("Could not relay tx %s " % claim_tx.Hash.ToString()) return claim_tx, relayed else: print("could not sign tx") return None, False
def portfolio(cmd, nocolor, value, profit): """Command to manage your local portfolio. Arguments: add, remove, clear, history""" # Database db = TinyDB('db.json') # Add transaction if cmd == 'add': click.echo('Add new transaction') response = requests.get('https://api.coinmarketcap.com/v1/ticker/') crypto_data = response.json() crypto_data_map = {} # Dictionary for faster access all_coins = [] # List of all coin names for crypto in crypto_data: all_coins.append(crypto['symbol']) crypto_data_map[crypto['symbol']] = crypto # buy/sell transaction tx_type_completer = WordCompleter(['buy', 'sell'], ignore_case=True) tx_type = prompt('type (buy/sell) > ', completer=tx_type_completer) while not (tx_type.lower() == 'buy' or tx_type.lower() == 'sell'): click.secho('ERROR: invalid transaction type', fg='red') tx_type = prompt('type (buy/sell) > ', completer=tx_type_completer) # coin type tx_coin_completer = WordCompleter(all_coins, ignore_case=True) tx_coin = prompt('coin > ', completer=tx_coin_completer) while tx_coin not in all_coins: click.secho('ERROR: coin does not exist in list', fg='red') tx_coin = prompt('coin > ', completer=tx_coin_completer) # buy/sell price tx_coin_price = prompt( tx_type + ' price per coin (leave blank to use market price) > ') if not tx_coin_price and tx_coin_price != 0: tx_coin_price = crypto_data_map[tx_coin]['price_usd'] # amount tx_amount = prompt('amount > ') while not tx_amount: click.secho('ERROR: invalid amount') tx_amount = prompt('amount > ') # date tx_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M") # coin market value coin_market_price = crypto_data_map[tx_coin]['price_usd'] # calculate tx ID db_transactions = db.all() if not db_transactions: tx_id = 0x1 else: db_transactions = sorted( db_transactions, key=lambda k: k['id'], reverse=True) tx_id = db_transactions[0]['id'] + 0x1 tx_info = { 'type': tx_type.upper(), 'coin': tx_coin, 'price': float(tx_coin_price), 'amount': float(tx_amount), 'date': tx_date, 'id': tx_id } db.insert(tx_info) hodl_change = float(tx_amount) * float(coin_market_price) if(tx_type.lower() == 'buy'): hodl_change = click.style('+' + str(hodl_change), fg='green') if(tx_type.lower() == 'sell'): hodl_change = click.style('-' + str(hodl_change), fg='red') tx_info_table = [ ['ADDED TRANSACTION'], ['Type', tx_type.upper()], ['Coin', tx_coin], ['Price ($)', tx_coin_price], ['Amount', tx_amount], ['Timestamp', tx_date], ['ID', tx_id], ['Δ holdings', hodl_change] ] click.echo(SingleTable(tx_info_table).table) # Remove transaction if cmd == 'remove': if not sys.stdin.isatty(): remove_tx_tuple = sys.stdin.readline() else: remove_tx_tuple = prompt('remove transactions > ') if not remove_tx_tuple: return remove_tx_tuple = tuple(int(x.strip()) for x in remove_tx_tuple.split(',')) transaction = Query() removed_ids = [] for tx_id in remove_tx_tuple: if db.search(transaction.id == tx_id): removed_ids.append(tx_id) db.remove(transaction.id == tx_id) if removed_ids: click.echo('Removed transaction(s): ' + str(tuple(removed_ids))) else: click.echo('No transactions were removed') # Clear transaction database if cmd == 'clear': if not db.all(): click.echo('There are no transactions to delete') return decision = prompt( 'are you sure you want to clear all transactions? (y/n) > ') if decision.lower() == 'y': db.purge() click.echo('DELETED ALL TRANSACTIONS') # Print all transactions if cmd == 'history': db_transactions = db.all() if not db_transactions: click.echo('There are no transactions to display') return for tx in db_transactions: if(tx['type'] == 'BUY'): tx_type = click.style(tx['type'], fg='green') if(tx['type'] == 'SELL'): tx_type = click.style(tx['type'], fg='red') tx_info_table = [ ['Type', tx_type], ['Coin', tx['coin']], ['Price ($)', tx['price']], ['Amount', tx['amount']], ['Timestamp', tx['date']], ['ID', tx['id']] ] table = SingleTable(tx_info_table) table.inner_heading_row_border = False click.echo(table.table) # Display portfolio data if not cmd: if not db.all(): click.echo('Your portfolio is empty.') return response = requests.get('https://api.coinmarketcap.com/v1/ticker/') crypto_data = response.json() crypto_data_map = {} # Dictionary for faster access all_coins = [] # List of all coin names for crypto in crypto_data: all_coins.append(crypto['symbol']) crypto_data_map[crypto['symbol']] = crypto total_hodlings_usd = 0 investment_usd = 0 all_coin_info = {} for tx in db.all(): if tx['coin'] in all_coin_info: coin_info = all_coin_info[tx['coin']] else: all_coin_info[tx['coin']] = coin_info = { 'amount': 0, 'investment': 0, 'profit': 0 } if tx['type'] == 'BUY': modifier = 1 elif tx['type'] == 'SELL': modifier = -1 total_hodlings_usd += modifier * \ tx['amount'] * float(crypto_data_map[tx['coin']]['price_usd']) investment_usd += modifier * tx['amount'] * tx['price'] coin_info['amount'] += modifier * tx['amount'] coin_info['investment'] += modifier * tx['amount'] * tx['price'] all_coin_info[tx['coin']] = coin_info # Calculate profit for each coin for key in all_coin_info: coin_info = all_coin_info[key] coin_info['coin'] = key coin_info['profit'] = coin_info['amount'] * float( crypto_data_map[key]['price_usd']) - coin_info['investment'] all_coin_info = all_coin_info.values() all_coin_info = sorted( all_coin_info, key=lambda k: k['profit'], reverse=True) # Calculate profits port_profit = round(total_hodlings_usd - investment_usd, 5) if not nocolor: if port_profit > 0: port_profit = click.style(str(port_profit), fg='green') elif port_profit < 0: port_profit = click.style(str(port_profit), fg='red') min_info = '' if value: min_info += 'Value: ' + str(round(total_hodlings_usd, 5)) + ' ' if profit: min_info += 'Profit: ' + str(port_profit) if value or profit: click.echo(min_info + '\n') return # Individual coin value and profit table coin_table = [ ['Coin', 'Amount', 'Investment ($)', 'Profit ($)'], ] + [ [ coin_info['coin'], round(coin_info['amount'], 5), round(coin_info['investment'], 5), click.style(str(round(coin_info['profit'], 5)), fg='green') if coin_info['profit'] > 0 else click.style(str(round(coin_info['profit'], 5)), fg='red') if not nocolor or (coin_info['profit'] == 0) else round(coin_info['profit'], 5) ] for coin_info in all_coin_info ] table = SingleTable(coin_table) table.inner_row_border = True table.inner_heading_row_border = False click.echo(table.table) # Portfolio value and profit table total_table = [ ['Portfolio Value ($)', round(total_hodlings_usd, 5)], ['Investment ($)', round(investment_usd, 5)], ['Profit ($)', str(port_profit)], ] table = SingleTable(total_table) table.inner_row_border = True table.inner_heading_row_border = False click.echo(table.table)
def input2(message, default): try: return prompt(message=message, default=default) except: return None
#!/usr/bin/env python from __future__ import unicode_literals from prompt_toolkit import prompt if __name__ == '__main__': print( 'This is multiline input. press [Meta+Enter] or [Esc] followed by [Enter] to accept input.' ) print('You can click with the mouse in order to select text.') answer = prompt('Multiline input: ', multiline=True, mouse_support=True) print('You said: %s' % answer)
def do_prompt(self): """Returns false if asked to quit.""" text = prompt('bitbox-editor (? for help) > ', history=self._herstory, completer=BBCompleter(self)) command = self.parse_command(text) if command['command'] == '?': self.help() return True elif command['command'] == 'q': return False elif command['command'] == 'dir': self._root = self.handle_dir(command) return True if not self._root: print("Please set 'dir foo/bar' for bitbox directory") return True if command['command'] == 'c': self._cur_preset = self.choose_preset(command) if self._cur_preset is not None: self.show_current_preset() return True if command['command'] == 'l': print('Presets in %s:' % self._root) print('\n'.join(self.list_presets())) return True if command['command'] == 'exportv1': self.export_v1() return True if not self._cur_preset: print('Please choose a preset with c') return True if command['command'] == 'p': self._cur_clip = self._choose_clip(command) if self._cur_clip is not None: self.play_current_clip() elif command['command'] == 'f': self.handle_fix(command) elif command['command'] == 'm': self.move_preset(command) elif command['command'] == 'r': self.handle_rename(command) elif command['command'] == 's': self.handle_swap(command) elif command['command'] == 'norm': self._cur_clip = self._choose_clip(command) if self._cur_clip is not None: self._handler.normalize_clip(self._root, self._cur_preset, self._cur_clip) self.play_current_clip() elif command['command'] == 'normall': self._handler.normalize_preset(self._root, self._cur_preset) elif command['command'] == 'trim': self._cur_clip = self._choose_clip(command) if self._cur_clip is not None: self._handler.trim_clip(self._root, self._cur_preset, self._cur_clip) self.play_current_clip() elif command['command'] == 'trimall': self._handler.trim_all(self._root, self._cur_preset) elif command['command'] == 'mono': self._cur_clip = self._choose_clip(command) if self._cur_clip is not None: self._handler.clip_to_mono(self._root, self._cur_preset, self._cur_clip) self.play_current_clip() elif command['command'] == 'undo': self._cur_clip = self._choose_clip(command) if self._cur_clip is not None: self._handler.undo_clip(self._root, self._cur_preset, self._cur_clip) self.play_current_clip() else: self.help() self.show_current_preset() return True
def main(): print( "\n\nWELCOME TO THE LIBRARY OF GOKHALE EDUCATION SOCIETY'S R.H. SAPAT COLLEGE OF ENGINEERING , NASHIK\n" ) print("For Members Of The Library") print(" issue : To Issue the Book") print(" donate : To Donate the Book") print(" return : To Return the Book") print(" search : To search the book in Library") print(" exit : To come out of Library\n") print( "Only For Authorized Users \n lentdata : To get information about the Books Lending Database \n delete book : To delete the Book in the Library \n returndata : To get the information about the Books Return Database \n delete member : To delete the member of library\n" ) print("\nThe available books in the library are as follows : ") ges.display() print("") Exit = False while Exit is not True: UserInput = input("Enter Your Choice : ") if UserInput == "issue": name_of_taker = input("Enter your name : ") bookindex = int( input( "Enter the number which is written at the left of the book : " )) bookname = ges.booklist[bookindex - 1] ges.lend_book(name_of_taker, bookname, bookindex) print("") print("The available Books in the library : ") ges.display() print("") if UserInput == "return": name_return = input("Enter your name : ") name_of_book = input("Enter the name of the book : ") ges.return_book(name_return, name_of_book) print("") print("The available Books in the library : ") ges.display() print("") if UserInput == "lentdata": if prompt("Enter the Password : "******"gescoe": print( "Authorization Granted......!!!!\n\nThe Lent Book Database is as follows......" ) ges.book_lent() print("\n") print("The available Books in the library : ") ges.display() print("") else: print("Access Denied.... \nNo Tresspassers are allowed.....") exit(0) if UserInput == "returndata": if prompt("Enter the Password : "******"gescoe": print( "Authorization Granted......!!!!\n\nThe Returned Book Batabase is as follows....." ) ges.book_return() print("\n") print("The available Books in the library : ") ges.display() print("") else: print("Access Denied.... \nNo Tresspassers are allowed.....") exit(0) if UserInput == "delete book": if prompt("Enter the Password : "******"gescoe": print("Authorization Granted......!!!!") bookindex = int( input( "Enter the number of the book which you want to delete : " )) ges.delete_book(bookindex) print("") print("The available Books in the library : ") ges.display() print("") else: print("Access Denied... \nNo Tresspassers are allowed.....") exit(0) if UserInput == "delete member": if prompt("Enter the Password : "******"gescoe": print("Authorization Granted......!!!!") name = input( "Enter the name of the member you want to delete : ") ges.delete_member(name) print("") print("The available Books in the library : ") ges.display() print("") else: print("Access Denied.... \nNo Tresspassers are allowed.....") exit(0) if UserInput == "donate": newbook = input("Enter the name of the Book : ") ges.add_books(newbook) print("") print("The available Books in the library : ") ges.display() print("") if UserInput == "search": book_name = input( "Enter the name of the Book you want to search : ") ges.search_book(book_name) print("") ges.display() print("") if UserInput == "exit": print("") print("THANK YOU SO MUCH FOR VISITING TO OUR LIBRARY.......") Exit = True
) completer = GrammarCompleter( g, { "operator1": WordCompleter(operators1), "operator2": WordCompleter(operators2), }, ) try: # REPL loop. while True: # Read input and parse the result. text = prompt(">", lexer=lexer, completer=completer, style=example_style) m = g.match(text) if m: vars = m.variables() else: print("Invalid command", vars) continue print(vars) if vars.get("operator1") or vars.get("operator2"): try: var1 = float(vars.get("var1", 0)) var2 = float(vars.get("var2", 0)) except ValueError:
#!/usr/bin/python3 # encoding: utf-8 # @Time : 2018/7/18 0018 10:56 # @author : zza # @Email : [email protected] from prompt_toolkit import prompt if __name__ == '__main__': answer = prompt('Give me some input: ') print('You said: %s' % answer)
def main(): home = str(Path.home()) engine = chess.engine.SimpleEngine.popen_uci(home + "/stockfish_10_x64") username = prompt(HTML('<violet>Enter your lichess username: </violet>')) client = berserk.Client() move_place = 0 moves = [] game_list = [] game_number = 0 analysis_archive = [] kb = KeyBindings() kba = KeyBindings() @kb.add('c-q') def exit_(event): nonlocal move_place nonlocal moves move_place = 0 moves = [] game_list = [] game_number = 0 event.app.exit() @kb.add('c-a') def prev(event): nonlocal move_place nonlocal moves if move_place > 0: move_place = move_place - 1 display_simple_screen(event, game_list, game_number, moves, move_place) @kb.add('c-d') def next(event): nonlocal move_place nonlocal moves if move_place < len(moves) - 1: move_place = move_place + 1 display_simple_screen(event, game_list, game_number, moves, move_place) @kba.add('c-q') def exit_(event): nonlocal move_place nonlocal moves move_place = 0 moves = [] game_list = [] game_number = 0 analysis_archive = [] event.app.exit() @kba.add('c-a') def prev(event): nonlocal move_place nonlocal moves if move_place > 0: move_place = move_place - 1 display_analysis_screen(event, game_list, game_number, moves, move_place, analysis_archive) @kba.add('c-d') def next(event): nonlocal move_place nonlocal moves if move_place < len(moves) - 1: move_place = move_place + 1 display_analysis_screen(event, game_list, game_number, moves, move_place, analysis_archive) try: game_generator = client.games.export_by_player(username, as_pgn=False, max=10) game_list = list(game_generator) command = prompt( HTML( '\n\u265A <cyan>Welcome to ChessView!</cyan> \u2654\nType "help" for info on commands\n>' )) while (command != 'exit'): if (command == 'list'): print_games(game_list) elif (command == 'help'): help() elif (command.startswith('info(')): print_formatted_text(game_list[int(command[5:6])]) elif (re.match('view\(\d\)', command)): game_number = int(command[5:6]) moves = game_to_fenlist(game_list[game_number]['moves']) chess_text = set_simple_chess_text(game_list, game_number, moves, 0) root_container = VSplit([ Window(width=30, content=FormattedTextControl(), dont_extend_width=True, wrap_lines=True, allow_scroll_beyond_bottom=True, always_hide_cursor=True), Window(width=1, char='|', always_hide_cursor=True), Window(content=FormattedTextControl(text=HTML(chess_text)), always_hide_cursor=True) ]) layout = Layout(root_container) app = Application(key_bindings=kb, layout=layout, full_screen=True) app.run() elif (re.match('analyze\(\d\)', command)): game_number = int(command[8:9]) moves = game_to_fenlist(game_list[game_number]['moves']) analysis_archive = analysis_to_move_archive( game_list[game_number]['moves'], engine) chess_text = set_analysis_chess_text(game_list, game_number, moves, 0, analysis_archive) root_container = VSplit([ Window(width=30, content=FormattedTextControl(), dont_extend_width=True, wrap_lines=True, allow_scroll_beyond_bottom=True, always_hide_cursor=True), Window(width=1, char='|', always_hide_cursor=True), Window(content=FormattedTextControl(text=HTML(chess_text)), always_hide_cursor=True) ]) layout = Layout(root_container) app = Application(key_bindings=kba, layout=layout, full_screen=True) app.run() command = prompt(HTML('>')) except Exception as e: print("Username not found or does not exist.") engine.quit()
def SplitUnspentCoin(wallet, args, prompt_passwd=True): """ example ``wallet split Ab8RGQEWetkhVqXjPHeGN9LJdbhaFLyUXz neo 1 100`` this would split the second unspent neo vin into 100 vouts :param wallet: :param args (list): A list of arguments as [Address, asset type, unspent index, divisions] :return: bool """ fee = Fixed8.Zero() try: addr = wallet.ToScriptHash(args[0]) asset = get_asset_id(wallet, args[1]) index = int(args[2]) divisions = int(args[3]) if len(args) == 5: fee = Fixed8.TryParse(args[4]) except Exception as e: logger.info("Invalid arguments specified: %s " % e) return None try: unspentItem = wallet.FindUnspentCoinsByAsset(asset, from_addr=addr)[index] except Exception as e: logger.info( "Could not find unspent item for asset with index %s %s : %s" % (asset, index, e)) return None outputs = split_to_vouts(asset, addr, unspentItem.Output.Value, divisions) # subtract a fee from the first vout if outputs[0].Value > fee: outputs[0].Value -= fee else: raise Exception("Fee could not be subtracted from outputs.") contract_tx = ContractTransaction(outputs=outputs, inputs=[unspentItem.Reference]) ctx = ContractParametersContext(contract_tx) wallet.Sign(ctx) print("Splitting: %s " % json.dumps(contract_tx.ToJson(), indent=4)) if prompt_passwd: passwd = prompt("[Password]> ", is_password=True) if not wallet.ValidatePassword(passwd): print("incorrect password") return None if ctx.Completed: contract_tx.scripts = ctx.GetScripts() relayed = NodeLeader.Instance().Relay(contract_tx) if relayed: wallet.SaveTransaction(contract_tx) print("Relayed Tx: %s " % contract_tx.Hash.ToString()) return contract_tx else: print("Could not relay tx %s " % contract_tx.Hash.ToString()) return None
print("Welcome to PreCrimeBot!") print("You can ask me to predict crime anywhere in London. Let's get started!") print() print("Each prediction will require a date and address as input.") print("Don't worry, I understand most date and address formats.") print("I will try to tell you when I can't understand you.") print() print("PS: type 'exit' and hit ENTER at any time to exit, or use CTLR+D") address_history = InMemoryHistory() date_history = InMemoryHistory() while True: print('-' * 50) address = prompt("Address: ", history=address_history) if 'exit' == address: break date = prompt("Date: ", history=date_history) if 'exit' == date: break try: result = predict(date, address) except ValueError as e: print("Woops! Error: '%s'" % str(e)) continue print("Here are the crime predictions you asked for:") print(" - theft %.2f%%" % round(result.theft * 100, 2))
def main(): """ The main function """ history = FileHistory(os.path.join(Path.home(), ".pip_login_history")) history.load_history_strings() try: version = pkg_resources.get_distribution(__name__).version except pkg_resources.DistributionNotFound: version = __name__ + " Unknown version" parser = ArgumentParser(description="pip login") parser.add_argument("--version", action="version", version=version) parser.add_argument("url", nargs="?", type=str, default=None, help="The repository index URL.") parser.add_argument("-u", "--username", type=str, default=None, help="The username.") parser.add_argument("-p", "--password", type=str, default=None, help="The password.") args = parser.parse_args() url = os.environ.get("PIP_LOGIN_REPOSITORY") username = os.environ.get("PIP_LOGIN_USERNAME") password = os.environ.get("PIP_LOGIN_PASSWORD") if args.url: url = args.url if args.username: username = args.username if args.password: password = args.password if not url: url = prompt("Repository URL: ", history=history, auto_suggest=AutoSuggestFromHistory()) if not username: username = prompt("Username: "******"@")[-1] keyring.set_password(netloc, username, password) pip_conf_path = os.environ.get("VIRTUAL_ENV") if platform.system() == "Linux": if pip_conf_path: pip_conf_path = os.path.join(pip_conf_path, "pip.conf") else: pip_conf_path = os.path.join(Path.home(), ".config", "pip", "pip.conf") elif platform.system() == "Darwin": if pip_conf_path: pip_conf_path = os.path.join(pip_conf_path, "pip.conf") else: pip_conf_path = os.path.join(Path.home(), "Library", "Application Support", "pip", "pip.conf") elif platform.system() == "Windows": if pip_conf_path: pip_conf_path = os.path.join(pip_conf_path, "pip.ini") else: appdata = os.environ.get("APPDATA") if appdata: os.path.join(appdata, "pip", "pip.ini") if not parsed_url.username: parsed_url = parsed_url._replace(netloc=f"{username}@{netloc}") extra_index_url = parsed_url.geturl() config = ConfigParser() if pip_conf_path: config.read(pip_conf_path) if "global" not in config: config["global"] = {} if "extra-index-url" not in config["global"]: config["global"]["extra-index-url"] = extra_index_url else: idx_url = config["global"]["extra-index-url"] if extra_index_url not in idx_url: config["global"][ "extra-index-url"] = f"{idx_url}\n{extra_index_url}" if not os.path.exists(os.path.dirname(pip_conf_path)): os.makedirs(os.path.dirname(pip_conf_path)) with open(pip_conf_path, "w+") as config_file: config.write(config_file) print(f"pip config written to: {pip_conf_path}")
def run(self): dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) dbloop.start(.1) Blockchain.Default().PersistBlocks() tokens = [(Token.Neo, 'NEO'), (Token.Default, ' cli. Type '), (Token.Command, "'help' "), (Token.Default, 'to get started')] print_tokens(tokens, self.token_style) print("\n") while self.go_on: if self._gathered_passwords and len( self._gathered_passwords) == self._num_passwords_req: self._gathering_password = False self._gather_password_action() if self._gathering_password: result = prompt("password> ", is_password=True) else: result = prompt( "neo> ", completer=self.completer, history=self.history, get_bottom_toolbar_tokens=self.get_bottom_toolbar, style=self.token_style) if self._gathering_password: self._gathered_passwords.append(result) else: try: command, arguments = self.parse_result(result) if command is not None and len(command) > 0: command = command.lower() if command == 'quit' or command == 'exit': self.quit() elif command == 'help': self.help() elif command == 'create': self.do_create(arguments) elif command == 'open': self.do_open(arguments) elif command == 'import': self.do_import(arguments) elif command == 'export': self.do_export(arguments) elif command == 'wallet': self.show_wallet(arguments) elif command == 'send': self.do_send(arguments) elif command == 'block': self.show_block(arguments) elif command == 'tx': self.show_tx(arguments) elif command == 'header': self.show_header(arguments) elif command == 'account': self.show_account_state(arguments) elif command == 'asset': self.show_asset_state(arguments) elif command == 'contract': self.show_contract_state(arguments) elif command == 'invoke': self.invoke_contract(arguments) elif command == 'testinvoke': self.test_invoke_contract(arguments) elif command == 'cancel': self.cancel_operations() elif command == 'mem': self.show_mem() elif command == 'nodes' or command == 'node': self.show_nodes() elif command == 'state': self.show_state() elif command == 'config': self.configure(arguments) elif command == None: print('please specify a command') else: print("command %s not found" % command) except Exception as e: print("could not execute command: %s " % e)
def connector(params): remote = telnetlib.Telnet(params['host'], params['port']) read_remote = True if not check_alive(params, remote): return False while True: if time.time() < params['delay_timeout']: remote.write('c'.encode('ascii') + b'\n') break if read_remote: try: textin = remote.read_until(params['prompt'].encode('ascii')) except ConnectionResetError: if params['debug']: print('DEBUG: Connection reset by peer') break text_main = textin.decode('ascii').rsplit(params['prompt'], 1) pad_line(params['pad_before']) for line in text_main[0].splitlines(): print_formatted_text( FormattedText([('class:output', line)], ), style=params['style'], ) pad_line(params['pad_after']) try: textout = prompt( params['prompt_local'], style=params['style'], history=params['history'], ).strip() except KeyboardInterrupt: if params['debug']: print('DEBUG: Keyboad interrupt') remote.write('c'.encode('ascii') + b'\n') exit_handler() if textout in ['e', 'exit', 'q', 'quit']: remote.write('c'.encode('ascii') + b'\n') exit_handler() m = p_continue_until.match(textout) if m: print_formatted_text( FormattedText( [('class:wait', 'Continuing for {} seconds...'.format( m.group(1)))], ), style=params['style'], ) pad_line(params['pad_after']) params['delay_timeout'] = time.time() + float(m.group(1)) break if textout in ['c']: remote.write('c'.encode('ascii') + b'\n') break elif textout in ['cl', 'clear']: pad_line(params['pad_before']) print_formatted_text( FormattedText([( 'class:alert', '`{}` is not allowed here (would block on stdin on the server)' .format(textout))], ), style=params['style'], ) pad_line(params['pad_after']) read_remote = False else: remote.write(textout.encode('ascii') + b'\n') read_remote = True remote.close() return True
def main(): print_logo() modules = load_modules() #Temporal project variables history = InMemoryHistory() suggest = AutoSuggestFromHistory() config = {} words = WordCompleter(PROJECT_OPTIONS, ignore_case=True, WORD=True) module = None end = False while not end: user_input = prompt('({0})> '.format(module) if module else '> ', get_bottom_toolbar_tokens=update_toolbar, auto_suggest=suggest, completer=words, history=history) if not module: #Base if user_input == 'help': print_help() elif user_input == 'exit': end = True elif 'use' in user_input: module = user_input.split(' ')[1] if not module in modules: module = None print('[-] Module "{0}" not found.'.format(module)) else: words = WordCompleter(modules[module].words, ignore_case=True) elif 'createProject' in user_input: config, history = create_project(*user_input.split(' ')) elif 'openProject' in user_input: open_project(*user_input.split(' ')) elif 'showInfo' in user_input: #TODO #Print project info print('[+] Modules jobs:') for m in modules: modules[m].show_info() elif 'showModules' in user_input: print("[+] Available modules:") for m in modules: print("\t{0}".format(m)) else: print( '[-] Option "{0}" not found. Please use "help" to see the correct options.' .format(user_input)) else: if user_input == 'back': module = None words = WordCompleter(PROJECT_OPTIONS, ignore_case=True) else: modules[module].run(user_input)
class cli(Completer): def get_completions(self, document, complete_event): word_before_cursor = document.get_word_before_cursor(WORD=True) matches = fuzzyfinder(word_before_cursor, Keywords) for m in matches: yield Completion(m, start_position=-len(word_before_cursor)) # prompt options while 1: user_input = prompt( u'popREPL>', history=FileHistory('history.txt'), auto_suggest=AutoSuggestFromHistory(), completer=cli(), vi_mode=True, ) if user_input == 'mntSt1': # chain = mntSt1 # chainBash.extend('ls') # chain = '; '.join(chainBash) # print(deleteList) print(ipList) # execBash(chain) elif user_input == 'exit': print('exit') exit() else: print('Invalid Entry')
def main(): completer = MyCompleter() text = prompt('> ', completer=completer, complete_while_typing=True) #print('You said: %s' % text) main()
def run(self, command): command_split = shlex.split(command) if len(command_split) < 2: print('[-] Invalid arguments. You must indicate the client.') return client_id = self.c2_manager.get_client_id_by_client_name( command_split[1]) try: self.c2_manager.master_connection.send_service( client_id, self.MODULE_NAME, {'command': 'pwd'}) response = self.c2_manager.master_connection.recv_service_response( client_id, self.MODULE_NAME) if response is None: return if 'error' in response and response[ 'error'] == ClientModuleNotLoaded.CLIENT_ERROR_CODE_MODULE_NOT_FOUND and 'client_type' in response: raise ClientModuleNotLoaded(client_id, self.MODULE_NAME, response['client_type']) client_prompt = base64.b64decode(response['prompt']).decode() while True: commands = None user_input = prompt('C2 [{}/{}] {}'.format( self.parameters['environment'], self.c2_manager.get_client_name_by_client_id(client_id), client_prompt)) if user_input == 'clear': os.system('clear') continue if user_input == 'exit': resp = prompt( '\n[!] Are you sure you want to exit the shell? Y/n: ') if resp.lower() == 'y' or not resp: break else: continue if '>>>' in user_input: user_input_split = user_input.split('>>>') user_input = user_input_split[0] commands = user_input_split[1] elif user_input.startswith('!'): print(os.system(user_input[1:].strip())) continue self.c2_manager.master_connection.send_service( client_id, self.MODULE_NAME, {'command': user_input}) response = self.c2_manager.master_connection.recv_service_response( client_id, self.MODULE_NAME) result = response['result'] if commands is not None: command = 'echo "{}" | base64 -d | {}'.format( result, commands) os.system(command) else: print(base64.b64decode(result).decode()) client_prompt = base64.b64decode(response['prompt']).decode() except KeyboardInterrupt: print('\n[!] Are you sure you want to exit the shell? Y/N') resp = input().lower() if resp != 'y': self.run(command)
def create_upload_form(arguments, entyname=None): if entyname == None: uploadpath = args.media else: uploadpath = args.media + entyname #iF The Upload path is a diresctory pick a video file for screenshots,mediainfo,etc if os.path.isdir(uploadpath): for enty in os.scandir(uploadpath): if re.search(".mkv", enty.name) != None or re.search( ".mp4", enty.name) != None: path = uploadpath + "/" + enty.name #Else just use the file itself else: path = uploadpath typeid = setTypeID(path, args) setType(path, args) title = getTitle(uploadpath, args, typeid) print(title) correct = input("Title is it Correct for Blu?:") if correct != "y" and correct != "yes" and correct != "Yes" and correct != "YES" and correct != "Y": title_completer = WordCompleter([title]) title = prompt('Enter Title: ', completer=title_completer, complete_while_typing=True) dir = tempfile.TemporaryDirectory() imgs = Thread(target=create_images, args=(path, args, dir)) imgs.start() torrentpath = args.torrentdir + "[Blutopia]" + title + '.torrent' # torrentpath=f'"{torrentpath}"' torrent = Thread(target=create_torrent, args=(uploadpath, args, torrentpath)) torrent.start() cat = setCat(args.format) res = setResolution(path) if check_dupe(typeid, title, args, cat, res) == False: return imdbid = getimdb(path) tmdbid = IMDBtoTMDB(imdbid.movieID, args) torrent.join() imgs.join() form = { 'imdb': imdbid.movieID, 'name': title, 'description': upload_image(dir, args), 'category_id': cat, 'tmdb': tmdbid, 'type_id': typeid, 'resolution_id': res, 'user_id': args.userid, 'anonymous': args.anon, 'stream': args.stream, 'sd': is_sd(path), 'tvdb': '0', 'igdb': '0', 'mal': '0', 'mediainfo': get_mediainfo(path) } output = os.path.join(tempfile.gettempdir(), os.urandom(24).hex() + ".txt") if args.txtoutput == "yes": txt = open(output, 'a+') for key, value in form.items(): txt.write('%s:\n\n%s\n\n' % (key, value)) txt.close() output = {'file': open(output, 'r')} post = requests.post(url="https://uguu.se/api.php?d=upload-tool", files=output) print(post.text) if args.autoupload == "yes": torrent = {'torrent': open(torrentpath, 'rb')} torrenturl = "https://blutopia.xyz/api/torrents/upload?api_token=" + args.bluapi upload = requests.post(url=torrenturl, files=torrent, data=form) print(upload.text)
def SplitUnspentCoin(wallet, asset_id, from_addr, index, divisions, fee=Fixed8.Zero(), prompt_passwd=True): """ Split unspent asset vins into several vouts Args: wallet (neo.Wallet): wallet to show unspent coins from. asset_id (UInt256): a bytearray (len 32) representing an asset on the blockchain. from_addr (UInt160): a bytearray (len 20) representing an address. index (int): index of the unspent vin to split divisions (int): number of vouts to create fee (Fixed8): A fee to be attached to the Transaction for network processing purposes. prompt_passwd (bool): prompt password before processing the transaction Returns: neo.Core.TX.Transaction.ContractTransaction: contract transaction created """ if wallet is None: print("Please open a wallet.") return unspent_items = wallet.FindUnspentCoinsByAsset(asset_id, from_addr=from_addr) if not unspent_items: print(f"No unspent assets matching the arguments.") return if index < len(unspent_items): unspent_item = unspent_items[index] else: print(f"unspent-items: {unspent_items}") print( f"Could not find unspent item for asset {asset_id} with index {index}" ) return outputs = split_to_vouts(asset_id, from_addr, unspent_item.Output.Value, divisions) # subtract a fee from the first vout if outputs[0].Value > fee: outputs[0].Value -= fee else: print("Fee could not be subtracted from outputs.") return contract_tx = ContractTransaction(outputs=outputs, inputs=[unspent_item.Reference]) ctx = ContractParametersContext(contract_tx) wallet.Sign(ctx) print("Splitting: %s " % json.dumps(contract_tx.ToJson(), indent=4)) if prompt_passwd: passwd = prompt("[Password]> ", is_password=True) if not wallet.ValidatePassword(passwd): print("incorrect password") return if ctx.Completed: contract_tx.scripts = ctx.GetScripts() relayed = NodeLeader.Instance().Relay(contract_tx) if relayed: wallet.SaveTransaction(contract_tx) print("Relayed Tx: %s " % contract_tx.Hash.ToString()) return contract_tx else: print("Could not relay tx %s " % contract_tx.Hash.ToString())
if __name__ == "__main__": Database.initialise(database='chip', host='localhost', user='******') # invoice_list = owner.get_filter_result("Search By Nickname", invoice_type) invoice_list = owner.get_all_gst_invoices("sale_invoice") estimate_list = owner.get_all_unsaved_invoices("sale_invoice") invoice_dict = {} estimate_dict = {} for a in invoice_list: invoice_dict[str(a[4])] = "{}, {}, {}, {}".format(str(a[0]), str(a[2]), str(a[3]), str(a[1])) for a in estimate_list: estimate_dict[str(a[3])] = "{}, {}, {}".format(str(a[1]), str(a[2]), str(a[0])) invoice_list = [str(a[4]) for a in invoice_list] completer = WordCompleter(["Connection Pipe 18", "Connection Wired 18", "Connection PVC Heavy 18", "Connection PVC Heavy 24"],sentence=True, match_middle=True, ignore_case=True, invoice_list=invoice_list, invoice_dict=invoice_dict, estimate_list=[*estimate_dict], estimate_dict=estimate_dict ) result = prompt("Enter input: ", completer=completer) """ Simple autocompletion on a list of words. :param words: List of words. :param ignore_case: If True, case-insensitive completion. :param meta_dict: Optional dict mapping words to their meta-information. :param WORD: When True, use WORD characters. :param sentence: When True, don't complete by comparing the word before the cursor, but by comparing all the text before the cursor. In this case, the list of words is just a list of strings, where each string can contain spaces. (Can not be used together with the WORD option.) :param match_middle: When True, match not only the start, but also in the middle of the word. """
# Code for my ML peeps # Level: NOOB from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory bot_template = "BOT : {0}" def respond(message): bot_message = "I can hear you! You said: " + message return bot_message def send_message(message): response = respond(message) return bot_template.format(response) while input != ':q': input = prompt( "USER: "******"history.txt"), auto_suggest=AutoSuggestFromHistory(), ) print(send_message(input), "\n")
def get_prompt(self): """Build a sensible prompt.""" return prompt(message=self.prompt_message, history=self.prompt_history)
def _export_step(): print("Config is complete. What is next?\n\n" "1. Preview config in YAML format\n" "2. Save config to file\n" "3. Discard changes and exit\n") return prompt("Enter the number: ")