Exemple #1
0
def render():
    console = Console(file=io.StringIO(), width=100)

    console.rule("empty")
    empty_columns = Columns([])
    console.print(empty_columns)
    columns = Columns(COLUMN_DATA)
    console.rule("optimal")
    console.print(columns)
    console.rule("optimal, expand")
    columns.expand = True
    console.print(columns)
    console.rule("columm first, optimal")
    columns.column_first = True
    columns.expand = False
    console.print(columns)
    console.rule("column first, right to left")
    columns.right_to_left = True
    console.print(columns)
    console.rule("equal columns, expand")
    columns.equal = True
    columns.expand = True
    console.print(columns)
    console.rule("fixed width")
    columns.width = 16
    console.print(columns)
    console.print()

    render_result = console.file.getvalue()
    return render_result
Exemple #2
0
def print_inference_summary(
    time_delta: str,
    pattern: str,
    directory: Path,
    csv_fname: Path,
    image_format: Union[List[str], str],
    matched_file_count: int,
    model_id: Optional[str] = None,
):
    """prints summary report"""
    print(flyswot_logo())
    if model_id:
        print(
            Panel(Columns([models.hub_model_link(model_id)]),
                  title="Model Info"))

    print(
        Panel(
            Text(f"CSV report file at: {csv_fname.as_uri()}", ),
            title=" :clipboard: CSV report :clipboard:",
        ))
    print(
        Panel(
            Text(f"{time_delta}", justify="center", style="bold green"),
            title=":stopwatch: Time taken to run :stopwatch:",
        ))
    print(
        create_file_summary_markdown(pattern, matched_file_count, directory,
                                     image_format))
    inference_summary_columns = get_inference_table_columns(csv_fname)
    print(Panel(Columns(inference_summary_columns),
                title="Prediction Summary"))
Exemple #3
0
    def __rich__(self) -> Columns:

        if self.cell_type == CellType.CODE:
            counter = self.exec_count or " "
            if settings.display_cell_index:
                panel_title = f"Index: {self.cell_index}"
            else:
                panel_title = None
            rendered_cell = Columns([
                f"\nIn [{counter}]:",
                Panel(
                    Syntax(self._source_excerpt,
                           "python",
                           background_color="default"),
                    width=int(rich.get_console().size[0] * 0.85),
                    title=panel_title,
                ),
            ])
        else:
            rendered_cell = Columns([
                "        ",
                Padding(NotebookMarkdown(self._source_excerpt), (1, 0, 1, 8)),
            ])

        return rendered_cell
def simulate(data: Dict):
    console = Console()
    queue = ProcessQueue()
    queue.fill_randomly(data["process_count"],
                        data["min_ex_t"],
                        data["max_ex_t"],
                        data["max_toa"])

    console.print(param_table(data))

    if data["verbose"]:
        console.print(queue.table(ProcessSorting.ET))

    s1 = Simulation(deepcopy(queue), fsfc_scheduler, "FSFC Scheduler")
    s2 = Simulation(deepcopy(queue), sjf_non_preemptive, "JSF Non Preemptive Scheduler")
    s3 = Simulation(deepcopy(queue), sjf_preemptive, "JSF Preemptive Scheduler")
    s4 = Simulation(deepcopy(queue), Rotational(), "Rotational Scheduler")

    s1.simulate()
    s2.simulate()
    s3.simulate()
    s4.simulate()

    stats1 = [
        s1.report(),
        s4.report()
    ]

    stats2 = [
        s2.report(),
        s3.report()
    ]

    console.print(Columns([Panel(i, expand=True) for i in stats1]))
    console.print(Columns([Panel(i, expand=True) for i in stats2]))
