def make_sponsor_message() -> Panel: """Some example content.""" sponsor_message = Table.grid(padding=1) sponsor_message.add_column(style="green", justify="right") sponsor_message.add_column(no_wrap=True) sponsor_message.add_row( "✔ GitHub 🤓 ", "[u blue link=https://github.com/jiaulislam]https://github.com/jiaulislam", ) intro_message = Text.from_markup( """Consider supporting my work via Github 🤘 🤘 🤘. - Jiaul Islam""" ) message = Table.grid(padding=1) message.add_column() message.add_column(no_wrap=True) message.add_row(intro_message, sponsor_message) message_panel = Panel( Align.center( RenderGroup(intro_message, "\n", Align.center(sponsor_message)), vertical="middle", ), box=box.ROUNDED, padding=(1, 2), title="[b red]Thanks for using my application!", border_style="bright_blue", ) return message_panel
def merge_layout(cls, progress, table) -> None: cls._layout["progress"].update( Panel(Align.center(progress, vertical="middle"), border_style="green", title="Overall Status")) cls._layout["tables"].update( Panel(Align.center(table, vertical="middle"), border_style="cyan", title="Details"))
def setup_layout(self): self.layout.split(Layout(name='A'), Layout(name='B')) self.layout['A'].size = 10 self.layout['A'].update(self.build_stats_panel()) self.layout['B'].split_row(Layout(name='C'), Layout(name='D')) self.layout['C'].split(Layout(name='E'), Layout(name='F')) self.layout['E'].update(Align.center(self.build_ps_histogram())) self.layout['D'].update(Align.center(self.build_top_offenders_panel())) self.layout['F'].update(Align.center(self.build_vuln_table())) #self.layout['AA'].update(self.build_stats_panel()) self.console.print(self.layout) return
def __init__( self, numRepos: int, follower: int = 0, following: int = 0, numStat: int = 5, ) -> None: self.numStat = numStat self.numRepos = numRepos self._profileText = Text( f"{follower:03d} Follower\n{following:03d} Following\n{numRepos:03d} Public Repositories" ) self.progressTable = Table.grid(expand=True) self.progressTotal = Progress( "{task.description}", SpinnerColumn(), BarColumn(), TextColumn("[progress.percentage]{task.percentage:>3.0f}%"), ) self.progressTable.add_row( Panel( Align.center(Text( """Placeholder""", justify="center", )), title="[b]Info", border_style="red", padding=(1, 1), ), Panel( Align.center(self._profileText), title="[b]Profile Info", border_style="yellow", padding=(1, 1), ), Panel( self.progressTotal, # type:ignore title="[b]Total Progress", border_style="green", padding=(1, 2), ), ) self.taskTotal = self.progressTotal.add_task(description="Progress", total=numStat * numRepos) self.taskRepo = self.progressTotal.add_task( description="Repository [bold yellow]#", total=numRepos) self.taskStat = self.progressTotal.add_task( description="Stat [bold violet]#", total=numStat)
def make_summary_table(overpasses, tz, twelvehour): """ Make a summary data table to print to console """ table = Table() table.add_column(Align("Date", "center"), justify="right") table.add_column(Align("Duration", "center"), justify="right") table.add_column(Align("Max Elev", "center"), justify="right") table.add_column(Align("Type", "center"), justify='center') def get_min_sec_string(total_seconds: int) -> str: """ Get total number of seconds, return string with min:sec format """ nmin = floor(total_seconds / 60) nsec = total_seconds - nmin * 60 return f"{nmin:.0f}:{nsec:0.0f}" for overpass in overpasses: row = [] date = overpass.aos.dt.astimezone(tz) day = date.strftime("%x").lstrip('0') # round to nearest minute if date.second >= 30: date.replace(minute=date.minute + 1) if twelvehour: time = date.strftime("%I:%M").lstrip("0") ampm = date.strftime('%p').lower() row.append(f"{day:>8} {time:>5} {ampm}") else: time = date.strftime("%H:%M") row.append(f"{day} {time}") # if overpass.brightness is not None: # brightness_str = f"{overpass.brightness:4.1f}" # else: # brightness_str = " "*4 # table_data += " "*2 + brightness_str row.append(get_min_sec_string(overpass.duration)) row.append(f"{int(overpass.tca.elevation):2}\u00B0") if overpass.type: row.append(overpass.type.value) # + '\n' fg = 'green' if overpass.type.value == PassType.visible else None else: fg = None row = tuple(row) table.add_row(*row, style=fg) return table
def print_progress(console, progress): is_first = progress['episode_number'] == 1 table = Table(show_header=is_first, header_style='bold #2070b2') table_centered = Align.center(table) with Live(table_centered, console=console, screen=False, refresh_per_second=20): table.add_column('Episode', justify='center') table.add_column('Acc. Reward', justify='center') table.add_column('Rol. Reward', justify='center') table.add_column('Record', justify='center') table.add_column('Epsilon', justify='center') table.add_column('Loss', justify='center') table.add_row("{: >5d}".format(progress['episode_number']), "{:+.2f}".format(progress['reward']), "{:+.2f}".format(progress['rolling_reward']), "{:+.2f}".format(progress['record']), "{:+.4f}".format(progress['epsilon']), "{:+.3f}".format(progress['loss']))
def get_top_layout() -> Panel: _memory: Tuple[str] = get_memory_info() _platform: str = get_platform() _pyversion: str = get_python_version() _total_memory: str = _memory[0] _available_memory: str = _memory[1] _used_percentage: str = _memory[2] _used_memory: str = _memory[3] _free_memory: str = _memory[4] table = Table.grid(expand=True) table.add_row("Total Memory: ", Text(_total_memory, style="yellow", justify="right")) table.add_row("Available Memory: ", Text(_available_memory, style="green", justify="right")) table.add_row("Used Memory: ", Text(_used_memory, style="red", justify="right")) table.add_row("Free Memory: ", Text(_free_memory, style="green", justify="right")) table.add_row("Used Percentage: ", Text(_used_percentage, style="magenta", justify="right")) table.add_row("OS: ", Text(_platform, style="blue", justify="right")) table.add_row("Python Version: ", Text(_pyversion, style="blue", justify="right")) return Panel( Align.center(table, vertical="middle", pad=False), title="System Info", border_style="white", )
def test_align_center_middle(): console = Console(file=io.StringIO(), width=10) console.print(Align("foo\nbar", "center", vertical="middle"), height=5) expected = " \n foo \n bar \n \n \n" result = console.file.getvalue() print(repr(result)) assert result == expected
def search(query: str, amount: int, ignore_errors: bool, min_views, max_views, game) -> None: channels = API.search(query, live=True, amount=amount) table = Table() table_centerd = Align.center(table) table.add_column("channel") table.add_column("views") table.add_column("game") table.add_column("title") table.title = f"search results for [bold]{query}[/bold]" with Live(table_centerd, console=Console, refresh_per_second=20): for channel in channels: try: stream = API.get_stream_info(channel) except Exception as e: if not ignore_errors: table.add_row(f"www.twitch.tv/{channel}", "[bold red]E[/bold red]", "[bold red]Error[/bold red]", f"[bold red]{e}[/bold red]") else: if max_views is not None and stream.views > max_views: continue if min_views is not None and stream.views < min_views: continue if game is not None and stream.game != game: continue table.add_row(f"www.twitch.tv/{stream.channel}", str(stream.views), str(stream.game), str(stream.title))
def show_toolbox_apps(toolbox: ToolBox) -> Dict[str, list[str]]: apps = toolbox.apps() columns = {"available": [], "unavailable": []} for app, path in apps.items(): if any(map(lambda x: app.lower().startswith(x.lower()), working)): columns["available"].append(app) else: columns["unavailable"].append(app) panel = Text() for i, available in enumerate(columns["available"], start=1): left = (f"{i}. ", "bold gray") right = (f"{available}\n", "green") panel.append(Text.assemble(left, right)) for unavailable in columns["unavailable"]: panel.append(Text(f" {unavailable}\n", style="red")) console.print(Align.center(Panel.fit(panel, title="Available IDEs"))) return columns
def test_align_width(): console = Console(file=io.StringIO(), width=40) words = "Deep in the human unconscious is a pervasive need for a logical universe that makes sense. But the real universe is always one step beyond logic" console.print(Align(words, "center", width=30)) result = console.file.getvalue() expected = " Deep in the human unconscious \n is a pervasive need for a \n logical universe that makes \n sense. But the real universe \n is always one step beyond \n logic \n" assert result == expected
def render(self) -> RenderableType: """Build a Rich renderable to render the calculator display.""" return Padding( Align.right(FigletText(self.value), vertical="middle"), (0, 1), style="white on rgb(51,51,51)", )
def test_align_bottom(): console = Console(file=io.StringIO(), width=10) console.print(Align("foo", vertical="bottom"), height=5) expected = " \n \n \n \nfoo \n" result = console.file.getvalue() print(repr(result)) assert result == expected
def get_renderable(self): tasks_panel_rendered = self.tasks_panel.get_renderable() metrics_panel_rendered = self.metrics_panel.get_renderable() if tasks_panel_rendered is None and metrics_panel_rendered is None: return Align( Text(f"Waiting for test to start... ({self.test_name})"), align="center") layout = Layout() layout.split_row( Layout(name="running", visible=False), Layout(name="metrics", ratio=2, visible=False), ) if metrics_panel_rendered is not None: layout["metrics"].visible = True layout["metrics"].update(metrics_panel_rendered) if tasks_panel_rendered is not None: layout["running"].visible = True layout["running"].update(tasks_panel_rendered) return Panel(layout, title=self.test_name)
def get_table_panel(table: Table) -> Panel: table_panel = Panel( Align.center( table, vertical="middle" ), title="Task Details", border_style="yellow", padding=(1, 0), expand=True ) return table_panel
def make_detail_table(overpasses, tz, twelvehour): """ Make a detailed data table to print to console """ table = Table() table.add_column(Align("Date", 'center'), justify="right") for x in ('Start', 'Max', 'End'): table.add_column(Align(f"{x}\nTime", "center"), justify="right") table.add_column(Align(f"{x}\nEl", "center"), justify="right", width=4) table.add_column(Align(f"{x}\nAz", "center"), justify="right", width=4) table.add_column(Align("Type", "center"), justify='center') def point_string(point): time = point.dt.astimezone(tz) point_data = [] if twelvehour: point_data.append( time.strftime("%I:%M:%S").lstrip("0") + ' ' + time.strftime("%p").lower()) else: point_data.append(time.strftime("%H:%M:%S")) point_data.append("{:>2}\u00B0".format(int(point.elevation))) point_data.append("{:3}".format(point.direction)) return point_data for overpass in overpasses: row = [] row.append("{}".format( overpass.aos.dt.astimezone(tz).strftime("%m/%d/%y"))) # if overpass.brightness is not None: # brightness_str = f"{overpass.brightness:4.1f}" # else: # brightness_str = " "*4 # table_data += " "*2 + brightness_str row += point_string(overpass.aos) row += point_string(overpass.tca) row += point_string(overpass.los) if overpass.type: row.append(overpass.type.value) # + '\n' fg = 'green' if overpass.type.value == PassType.visible else None else: fg = None row = tuple(row) table.add_row(*row, style=fg) return table
def render(self) -> RenderableType: """Get renderable for widget. Returns: RenderableType: Any renderable """ return Panel(Align.center(Pretty(self), vertical="middle"), title=self.__class__.__name__)
def test_align_right_style(): console = Console(file=io.StringIO(), width=10, color_system="truecolor", force_terminal=True) console.print(Align("foo", "right", style="on blue")) assert console.file.getvalue( ) == "\x1b[44m \x1b[0m\x1b[44mfoo\x1b[0m\n"
def render(self) -> RenderableType: return Panel( Align.center(self.pretty_text, vertical="middle"), # title=self.name, border_style="green" if self.mouse_over else "blue", box=box.HEAVY if self.has_focus else box.ROUNDED, style=self.style, height=self.height, )
def render(self): return Panel( Align.left(self._display_str), title=self.title, border_style='blue', box=box.DOUBLE if self.has_focus else box.ROUNDED, # style=None, height=self._height, )
def generate_table(count): '''make a new table''' table = Table(title="keypress frequency") table.add_column('Key') table.add_column('Frequency') temp_dict = dict(itertools.islice(total_keystrokes.items(), count)) for key, val in temp_dict.items(): table.add_row(key, str(val)) return Align.center(table)
def render(self): return Panel( Align.left(self._display_str, vertical='top'), title=self.title, border_style='blue', box=box.HEAVY if self.has_focus else box.ROUNDED, style=self.style, height=self.height, width=self.width, )
def __rich_console__(self, console: Console, options: ConsoleOptions) -> RenderResult: width = options.max_width height = options.height or 1 yield Align.center(self.label, vertical="middle", style=self.style, width=width, height=height)
def render(self): return Panel( Align.left(self._emoji_str), title=self._title_str, border_style=self.border_style, style=self.style, height=min(self.height, len(self._emoji) + 2), width=self.width, )
def render(self) -> RenderableType: return Panel( Align.center(Pretty(self, no_wrap=True, overflow="ellipsis"), vertical="middle"), title="Department", border_style="green" if self.mouse_over else "blue", box=box.HEAVY if self.has_focus else box.ROUNDED, style=self.style, height=self.height, )
def get_panel(title, width, zone, render_secs, render_ms, color): return Panel( Align.center( get_time_string(zone=zone, render_secs=render_secs, render_ms=render_ms, color=color), #vertical="middle", ), title=title, #width=width, height=8, highlight=True, style=Style(color=color))
def make_stack_panel(debugger) -> Panel: stack_table = stackdump(debugger.executor.vm_context._stack.values) stack_panel = Panel( Align.center(stack_table), box=box.ROUNDED, padding=(1, 1), title="[b red]Stack", border_style="bright_blue", ) return stack_panel
def present_hyperparameters(console, hyperparameters): assert isinstance(hyperparameters, dict), "Hyperparameters must be a dictionary" table = Table(show_header=True, header_style="bold green") table.add_column("Hyperparameter Name", style="dim", width=25, justify="center") table.add_column("Value", justify="center", width=15) table.width = Measurement.get(console, table, console.width).maximum Align.center(table) for key in hyperparameters: table.add_row('[red]' + key + '[/red]', str(hyperparameters[key])) console.print(table)
def main(filename: str) -> None: with open(Path(filename) / "setup.py") as f: tree = ast.parse(f.read()) analyzer = Analyzer() analyzer.visit(tree) if analyzer.setup_function is None: raise RuntimeError("Invalid, no setup function found") print(Panel(Align("New [bold]setup.cfg", align="center"))) print() print(analyzer.metadata) print() print(analyzer.options) print() print(Panel(Align("New setup() in [bold]setup.py", "center"))) print() new_setup_py = black.format_str(ast.unparse(analyzer.setup_function), mode=black.Mode()) print(Syntax(new_setup_py, "python", theme="ansi_light"))
def final_check(pgscatalog_df, plink_variants_df): overlaps = pgscatalog_df[PGSCATALOG_KEY_COLUMN].isin( plink_variants_df[PLINK_KEY_COLUMN]) sample = pgscatalog_df.loc[overlaps, [PGSCATALOG_KEY_COLUMN]].head(10) layout["top"]["leftfile"].update( Align( render_file_table(sample, title="PRS WM file key"), align="center", )) layout["top"]["rightfile"].update( Align( render_file_table(sample, title="plink data key"), align="center", )) console.print(layout) printout( "-----------------\nPlease review the keys the data will be matched on" ) if CONFIG is not None: is_to_run = True # auto mode else: # this is intentionally not done using "ask()" due to a different logic is_to_run = Confirm.ask( "Do you confirm you want to match the files on these keys?" ) # manual mode if is_to_run: layout["top"]["leftfile"].update( render_file_table(pgscatalog_df, title="PRS WM file")) layout["top"]["rightfile"].update( render_file_table(plink_variants_df, title="plink data")) console.print(layout) printout("-----------------") else: printout( "You have decided to halt the execution due to the mismatch between the IDs in two files." ) printout( "Please, review this troubleshooting guide, if you need an inspiration about how fixing this:" ) print_error_files() exit(50)