Beispiel #1
0
 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
Beispiel #2
0
 def format_raw(self, index, cell, config):
     """Format raw code block. Render only input source."""
     panels = []
     panels.append(self.format_index(index))
     text = self.get_source_text(cell)
     if config.no_cell_border:
         panels.append("\n")
         panels.append(text)
         panels.append("\n")
     else:
         panels.append(Panel(text))
     return panels
Beispiel #3
0
def make_logo():
    """Make logo component."""
    logo = Panel("\t \n \t :honeybee: RICH TERMINAL \n \t A proof of concept",
                 width=42,
                 height=6,
                 style=Style(
                     color='yellow',
                     bgcolor='black',
                 ),
                 border_style='white')

    return logo
Beispiel #4
0
 def render_video(self, video: Video):
     formatted = video.get_formatted()
     title = formatted['title']
     title.stylize('bold')
     stats = formatted['stats']
     stats.stylize('blue')
     up = formatted['up']
     up.stylize('magenta')
     desc = formatted['desc']
     desc.truncate(90, overflow='ellipsis')
     summary = Text.assemble(title, '\n', stats, '\n', up, '\n', desc)
     self.panels.append(Panel(summary, expand=True))
Beispiel #5
0
def get_vms():
    vcenter_id = config['vcenter']['id']
    limit = config['api']['limit']
    base_url = config['api']['base_url']
    get_vm_api_path = '/datasources/vmware/vcenters/' + vcenter_id + '/vms'

    # params = {'limit': '<limit>', 'start': '<start>', 'filter': '<filter>'}
    params = {'limit': limit}
    headers = headers_func()

    data = my_request(base_url, get_vm_api_path, headers, params)
    pages = get_pages(data)

    alldf = pd.DataFrame([])
    vm_table(data)
    rprint(
        Panel('[cyan]START: Fething and Building VM List via Clumio API',
              title="EXECUTION STATUS"))
    i = 1
    for i in track(range(1, int(pages))):
        print(Fore.CYAN + Style.BRIGHT + '...Fetching page ' + str(i) +
              ' from Clumio API...' + Style.RESET_ALL)
        get_vm_api_path = ('/datasources/vmware/vcenters/' + vcenter_id +
                           '/vms?limit=' + limit + '&start=' + str(i))
        log(get_vm_api_path)
        data = my_request(base_url, get_vm_api_path, headers, params)
        table = vm_table(data)
        alldf = my_df(alldf, table, i)
    rprint(
        Panel('[green]DONE: Fething VM List via Clumio API',
              title="EXECUTION STATUS"))
    rprint(Panel('[cyan]START: Create DataFrame', title="EXECUTION STATUS"))
    print(alldf)
    rprint(
        Panel('[cyan]START: Writing DataFrame to vms.csv for future use',
              title="EXECUTION STATUS"))
    alldf.to_csv('vms.csv', index=False)
    rprint(
        Panel('[green]DONE: Writing DataFrame to vms.csv',
              title="EXECUTION STATUS"))
Beispiel #6
0
        async def plugin_command(ctx):

            all = []

            doc = self.get_plugin_doc(name)
            doc.extract_metadata("examples")

            desc_string = f"## Package type: **{name}**\n"
            if doc.get_short_help(default=None):
                desc_string += doc.get_short_help() + "\n\n"

            desc_string += f"\n## Arguments\n\nThis is the list of arguments that can be used to describe a package of the *{name}* type:\n"
            desc = Markdown(
                desc_string,
                style=bring_style,
                code_theme=bring_code_theme,
                justify="left",
            )
            all.append(desc)

            plugin = self.get_plugin(name)

            args = plugin.get_args()
            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 print(self):
        console = Console()
        df = self.df

        # print file info
        console.print(Panel(self.filename, style="green bold"),
                      justify="center")
        console.print()
        console.print('FILE INFO', style="green bold")
        console.print(f'   File size: {sizeof_fmt(self.bite_size)}',
                      style="green")
        console.print(f'   Rows: {self.nrows},  Columns: {self.ncolumns}',
                      style="green")

        # print columns info
        console.print()
        console.print('COLUMN INFO', style="green bold")
        if df is not None:
            table = Table()

            table.add_column("Name", style="cyan", no_wrap=True)
            table.add_column("Data Type", style="magenta")
            table.add_column("Is Unique", justify="center", style="green")
            table.add_column("Empty Cell Count", style="green")

            for col, dtype in df.dtypes.iteritems():
                empty_count = df[col].isnull().sum()
                table.add_row(
                    col,  # column name
                    clean_dtypes(
                        dtype),  # data type, turned into human-readable format
                    ok('✔') if df[col].is_unique else error('✗'),
                    ok(empty_count)
                    if empty_count == 0 else warning(empty_count))

            console.print(table)
        else:
            console.print("  Couldn't be parsed by pandas.", style='red')

        # go through validation tests
        console.print()
        console.print('VALIDATION TESTS', style="green bold")
        console.print(self.parsable_by_pandas)
        console.print(self.column_names_unique)
        console.print(self.rows_unique)
        console.print(self.column_names_not_null)
        console.print(self.rows_have_equal_number_of_columns)
        console.print(self.has_utf8_encoding)
        # console.print(self.quotes_are_escaped)
        # console.print(self.line_endings_are_CRLF)

        console.print()