Exemple #5
0
def pretty_print_data(data):
    """
    Users rich to generate panels for individual API response fields for better readability!

    :param data: the response from ipdata.lookup
    """
    # we print single value panels first then multiple value panels for better organization
    single_value_panels = []
    multiple_value_panels = []

    # if data is empty do nothing
    if not data:
        return

    # push the blocklists field up a level, it's usually nested under the threat data
    if data.get("threat", {}).get("blocklists"):
        data["blocklists"] = data.get("threat", {}).pop("blocklists")

    # generate panels!
    for key, value in data.items():
        # simple case
        if type(value) in [str, bool]:
            single_value_panels.append(
                Panel(f"[b]{key}[/b]\n[yellow]{value}", expand=True))

        # if the value is a dictionary we generate a tree inside a panel
        if type(value) is dict:
            tree = Tree(key)
            for k, v in value.items():
                if key == "threat":
                    if v:
                        sub_tree = tree.add(f"[b]{k}[/b]\n[bright_red]{v}")
                    else:
                        sub_tree = tree.add(f"[b]{k}[/b]\n[green]{v}")
                else:
                    sub_tree = tree.add(f"[b]{k}[/b]\n[yellow]{v}")
            multiple_value_panels.append(Panel(tree, expand=False))

        # if value if a list we generate nested trees
        if type(value) is list:
            tree = Tree(key)
            for item in value:
                branch = tree.add("")
                for k, v in item.items():
                    _ = branch.add(f"[b]{k}[/b]\n[yellow]{v}")
            multiple_value_panels.append(Panel(tree, expand=False))

    # print the single value panels to the console
    console.print(Columns(single_value_panels), overflow="ignore", crop=False)

    # print the multiple value panels to the console
    console.print(Columns(multiple_value_panels),
                  overflow="ignore",
                  crop=False)
Exemple #6
0
        def make_header_columns():
            # Epoch and LR
            columns = [Text("#", justify="right", style="bold")]
            if learning_rate is not None:
                columns += [Text("LR", justify="right")]
            yield Columns(columns, align="center", width=6)

            # Training losses
            text = Align(
                Text("Total", justify="right", style="bold red"),
                width=col_width,
                align="center",
            )
            if multi_target:
                columns = [text] + [
                    Align(Text(n, justify="right", style="red"),
                          width=col_width) for n in losses_training.keys()
                ]
                yield Columns(columns, align="center", width=col_width)
            else:
                yield text

            # Validation losses
            if total_loss_validation is not None:
                text = Align(
                    Text("Total", justify="center", style="bold blue"),
                    width=col_width,
                    align="center",
                )
                if multi_target:
                    columns = [text] + [
                        Align(Text(n, justify="center", style="blue"),
                              width=col_width)
                        for n in losses_validation.keys()
                    ]
                    yield Columns(columns, align="center", width=col_width)
                else:
                    yield text

            # Metrics
            if metrics is not None:
                for name, values in metrics.items():
                    if isinstance(values, dict):
                        columns = [
                            Align(
                                Text(n, justify="center", style="purple"),
                                width=col_width,
                            ) for n in values.keys()
                        ]
                        yield Columns(columns, align="center", width=col_width)
                    else:
                        yield Align(Text(""), width=col_width)
Exemple #7
0
 def __rich__(self) -> Columns:
     try:
         if self._current_tag == None:
             return Columns([Panel(x) for x in self._tags], equal=True)
         else:
             pretty_tags = []
             for i, tag in enumerate(self._tags):
                 if self._current_tag == i:
                     pretty_tags.append(
                         Panel('[green]' + self._tags[i], title='X'))
                 else:
                     pretty_tags.append(Panel(self._tags[i]))
             return Columns(pretty_tags, equal=True)
             return Panel(self.progress)
     except Exception as e:
         print(e)
