def run(self): if not self.quiet: version = "# **** FTIS v2.1.0a ****" self.console.print(Markdown(version)) # Construct information table corpora_paths = Table(title="Corpora", box=box.HORIZONTALS, show_lines=True) corpora_paths.add_column("Path") corpora_paths.add_column("Items", style="cyan") for c in self.corpora: corpora_paths.add_row(str(c.path), str(len(c.items))) print("\n") self.console.print(corpora_paths) sink_text = Text(f" Sink: {self.sink}") print("\n") self.console.print(sink_text) self.console.print(Markdown("---")) print("\n") for c in self.corpora: c.walk_chain() self.teardown()
def run(self): console.print( Markdown( 'Starting bot with the following `handlers` registered...')) console.print(Markdown('## Registered Handler')) table = Table(show_header=True, header_style='bold magenta', expand=True, box=box.SIMPLE_HEAVY) table.add_column('command', style='cyan') table.add_column('handler') for command, handler in self._handlers.items(): table.add_row(command, type(handler).__name__) console.print(table) self._connect() console.print( Markdown( 'Twitch connection successful and bot started! `Have fun`!')) console.print(Markdown('## Log')) read_thread = threading.Thread(target=self._read) write_thread = threading.Thread(target=self._write) read_thread.start() write_thread.start() read_thread.join() write_thread.join()
def check(self) -> bool: if not self.config.github_token: raise ValueError("need to set github token") new_repos = self.config.new_repositories unsync_secrets = self.config.unsynced_secrets if not new_repos and not unsync_secrets: print(f"{sty.sync_style('Everything is up to date')}") return True markdown_str = "# Github Secrets Check\n" if new_repos: markdown_str += "## New Repositories\n" markdown_str += "\n".join([f"- {repo}\n" for repo in new_repos]) markdown_str += '\n' if unsync_secrets: markdown_str += "\n## Unsynced Secrets" table = Table(show_header=True, header_style="bold") table.add_column("Repository") table.add_column("Secret") for sync_config in unsync_secrets: table.add_row(sync_config.repository, sync_config.secret_name) print(Markdown(markdown_str)) print(table) else: print(Markdown(markdown_str)) return False
async def plugin_command(ctx): all = [] doc = self.get_plugin_doc(name) doc.extract_metadata("examples") desc_string = f"## Mogrifier: **{name}**\n" if doc.get_short_help(default=None): desc_string += doc.get_short_help() + "\n\n" desc_string += f"\n## Input Arguments\n\nThis is the list of arguments the *{name}* mogrifier accepts as input:\n" desc = Markdown( desc_string, style=bring_style, code_theme=bring_code_theme, justify="left", ) all.append(desc) plugin = self.get_plugin(name) if hasattr(plugin, "_requires"): args = plugin._requires else: args = plugin.requires(None) record_arg = self._arg_hive.create_record_arg(childs=args) arg_table = to_rich_table(record_arg) all.append(arg_table) desc_string = f"\n## Output Arguments\n\nThis is the list of arguments the *{name}* mogrifier provides as output:\n" desc = Markdown( desc_string, style=bring_style, code_theme=bring_code_theme, justify="left", ) all.append(desc) if hasattr(plugin, "_provides"): args = plugin._provides else: args = plugin.provides(None) record_arg = self._arg_hive.create_record_arg(childs=args) arg_table = to_rich_table(record_arg) all.append(arg_table) desc_string = await create_pkg_type_markdown_string( bring=self.bring, plugin_doc=doc) desc = Markdown( desc_string, style=bring_style, code_theme=bring_code_theme, justify="left", ) all.append(desc) group = RenderGroup(*all) console.print(Panel(Panel(group, box=box.SIMPLE)))
def run_tests(dataset, schema, validity, duplicate, doi, duplicated_entries, markdown): print(f"Checking {dataset} against schema {schema}") check_list = [] table_list = [] error_list = [] danger_style = Style(color="red", blink=True) ok_style = Style(color="green") console = Console() try: check_list.append(check_extra_missing_columns(dataset, schema)) if duplicate: check_list.append(check_duplicates(dataset)) if doi: check_list.append(check_DOI_duplicates(dataset)) if duplicated_entries: check_list.append( check_duplicates_in_column(dataset, duplicated_entries.split(","))) if validity: check_list.append(check_validity(dataset, schema)) check_list = list(filter(None.__ne__, check_list)) [error_list.append(i[0]) for i in check_list] [table_list.append(i[1]) for i in check_list if len(i) > 1] error_list = ["* `" + i + "`\n" for i in error_list] if len(error_list) > 0: raise DatasetValidationError( f"**The following type of errors were found**:\n{''.join(error_list)}" ) else: md = Markdown("**All is good, no errors were found !**") console.print(md, style=ok_style) except DatasetValidationError as e: if markdown: print( "\n **Errors were found, please unfold below to see errors:**\n\n <details>\n\n```" ) for table in table_list: console.print(table) md = Markdown(str(e)) console.print(md, style=danger_style) if markdown: print("```\n</details>") sys.exit(1)
def format_markdown(self, index, cell, config): """Format the markdown cell content. Render only input and leave out output.""" panels = [] panels.append(self.format_index(index, source_type="input")) source = self.get_source_text(cell) if config.no_cell_border: panels.append("\n") panels.append(Markdown(source)) panels.append("\n") else: panels.append(Panel(Markdown(source))) return panels
def list_brazil_brands(): """List Brazil brands.""" console = Console() markdown = Markdown(""" - Liber - Antarctica - Cervejaria Wäls - Aqua Fratelli Vita - Cervejaria Colorado """) markdown = Markdown(markdown) console.print(markdown)
def print_param_header(self, param_id, param_obj): if "description" not in param_obj and "help_text" not in param_obj: return console = Console() console.print("\n") console.print(param_obj.get("title", param_id), style="bold") if "description" in param_obj: md = Markdown(param_obj["description"]) console.print(md) if "help_text" in param_obj: help_md = Markdown(param_obj["help_text"].strip()) console.print(help_md, style="dim") console.print("\n")
def rules_as_rich(rules: RulesCollection) -> Iterable[Table]: """Print documentation for a list of rules, returns empty string.""" for rule in rules: table = Table(show_header=True, header_style="title", box=box.MINIMAL) table.add_column(rule.id, style="dim", width=16) table.add_column(Markdown(rule.shortdesc)) table.add_row("description", Markdown(rule.description)) if rule.version_added: table.add_row("version_added", rule.version_added) if rule.tags: table.add_row("tags", ", ".join(rule.tags)) if rule.severity: table.add_row("severity", rule.severity) yield table
def print_param_header(self, param_id, param_obj, is_group=False): if "description" not in param_obj and "help_text" not in param_obj: return console = Console(force_terminal=nf_core.utils.rich_force_colors()) console.print("\n") console.print("[bold blue]?[/] [bold on black] {} [/]".format( param_obj.get("title", param_id))) if "description" in param_obj: md = Markdown(param_obj["description"]) console.print(md) if "help_text" in param_obj: help_md = Markdown(param_obj["help_text"].strip()) console.print(help_md, style="dim") if is_group: console.print("(Use arrow keys)", style="italic", highlight=False)
def prepare_build(console, args): console.print(Markdown("- **Check the build configuration**")) console.print(TAB + '> Number of documents to retrieve:') if args.max_documents is None: if args.doc_ids: console.print( TAB + ' ⮡ [bold blue]! Document ids provided. The number of documents to retrieve will be automatically determined.') else: console.print( TAB + ' ⮡ [bold blue]! No maximum number of documents specified, the number of documents to retrieve will be automatically determined.') else: console.print(TAB + ' ⮡ [bold blue]! Database will be built with a maximum number of {} documents'.format( args.max_documents)) if args.doc_ids: console.print(TAB + '> Documents for the build:') f_ids = format_doc_ids(args.doc_ids) if len(f_ids) == 0: console.print(TAB + ' ⮡ [bold red]! All provided doc ids in wrong format') exit(1) else: console.print(TAB + ' ⮡ [bold blue]! Doc ids provided in correct format') doc_ids = f_ids else: doc_ids = None workflow = load_workflow(console, args) force, update = prepare_build_folder(console, args) place_lock(console) build_log_path = prepare_logs(console, args) return workflow, build_log_path, update, force, doc_ids
def prompt(upgrade_from: Version, upgrade_to: Version) -> bool: """ Returns ``True`` if the user wants to upgrade, ``False`` otherwise. """ if answered_yes_to( f"See what changed from v{upgrade_from} to v{upgrade_to}?", ): release_notes = get_release_notes() all_versions = get_versions_list_from_release_notes(release_notes) # If the version jump is more than one version, print concatednated release notes # so that the user can get all of the changes. # eg: i'm upgrading from 0.6.0 to 0.10.0, but there has been 0.8.0 and 0.9.0 in between, # i want all the changes, not just the ones from 0.9.0 to 0.10.0 if len([v for v in all_versions if upgrade_from < v <= upgrade_to]) > 1: notes = get_release_notes_between_versions(release_notes, upgrade_from, upgrade_to) # else just get the single one. # this is because doing get_release_notes_between_versions would still return # the version <h2>, which would be stupid to show here else: notes = get_release_notes_for_version(release_notes, upgrade_to) print( Rule( f"Release notes for [bold blue]{upgrade_from}[/] [magenta]->[/] [bold blue]{upgrade_to}[/]" )) print(Markdown(notes)) return answered_yes_to("Update now?") return True
def render2markdown(file_string, options={}): "Render file or string to Markdown" file_string = file_string.strip() if os.path.isfile(file_string): with open(file_string) as md: markdown = md.read() else: markdown = file_string page = options.get("page", False) justify = options.get("justify", False) code_theme = options.get("code_theme", "monokai") hyperlinks = options.get("hyperlinks", False) inline_code_lexer = options.get("inline_code_lexer") print_output( Markdown( markdown, justify="full" if justify else "left", code_theme=code_theme, hyperlinks=hyperlinks, inline_code_lexer=inline_code_lexer, ), page, )
def report_outcome(matches: List["MatchError"], options) -> int: """Display information about how to skip found rules. Returns exit code, 2 if erros were found, 0 when only warnings were found. """ failure = False msg = """\ You can skip specific rules by adding them to the skip_list section of your configuration file: ```yaml # .ansible-lint warn_list: # or 'skip_list' to silence them completely """ matched_rules = {match.rule.id: match.rule.shortdesc for match in matches} for id in sorted(matched_rules.keys()): if id not in options.warn_list: msg += f" - '{id}' # {matched_rules[id]}'\n" failure = True msg += "```" if failure: if not options.quiet and not options.parseable: console.print(Markdown(msg)) return 2 else: return 0
async def __get_migration_title(database_name: str) -> Markdown: """Get a migration title. :param database_name: Database name :return: Migration title """ return Markdown(f"# {database_name} database", style="bold magenta")
def check_for_updates() -> None: """Checks for new releases. Using Github API checks for new release and prints information of new release if available. """ console = Console() try: headers: dict = { "Content-Type": "application/json", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36", } conn = http.client.HTTPSConnection("api.github.com") conn.request( method="GET", url= "/repos/Dineshkarthik/telegram_media_downloader/releases/latest", headers=headers, ) res = conn.getresponse() latest_release: dict = json.loads(res.read().decode("utf-8")) if f"v{__version__}" != latest_release["tag_name"]: update_message: str = ( f"## New version of Telegram-Media-Downloader is available - {latest_release['name']}\n" f"You are using an outdated version v{__version__} please pull in the changes using `git pull` or download the latest release.\n\n" f"Find more details about the latest release here - {latest_release['html_url']}" ) console.print(Markdown(update_message)) except Exception as e: console.log( f"Following error occured when checking for updates\n{e.__class__}, {e}" )
def report_outcome(matches: List["MatchError"], options) -> int: """Display information about how to skip found rules. Returns exit code, 2 if errors were found, 0 when only warnings were found. """ failure = False msg = """\ You can skip specific rules or tags by adding them to your configuration file: ```yaml # .ansible-lint warn_list: # or 'skip_list' to silence them completely """ matches_unignored = [match for match in matches if not match.ignored] matched_rules = {match.rule.id: match.rule for match in matches_unignored} for id in sorted(matched_rules.keys()): if {id, *matched_rules[id].tags}.isdisjoint(options.warn_list): msg += f" - '{id}' # {matched_rules[id].shortdesc}\n" failure = True for match in matches: if "experimental" in match.rule.tags: msg += " - experimental # all rules tagged as experimental\n" break msg += "```" if matches and not options.quiet: console_stderr.print(Markdown(msg)) if failure: return 2 else: return 0
def get_rich(self): lines = [] for endpoint in self.raw: out = f" * {endpoint['qtsp_id']} @ {endpoint['signDoc']}\n conformance_levels_supported: {', '.join(endpoint['conformance_levels_supported'])}" lines.append(out) return Markdown("\n".join(lines))
def search_note(self) -> None: """ Function that displays a tree with Panels as child nodes with the notes searched """ root = Tree('📒[bold #964B00] List of Notes Found') query = self.sql_query() if query: notes_sorted = sorted(query, key=sorter) actual_note = notes_sorted[0] actual_category = actual_note[2] child_node = root.add(f':file_folder:[#d898ed]{actual_category}') for actual_note in notes_sorted: if actual_note[2] != actual_category: actual_category = actual_note[2] child_node = root.add(f':file_folder: [#d898ed]{actual_category}') if actual_note[3] == 0: child_node.add( Panel( actual_note[1] if actual_note[1] else '[red bold]Empty note[/red bold]', title=f'{actual_note[0]} {actual_note[4]}' ) ) else: # actual_note[3] == 1 markdown = Markdown( actual_note[1] if actual_note[1] else '# Note Empty') child_node.add( Panel(markdown, title=f'{actual_note[0]} {actual_note[4]}') ) else: root.add('[red]❌ No Note Found') self.console.print(root)
def main(url, verbose, plugin, verify, disable, delay, engine, workers, **kwargs): """This script will crawl give URL and analyse the output using plugins.""" if verbose: traceback_install() if url is None: console = Console() ctx = click.get_current_context() try: with open("README.md") as f: rawMarkdown = f.read() md = Markdown(rawMarkdown) console.print(md) console.print("\n") except FileNotFoundError: pass console.print(ctx.get_help()) ctx.exit() crawler = Crawler( url, verbose=verbose, plugins=plugin, verify=verify, disabled=disable, delay=delay, engine=engine, plugin_options=kwargs, ) asyncio.run(crawler.crawl())
def display_config(self) -> None: msg = yaml.dump(dict(self.cfg), default_flow_style=False, tags=False, sort_keys=False) term.print( Markdown("```yaml\n# %s\n%s\n```" % (self.cfg.config_file, msg)))
def comments( id: str, workspace: str = get_workspace(), slug: str = get_slug(), ): """View comments for PR by ID""" url = comments_url.format(workspace=workspace, slug=slug, id=id) console = Console() with console.status("[bold green]Loading..."): resp = get(url) handle_error(resp) for comment in resp["values"]: user = comment["user"]["display_name"] updated = parse_dt(comment["updated_on"]) path = comment["inline"]["path"] # _from = comment["inline"]["from"] or "" to = comment["inline"]["to"] or "" line = f":{to}" if to else "" deleted = "(Deleted)" if comment["deleted"] else "" console.print( f"[bold]{user}[/bold] {path}{line} [dim]{updated}[/dim] {deleted}" ) markdown = comment["content"]["raw"] console.print(Padding(Markdown(markdown, code_theme=config.THEME), 1))
def documentation(self, title: str, doc: str, markdown: bool = False): self.__console.rule(f"[bold yellow]{title}", align="center") if markdown: md = Markdown(doc) self.__console.print(md, justify="center") else: self.__console.print(f"[bold yellow]{doc}", justify="left")
def console(msg: Union[str, Text, Tree, Table, JSON] = ' ', nl: bool = False, nlb: bool = False, end: str = '\n', plain: bool = False, isError: bool = False, isHeader: bool = False) -> None: """ Print a message or object on the console. """ # if this is a header then call the method again with different parameters if isHeader: Logging.console(f'**{msg}**', nlb=True, nl=True) return style = Logging.terminalStyle if not isError else Logging.terminalStyleError if nlb: # Empty line before Logging._console.print() if isinstance(msg, str): Logging._console.print(msg if plain else Markdown(msg), style=style, end=end) elif isinstance(msg, dict): Logging._console.print(msg, style=style, end=end) elif isinstance(msg, (Tree, Table, Text)): Logging._console.print(msg, style=style, end=end) if nl: # Empty line after Logging._console.print()
def menu(): while True: """Function for displaying main menu""" print("\n \n [u]Welcome to [bold red]Oregon Trail[/bold red]:\ Python Edition![/u]\n") # Menu option selection handlers print("1.) Start") print("2.) Exit") print("3.) Changelog") option = input("\n--> ") if option == "start": job() break elif option == "exit": continue elif option == "1": job() break elif option == "2": continue elif option == "3": with open("changelog.md") as md: markdown = Markdown(md.read()) console.print(markdown) else: print("[bold red]Invalid Selection[/bold red]")
def make_card( title: Optional[str], right_of_title: str, description: str, labels: Iterable[Label], card_title: str, card_style: str = "default", ) -> Panel: title = title or "" # no silly 'None' as title header = Table.grid(expand=True) header.add_column() header.add_column(justify="right") header.add_row( f"[bold]{rich.markup.escape(title)}", f"[bold blue]{right_of_title}", ) card = Table.grid(padding=1, expand=True) card.add_column() card.add_row(header) card.add_row(Markdown(description)) if labels: label_row = Table.grid(expand=True) label_row.add_column(justify="right") label_row.add_row(", ".join(map(str, labels))) card.add_row(label_row) return Panel( card, title=card_title, style=card_style, box=rich.box.ROUNDED if "on " not in card_style else Box(" \n" * 8), )
def info(self): """ Return info of the directive """ console = Console() md = Markdown(self.get_markdown()) console.print(md)
def print_mark_down_text(self): rendered_markdown = Markdown(self.markdown_text) if self.do_console_print: self.console.print(rendered_markdown) return rendered_markdown
def handle(self, *args, **options): if options['id']: article = Articles.objects.get(id=int(options['id'])) content = pypandoc.convert_text(article.text, 'markdown_github', format='html') table = Table(show_header=True, header_style="bold magenta") table.add_column("ID") table.add_column("Title") table.add_column("Body") table.add_row(str(article.id), article.title, Markdown(content)) article.read = True article.save() else: articles = Articles.objects.all() table = Table(show_header=True, header_style="bold magenta") table.add_column("ID") table.add_column("Feeds") table.add_column("Title") table.add_column("Read") table.add_column("Later") table.add_column("Created") for line in articles: read = "[green]Unread[/]" if line.read is False else "[yellow]Read[/]" read_later = "[green]Unread[/]" if line.read_later is False else "[yellow]Read[/]" table.add_row(str(line.id), line.feeds.title, line.title, read, read_later, str(line.date_created)) console.print(table)
def report_check_result(result): table = Table(title="Check Result", show_lines=True, width=100, box=box.ROUNDED) table.add_column("Pass/Fail", justify="center") table.add_column("Requirement") table.add_column("Tips") for requirement, fail_reason in result: if not fail_reason: table.add_row("✅", Markdown(requirement, style="green"), "") continue elif type(fail_reason) is AssertionError: tb = traceback.extract_tb(fail_reason.__traceback__, limit=-1) if fail_reason.args: reason_txt = fail_reason.args[0] else: reason_txt = Text.assemble( ("AssertionError", "bold red"), (": We expected\n", "blue"), (tb[0].line.replace("assert ", "") + "\n", "white"), ) elif type(fail_reason) is AttributeError: fail_reason = str(fail_reason).split(" ") reason_txt = Text.assemble( ("AttributeError", "bold red"), (": The ", "blue"), (fail_reason[0], "white"), (" ", ""), (" ".join(fail_reason[1:-1]), "blue"), (" ", ""), (fail_reason[-1], "white"), ) elif issubclass(type(fail_reason), Exception): reason_txt = Text.assemble( (type(fail_reason).__name__, "bold red"), (": " + str(fail_reason), "blue"), ) else: reason_txt = Text(str(fail_reason)) if type(reason_txt) is not Text: reason_txt = Markdown(reason_txt) table.add_row("❌", Markdown(requirement, style="red"), reason_txt) console.print(table)