def __init__(self) -> None: cf.use_style("solarized") cf.use_true_colors() self._token_formatting_mapping: Dict[StructlogKeywords, Callable[[ str ], cf.Colorful]] = { StructlogKeywords.Exception: cf.bold_red, StructlogKeywords.Timestamp: cf.bold_yellow # StructlogKeywords.Message: f"{token}", # don't mess with level formatting, it breaks structlog console renderer # StructlogKeywords.Level: cf.bold, }
def colored(text, color=None, on_color=None, attrs=None, style=None, palette=None): """ Colorize text. :param text: text to be colorized :param color: text color :param on_color: background color :param attrs: single styling attribute or list of styling attributes :param style: colorful styling function, e.g. red_on_green (for green foreground and red background colors) :param palette: predefined palette's name (e.g. 'monokai') :return: styled string Available styling attributes: blinkrapid, blinkslow, bold, concealed, dimmed, inversed, italic, reset, struckthrough, underlined Available palettes: monokai, solarized """ if isinstance(style, (list, tuple)): style = "_".join(style) s = style or "" if palette: colorful.use_style(palette) if s == "": if attrs: if not isinstance(attrs, list): attrs = [attrs] for attr in attrs: if attr not in colorful.ansi.MODIFIERS.keys(): raise ValueError("Bad ANSI modifier '%s'" % attr) s += str(attr) + "_" if color: if color not in colorful.colorpalette.keys(): raise ValueError("Bad color '%s'" % color) s += str(color) + "_" if on_color: if on_color not in colorful.colorpalette.keys(): raise ValueError("Bad color '%s'" % on_color) s += "on_" + str(on_color) if s != "": c = getattr(colorful, s.rstrip("_")) try: return c(text).styled_string if s and TTY else text finally: # ensure that the palette is restored colorful.use_palette(COLOR_PALETTE)
def __init__(self, style='monokai'): self.style = style if self.style == 'solarized': self.colors = [ 'yellow', 'orange', 'red', 'magenta', 'violet', 'blue', 'cyan', 'green', 'fg', 'bg' ] elif self.style == 'monokai': self.colors = [ 'orange', 'magenta', 'purple', 'blue', 'seagreen', 'green', 'yellow', 'fg', 'bg' ] self.color_map = { 'seagreen': 'seaGreen', } self.mods = ['bold', 'italic', 'underlined', 'reset'] c.use_style(style)
def main(): """Converts a given url with the specified arguments.""" options = get_options() cf.use_style("solarized") if options["nocolor"]: cf.disable() newline() header("Thumbor v%s (of %s)" % (__version__, __release_date__)) newline() print( "Thumbor doctor will analyze your install and verify if everything is working as expected." ) errors = check_modules() errors += check_compiled_extensions() errors += check_filters() errors += check_extensions() newline() if errors: print( cf.bold_red( "😞 Oh no! We found some things that could improve... 😞")) newline() print("\n".join(["* %s" % str(err) for err in errors])) newline() newline() print( cf.cyan( "If you don't know how to fix them, please open an issue with thumbor." )) print( cf.cyan( "Don't forget to copy this log and add it to the description of your issue." )) print("Open an issue at https://github.com/thumbor/thumbor/issues/new") sys.exit(1) return print(cf.bold_green("🎉 Congratulations! No errors found! 🎉"))
def test_color(): colorful.use_true_colors() colorful.use_style('monokai') cnames = [ 'blue', 'green', 'yellow', 'brown', 'darkGray', 'magenta', 'gray', 'lightGray', 'lightGhostWhite', 'lightOrange', 'brownGray', 'orange', 'ghostWhite', 'purple', 'seaGreen' ] colors = [getattr(colorful, cname) for cname in cnames] styles = [c.style for c in colors] lines = ['demo'] * 20 colored = [ color(line) for line, color in zip(lines, itertools.cycle(colors)) ] cls = [str(line) for line in colored] for c in cls: print(c)
def __init__( self, colors: List[str] = None, colors_palette: str = None, tags: List[str] = None, ): """ Visualize Sequence Tagging Parameters ---------- colors: List[str] The set of colors that will be used for tagging colors_palette: str The color palette that should be used. We recommend For more information on color palettes you can refer to the documentation of the python package `colorful` tags: List[str] The set of all labels that can be labelled If this is not given, then the tags will be infered using the labels during tagging """ if colors is None: colors = [ "yellow", "orange", "red", "magenta", "violet", "blue", "cyan", "green", ] if colors_palette is None: colors_palette = "solarized" self.colors = colors self.colors_palette = colors_palette self.colors_iter = itertools.cycle(self.colors) self.tags = tags colorful.use_style(self.colors_palette)
try: import colorful except ImportError: def identity(string: str) -> str: return string class ColorfulDummy: def __getattr__(self, item): return identity colorful = ColorfulDummy() else: colorful.use_style('solarized') from yaml import safe_load from algorithm import Deck, CardId, Rarity, generate_booster_pack, summarize_deck, evaluate_deck, parse_cards_csv, basic_land_info # Describe test case schema class TestCard(NamedTuple): set: str card_number: int quantity: int = 1 class TestCase(NamedTuple): cards: Sequence[TestCard]
# nest colors print(cf.red('red {0} red'.format(cf.white('white')))) print(cf.red('red' + cf.white(' white ', nested=True) + 'red')) # combine styles with strings print(cf.bold & cf.red | 'Hello World') # use true colors cf.use_true_colors() # extend default color palette cf.update_palette({'mint': '#c5e8c8'}) print(cf.mint_on_snow('Wow, this is actually mint')) # choose a predefined style cf.use_style('solarized') # print the official solarized colors print(cf.yellow('yellow'), cf.orange('orange'), cf.red('red'), cf.magenta('magenta'), cf.violet('violet'), cf.blue('blue'), cf.cyan('cyan'), cf.green('green')) # directly print with colors cf.print('{c.bold_blue}Hello World{c.reset}') # choose specific color mode for one block with cf.with_8_ansi_colors() as c: print(c.bold_green('colorful is awesome!')) # create and choose your own color palette MY_COMPANY_PALETTE = {
"""Functions associated with formatting output.""" import math import shutil from itertools import zip_longest from typing import Any, List, Text, Tuple import colorful from colorful import Colorful colorful.use_style("solarized") COLUMN_MARGIN = 3 def get_columns_count_and_width(strings: List[Text]) -> Tuple[int, int]: """Calculate how to break a list of strings into multiple columns. Calculate the optimal column width and number of columns to display a list of strings on screen. :param strings: list of strings :return: a tuple with the number of columns and column width """ terminal_width = shutil.get_terminal_size((80, 20)).columns max_string_width = max(len(string) for string in strings) col_width = max_string_width + COLUMN_MARGIN num_cols = int(terminal_width / col_width) if num_cols > len(strings): num_cols = len(strings)
import os import sys import pandas as pd import colorful as cf from manual import AdjustClassification # for nice formatting cf.use_style('monokai') class Train: ''' Runs anvio and shell commands to manually classify the data ''' def __init__(self, directory, coverage_values_file, classified_values_file, tree_file, title, override=False, export=True): self.directory = directory self.coverage_values_file = coverage_values_file self.classified_values_file = classified_values_file self.tree_file = tree_file self.train = True
session, database_exists, create_database, drop_database, load_sql_from_file, sql_from_file, raw_execute, copy_url, ) from schemainspect import NullInspector from migra import Migration, UnsafeMigrationException from migra.changes import statements_for_changes from .roles import extract_roles cf.use_style("solarized") def temporary_name(prefix="migra_"): random_letters = [random.choice(string.ascii_lowercase) for _ in range(10)] rnd = "".join(random_letters) tempname = prefix + rnd return tempname @contextmanager def temporary_database(base_uri): # Create temporary database tempname = temporary_name() temp_uri = copy_url(base_uri) temp_uri.database = tempname
def run_suite(self, suite_dir: SuiteDirectory) -> None: print(f'Running suite in {suite_dir.path}.') # Sanity check args and inputs. args = self.args() inputs = self.inputs() assert len(inputs) > 0, inputs # Record args and inputs. suite_dir.write_dict('args.json', args) suite_dir.write_string('inputs.txt', '\n'.join(str(i) for i in inputs)) # Create file to record suite results. results_file = suite_dir.create_file('results.csv') results_writer = csv.writer(results_file) suite_start_time = datetime.datetime.now() for (i, input) in enumerate(inputs, 1): bench_start_time = datetime.datetime.now() with suite_dir.benchmark_directory() as bench: # Run the benchmark. bench.write_string('input.txt', str(input)) bench.write_dict('input.json', util.tuple_to_dict(input)) output = self.run_benchmark(bench, args, input) # Write the header if needed. if i == 1: results_writer.writerow( util.flatten_tuple_fields(input) + util.flatten_tuple_fields(output)) # Write the results. row = util.flatten_tuple(input) + util.flatten_tuple(output) results_writer.writerow([str(x) for x in row]) results_file.flush() # Display some information about the benchmark. colorful.use_style('monokai') #First, we show the progress of the suite. n = len(inputs) percent = (i / n) * 100 info = f'{colorful.bold}[{i:03}/{n:03}{colorful.reset}; ' info += f'{percent:#.4}%] ' # Next, we show the time taken to run this benchmark, the total # elapsed time, and the estimated time left. current_time = datetime.datetime.now() bench_duration = current_time - bench_start_time suite_duration = current_time - suite_start_time duration_per_iteration = suite_duration / i remaining_duration = (n - i) * duration_per_iteration def round_timedelta(d): return datetime.timedelta(seconds=int(d.total_seconds())) info += f'{colorful.blue(round_timedelta(bench_duration))} / ' info += f'{colorful.green(round_timedelta(suite_duration))} + ' info += f'{colorful.magenta(round_timedelta(remaining_duration))}? ' # Finally, we display a summary of the benchmark. info += f'{colorful.lightGray(self.summary(input, output))}' print(info)
#:::LED MASTER::: import os import sys import json import time import datetime import colorful from raspledstrip.bootstrap import * from utils.processControl import Process #:::INITIALIZATION::: colorful.use_style('monokai') #:::DEFINITIONS::: #: Print Log w/ timestamp def printLog(text): print(colorful.bold(datetime.datetime.now().strftime("%m/%d/%Y-%H:%M:%S")) + ' ' + text) #: Print error message def printError(text): printLog(colorful.bold_magenta('ERROR: ') + text) return True #: Print success message