Exemple #8
0
def weights(config):
    manager = digitalocean.Manager(token=TOKEN)
    droplets = manager.get_all_droplets(tag_name=[TAG])
    if config.names == None:
        config.names = [droplet.name for droplet in droplets]

    meta = bittensor.metagraph.Metagraph()
    console = Console()
    meta.load()
    meta.sync()
    meta.save()
    for name in config.names:
        wallet = bittensor.wallet.Wallet(name=TAG, hotkey=name)
        if wallet.has_hotkey:
            try:
                uid_i = meta.hotkeys.index(wallet.hotkey.public_key)
                weights = meta.W[uid_i, :]

                # Chain weights column.
                chain_weight_cols_vals = ['[blue]{}[/blue]: '.format(name)]
                for uid_j, weight in enumerate(weights.tolist()):
                    if weight != 0:
                        chain_weight_cols_vals.append(
                            '[bold white frame]{} [dim green frame]{:.3}'.
                            format(uid_j, weight))
                chain_weight_columns = Columns(chain_weight_cols_vals,
                                               equal=True,
                                               expand=True)
                console.print(chain_weight_columns)

            except Exception as e:
                logger.exception(e)
Exemple #9
0
def start_commands(gradebook):
    command = ''
    print('Welcome!')
    print('Enter "course" to select a course to view')
    command = Prompt.ask("Enter a command")
    while command.lower() != 'end':
        if command == 'course':
            grid = Table()
            grid.add_column('ID')
            grid.add_column('Course')
            count = 1
            for course in gradebook.courses:
                grid.add_row(str(count), course.title)
                count += 1
            console.print(Columns(
                (grid, ),
                align="center",
                expand=True,
            ), )
            course_id = IntPrompt.ask(
                "Enter the ID of the course you want to view")
            console.clear()
            gradebook.courses[course_id - 1].print_grade_table()
            course_commands(gradebook.courses[course_id - 1])
            console.clear()
            print_grade_table(gradebook)
        elif command == 'help':
            print('[green bold] course: Pick a course to view')
            print('[red bold] end: Exit Scholaris')
        else:
            console.clear()
            print_grade_table(gradebook)
            print(
                "[red]Invalid command! Enter 'help' to see possible commands")
        command = Prompt.ask("Enter a command")
Exemple #10
0
def show_columns(data, headers):
    user_renderables = [
        Panel("\n".join([str(i) for i in d[1:]]), width=30, highlight=True, title=d[0], title_align='left', height=13)
        for d in data
    ]
    console = Console()
    console.print(Columns(user_renderables))
Exemple #11
0
    def __init__(
        self,
        df: pd.DataFrame,
        row_limit: int = 20,
        col_limit: int = 10,
        first_rows: bool = True,
        first_cols: bool = True,
        delay_time: int = 5,
    ) -> None:
        self.df = df.reset_index().rename(columns={"index": ""})
        self.table = Table(show_footer=False)
        self.table_centered = Columns((self.table, ),
                                      align="center",
                                      expand=True)
        self.num_colors = len(COLORS)
        self.delay_time = delay_time
        self.row_limit = row_limit
        self.first_rows = first_rows
        self.col_limit = col_limit
        self.first_cols = first_cols

        if first_cols:
            self.columns = self.df.columns[:col_limit]
        else:
            self.columns = list(self.df.columns[-col_limit:])
            self.columns.insert(0, "index")

        if first_rows:
            self.rows = self.df.values[:row_limit]
        else:
            self.rows = self.df.values[-row_limit:]

        console.clear()
Exemple #12
0
def generate(
    source: Path = DEFAULT_SOURCE,
    output_directory: Path = DEFAULT_OUTPUT_DIR,
    background_color: str = DEFAULT_BG,
    transparent: bool = DEFAULT_TRANSPARENT,
    base_url: str = DEFAULT_BASE_URL,
) -> None:
    """Generate Favicons"""  # noqa: D400

    favicons = Favicons(
        source=source,
        output_directory=output_directory,
        background_color=background_color,
        transparent=transparent,
        base_url=base_url,
    )

    favicons._validate()
    for fmt in track(
            favicons._formats,
            description="Generating Favicons...",
            total=len(favicons._formats),
            console=console,
    ):
        favicons._generate_single(fmt)

    generated = [Panel(item_name(f), expand=True) for f in favicons._formats]

    console.print(
        f"\n[green]Generated [b]{favicons.completed}[/b] icons:[/green]\n")
    console.print(Columns(generated))