Beispiel #8
0
    def style(self):
        title = 'HELP MESSAGE'

        def terminal_width(width: int) -> int:
            '''controle the ruler width
            max width = 1
            minmim width = 0
            '''
            square_text = 6
            terminal_width = terminal().size['width'] - square_text
            return int(terminal_width * float(width) / float(1))

        # RULER = lambda: '[white]' + '─' * (terminal_width(1))
        RULER = lambda: f'[bold][white]{"─" * terminal_width(1)}[/bold][/white]'

        if self.title:
            title = f"[bold][green]{self.title.upper()}[/green]"

        sections = []
        temp = 0
        for section_title, commands in self.sections.items():
            sections.append('')
            sections[temp] += f'[white][bold] {section_title.lower()}: [/bold]\n' + RULER() + '\n'

            # commands
            tempFixwidth = [key[0] for key in commands]
            tempFixwidth = Text.full(tempFixwidth)
            tempCommands = [key[0] for key in commands]

            for command, helpMsg in commands:
                command = tempFixwidth[tempCommands.index(command)]
                if Config.get('settings', 'ARABIC_RESHAPER'):
                    helpMsg = Text.arabic(helpMsg)
                sections[temp] += f'  [yellow]{command}[/yellow]  [white]{helpMsg}\n'

            # sections[temp] += RULER() + '\n\n'
            sections[temp] += '\n\n'
            temp += 1

        style = ''
        for section in sections:
            style += section

        print(
            Panel(
                style[:-3],
                box=box.ROUNDED,
                padding=(1, 2),
                title=title,
                border_style='bold green',
            )
        )
Beispiel #9
0
    def __rich_console__(self, *args):
        """
        Yields the panel elements for printing in rich console
        """
        yield Panel.fit(
            self.tb,
            width=self.width,
            border_style=self.dim,
            padding=(0, 2, 1, 2),
        )

        if self.show_info:
            yield f"[dim {self.color}]{self._info()}"
def generate_log_table(data):
    new_data = "\n".join(data)
    data = new_data.split("\n")
    c = Console()
    last_n = c.size.height - 10
    log_table = Table(expand=True,
                      show_header=False,
                      show_footer=False,
                      box=box.SIMPLE)
    log_table.add_column("Script execution log")
    for row in data[-last_n:]:
        log_table.add_row(row)
    return Panel(log_table, title="Execution log")
Beispiel #11
0
async def on_ready():
    console.print(
        Panel('[bold green]Connected to Discord API ✓\nLoading Complete ✓'),
        justify='center')
    console.print(Markdown('# Logging Commands:'))
    embed = Embed(title="Good Morning",
                  description="It's a beautiful day for pie",
                  color=0x00ff00)
    embed.set_image(
        url=
        "https://media1.tenor.com/images/4443069022c0e23622626a46909162ec/tenor.gif?itemid=10618052"
    )
    await bot.get_channel(830932320771899432).send(embed=embed)
Beispiel #12
0
    def _generate_power_panel(self) -> Panel:
        """
        Generate Power readout

        :return: Power readout
        """
        text = Text(f"\n{round(self.piloton.bike.power)}\n", justify="center")
        text.stylize("bold white")
        panel = Panel(text,
                      title="Power (W)",
                      box=box.HEAVY,
                      border_style="#E89005")
        return panel
Beispiel #13
0
    def _generate_resistance_panel(self) -> Panel:
        """
        Generate resistance readout

        :return: Resistance readout
        """
        text = Text(f"\n{self.piloton.bike.resistance}\n", justify="center")
        text.stylize("bold white")
        panel = Panel(text,
                      title="Resistance",
                      box=box.HEAVY,
                      border_style="#E9CE2C")
        return panel
