def browse(current_date, data_base): while True: # show menu action = browse_menu(day_string(current_date, data_base)) clear() if action == "b": return elif action == "p" or action == "Keys.Right": current_date = change_date(current_date, -1) continue elif action == "n" or action == "Keys.Left": current_date = change_date(current_date, 1) continue elif action == "g": browse_date = prompt([ ('class:key', 'Which day do you want to display (YYYYMMDD)? ') ], style=style) try: datetime.strptime(browse_date, "%Y%m%d") #check if formatted correctly current_date = browse_date except: print("Invalid date, use format YYYYMMDD, e.g. 20200420") continue
async def show_availability(self): name = await self._prompt_facility() dows = await self._prompt_dow(7) dows = ArrayDayOfWeek(map(DayOfWeek, dows)) res = await self._proxy.query_availability(String(name), dows) if "error" in res: self._print_error(str(res.value)) return clear() print( HTML( f"<b>Availability periods for</b> <ansigreen><u>{name}</u></ansigreen>:" )) def formatted_gen(): for tr in res.value: dtrange = rpc_tr_as_dtrange(tr) yield ( DayOfWeek.VALUES(dtrange.start.weekday()).name, dtrange.start_str, dtrange.end_str, ) table_data = tuple(formatted_gen()) print( tabulate( table_data, headers=("Weekday", "Start", "End"), stralign="left", tablefmt="psql", )) self._known_facilities.add(name)
async def interact(connection): write = connection.send # When a client is connected, erase the screen from the client and say # Hello. clear() write('Welcome to our chat application!\n') write('All connected clients will receive what you say.\n') name = await prompt(message='Type your name: ', async_=True) # Random color. color = random.choice(COLORS) _connection_to_color[connection] = color # Send 'connected' message. _send_to_everyone(connection, name, '(connected)', color) # Prompt. prompt_msg = HTML('<reverse fg="{}">[{}]</reverse> > ').format( color, name) _connections.append(connection) try: # Set Application. while True: try: result = await prompt(message=prompt_msg, async_=True) _send_to_everyone(connection, name, result, color) except KeyboardInterrupt: pass except EOFError: _send_to_everyone(connection, name, '(leaving)', color) finally: _connections.remove(connection)
async def book(self): """ Book handles the "book" command. """ name = await self._prompt_facility() print(HTML("<u>Enter <b>start</b> time</u>:")) start = await self._prompt_time() print(HTML("<u>Enter <b>end</b> time</u>")) end = await self._prompt_time() try: rpc_tr = dtrange_as_rpc_tr(DateTimeRange(start, end)) except ValueError as e: self._print_error(f"invalid time range: {e.args[0]}") return res = await self._proxy.book(String(name), rpc_tr) if "error" in res: self._print_error(str(res.value)) return clear() print( HTML(f"<ansigreen>Successfully</ansigreen> booked {name}." f" Confirmation ID: <b><u>{res.value}</u></b>."))
async def interact(connection): write = connection.send # When a client is connected, erase the screen from the client and say # Hello. clear() write('Welcome to our chat application!\n') write('All connected clients will receive what you say.\n') name = await prompt(message='Type your name: ', async_=True) # Random color. color = random.choice(COLORS) _connection_to_color[connection] = color # Send 'connected' message. _send_to_everyone(connection, name, '(connected)', color) # Prompt. prompt_msg = HTML('<reverse fg="{}">[{}]</reverse> > ').format(color, name) _connections.append(connection) try: # Set Application. while True: try: result = await prompt(message=prompt_msg, async_=True) _send_to_everyone(connection, name, result, color) except KeyboardInterrupt: pass except EOFError: _send_to_everyone(connection, name, '(leaving)', color) finally: _connections.remove(connection)
def clear_(event): # pylint: disable=unused-variable """ Clear the screen. """ clear() print(env.welcome) print(env.get_prompt(), end="")
def handle(self): command, *args = self.text.strip().split(" ") self._args = args if command == self.ENV_COMMAND_CLEAR: clear() elif command == self.ENV_COMMAND_LIST: self.command_list()
def client_execute_command(self, command_name, *args): command = command_name.upper() if command == "HELP": yield self.do_help(*args) if command == "PEEK": yield from self.do_peek(*args) if command == "CLEAR": clear() if command == "EXIT": exit()
async def interact(connection): clear() connection.send("Welcome!\n") # Ask for input. result = await prompt(message="Say something: ", async_=True) # Send output. connection.send("You said: {}\n".format(result)) connection.send("Bye.\n")
def interact(connection): clear() connection.send('Welcome!\n') # Ask for input. result = yield From(prompt(message='Say something: ', async_=True)) # Send output. connection.send('You said: {}\n'.format(result)) connection.send('Bye.\n')
async def _run_buffer(): buffer_filename = f"{current_file or 'buffer'}.qpython" with open(buffer_filename, "w") as buffer_file: buffer_file.write(app.current_buffer.text) try: clear() await app.run_system_command(f'{sys.executable} "{buffer_filename}"') finally: os.remove(buffer_filename)
def _init_window(self): clear() set_title("Test Infra CLI") if not self._global_variables.pull_secret: message_dialog( title="Pull Secret", text= "Cant find PULL_SECRET, some functionality might not work as expected" ).run()
def run(self): while True: try: text = self.session.prompt('> ') if text.strip() == "*": clear() else: self.func(text) except KeyboardInterrupt: continue except EOFError: break print('GoodBye!')
def clear_screen(args: Dict): """ Clears the screen and resets the prompt to the top left hand corner of the terminal just as in bash shell Usage: clear [options] Options: -h, --help Shows this message """ clear() # Clear the screen with the built in macro
def render_chain(path_to_chain, title): clear() all_links = read_in_all_links(path_to_chain) unbroken_links = links_to_today(all_links) dates_with_colors = make_dates_with_colors(unbroken_links) output = make_blocks(dates_with_colors) streak_count = len([d for d in dates_with_colors if d.color == 'red']) print( HTML( f'<bold><title> â–¶ {title.upper()} â—€ </title><title>({streak_count})</title></bold>' ), style=style, ) print(HTML(output))
def evaluate(command, args): res = None global library if command == 'print': res = args elif command == 'help': res = render_help_text() elif command == 'clear': clear() elif command == 'exit': res = 'Press CTRL + D to exit' else: res = dispatch(command, args) return res
async def list_facilities(self): """ list_facilities handles the "list" command. """ res = await self._proxy.facilities() facilities = tuple(map(str, res)) clear() print( tabulate( tuple((f, ) for f in facilities), headers=("Available facilities", ), tablefmt="psql", )) self._known_facilities.update(facilities)
async def _run_buffer(debug: bool = False): buffer_filename = f"{current_file or 'buffer'}.qpython" with open(buffer_filename, "w") as buffer_file: user_code = app.current_buffer.text if not user_code.endswith("\n"): user_code += "\n" with_qpython_injected = isort.code(user_code, add_imports=["import quickpython.extensions"]) buffer_file.write(isort_format_code(with_qpython_injected)) if debug: buffer_file.write("breakpoint()") try: clear() os.environ["PYTHONBREAKPOINT"] = "ipdb.set_trace" await app.run_system_command(f'{sys.executable} "{buffer_filename}"') finally: os.remove(buffer_filename)
async def modify(self): """ modify handles the "modify" command. """ bid = await self._prompt_bid() shift = await self._prompt_timedelta() res = await self._proxy.modify(String(bid), shift) if "error" in res: self._print_error(str(res.value)) return clear() print( HTML(f"<ansigreen>Successfully</ansigreen> modified booking" f" <b><u>{res.value}</u></b>."))
async def cancel(self): """ cancel handles the "cancel" command. """ bid = await self._prompt_bid() res = await self._proxy.cancel(String(bid)) if "error" in res: self._print_error(str(res.value)) return clear() print( HTML( f"<ansigreen>Successfully</ansigreen> canceled booking <u>{bid}</u>" ))
def do_reflection(time, data_base): # load questions from database Questions = Query() questions = get_questions(time, data_base) # TODO check for empty questions if len(questions) == 0: clear_screen() print("No questions for %s reflection. Add some questions.\n" % time) return #load answers for today if they are there Answers = Query() old_answers = data_base.search((Answers.time == time) & (Answers.date == today()) & (Answers.type == "reflection")) old_answers = (old_answers[0] if len(old_answers) > 0 else {}) answers = {} answers["time"] = time answers["type"] = "reflection" answers["date"] = today() # store answers for today in database ref_qs = [] for i, q in enumerate(questions): default = old_answers[q["id"]] if q["id"] in old_answers else "" new_answer = prompt([('class:key', q["text"].replace("?", "") + "?"), ('class:default_answer', " <%s>: " % default)], style=style) if len(new_answer) > 0: answers[q["id"]] = new_answer else: answers[q["id"]] = default if len(old_answers) == 0 and i == 0: data_base.insert(answers) else: data_base.update(answers, (Answers.time == time) & (Answers.date == today()) & (Answers.type == "reflection")) clear() print("%s-reflection stored.\n" % time)
async def swap(self): """ swap handles the "swap" command. """ print(HTML("<u>Enter <b>first</b> booking</u>:")) bid1 = await self._prompt_bid() print(HTML("<u>Enter <b>second</b> booking</u>")) bid2 = await self._prompt_bid() res = await self._proxy.swap(String(bid1), String(bid2)) if "error" in res: self._print_error(str(res.value)) return clear() print( HTML( f"<ansigreen>Successfully</ansigreen> swapped bookings <b><u>{bid1}</u></b> and <b><u>{bid2}</u></b>." ))
async def lookup(self): """ lookup handles the "lookup" command. """ bid = await self._prompt_bid() res = await self._proxy.lookup(String(bid)) if "error" in res: self._print_error(str(res.value)) return booking = res["booking"] facility = str(booking["facility"]) dtrange = rpc_tr_as_dtrange(booking["trange"]) clear() print( HTML( f"Booking <b><u>{bid}</u></b> <ansigreen>exists</ansigreen> and corresponds to the time period\n" f"<i>{dtrange}</i> for facility <b>{facility}</b>."))
def enter_wallet_words(self) -> str: print("\nEnter BIP39 phrase for wallet below (CTRL-D to submit): ") lines: List = [] while True: try: line = prompt("", completer=self.WalletWordCompleter, **self.options).strip() except EOFError: break words = line.lower().split() if set(words).issubset(WalletWords): lines += words else: for word in words: if word not in ShardWords: print(("{} is not a valid wallet word, " + "ignoring last line").format(word)) shortcuts.clear() return ' '.join(lines)
def execute(self, command): command = command.strip() if command == "exit": self.settings.save_settings() sys.exit(0) elif command == "clear": shortcuts.clear() elif command == "save": self.settings.save_settings() print("Saved settings!") elif command == "version": print(version.get_version()) elif command.startswith("cluster-"): self.execute_cluster_command(command) elif command.startswith(valid_command_prefixes): self.execute_valid_command(command)
def main(): global gprint with GoCLI() as cli: gprint = gprint(cli.current_buffer) while True: doc = cli.run() err, message = evaluate_exit_cond(doc) if err: gprint(message) break if doc.text == 'clear': clear() continue response = repl(doc.text.strip().rstrip(';;'), file_name='test.go') result = response.evaluate() gprint(result) #gprint(response) #if line breaks then increase the counter cli.current_buffer.inc()
async def register_notifications(self): """ register_notifications handles the "register" command. """ facility = await self._prompt_facility() monitoring_time = await self._prompt_monitoring_time() res = await self._proxy.register_notification(u32(self._cbport), u64(0), String(facility), monitoring_time) if "error" in res: self._print_error(res.value) return self._known_facilities.add(facility) clear() print( HTML( f"<ansigreen>Successfully</ansigreen> registered for notifications regarding <u>{facility}</u>." ))
def enter_shard_words(self, name: str) -> str: print(("\nEnter SLIP39 phrase for shard {} below (CTRL-D to submit):". format(name))) lines: List = [] while True: try: line = prompt("", completer=self.ShardWordCompleter, **self.options).strip() except EOFError: break # Test against wordlist words = line.lower().split() if set(words).issubset(ShardWords): lines += words else: for word in words: if word not in ShardWords: print(("{} is not a valid shard word, " + "ignoring last line").format(word)) shortcuts.clear() return ' '.join(lines)
def interact(self): """ Automatically generate an example configuration in interactive mode. Returns ------- configuration : str The generated configuration as a formatted string. Note ---- This method should *only* be used in terminals, and not in Jupyter notebooks. """ # clear the screen first clear() # print the preamble and some instructions sys.stderr.write("\n") sys.stderr.write("Entering interactive mode:\n") sys.stderr.write( " - press ctrl-d to exit without generating a configuration\n") sys.stderr.write( " - press tab or start typing when choosing files/directories/models\n" ) sys.stderr.write( " - press enter to accept the default value for a field (underlined)\n" ) sys.stderr.write( " - press ctrl-c to cancel current entry for a field and enter again\n" ) sys.stderr.write( " - you may still need to edit the generated configuration\n") sys.stderr.write("\n") if not self.use_subgroups: sys.stderr.write( "IMPORTANT: If you have subgroups and didn't specify the '-g' " "option, exit now (ctrl-d) and re-run!\n") sys.stderr.write("\n") # instantiate a blank dictionary configdict = OrderedDict() # iterate over the required fields first, and then the (sorted) optional fields # keep track of which field type we are currently dealing with for field_type, field_name in chain( product(['required'], self._required_fields), product(['optional'], self._optional_fields)): # skip the subgroups field unless we were told to use subgroups if field_name == 'subgroups' and not self.use_subgroups: configdict['subgroups'] = DEFAULTS.get('subgroups') continue # if the field is not one that is meant to be filled interactively, # then just use its default value; for "general_sections", expand it # so that it is easy for the user to remove sections if field_name not in INTERACTIVE_MODE_METADATA: non_interactive_field_value = DEFAULTS.get(field_name, '') if field_name == 'general_sections': non_interactive_field_value = self._get_all_general_section_names( ) configdict[field_name] = non_interactive_field_value else: # instantiate the interactive field first try: interactive_field = InteractiveField( field_name, field_type, INTERACTIVE_MODE_METADATA[field_name]) configdict[field_name] = interactive_field.get_value() # if the user pressed Ctrl-D, then exit out of interactive mode # without generating anything and return an empty string except EOFError: sys.stderr.write("\n") sys.stderr.write( "You exited interactive mode without a configuration.") sys.stderr.write("\n") return '' # otherwise get the field value and save it # create a Configuration instance from the dictionary we just generated sys.stderr.write("\n") config_object = Configuration(configdict, configdir=os.getcwd(), context=self.context) # convert the Configuration object to a string - we are using # a special wrapper method since we also want to insert comments return self._convert_to_string(config_object, insert_required_comment=False)
def __clear(): try: clear() except: print("Something went wrong... clear() 122 main.py")
def source_new_column(self, target_type, add=None, source_field: Field = None, source_type: Type = None, custom: list = None): """ We know what Field the new column should be of, now determine how we should extend it: Summarize what order has the source field and what type the source field should be considered alike. :type source_field: Field :type source_type: Type :type target_type: Type :type add: bool if the column should be added to the table; None ask :type custom: List :return Field """ if custom is None: # default [] would be evaluated at the time the function is defined, multiple columns may share the same function custom = [] dialog = Dialog(autowidgetsize=True) if not source_field or not source_type: print("\nWhat column we base {} on?".format(target_type)) guesses = self.parser.identifier.get_fitting_source_i(target_type) source_col_i = pick_option(self.parser.get_fields_autodetection(), title="Searching source for " + str(target_type), guesses=guesses) source_field = self.parser.fields[source_col_i] source_type = self.parser.identifier.get_fitting_type( source_col_i, target_type, try_plaintext=True) if source_type is None: # ask how should be treated the column as, even it seems not valid # list all known methods to compute the desired new_field (e.g. for incident-contact it is: ip, hostname, ...) choices = [(k.name, k.description) for k, _ in graph.dijkstra( target_type, ignore_private=True).items()] # if len(choices) == 1 and choices[0][0] == Types.plaintext: # # if the only method is derivable from a plaintext, no worries that a method # # converting the column type to "plaintext" is not defined; everything's plaintext # source_type = Types.plaintext # el if choices: s = "" if self.parser.sample_parsed: s = f"\n\nWhat type of value '{self.parser.sample_parsed[0][source_col_i]}' is?" title = f"Choose the right method\n\nNo known method for making {target_type} from column {source_field} because the column type wasn't identified. How should I treat the column?{s}" code, source_type = dialog.menu(title, choices=choices) if code == "cancel": return source_type = getattr(Types, source_type) else: dialog.msgbox( "No known method for making {}. Raise your usecase as an issue at {}." .format(target_type, Config.PROJECT_SITE)) return clear() if not custom: if target_type.group == TypeGroup.custom: if target_type == Types.code: print( "What code should be executed? Change 'x'. Ex: x += \"append\";" ) custom = Preview(source_field, source_type).code() elif target_type in [Types.reg, Types.reg_m, Types.reg_s]: *custom, target_type = Preview(source_field, source_type, target_type).reg() elif target_type == Types.external: # choose a file with a needed method while True: title = "What .py file should be used as custom source?" try: code, path = dialog.fselect(str(Path.cwd()), title=title) except DialogError as e: try: # I do not know why, fselect stopped working and this helped code, path = dialog.fselect( str(Path.cwd()), title=title, height=max(get_terminal_size()[0] - 20, 10)) except DialogError as e: input( "Unable launch file dialog. Please post an issue to the Github! Hit any key..." ) return if code != "ok" or not path: return module = get_module_from_path(path) if module: # inspect the .py file, extract methods and let the user choose one code, method_name = dialog.menu( f"What method should be used in the file {path}?", choices=[(x, "") for x in dir(module) if not x.startswith("_")]) if code == "cancel": return custom = path, method_name break else: dialog.msgbox( "The file {} does not exist or is not a valid .py file." .format(path)) if not custom: return path = graph.dijkstra(target_type, start=source_type, ignore_private=True) for i in range(len(path) - 1): m = methods[path[i], path[i + 1]] if isinstance(m, PickBase): c = None if Config.get("yes"): pass elif type(m) is PickMethod: m: PickMethod code, c = dialog.menu(f"Choose subtype", choices=m.get_options()) if code == "cancel": return elif type(m) is PickInput: m: PickInput c = Preview(source_field, source_type, target_type).pick_input(m) custom.insert(0, c) if add is None: if dialog.yesno( "New field added: {}\n\nDo you want to include this field as a new column?" .format(target_type)) == "ok": add = True f = Field(target_type, is_chosen=add, source_field=source_field, source_type=source_type, new_custom=custom) self.parser.settings["add"].append(f) self.parser.add_field(append=f) return f