Exemple #13
0
def assemble_panels(data):
    global console
    panel_list = [
        Panel.fit(get_panel(dataset)) for dataset in grouper(
            sorted(data.items(), key=lambda x: x[0]), max_height(), ("", {}))
    ]
    return Columns(panel_list)
Exemple #14
0
 def print_grade_table(self):
     table = self.generate_assignment_table()
     p_table = self.generate_overall_grade_table()
     console.print(
         Panel(
             RenderGroup(
                 Columns(
                     (table, ),
                     align="center",
                     expand=True,
                 ), Columns(
                     (p_table, ),
                     align="center",
                     expand=True,
                 )),
             title=f"[white bold]{self.title}",
         ))
Exemple #15
0
def get_inference_table_columns(csv_fname: Path) -> Columns:
    """print_inference_summary from `fname`"""
    labels_to_print = labels_from_csv(csv_fname)
    tables = [
        print_table(labels, f"Prediction summary {i+1}", print=False)
        for i, labels in enumerate(labels_to_print)
    ]
    return Columns(tables)
Exemple #16
0
def debug_info() -> None:
    """Show debug info relatives to the bot"""
    python_version = sys.version.replace("\n", "")
    pip_version = pip.__version__
    tuxbot_version = __version__
    dpy_version = discord.__version__

    uptime = os.popen("/usr/bin/uptime").read().strip().split()

    console.print(
        Panel("[bold blue]Debug Info", style="blue"), justify="center"
    )
    console.print()

    columns = Columns(expand=True, padding=2, align="center")

    table = Table(style="dim", border_style=BORDER_STYLE, box=box.HEAVY_HEAD)
    table.add_column(
        "Bot Info",
    )
    table.add_row(f"[u]Tuxbot version:[/u] {tuxbot_version}")
    table.add_row(f"[u]Major:[/u] {version_info.major}")
    table.add_row(f"[u]Minor:[/u] {version_info.minor}")
    table.add_row(f"[u]Micro:[/u] {version_info.micro}")
    table.add_row(f"[u]Level:[/u] {version_info.releaselevel}")
    table.add_row(f"[u]Last change:[/u] {version_info.info}")
    columns.add_renderable(table)

    table = Table(style="dim", border_style=BORDER_STYLE, box=box.HEAVY_HEAD)
    table.add_column(
        "Python Info",
    )
    table.add_row(f"[u]Python version:[/u] {python_version}")
    table.add_row(f"[u]Python executable path:[/u] {sys.executable}")
    table.add_row(f"[u]Pip version:[/u] {pip_version}")
    table.add_row(f"[u]Discord.py version:[/u] {dpy_version}")
    columns.add_renderable(table)

    table = Table(style="dim", border_style=BORDER_STYLE, box=box.HEAVY_HEAD)
    table.add_column(
        "Server Info",
    )
    table.add_row(f"[u]System:[/u] {os.uname().sysname}")
    table.add_row(f"[u]System arch:[/u] {os.uname().machine}")
    table.add_row(f"[u]Kernel:[/u] {os.uname().release}")
    table.add_row(f"[u]User:[/u] {os.getlogin()}")
    table.add_row(f"[u]Uptime:[/u] {uptime[2][:-1]}")
    table.add_row(
        f"[u]Load Average:[/u] {' '.join(map(str, os.getloadavg()))}"
    )
    columns.add_renderable(table)

    console.print(columns)
    console.print()

    sys.exit(os.EX_OK)
