def example(context, container=None): ''' Discover API members that have a code example. ''' from static_frame.core.display_color import HexColor from doc.source.conf import get_jinja_contexts contexts = get_jinja_contexts() defined = contexts['examples_defined'] signatures = set() # discover all signatures; if it is defined, print in a darker color for name, cls, frame in contexts['interface'].values(): for signature, row in frame.iter_tuple_items(axis=1): target = f'{name}-{row.signature_no_args}' signatures.add(target) # accumulate all signatures if container and name != container: continue if target in defined: print(HexColor.format_terminal(0x505050, target)) else: print(target) for line in sorted(defined - signatures): print(HexColor.format_terminal(0x00ccff, line))
def __str__(self) -> str: if self.value[0]: v = '✓' # make a check mark else: v = '?' if self.value[1]: return HexColor.format_terminal('darkgreen', str(v)) return HexColor.format_terminal('darkorange', str(v))
def test_hex_color_format_a(self) -> None: msg = HexColor.format_terminal('#4b006e', 'test') self.assertEqual(msg, '\x1b[38;5;53mtest\x1b[0m') msg = HexColor.format_terminal(0xaaaaaa, 'test') self.assertEqual(msg, '\x1b[38;5;248mtest\x1b[0m') msg = HexColor.format_terminal('0xaaaaaa', 'test') self.assertEqual(msg, '\x1b[38;5;248mtest\x1b[0m') msg = HexColor.format_terminal('#040273', 'test') self.assertEqual(msg, '\x1b[38;5;4mtest\x1b[0m')
def format(key: tp.Tuple[tp.Any, str], v: object) -> str: nonlocal name_root_last nonlocal name_root_count if isinstance(v, float): if np.isnan(v): return '' return str(round(v, 4)) if isinstance(v, (bool, np.bool_)): if v: return HexColor.format_terminal('green', str(v)) return HexColor.format_terminal('orange', str(v)) return str(v)
def test_display_value_color_a(self) -> None: f1 = ff.parse('s(10,3)|i(I,str)') s2 = f1.assign[1].apply(lambda s: s.iter_element().apply( lambda e: HexColor.format_terminal('green' if e > 0 else 'blue', str(e)))) post = s2.display()
def type_color_markup(type_label: str, type_category: DisplayTypeCategory, config: DisplayConfig) -> str: ''' Return a format string for applying color to a type based on type category and config. ''' color = getattr(config, type_category.CONFIG_ATTR) if config.display_format in _DISPLAY_FORMAT_HTML: return HexColor.format_html(color, FORMAT_EMPTY) if config.display_format in _DISPLAY_FORMAT_TERMINAL: if terminal_ansi(): return HexColor.format_terminal(color, FORMAT_EMPTY) # if not a compatible terminal, return label unaltered return FORMAT_EMPTY raise NotImplementedError('no handling for display format:', config.display_format)
def type_color_markup( type_label: str, type_category: DisplayTypeCategory, config: DisplayConfig ): ''' Return type label with markup for color. ''' color = getattr(config, type_category.CONFIG_ATTR) if config.display_format in _DISPLAY_FORMAT_HTML: return HexColor.format_html(color, type_label) elif config.display_format in _DISPLAY_FORMAT_TERMINAL: if terminal_ansi(): return HexColor.format_terminal(color, type_label) # if not a compatible terminal, return label unaltered return type_label raise NotImplementedError('no handling for display format:', config.display_format)
def type_color_markup(type_category: tp.Type[DisplayTypeCategory], config: DisplayConfig) -> str: ''' Return a format string for applying color to a type based on type category and config. Returns: A templated string with a "text" field for formatting. ''' color = getattr(config, type_category.CONFIG_ATTR) if config.display_format in _DISPLAY_FORMAT_HTML: return HexColor.format_html(color, FORMAT_EMPTY) if config.display_format in _DISPLAY_FORMAT_TERMINAL and terminal_ansi( ): return HexColor.format_terminal(color, FORMAT_EMPTY) #pragma: no cover # if not a compatible terminal, return label unaltered return FORMAT_EMPTY
class Animator: PROMPT = HexColor.format_terminal('lightgrey', '>>> ') CHAR_INTERVAL = 0.04 #0.07 CHAR_JITTER = [x * .01 for x in range(6)] + [0.08, .12] @classmethod def print_char(cls, char: str) -> None: print(char, end='') sys.stdout.flush() time.sleep(cls.CHAR_INTERVAL + random.choice(cls.CHAR_JITTER)) @classmethod def pause(cls, interval: float) -> None: print(cls.PROMPT, end='') sys.stdout.flush() time.sleep(interval) print() # newline sys.stdout.flush() @classmethod def main(cls, func: tp.Callable[[], LineIter]) -> None: for line in func(): if line is PAUSE_SHORT: cls.pause(0.5) continue if line is PAUSE_LONG: cls.pause(2) continue if line is PAUSE_FINAL: cls.pause(5) continue assert isinstance(line, (Comment, str)) print(cls.PROMPT, end='') for char in line: cls.print_char(char) cls.print_char('\n') # get new line if isinstance(line, Comment): continue try: post = eval(line) if post is not None: print(post) except SyntaxError: exec(line) except MemoryError as e: traceback.print_exc(limit=-3)
def format(key: tp.Tuple[tp.Any, str], v: object) -> str: nonlocal name_root_last nonlocal name_root_count if isinstance(v, float): if np.isnan(v): return '' return str(round(v, 4)) if isinstance(v, (bool, np.bool_)): if v: return HexColor.format_terminal('green', str(v)) return HexColor.format_terminal('orange', str(v)) if isinstance(v, str): if key[1] == 'explanation': return HexColor.format_terminal('gray', v) if key[1] == 'name': name_root = v.split('.')[0] if name_root != name_root_last: name_root_last = name_root name_root_count += 1 if name_root_count % 2: return HexColor.format_terminal('lavender', v) return HexColor.format_terminal('lightslategrey', v) return str(v)
def test_hex_str_to_int_a(self) -> None: post = HexColor._hex_str_to_int('aqua') self.assertEqual(post, 65535)
columns_dtype_group=columns_dtype_group) return st.one_of((st_frame, st_frame_go)) if __name__ == '__main__': import fnmatch from argparse import ArgumentParser from static_frame.core.display_color import HexColor parser = ArgumentParser() parser.add_argument('-n', '--name', default=None) parser.add_argument('-c', '--count', default=2, type=int) options = parser.parse_args() local_items = tuple(locals().items()) for v in (v for k, v in local_items if callable(v) and k.startswith('get')): if options.name: if not fnmatch.fnmatch(v.__name__, options.name): continue print(HexColor.format_terminal('grey', '.' * 50)) print(HexColor.format_terminal('hotpink', str(v.__name__))) for x in range(options.count): print(HexColor.format_terminal('grey', '.' * 50)) example = v().example() print(repr(example))
def __iter__(self) -> tp.Iterator[str]: return HexColor.format_terminal(self.color, self.message).__iter__()
class Animator: PROMPT = HexColor.format_terminal('lightgrey', '>>> ') CHAR_INTERVAL = 0.03 #0.07 CHAR_JITTER = [x * .01 for x in range(6)] + [0.10, .12] @classmethod def print_char(cls, char: str) -> None: print(char, end='') sys.stdout.flush() # time.sleep(cls.CHAR_INTERVAL + random.choice(cls.CHAR_JITTER)) @classmethod def pause(cls, interval: float) -> None: print(cls.PROMPT, end='') sys.stdout.flush() time.sleep(interval) print() # newline sys.stdout.flush() @classmethod def main(cls, func: tp.Callable[[], LineIter]) -> None: import static_frame as sf import numpy as np from string import ascii_lowercase for line in func(): if line is PAUSE_SHORT: cls.pause(1) continue if line is PAUSE_LONG: cls.pause(2.5) continue if line is PAUSE_FINAL: cls.pause(5) continue assert isinstance(line, (Comment, str)) print(cls.PROMPT, end='') for char in line: cls.print_char(char) cls.print_char('\n') # get new line if isinstance(line, Comment): continue # NOTE: exec puts variables in this scope; pass globals and locals eval, exec g = globals() g['sf'] = sf g['np'] = np g['ascii_lowercase'] = ascii_lowercase l = locals() try: post = eval(line, g, l) if post is not None: print(post) except SyntaxError: exec(line, g, l) except MemoryError as e: traceback.print_exc(limit=-3)
class StyleConfigCSS(StyleConfig): COLOR_LIGHT_GREY = HexColor.get_html(0xe0e0e0) COLOR_OFF_BLACK = HexColor.get_html(0x2b2a2a) COLOR_GREY = HexColor.get_html(0xd1d2d4) COLOR_DARK_GREY = HexColor.get_html(0x898b8e) COLOR_WHITE = HexColor.get_html(0xffffff) COLOR_OFF_WHITE = HexColor.get_html(0xf2f2f2) FONT_SIZE = '14px' CSS_COMMON = dict( font_size=FONT_SIZE, border_width='1px', border_color=COLOR_DARK_GREY, border_style='solid', color=COLOR_OFF_BLACK, ) @staticmethod def _dict_to_style(css_dict: CSSDict) -> str: ''' Return a style attribute string containing all CSS in the CSSDict. ''' style = ';'.join(f'{k.replace("_", "-")}:{v}' for k, v in css_dict.items()) # NOTE: keep leading space to separate from tag return f' style="{style}"' def frame(self) -> str: ''' Frame- (or table-) level styling. ''' css = dict( border_collapse='collapse', border_width='1px', border_color=self.COLOR_DARK_GREY, border_style='solid', ) return self._dict_to_style(css) def apex(self, value: tp.Any, coordinates: tp.Tuple[int, int], ) -> tp.Tuple[str, str]: css = dict( background_color=self.COLOR_LIGHT_GREY, font_weight='normal', padding='2px', border_width='0px', ) return str(value), self._dict_to_style(css) def values(self, value: tp.Any, coordinates: tp.Tuple[int, int], ) -> tp.Tuple[str, str]: row, _ = coordinates def get_bg(row: int) -> str: if (row % 2) == 1: return self.COLOR_OFF_WHITE return self.COLOR_WHITE css = dict( background_color=get_bg(row), font_weight='normal', padding='2px', **self.CSS_COMMON, ) return str(value), self._dict_to_style(css) def index(self, label: tp.Hashable, ) -> tp.Tuple[str, str]: css = dict( background_color=self.COLOR_GREY, font_weight='bold', **self.CSS_COMMON, ) return str(label), self._dict_to_style(css) def columns(self, label: tp.Hashable, ) -> tp.Tuple[str, str]: css = dict( background_color=self.COLOR_GREY, font_weight='bold', **self.CSS_COMMON, ) return str(label), self._dict_to_style(css)
def test_format_html_a(self) -> None: post = HexColor.format_html('aqua', 'test') self.assertEqual(post, '<span style="color: #ffff">test</span>')
try: # This lets us play nicely with IPython: from builtins import __IPYTHON__ #type: ignore from IPython import embed from IPython import get_ipython except ImportError: is_ipython = False else: is_ipython = __IPYTHON__ if __name__ == '__main__': if is_ipython: ipython = get_ipython() print() # Spacer. for command in commands: ipython.auto_rewrite_input(command) print() # Spacer. embed(user_ns=imports, colors='neutral') else: banner_head = f'Python {version} on {platform}\n' banner_body = '\n'.join(f'>>> {command}' for command in commands) interact(banner=(banner_head + HexColor.format_terminal(0x505050, banner_body)), local=imports, exitmsg='')