Beispiel #14
0
def messages(cli_args):
    r = requests.get(
        "https://passio3.com/www/goServices.php?getAlertMessages=1&json=%7B%22systemSelected0%22%3A%2276%22%2C%22amount%22%3A1%2C%22routesAmount%22%3A0%7D"
    )
    messages_data = r.json()
    messages_data = messages_data["msgs"]

    messages_data_new = [{
        "title": m["name"],
        "html": m["html"],
        "date_from": m["from"],
        "date_to": m["to"]
    } for m in messages_data]

    console = Console()
    console.print(Panel(Text("Messages", justify="center", style="bold")))
    for m in messages_data_new:
        group = RenderGroup(
            Text(m["title"], justify="center", style="bold"),
            Text(m["date_from"] + " to " + m["date_to"], justify="center"),
            Padding(Text(m["html"]), (1, 0, 0, 0)))
        console.print(Panel(group, expand=True))
Beispiel #15
0
    def _drawComponents(self, aPkgs):
        if not aPkgs:
            return ''

        lString = ''
        for pkg in sorted(aPkgs):
            lString += '+ %s (%d)\n' % (pkg, len(aPkgs[pkg]))
            lSortCmps = sorted(aPkgs[pkg])
            for cmp in lSortCmps[:-1]:
                lString += u'  ├──' + str(cmp) + '\n'
            lString += u'  └──' + str(lSortCmps[-1]) + '\n'

        return Panel.fit(lString[:-1])
Beispiel #16
0
def main():
    p = 0.125
    dim = 5
    bfs = np.random.randint(0, 2, dim)
    bflpn = HBOracle(bfs, p)


    print(Panel(f"[yellow2]Brute Force on HB Protocol\n[cyan3]Error Rate = {p}\nKey Length = {dim}\nSecret Key = {bfs}", 
                title="[yellow]HB Protocol", expand=False))
    

    print(f"[light_steel_blue]Found key:     {BruteForceHB(bflpn)}")
    print(f"[light_steel_blue]Actual secret: {bflpn.secret}")
Beispiel #17
0
    def render_numbers(numbers, name):
        grid = Table.grid(padding=1)

        for row in range(16):
            row = [
                Text(
                    str(numbers[row * 16 + col]),
                    style=styles[numbers[row * 16 + col] % 16],
                )
                for col in range(16)
            ]
            grid.add_row(*row)
        columns.add_renderable(Panel.fit(grid, title=name))
Beispiel #18
0
def test_justify_renderable_right():
    console = Console(
        file=io.StringIO(),
        force_terminal=True,
        width=20,
        legacy_windows=False,
        _environ={},
    )
    console.print(Panel("FOO", expand=False, padding=0), justify="right")
    assert (
        console.file.getvalue()
        == "               ╭───╮\n               │FOO│\n               ╰───╯\n"
    )
Beispiel #19
0
def generate_panel(notes, note_choice, note_played, color, score):

    if note_choice not in notes:
        # it means note_choice is 'Good job!' when the player hits the note
        play_note_row = note_choice
    else:
        play_note_row = f'Play this note: [blue bold]{note_choice}[/]'
    note_played_row = f'You played: [{color} bold]{note_played}[/]'

    all_notes_row = Text.assemble(('\nAll available notes: ', 'grey53 bold'),
                                  ((', ').join(notes), 'grey53'))

    current_score_text = Text(f'\nCurrent score: {score}\n')
    current_score_text.stylize('yellow bold', 16)

    quit_text = Text('\n\n(press ctrl+C to quit at any time)')
    quit_text.stylize('grey37')

    panel_group = RenderGroup(current_score_text, Panel(play_note_row),
                              Panel(note_played_row), all_notes_row, quit_text)

    return Panel(panel_group, title='FRETBOARD LEARNER', box=box.ASCII)
Beispiel #20
0
def generate_display(display: str) -> Panel:
    """Generate a panel to display using the rich library.

    Args:
        display (str): The visualized values to display.

    Returns:
        rich.Panel: The generated panel.
    """
    table = Panel(display,
                  expand=False,
                  title="[bold blue]Devilizer[/bold blue]")
    return Align(table, align="center")
Beispiel #21
0
def nowplayingupdate(title: dict):
    """
    updates the now playing text
    """

    nowplayingstring = updatercore("nowplaying", title)

    obsinstance.call(
        requests.SetTextGDIPlusProperties("nowplaying", text=nowplayingstring))

    return console.log(Panel.fit(nowplayingstring, title="Now Playing"))

    pass