Exemple #17
0
def main(
        file: typer.FileText = typer.Argument(None, help="File to read, stdin otherwise"),
        colorize: bool = typer.Option(True, "--no-color"),
        n_columns: Optional[int] = typer.Option(None, "--columns", "-c"),
        ignore: Optional[str] = typer.Option(None, "--ignore", "-i", callback=list_topics),
        just: Optional[str] = typer.Option(None, "--just", "-j", callback=list_topics),
):
    topics = list(TOPICS)

    # We can take input from a stdin (pipes) or from a file
    input_ = file if file else sys.stdin
    # Print just some topics or exclude some topics (good for avoiding verbose ones)
    if just:
        topics = just
    if ignore:
        topics = [lvl for lvl in topics if lvl not in set(ignore)]

    topics = set(topics)
    console = Console()
    width = console.size.width

    panic = False
    for line in input_:
        try:
            if "FAIL    6.824/raft" in line:
                print(line)
                return 1
            time, topic, *msg = line.strip().split(" ")
            if  not isDigit(time):
                print(line,end="")
            # To ignore some topics
            if topic not in topics:
                continue

            i = int(msg[1][1:])

            msg = " ".join(msg)


            # Colorize output by using rich syntax when needed
            if colorize and topic in TOPICS:
                color = TOPICS[topic]
                msg = f"[{color}]{time} {topic} {msg}[/{color}]"

            # Single column printing. Always the case for debug stmts in tests
            if n_columns is None:
                print(time, msg)
            # Multi column printing, timing is dropped to maximize horizontal
            # space. Heavylifting is done through rich.column.Columns object
            else:
                cols = ["" for _ in range(n_columns)]
                msg = "" + msg
                cols[i] = msg
                col_width = int(width / n_columns)
                cols = Columns(cols, width=col_width - 1, equal=True, expand=True)
                print(cols)
        except:
            print(line, end="")
 def __rich_console__(self, console: Console,
                      options: ConsoleOptions) -> RenderResult:
     yield Columns([
         Panel.fit(
             Backend(backend.used, backend.available),
             box=box.SQUARE,
             title=emojify_device(backend.device),
         ) for backend in self.backends.values()
     ], )
Exemple #19
0
    def _build_columns(self) -> Columns:
        timezone_groups = self._sort_and_group()
        panels = [
            Panel('\n'.join(timezone_groups[group]), title=group.upper())
            for group in timezone_groups
            if timezone_groups[group]
        ]

        return Columns(panels, expand=False)
Exemple #20
0
def render_demand(props: dict, cons: str):
    from rich.panel import Panel
    from rich.columns import Columns

    format_items = "\n\n".join(f"[b cyan]{key}:[/b cyan]\n{repr(value)}"
                               for key, value in props.items())
    props_panel = Panel(f"[bold]Props:[/bold]\n\n{format_items}")
    cons_panel = Panel(f"[bold]Cons:[/bold]\n\n{cons}", expand=True)
    return Columns([props_panel, cons_panel], equal=True)
Exemple #21
0
    def interface(self):

        self.get_json()
        sponame = []
        print("\n\tConnecting to spotify...\n")
        sp = self.get_credentials()

        plLink = input("\nEnter the Spotify playlist/album URL: ")
        plName = input("\nGive a name to your playlist: ")

        if "playlist" in plLink:
            plID = self.get_id(plLink)
            tracks, alburls = self.get_playlist_tracks(sp, plID)
        elif "album" in plLink:
            alID = self.get_id(plLink)
            tracks, alburls = self.get_album_tracks(sp, alID)
        else:
            print("Invalid link, exiting")
            return

        start_time = time.time()
        Console().print(f"\n[bold]Fetching all the relevant URLs[/bold]")
        urls = self.get_yt_urls(tracks)
        end_time = time.time()
        print(f"Time taken to fetch the URLs from Youtube: %.2f secs\n" %
              (end_time - start_time))

        Console().print("\n[green]Downloading the songs[/green]\n")
        for i in tracks.keys():
            sponame.append(tracks[i] + " - " + i)

        # download the tracks
        self.download_PL(plName, urls, alburls, sponame)

        # check if all the songs are downloaded
        total_songs = len(urls)
        downloaded_songs = len(os.listdir())
        if total_songs - downloaded_songs != 0:
            print(
                f"\n{total_songs-downloaded_songs}/{total_songs} songs were not downloaded due to some error"
            )

        Console().print(
            Columns([
                Panel(
                    f"\n     Your playlist is downloaded in \"[bold]/musicDL downloads/Playlists/{plName}[/bold]\" folder on desktop     \n"
                )
            ]))
        op = input("Would you like to open the the playlist? (Y/N) ")
        if op.lower() == "y":
            if sys.platform == 'win32' or os.name == 'nt':
                os.startfile(".")
            elif sys.platform == 'linux' or os.name == 'posix':
                subprocess.call(['xdg-open', '.'])
        else:
            return
    def get_renderable(self):
        if self.displays == {}:
            return None

        return Panel(
            Columns([
                display.get_renderable() for display in self.displays.values()
            ]),
            title="metrics",
        )
