def main(): global opts, one_btc, table opts = vars(parser.parse_args()) # websocket.enableTrace(True) ws = websocket.WebSocketApp("wss://ws.blockchain.info/inv", on_message=on_message, on_error=on_error, on_open=on_open) one_btc = json.loads( requests.get("https://blockchain.info/ticker").content)["AUD"]["15m"] # build table table = Table(show_lines=True) table.add_column("timestamp", overflow="fold", justify="center") table.add_column("hash", overflow="fold", min_width=32, max_width=32) # hash length 64 table.add_column("from_addr", overflow="fold") table.add_column("from_amt", overflow="fold") table.add_column("to_addr", overflow="fold") table.add_column("to_amt", overflow="fold") table.add_column("est_aud", overflow="fold") live = Live( table, vertical_overflow="visible" if opts["overflow"] else "ellipsis", refresh_per_second=1) live.start() thread = threading.Thread(target=close_ws, args=(ws, )) thread.daemon = True thread.start() ws.run_forever()
def write_to_console( ticker: str, interval: str, data_downloaded: Candles, live: Live, table: Table, ) -> Table: """Write data to console. Args: ticker (str): Quote + base currency. interval (str): Candlestick interval. data_downloaded (Candles): Response from the exchange. live (Live): Context manager. table (Table): Rich table. Returns: Table: Updated table to be rendered. """ for row_limit, single_candle in enumerate(data_downloaded[::-1]): timestamp = pd.to_datetime(single_candle[0], unit='ms') add_row_to_table(ticker, interval, table, single_candle, timestamp) max_rows = 15 if row_limit == max_rows: live.update(table) break live.update(table) return table
def __init__(self) -> None: self.console = Console(highlight=False) self._crawl_progress = Progress( TextColumn("{task.description}", table_column=Column(ratio=1)), BarColumn(), TimeRemainingColumn(), expand=True, ) self._download_progress = Progress( TextColumn("{task.description}", table_column=Column(ratio=1)), TransferSpeedColumn(), DownloadColumn(), BarColumn(), TimeRemainingColumn(), expand=True, ) self._live = Live(console=self.console, transient=True) self._update_live() self._showing_progress = False self._progress_suspended = False self._lock = asyncio.Lock() self._lines: List[str] = [] # Whether different parts of the output are enabled or disabled self.output_explain = False self.output_status = True self.output_report = True
def write_to_column( ticker: str, interval: str, data_downloaded: Candles, live: Live, ) -> Table: """Write data to console. Args: ticker (str): Quote + base currency. interval (str): Candlestick interval. data_downloaded (Candles): Response from the exchange. live (Live): Context manager. Returns: Table: Updated table to be rendered. """ table = setup_table() for row_limit, single_candle in enumerate(data_downloaded[::-1]): table.add_row( f'[bold white]{single_candle[2]}[/bold white]', # Open f'[bold white]{single_candle[1]}[/bold white]', # Close f'[bold white]{single_candle[3]}[/bold white]', # High f'[bold white]{single_candle[4]}[/bold white]', # Low f'[bold white]{single_candle[5]}[/bold white]', # Volume f'[bold white]{ticker}[/bold white]', f'[bold white]{interval}[/bold white]', f"[bold white]{pd.to_datetime(single_candle[0], unit='ms')}[/bold white]", ) if row_limit == 15: live.update(table) break live.update(table) return table
def recurse_solve(xw: Crossword, display_context: Live) -> Optional[Crossword]: open_words = [w for w in xw.iterwords() if w.is_open()] if len(open_words) == 0: return xw num_matches = np.array( [len(word_list.find_matches(w)) for w in open_words]) noise = np.abs(np.random.normal(scale=num_matches)) * temperature word_to_match = open_words[np.argmin(num_matches + noise)] matches = word_to_match.find_matches(word_list) if len(matches) == 0: return else: noisy_matches = matches.rescore( lambda _, s: s * np.random.lognormal( 0.0, 0.1 * temperature)) new_xw = copy.deepcopy(xw) for match in noisy_matches.words: if timeout and time.time() > start_time + timeout: return new_xw[word_to_match.index] = match display_context.update(new_xw._text_grid()) fill = recurse_solve(new_xw, live) if fill: return fill
class Monitor: 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) def addRow(self, renderable: ConsoleRenderable): self.columns.add_row(renderable) def __aenter__(self): '''Convenience Method''' return self.__aenter__() def __aexit__(self, *args, **kwargs): self.__exit__(*args, **kwargs) def __enter__(self): current_monitor.set(self) self.live.__enter__() return self def __exit__(self, *args, **kwargs): self.live.__exit__(*args, **kwargs) current_monitor.set(None)
def parseLinkBudget(self, link_codes: list[str], site_codes: list[str]): """ Parse the Link Budget """ if link_codes is not None: parse_info = ParseLinkBudget(driver=self._driver, timeout=3) parse_info.login_ldma() parse_info.make_dir() with Live(panel, refresh_per_second=1, vertical_overflow="visible"): try: for _index, _link_code in enumerate(link_codes): parse_info.goto_links() parse_info.insert_link_code(_link_code) parse_info.click_search() try: parse_info.select_found_link_code(_link_code) table.add_row(f"{(_index + 1)}", f"{_link_code}", "✅") # TODO: Need a way to verify if LB is blank except TimeoutException: table.add_row(f"{(_index + 1)}", f"{_link_code}", "❌") continue # parse_info.export_pdf_file(id) # Export As PDF parse_info.export_file(_link_code) # Export As HTML # parse_info.export_word_file(id) # Export As DOC # parse_info.delete_html_file(id) # Delete the Exported HTML file parse_info.logout_ldma() self._driver.quit() except Exception as error: print(error) else: parse_info = ParseLinkBudget(driver=self._driver, timeout=3) parse_info.login_ldma() parse_info.make_dir() with Live(panel, refresh_per_second=1): for _index, _site_code in enumerate(site_codes): parse_info.goto_links() # parse_info.select_all_dropdown() parse_info.insert_site_code_1(_site_code) parse_info.click_search() if parse_info.is_available_site_1(): _link_id = parse_info.get_link_id() parse_info.search_lb_with_sitecode(_site_code) parse_info.export_file(_link_id) table.add_row(f"{(_index + 1)}", f"{_site_code}", "✅") continue parse_info.clear_site_code_1() parse_info.insert_site_code_2(_site_code) parse_info.click_search() if parse_info.is_available_site_2(): _link_id = parse_info.get_link_id() parse_info.search_lb_with_sitecode(_site_code) parse_info.export_file(_link_id) table.add_row(f"{(_index + 1)}", f"{_site_code}", "✅") continue else: table.add_row(f"{(_index + 1)}", f"{_site_code}", "❌") parse_info.logout_ldma() self._driver.quit()
def __init__(self, content): self.slides = [ slide_content.strip() for slide_content in content.split("---\n") ] print(self.slides) for i in range(1, len(self.slides)): self.slides[i] = "# " + self.slides[i] self.index = 0 self.live = Live()
def __init__(self): self._table = Table.grid() self._live = Live(self._table, console=console) async def close(): self._live.stop() on_close_callbacks.append(close) self._live.start()
def __init__(self, *parts): self.console = Console(color_system="standard", file=REAL_STDOUT) self.lv = Live( auto_refresh=False, redirect_stdout=False, redirect_stderr=False, console=self.console, screen=True, ) self.stack = StackedTerminalLines(parts, self.lv.console.height - 2) self.header = Text("<header>") self.footer = Text("<footer>")
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)
def attack( target: int, client: VBitve, profile: Profile, live: Live, log: Callable[[Any], None], ) -> None: attack = client.attack(target) if attack: profile.update(attack["new_user"]) live.update(profile.table, refresh=True) text = attack["snackbar"]["text"].split("\n")[-1] log(f"Напал на id{target}: +{text}")
def __init__(self): self._bar = create_bar() self._tree = Tree(self._bar) self._live = Live(self._tree, console=console) async def close(): self._live.stop() on_close_callbacks.append(close) self._live.start() self._overall_bar = OverallBar(self._bar)
def exhaust_generator(progress: Generator, count: int, multi_threaded: bool) -> List[Dict[str, Any]]: """Exhausts the generator passed as parameter. Can be done multi threaded if desired Parameters ---------- progress : Generator Generator to exhaust count : int Size of the generator multi_threaded : bool Flag for multi-threaded enabled operations Returns ------- List[dict] List of responses from the generator execution """ responses = [] if multi_threaded: pbar = ProgressBar(total=count) def update(*a): pbar.completed += 1 with Live(pbar): with mp.Pool(mp.cpu_count()) as pool: for f in progress: responses.append(pool.apply_async(_f, args=(f,), callback=update)) pool.close() pool.join() responses = [response.get() for response in responses if response.successful()] else: for f in track(progress, total=count, description="Progress"): responses.append(_f(f)) return responses
def main() -> None: previous: list[str] = [""] * 20 with Live() as live: while True: mvp, non_mvp = get_idols() above = Table.grid(expand=True) above.add_column(width=2) above.add_column(width=3) above.add_column() for i, player in enumerate(mvp): above.add_row(*format_row(i, player, previous)) noodle = r"[yellow]\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/" below = Table.grid(expand=True) below.add_column(width=2) below.add_column(width=3) below.add_column() for j, player in enumerate(non_mvp): below.add_row(*format_row(i + j + 1, player, previous)) live.update(Panel(RenderGroup(above, noodle, below))) previous = mvp + non_mvp time.sleep(30)
def LiveRender(self): ''' docstring ''' # term = Terminal() # print(self.RichLayout()) # while True: response = '' initial = '' timedOut = False console = Console() with Live(console=console, auto_refresh=False, screen=True, vertical_overflow='ellipsis', redirect_stdout=False, redirect_stderr=False) as live: # term.inkey(timeout=5) live.update(self.RichLayout(), refresh=True) while response != 'exit': response, timedOut = inputAdv('', initial, 3600) if timedOut: initial = response else: initial = '' self.inputManager._ExecuteInput(response.strip()) live.update(self.RichLayout(), refresh=True)
def grid_search(relevance, docs, summarize_class, parameter_space): scores = {} with Live(console=console, screen=True, auto_refresh=False) as live: for i, param in enumerate(parameter_space, 1): summarizer = summarize_class(**param) score_10, score_50, score_80 = [], [], [] for y_true, d in zip(relevance, docs): y_pred = [summarizer.predict(d)] score_10.append( ndcg_score(y_true, y_pred, k=ceil(len(d) * 0.1))) score_50.append( ndcg_score(y_true, y_pred, k=ceil(len(d) * 0.5))) score_80.append( ndcg_score(y_true, y_pred, k=ceil(len(d) * 0.8))) scores[(summarizer.__class__.__name__, json.dumps(param))] = np.array(score_10).mean(), np.array( score_50).mean(), np.array(score_80).mean() live.update(topk_table(scores, i, len(parameter_space)), refresh=True) return scores
def print_movies_to_exclude(movies, total_filesize): # Setup console console = Console() # Setup table table = Table(show_footer=True, row_styles=["none", "dim"], box=box.MINIMAL, pad_edge=False) with Live(table, console=console, screen=False): # Setup table columns and totals table.add_column("Release Date") or "Unknown" table.add_column( "Title", Text.from_markup("[b][i]Total Used Diskspace", justify="right")) table.add_column("Used Diskspace", filters.get_filesize_gb(total_filesize)) table.add_column("Streaming Providers") for _, movie in movies.items(): release_date = movie["release_date"] title = movie["title"] diskspace = filters.get_filesize_gb(movie["filesize"]) providers = ", ".join(movie["providers"]) # Add table rows table.add_row(release_date, title, diskspace, providers)
def start_watcher(settings: Settings) -> None: # noqa: WPS210 """ Gather all info from services and renders it to terminal. :param settings: current application settings. """ binance_status = None profit_today = {} profit_yesterday = {} nb_service = NBMinerService(settings) binance_service = BinanceService(settings) cryptonator_service = CryptonatorService(settings) with Live("Waiting for data...", screen=True) as term: while True: # noqa: WPS457 nb_status = nb_service.get_status() algorithm = settings.binance_algo if nb_status: algorithm = nb_status.stratum.algorithm new_bin_status = binance_service.get_status(algorithm) if new_bin_status: binance_status = new_bin_status profit_today = cryptonator_service.convert( binance_status.profit_today) profit_yesterday = cryptonator_service.convert( binance_status.profit_yesterday, ) term.update( get_layout( nb_status, binance_status, profit_today, profit_yesterday, ), ) time.sleep(2)
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 monitor_cards() -> None: c.print("AMD Fan Control - ctrl-c to quit") scanner = Scanner() with Live(refresh_per_second=4) as live: while 1: time.sleep(0.4) live.update(show_table(scanner.cards))
def main() -> None: parser = argparse.ArgumentParser(description="Show Blaseball Feeds") parser.add_argument("-c", "--category", type=int, default=None) parser.add_argument("-n", "--interval", type=int, default=60) parser.add_argument("--no-ghosts", action="store_true") group = parser.add_mutually_exclusive_group() group.add_argument("-t", "--team", type=str) group.add_argument("-p", "--player", type=str) args = parser.parse_args() excludes = [] if args.no_ghosts: excludes.append("INHABITING") if args.player: func = partial(player_feed, args.player, args.category) elif args.team: func = partial(team_feed, args.team, args.category) else: func = partial(global_feed, args.category) with Live(Table(), vertical_overflow="crop") as live: while True: live.update(_do_feed(func(), excludes)) try: time.sleep(args.interval) except KeyboardInterrupt: break
def print_series_to_re_add(series): # Setup console console = Console() # Setup table table = Table(show_footer=False, row_styles=["none", "dim"], box=box.MINIMAL, pad_edge=False) with Live(table, console=console, screen=False): # Setup table columns table.add_column("Release Year") table.add_column("Title") table.add_column("Seasons") table.add_column("Episodes") table.add_column("Ended") for _, serie in series.items(): release_year = str(serie["release_year"]) title = serie["title"] season = filters.get_pretty_seasons(serie["seasons"]) episodes = filters.get_pretty_episodes(serie["episodes"]) ended = filters.bool2str(serie["ended"]) # Add table rows table.add_row(release_year, title, season, episodes, ended)
def BruteForceHB(lpn): """Brute Force attack on HB Protocol Args: lpn (HBOracle): HBOracle object representing the lock Returns: np.array: Secret key which passes the Hypothesis Test """ # Generate all candidates candidates = generate_binary(lpn.dimension) table = Table() table.add_column("Candidate Key", justify="center", style="turquoise2") table.add_column("Hypothesis Test Result", justify="center", style="orange_red1") with Live(table, refresh_per_second=4): # Loop through all candidates for candidate in candidates: # Test a candidate if HypothesisTest(lpn, candidate): table.add_row(f"[bold][cornflower_blue]{candidate}", "[sea_green2]:heavy_check_mark: Passed") return candidate table.add_row(f"{candidate}", "✗ Failed") time.sleep(0.2) print("Could not find.") return None
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))
class MultiProgress: """Track progress of multiple processes, plus overall combined progress""" def __init__( self, totals: Dict[str, int], total_progress: Progress = None, job_progress: Progress = None, task_description: str = 'Loading', ): self.total_progress = total_progress or _get_progress() self.total_task = self.total_progress.add_task('[cyan]Total', total=sum( totals.values())) self.job_progress = job_progress or _get_progress() self.job_task = self.job_progress.add_task('[cyan]File ') self.table = Table.grid() self.table.add_row(self.total_progress) self.table.add_row(self.job_progress) self.task_description = task_description self.totals = totals self.live = Live(self.table, refresh_per_second=10) def __enter__(self): self.live.__enter__() return self def __exit__(self, *args): self.total_progress.tasks[0].completed = self.total_progress.tasks[ 0].total self.job_progress.tasks[0].completed = self.job_progress.tasks[0].total self.live.__exit__(*args) def start_job(self, name: PathOrStr): if isinstance(name, Path): name = _fname(name) self.job_progress.update( self.job_task, completed=0, total=self.totals[str(name)], ) self.job_progress.log( f'[cyan]{self.task_description} [white]{name}[cyan]...') def advance(self, advance: int = 1): self.total_progress.advance(self.total_task, advance) self.job_progress.advance(self.job_task, advance)
def get_candles( # noqa: WPS210 ticker: str, start_time: float, end_time: float, interval: str, step_size: int = 86400000, ) -> Candles: """Call the exchange for the data and extends it into a list. Args: ticker (str): Ticker to download the data. start_time (float): Time in ms on which the data will start. end_time (float): Time in ms on which the data will finish. interval (str): Period downloaded. step_size (int): The size step for each call. Defaults to _STEP_SIZE. Returns: Candles: A list of floats containing OHLC """ rate_limit = 1.85 candle_data: Candles = [] if not validate_symbol(ticker.lower()): click.secho( f"Cannot download ❌, check '{ticker}' is listed on Bitfinex", fg='red', ) sys.exit(1) click.secho( f'Downloading {ticker} data for {interval} interval...', fg='yellow', ) exchange = Bitfinex() with Live(vertical_overflow='ellipsis', auto_refresh=False) as live: while start_time <= end_time: period = start_time + step_size max_candles = 10000 candlestick = exchange.get_candles( ticker=ticker, time_interval=interval, history_limit=max_candles, start_time=start_time, end_time=period, ) candle_data.extend(candlestick) write_to_console( ticker, interval, candlestick, live, setup_table(), ) live.refresh() start_time = period sleep(rate_limit) return candle_data
class OverallBarManager: def __init__(self): self._bar = create_bar() self._tree = Tree(self._bar) self._live = Live(self._tree, console=console) async def close(): self._live.stop() on_close_callbacks.append(close) self._live.start() self._overall_bar = OverallBar(self._bar) def get_bar(self): return VirtualBar(self._tree, self._overall_bar)
def main(): with Live(generate_kimp_table(calculate_kimp()), auto_refresh=False, transient=True) as live: live.console.print(f'[*] Kimp Calculator v{version}', style='bold #47C83E') live.console.print('[*] If you exit calculator -> ctrl + C', style='bold #47C83E') while True: sleep(1) live.update(generate_kimp_table(calculate_kimp()), refresh=True)
class CommonBarManager: def __init__(self): self._table = Table.grid() self._live = Live(self._table, console=console) async def close(): self._live.stop() on_close_callbacks.append(close) self._live.start() def get_bar(self): bar = create_bar() tree = Tree(bar) self._table.add_row(tree) return CommonBar(tree, bar)