Beispiel #22
0
def update_audio_idx(brick):
    panel = Table.grid()
    panel.add_column(ratio=2)
    for _ in range(brick.config.settings.notchCount):
        panel.add_column(ratio=1)
    notches = ["0x%02X " % x for x in brick.config.settings.notchBounds]
    n = brick.state.audio_notch
    if n < len(brick.config.settings.notchBounds):
        notches[n] = "[black on white]0x%02X " % (
            brick.config.settings.notchBounds[n])
    panel.add_row("Curr Notch ", "%d" % (brick.state.audio_notch + 1))
    panel.add_row("Notch", *notches)
    return Panel(panel)
Beispiel #23
0
 def add_failure(self, task, fail_info):
     console = Console()
     if isinstance(fail_info, TaskError):
         console.print(f'[red]Task Error - {task.name}'
                       f' => {fail_info.message}')
     if fail_info.traceback:
         console.print(
             Panel(
                 "".join(fail_info.traceback),
                 title=f"{task.name}",
                 subtitle=fail_info.message,
                 border_style="red",
             ))
Beispiel #24
0
    def __init__(self, title="Monitor", log=False) -> None:
        """Monitor allows you to monitor the progress of what is happenening inside your application


        Args:
            title (str, optional): The Title of this Monitor (Is the Panels Title). Defaults to "Monitor".
            progress (bool, optional): Do you want to monitor the progress of assignments and reservations? Defaults to False.
        """
        self.columns = Table.grid(expand=True)
        self.columns.add_column()
        self.log = log
        self.panel = Panel(self.columns, title=title)
        self.live = Live(self.panel, refresh_per_second=4, console=console)
Beispiel #25
0
 def __rich_console__(self, console: Console,
                      options: ConsoleOptions) -> RenderResult:
     width = options.max_width
     height = options.height or options.size.height
     layout = self.layout
     title = (f"{layout.name!r} ({width} x {height})"
              if layout.name else f"({width} x {height})")
     yield Panel(
         Align.center(Pretty(layout), vertical="middle"),
         style=self.style,
         title=self.highlighter(title),
         border_style="blue",
     )
Beispiel #26
0
def reset():
    """
    Reset the configuration to default.
    """

    if Confirm.ask("\n:bomb: Are you sure you want to reset the config file?"):
        reset_config()
        console.print(
            Panel.fit(
                f":thumbs_up_dark_skin_tone: Successfully reset the config file: {config_path} :thumbs_up_dark_skin_tone:"
            ),
            style="bold green",
        )
Beispiel #27
0
    def render(self, displays, bootstrap=True):
        b = self.board
        # Recover state
        for display in displays:
            self.round += 1
            self.count = [display['blackCount'], display['whiteCount']]
            if 'x0' not in display: continue
            x0 = display['x0']
            if x0 == -1: continue
            y0 = display['y0']
            x1 = display['x1']
            y1 = display['y1']
            x2 = display['x2']
            y2 = display['y2']
            color = 2 - self.round % 2
            b[x1][y1] = b[x0][y0]
            b[x0][y0] = 0
            b[x2][y2] = -1

        message = 'Round: %d\n%s: %d\n%s: %d\nNext: %s' % (
            self.round, self.stones[1], self.count[0], self.stones[2],
            self.count[1], self.stones[1 + self.round % 2])
        styles = [[
            self.stones[b[i][j]]
            if b[i][j] >= 0 else Text(self.stones[b[i][j]], style='blue')
            for j in range(self.size)
        ] for i in range(self.size)]
        if displays:
            d = displays[-1]
            if not d: d = {}
            x0 = d.get('x0', -1)
            y0 = d.get('y0', -1)
            if x0 != -1 and isinstance(styles[x0][y0], str):
                styles[x0][y0] = Text(styles[x0][y0], 'on red')
            x1 = d.get('x1', -1)
            y1 = d.get('y1', -1)
            if x1 != -1:
                styles[x1][y1] = Text(styles[x1][y1], 'on green')
            x2 = d.get('x2', -1)
            y2 = d.get('y2', -1)
            if x2 != -1:
                styles[x2][y2].style = 'blue on yellow'
            if 'winner' in d:
                message += '\n%s wins!' % self.stones[d['winner'] + 1]
        t = Table.grid(padding=(0, 1))
        t.add_row('', *map(chr, range(65, 65 + self.size)))
        for j in range(self.size):
            t.add_row(str(1 + j), *[styles[i][j] for i in range(self.size)])
        tt = Table.grid(padding=(0, 4))
        tt.add_row(t, message)
        print(Panel.fit(tt, box=box.SQUARE))