Exemple #23
0
    def stats(self, command=None, url=None, short=False) -> None:
        """
        Launch stats command for plugin
        """
        map_command = self.__get_directives_and_class()
        if command is None:
            command_to_run = self.__get_directives_str()
        else:
            command_to_run = [command]
        if url is None:
            url_to_run = self.__get_urls_all()
        else:
            url_to_run = [url]

        if short:
            commands = []
            for command in command_to_run:
                data = {
                    k: self.data["server"][k]
                    for k in self.data["server"].keys() & set(url_to_run)
                }
                plugin = map_command[command]()
                _, errors = plugin.stats(command, data)
                commands.append(len(errors))
            stats_tab = self.__to_table(
                zip(command_to_run, commands),
                "ServerGrimoire",
                ["Command", "# Error"],
            )
            stats_tab.box = box.SIMPLE
            print(stats_tab)

            return
        for command in command_to_run:
            data = {
                k: self.data["server"][k]
                for k in self.data["server"].keys() & set(url_to_run)
            }
            plugin = map_command[command]()
            stats, errors = plugin.stats(command, data)
            stats_tab = self.__to_table(
                stats, plugin.title_stats(), plugin.header_stats()
            )

            error_tab = self.__to_table(
                errors, plugin.title_error(), plugin.header_error()
            )
            print(
                Panel(
                    Columns([stats_tab, error_tab]),
                    title=command,
                    highlight=True,
                )
            )
Exemple #24
0
    def output_status(self):
        from rich.columns import Columns
        from rich.panel import Panel

        missing = str(len(self.missing()))
        disabled = str(len(self.disabled()))
        self.console.print(
            Columns([
                Panel(disabled, title="Disabled"),
                Panel(missing, title="Missing")
            ]))
Exemple #25
0
def print_probe(probe: VideoProbe) -> None:
    format_panel = PropertyPanel(probe.format, "Format", expand=True)
    if probe.metadata:
        format_panel.add_section(
            PropertyPanel(probe.metadata, "Metadata", expand=True))

    stream_group = RenderGroup()
    for i, stream in enumerate(probe.streams, 1):
        stream_group.renderables.append(
            PropertyPanel(stream, f"Stream {i}", expand=True))

    print(Columns([format_panel, stream_group]))
Exemple #26
0
def pretty_dict(data, return_str=True, ignored_keys=None, n_rows=1):
    ignored_keys = ignored_keys or []
    pretty = Columns([
        pretty_var(k, data[k], return_str=False)
        for k in data if k not in ignored_keys
    ],
                     equal=True,
                     expand=False)
    if not return_str:
        return pretty
    canvas = RichDraw()
    canvas.print(pretty)
    return canvas.export_text()
def display_volunteerd(data, data_type):
    """
    Displays the  volunteer data
    :data : will be the calendar data
    :type_data : will be the header for the border eg. "BOOKED", "SLOTS"
    """
    console = Console()
    user_render = [
        Panel(get_volunteerd(user),
              expand=False,
              title=data_type,
              box=box.HEAVY_HEAD,
              border_style="pale_turquoise1") for user in data
    ]
    console.print(Columns(user_render))
Exemple #28
0
def print_grade_table(gradebook):
    table = Table(title="Grades")

    table.add_column("Course", justify="left")
    table.add_column('Percent')
    table.add_column('Letter')

    for course in gradebook.courses:
        grade_display = f'[{grade_associate[course.total_grade_letter]}]{gradebook.grades[course.title] * 100}%' if \
            gradebook.grades[course.title] else f'No Grade'
        letter_display = f'[{grade_associate[course.total_grade_letter]}]{course.total_grade_letter}' if course.total_grade_letter is not None else f'No Grade'
        table.add_row(course.title, grade_display, letter_display)
    console.print(
        Panel(Columns((table, ), align="center", expand=True),
              title=f"[bold white]All Courses"))
Exemple #29
0
    async def list(self, by_status: Optional[str] = None):
        """
        Lists all invoices.
        """
        from rich.columns import Columns
        from rich.text import Text

        def status_to_color(status: payment.InvoiceStatus) -> Optional[str]:
            return INVOICE_STATUS_COLOR.get(str(status), None)

        def filter_invoice(invoice: payment.Invoice) -> bool:
            if by_status:
                return str(invoice.status) == by_status
            return True

        def format_invoice(invoice: payment.Invoice):
            status_style = status_to_color(invoice.status) or ""
            table = Table(
                "[yellow]Attribute[/yellow]",
                "[yellow]Value[/yellow]",
                header_style="bold yellow",
                title=invoice.invoice_id,
                style=status_style,
                title_style=status_style,
            )
            table.add_row(Text.assemble("issuer", style="bold"), invoice.issuer_id)
            date_txt = str(invoice.timestamp.date())
            time_txt = str(invoice.timestamp.time())
            table.add_row("ts", f"{date_txt} [dim]{time_txt}[/dim]")

            table.add_row("amount", invoice.amount)
            table.add_row("status", Text.assemble(str(invoice.status), style=status_style))
            return table

        console = Console()
        async with self._cli.payment() as client:
            p = Payment(client)
            console.print(
                Columns(
                    [
                        format_invoice(invoice)
                        async for invoice in p.invoices()
                        if filter_invoice(invoice)
                    ],
                    width=60,
                    padding=(2, 1),
                )
            )
Exemple #30
0
    def __rich_console__(self, console: Console,
                         options: ConsoleOptions) -> RenderResult:

        # Repository name
        repo_name = "\n"
        repo_name += "[blue bold underline]REPOSITORY[/blue bold underline]"
        repo_name += "[blue bold]:[/blue bold] "
        repo_name += f"[green]{self.repository_metadata.repository_name}[/green]\n"
        repo_name += "[blue bold]      PATH:[/blue bold] "
        repo_name += f"[grey50]{self.repo.path.resolve().parent}/"
        repo_name += f"[bold]{self.repo.path.resolve().name}[bold][/grey50]\n"
        yield repo_name

        if not settings.hide_stats:

            # Statistics panels
            yield "\n[blue bold]STATISTICS[/blue bold]\n"

            # Stats
            repo_stats = "\n"
            repo_stats += "[green]Analyzed notebooks[/green]: "
            repo_stats += f"{self.repository_stats.number_of_notebooks}\n"

            metadata_panels = [Panel(repo_stats, title="Stats")]
            yield Columns(metadata_panels, equal=True)
            yield "\n\n"

        # Repo-level linting results
        if self.has_linting_results:
            yield Rule(
                "[turquoise2 bold]REPOSITORY-LEVEL RESULTS[/turquoise2 bold]",
                align="left",
                style="",
            )
            yield "\n"
            yield self.get_renderable_linting_results()
            yield "\n\n\n"

        # Notebook-level linting results
        if self.has_notebook_level_linting_results:
            yield Rule(
                "[turquoise2 bold]NOTEBOOK-LEVEL RESULTS[/turquoise2 bold]",
                align="left",
                style="",
            )
            yield "\n"
            yield self.get_renderable_nblevel_linting_results()
        yield "\n"