Beispiel #28
0
def main(hydra_cfg: DictConfig):

    print_title()

    logger.setLevel(hydra_cfg.log_level)
    if hydra_cfg.log_level.upper() == "DEBUG":
        verbose = True
    else:
        verbose = False
    # really unclear why hydra has so many unclear validation issues with structure configs using ConfigStore
    # this correctly assigns the correct structured config
    # and updates from the passed hydra config
    # annoying... but this resolves all these issues
    cfg = OmegaConf.structured(Config())
    cfg.update(hydra_cfg)

    # debug
    if verbose:
        print_yaml(cfg)

    from pytorch_lightning.loggers import WandbLogger

    # explicitly convert the DictConfig back to Config object
    # has the added benefit of performing validation upfront
    # before any expensive training or logging initiates
    config = Config.from_dict_config(cfg)

    wandb_logger = WandbLogger(project="pytorchlightning", offline=config.offline)

    # initialize the training module
    training_module = TrainingModule(config)

    logger.info("Priming the model with data")
    prime_the_model(training_module, config)
    logger.debug(Panel("Model", expand=False))

    if verbose:
        print_model(training_module)

    logger.info("Generating data...")
    data = DataGenerator(config.data)
    data.init()

    logger.info("Beginning training...")
    trainer = Trainer(gpus=config.gpus, logger=wandb_logger, check_val_every_n_epoch=5)

    trainer.fit(
        training_module,
        train_dataloader=data.train_loader(),
        val_dataloaders=data.eval_loader(),
    )
Beispiel #29
0
    def output_test_result_summary(
        self, test_results: List[TestResult], time_taken: float, show_slowest: int
    ):
        if show_slowest:
            self.console.print(TestTimingStatsPanel(test_results, show_slowest))

        result_table = Table.grid()
        result_table.add_column(justify="right")
        result_table.add_column()
        result_table.add_column()

        outcome_counts = self._get_outcome_counts(test_results)
        test_count = sum(outcome_counts.values())
        result_table.add_row(
            Padding(str(test_count), pad=HORIZONTAL_PAD, style="bold"),
            Padding(
                f"{'Test' if test_count==1 else 'Tests' } Encountered",
                pad=HORIZONTAL_PAD,
            ),
            style="default",
        )
        for outcome, count in outcome_counts.items():
            if count > 0:
                result_table.add_row(
                    Padding(str(count), pad=HORIZONTAL_PAD, style="bold"),
                    Padding(outcome.display_name, pad=HORIZONTAL_PAD),
                    Padding(f"({100 * count / test_count:.1f}%)", pad=HORIZONTAL_PAD),
                    style=outcome_to_style(outcome),
                )

        exit_code = get_exit_code(test_results)
        if exit_code == ExitCode.SUCCESS:
            result_style = "pass.textonly"
        else:
            result_style = "fail.textonly"

        result_summary_panel = Panel(
            result_table,
            title="[b default]Results[/b default]",
            style="none",
            expand=False,
            border_style=result_style,
        )
        self.console.print(result_summary_panel)

        self.console.print(
            Rule(
                f"[b]{exit_code.clean_name}[/b] in [b]{time_taken:.2f}[/b] seconds",
                style=result_style,
            )
        )
Beispiel #30
0
def cli(info_jsons):

    info_re = re.compile('^info_.*\.json$')
    if not info_jsons:
        info_jsons = tuple(f for f in os.listdir() if info_re.match(f))

    info_threads = {j: InfoThread(j, 1) for j in info_jsons}
    for a, t in info_threads.items():
        t.start()

    layout = make_layout()
    layout["header"].update(Panel(Text("nano Opmon", justify="center")))
    layout["footer"].update(
        Panel(Text("extra infos will go here", justify="center")))
    layout["side"].update(
        Panel(Text("app status will go here", justify="center")))
    tables = {}
    try:
        with Live(layout, refresh_per_second=2, screen=True):
            while True:

                for app, trd in info_threads.items():
                    j = None
                    try:
                        j = trd.queue.get(block=False)
                    except:
                        pass
                    if j is not None:
                        t = info_to_table(j, app)
                        tables[app] = Panel(t, expand=True)
                layout["body"].update(Columns(tables.values()))
                time.sleep(1)

    except KeyboardInterrupt:
        for a, t in info_threads.items():
            t.running = False
        for a, t in info_threads.items():
            t.join()