code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
morphlist = list(self._morph_rgb(start, stop, step=step)) if movefactor: # Moving means we need the morph to wrap around. morphlist.extend(self._morph_rgb(stop, start, step=step)) if movefactor < 0: # Increase the start for each line. ...
def _gradient_rgb_lines( self, text, start, stop, step=1, fore=None, back=None, style=None, movefactor=None)
Yield colorized characters, morphing from one rgb value to another. This treats each line separately.
3.054268
2.971889
1.027719
if fore and back: raise ValueError('Both fore and back colors cannot be specified.') pos = 0 end = len(text) numbergen = self._iter_wave(numbers) def make_color(n): try: r, g, b = n except TypeError: i...
def _iter_text_wave( self, text, numbers, step=1, fore=None, back=None, style=None, rgb_mode=False)
Yield colorized characters from `text`, using a wave of `numbers`. Arguments: text : String to be colorized. numbers : A list/tuple of numbers (256 colors). step : Number of characters to colorize per color. fore : Fore color t...
3.459455
3.309092
1.045439
up = True pos = 0 i = 0 try: end = len(iterable) except TypeError: iterable = list(iterable) end = len(iterable) # Stop on count, or run forever. while (i < count) if count > 0 else True: try: ...
def _iter_wave(iterable, count=0)
Move from beginning to end, and then end to beginning, a number of iterations through an iterable (must accept len(iterable)). Example: print(' -> '.join(_iter_wave('ABCD', count=8))) >> A -> B -> C -> D -> C -> B -> A -> B If `count` is less than 1, ...
4.219707
3.861226
1.092841
pos1, pos2 = list(rgb1), list(rgb2) indexes = [i for i, _ in enumerate(pos1)] def step_value(a, b): if a < b: return step if a > b: return -step return 0 steps = [step_value(pos1[x], pos2[x]) for ...
def _morph_rgb(self, rgb1, rgb2, step=1)
Morph an rgb value into another, yielding each step along the way.
2.607846
2.496447
1.044623
return ( (c, self._rainbow_color(freq, offset + i / spread)) for i, c in enumerate(s) )
def _rainbow_hex_chars(self, s, freq=0.1, spread=3.0, offset=0)
Iterate over characters in a string to build data needed for a rainbow effect. Yields tuples of (char, hexcode). Arguments: s : String to colorize. freq : Frequency/"tightness" of colors in the rainbow. Best results when...
5.057742
4.731557
1.068938
fore = colorargs.get('fore', None) back = colorargs.get('back', None) style = colorargs.get('style', None) if fore: color_args = (lambda value: { 'back': value if rgb_mode else hex2term(value), 'style': style, 'fore': f...
def _rainbow_line( self, text, freq=0.1, spread=3.0, offset=0, rgb_mode=False, **colorargs)
Create rainbow using the same offset for all text. Arguments: text : String to colorize. freq : Frequency/"tightness" of colors in the rainbow. Best results when in the range 0.0-1.0. Default: 0.1 ...
2.779355
2.72645
1.019404
if not movefactor: def factor(i): return offset else: # Increase the offset for each line. def factor(i): return offset + (i * movefactor) return '\n'.join( self._rainbow_line( line, ...
def _rainbow_lines( self, text, freq=0.1, spread=3.0, offset=0, movefactor=0, rgb_mode=False, **colorargs)
Create rainbow text, using the same offset for each line. Arguments: text : String to colorize. freq : Frequency/"tightness" of colors in the rainbow. Best results when in the range 0.0-1.0. Default: 0.1 ...
2.529328
2.722257
0.929129
# Borrowed from lolcat, translated from ruby. red = math.sin(freq * i + 0) * 127 + 128 green = math.sin(freq * i + 2 * math.pi / 3) * 127 + 128 blue = math.sin(freq * i + 4 * math.pi / 3) * 127 + 128 return int(red), int(green), int(blue)
def _rainbow_rgb(self, freq, i)
Calculate a single rgb value for a piece of a rainbow. Arguments: freq : "Tightness" of colors (see self.rainbow()) i : Index of character in string to colorize.
2.100813
2.117628
0.99206
return ( (c, self._rainbow_rgb(freq, offset + i / spread)) for i, c in enumerate(s) )
def _rainbow_rgb_chars(self, s, freq=0.1, spread=3.0, offset=0)
Iterate over characters in a string to build data needed for a rainbow effect. Yields tuples of (char, (r, g, b)). Arguments: s : String to colorize. freq : Frequency/"tightness" of colors in the rainbow. Best results wh...
4.66579
4.42079
1.05542
return self.chained(text=text, fore=fore, back=(r, g, b), style=style)
def b_rgb(self, r, g, b, text=None, fore=None, style=None)
A chained method that sets the back color to an RGB value. Arguments: r : Red value. g : Green value. b : Blue value. text : Text to style if not building up color codes. fore : Fore color for the text. ...
6.001723
6.265464
0.957906
self.data = ''.join(( self.data, self.color(text=text, fore=fore, back=back, style=style), )) return self
def chained(self, text=None, fore=None, back=None, style=None)
Called by the various 'color' methods to colorize a single string. The RESET_ALL code is appended to the string unless text is empty. Raises ValueError on invalid color names. Arguments: text : String to colorize, or None for BG/Style change. fore ...
3.883551
4.556387
0.852331
has_args = ( (fore is not None) or (back is not None) or (style is not None) ) if hasattr(text, '__colr__') and not has_args: # Use custom __colr__ method in the absence of arguments. return str(self._call_dunder_colr(text)) ...
def color( self, text=None, fore=None, back=None, style=None, no_closing=False)
A method that colorizes strings, not Colr objects. Raises InvalidColr for invalid color names. The 'reset_all' code is appended if text is given.
5.053883
4.896638
1.032113
# Map from style type to raw code formatter function. colorcodes = [] resetcodes = [] userstyles = {'style': style, 'back': back, 'fore': fore} for stype in userstyles: stylearg = userstyles.get(stype, None) if not stylearg: # No v...
def color_code(self, fore=None, back=None, style=None)
Return the codes for this style/colors.
4.707881
4.640487
1.014523
return self.__class__(self.data.format(*args, **kwargs))
def format(self, *args, **kwargs)
Like str.format, except it returns a Colr.
5.593735
3.702949
1.510616
valuefmt = str(value).lower() code = codes[codetype].get(valuefmt, None) if code: # Basic code from fore, back, or style. return code named_funcs = { 'fore': format_fore, 'back': format_back, 'style': format_style, ...
def get_escape_code(self, codetype, value)
Convert user arg to escape code.
5.085949
5.017601
1.013622
try: # Try explicit offset (passed in with `name`). offset = int(name) except (TypeError, ValueError): name = name.lower().strip() if name else 'black' # Black and white are separate methods. if name == 'black': return ...
def gradient( self, text=None, name=None, fore=None, back=None, style=None, freq=0.1, spread=None, linemode=True, movefactor=2, rgb_mode=False)
Return a gradient by color name. Uses rainbow() underneath to build the gradients, starting at a known offset. Arguments: text : Text to make gradient (self.data when not given). The gradient text is joined to self.data when ...
2.317665
2.248255
1.030873
gradargs = { 'step': step, 'fore': fore, 'back': back, 'style': style, 'reverse': reverse, 'rgb_mode': rgb_mode, } if linemode: gradargs['movefactor'] = 2 if movefactor is None else movefactor ...
def gradient_black( self, text=None, fore=None, back=None, style=None, start=None, step=1, reverse=False, linemode=True, movefactor=2, rgb_mode=False)
Return a black and white gradient. Arguments: text : String to colorize. This will always be greater than 0. fore : Foreground color, background will be gradient. back : Background color, foreground will be gradie...
3.432805
3.67194
0.934875
gradargs = { 'step': step, 'fore': fore, 'back': back, 'style': style, } start = start or (0, 0, 0) stop = stop or (255, 255, 255) if linemode: method = self._gradient_rgb_lines gradargs['movefactor'...
def gradient_rgb( self, text=None, fore=None, back=None, style=None, start=None, stop=None, step=1, linemode=True, movefactor=0)
Return a black and white gradient. Arguments: text : String to colorize. fore : Foreground color, background will be gradient. back : Background color, foreground will be gradient. style : Name of style to use for the gra...
3.081911
3.074381
1.002449
if rgb_mode: try: colrval = hex2rgb(value, allow_short=True) except ValueError: raise InvalidColr(value) else: try: colrval = hex2term(value, allow_short=True) except ValueError: rais...
def hex(self, value, text=None, back=None, style=None, rgb_mode=False)
A chained method that sets the fore color to an hex value. Arguments: value : Hex value to convert. text : Text to style if not building up color codes. back : Back color for the text. style : Style for the text. r...
3.557538
3.425175
1.038644
flat = [] for clr in colrs: if isinstance(clr, (list, tuple, GeneratorType)): # Flatten any lists, at least once. flat.extend(str(c) for c in clr) else: flat.append(str(clr)) if colorkwargs: fore = colo...
def join(self, *colrs, **colorkwargs)
Like str.join, except it returns a Colr. Arguments: colrs : One or more Colrs. If a list or tuple is passed as an argument it will be flattened. Keyword Arguments: fore, back, style... see color().
2.857291
2.859279
0.999305
return self.__class__( self._str_strip('lstrip', chars), no_closing=chars and (closing_code in chars), )
def lstrip(self, chars=None)
Like str.lstrip, except it returns the Colr instance.
16.591484
12.854486
1.290716
print(self, *args, **kwargs) self.data = '' return self
def print(self, *args, **kwargs)
Chainable print method. Prints self.data and then clears it.
7.866806
3.052113
2.577495
if fore and back: raise ValueError('Cannot use both fore and back with rainbow()') rainbowargs = { 'freq': freq, 'spread': spread, 'offset': offset, 'fore': fore, 'back': back, 'style': style, 'rgb_...
def rainbow( self, text=None, fore=None, back=None, style=None, freq=0.1, offset=30, spread=3.0, linemode=True, movefactor=2, rgb_mode=False)
Make rainbow gradient text. Arguments: text : Text to make gradient. Default: self.data fore : Fore color to use (makes back the rainbow). Default: None back : Back color to use (makes...
3.0471
3.12434
0.975278
return self.__class__( self._str_strip('rstrip', chars), no_closing=chars and (closing_code in chars), )
def rstrip(self, chars=None)
Like str.rstrip, except it returns the Colr instance.
18.751427
14.901057
1.258396
return self.__class__( self._str_strip('strip', chars), no_closing=chars and (closing_code in chars), )
def strip(self, chars=None)
Like str.strip, except it returns the Colr instance.
20.488787
16.315269
1.255804
label_args = label_args or {'fore': 'red'} value_args = value_args or {'fore': 'blue', 'style': 'bright'} return Colr(self.default_format.format( label=Colr(self.label, **label_args), value=Colr(repr(self.value), **value_args), ))
def as_colr(self, label_args=None, value_args=None)
Like __str__, except it returns a colorized Colr instance.
2.854757
2.436772
1.171532
label_args = label_args or {'fore': 'red'} type_args = type_args or {'fore': 'yellow'} type_val_args = type_val_args or {'fore': 'grey'} value_args = value_args or {'fore': 'blue', 'style': 'bright'} return Colr(self.default_format.format( label=Colr(':\n ...
def as_colr( self, label_args=None, type_args=None, type_val_args=None, value_args=None)
Like __str__, except it returns a colorized Colr instance.
3.288301
3.152806
1.042976
label_args = label_args or {'fore': 'red'} type_args = type_args or {'fore': 'yellow'} type_val_args = type_val_args or {'fore': 'grey'} value_args = value_args or {'fore': 'blue', 'style': 'bright'} spec_args = spec_args or {'fore': 'blue'} spec_repr = repr(self...
def as_colr( self, label_args=None, type_args=None, type_val_args=None, value_args=None, spec_args=None)
Like __str__, except it returns a colorized Colr instance.
3.008234
2.920432
1.030065
label_args = label_args or {'fore': 'red'} type_args = type_args or {'fore': 'yellow'} value_args = value_args or {'fore': 'blue', 'style': 'bright'} return Colr(self.default_format.format( label=Colr(':\n ').join( Colr('Expecting style value', **...
def as_colr( self, label_args=None, type_args=None, value_args=None)
Like __str__, except it returns a colorized Colr instance.
4.052673
3.843014
1.054556
isatty = getattr(file, 'isatty', None) if isatty is None: raise TypeError( 'Cannot detect tty, file has no `isatty` method: {}'.format( getattr(file, 'name', type(file).__name__) ) ) if not isatty(): raise TypeError( 'This will...
def ensure_tty(file=sys.stdout)
Ensure a file object is a tty. It must have an `isatty` method that returns True. TypeError is raised if the method doesn't exist, or returns False.
2.702219
2.392602
1.129406
erase.display(method).write(file=file)
def erase_display(method=EraseMethod.ALL_MOVE, file=sys.stdout)
Clear the screen or part of the screen, and possibly moves the cursor to the "home" position (1, 1). See `method` argument below. Esc[<method>J Arguments: method: One of these possible values: EraseMethod.END or 0: Clear from curs...
17.033236
82.703644
0.205955
erase.line(method).write(file=file)
def erase_line(method=EraseMethod.ALL, file=sys.stdout)
Erase a line, or part of a line. See `method` argument below. Cursor position does not change. Esc[<method>K Arguments: method : One of these possible values: EraseMethod.END or 0: Clear from cursor to the end of the line. ...
17.429485
84.661232
0.205873
move.back(columns).write(file=file)
def move_back(columns=1, file=sys.stdout)
Move the cursor back a number of columns. Esc[<columns>D: Moves the cursor back by the specified number of columns without changing lines. If the cursor is already in the leftmost column, ANSI.SYS ignores this sequence.
13.212356
64.176422
0.205876
move.column(column).write(file=file)
def move_column(column=1, file=sys.stdout)
Move the cursor to the specified column, default 1. Esc[<column>G
14.742959
38.8727
0.379263
move.down(lines).write(file=file)
def move_down(lines=1, file=sys.stdout)
Move the cursor down a number of lines. Esc[<lines>B: Moves the cursor down by the specified number of lines without changing columns. If the cursor is already on the bottom line, ANSI.SYS ignores this sequence.
15.029803
50.186413
0.29948
move.forward(columns).write(file=file)
def move_forward(columns=1, file=sys.stdout)
Move the cursor forward a number of columns. Esc[<columns>C: Moves the cursor forward by the specified number of columns without changing lines. If the cursor is already in the rightmost column, ANSI.SYS ignores this sequence.
13.570612
55.153614
0.246051
move.next(lines).write(file=file)
def move_next(lines=1, file=sys.stdout)
Move the cursor to the beginning of the line, a number of lines down. Default: 1 Esc[<lines>E
15.482288
45.669262
0.339009
move.pos(line=line, col=column).write(file=file)
def move_pos(line=1, column=1, file=sys.stdout)
Move the cursor to a new position. Values are 1-based, and default to 1. Esc[<line>;<column>H or Esc[<line>;<column>f
10.317538
20.057451
0.514399
move.prev(lines).write(file=file)
def move_prev(lines=1, file=sys.stdout)
Move the cursor to the beginning of the line, a number of lines up. Default: 1 Esc[<lines>F
13.608455
40.191471
0.338591
move.up(lines).write(file=file)
def move_up(lines=1, file=sys.stdout)
Move the cursor up a number of lines. Esc[ValueA: Moves the cursor up by the specified number of lines without changing columns. If the cursor is already on the top line, ANSI.SYS ignores this sequence.
13.745725
53.140987
0.258665
kwargs.setdefault('file', sys.stdout) kwargs.setdefault('end', '') pos_save(file=kwargs['file']) delay = None with suppress(KeyError): delay = kwargs.pop('delay') if delay is None: print(*args, **kwargs) else: for c in kwargs.get('sep', ' ').join(str(a) for a in ...
def print_inplace(*args, **kwargs)
Save cursor position, write some text, and then restore the position. Arguments: Same as `print()`. Keyword Arguments: Same as `print()`, except `end` defaults to '' (empty str), and these: delay : Time in seconds between character writes.
3.106008
3.021265
1.028049
kwargs.setdefault('file', sys.stdout) print(*args, **kwargs) kwargs['file'].flush()
def print_flush(*args, **kwargs)
Like `print()`, except the file is `.flush()`ed afterwards.
3.222153
2.505953
1.2858
kwargs.setdefault('file', sys.stdout) kwargs.setdefault('end', '') delay = None with suppress(KeyError): delay = kwargs.pop('delay') erase_line() # Move to the beginning of the line. move_column(1, file=kwargs['file']) if delay is None: print(*args, **kwargs) els...
def print_overwrite(*args, **kwargs)
Move to the beginning of the current line, and print some text. Arguments: Same as `print()`. Keyword Arguments: Same as `print()`, except `end` defaults to '' (empty str), and these: delay : Time in seconds between character writes.
3.112555
3.050559
1.020323
scroll.down(lines).write(file=file)
def scroll_down(lines=1, file=sys.stdout)
Scroll the whole page down a number of lines, new lines are added to the top. Esc[<lines>T
17.269308
31.460703
0.548917
scroll.up(lines).write(file=file)
def scroll_up(lines=1, file=sys.stdout)
Scroll the whole page up a number of lines, new lines are added to the bottom. Esc[<lines>S
15.516645
30.823534
0.503403
return self.chained(erase.display(method))
def erase_display(self, method=EraseMethod.ALL_MOVE)
Clear the screen or part of the screen. Arguments: method: One of these possible values: EraseMethod.END or 0: Clear from cursor to the end of the screen. EraseMethod.START or 1: ...
41.339214
65.262535
0.633429
return self.chained(erase.line(method=method))
def erase_line(self, method=EraseMethod.ALL)
Erase a line, or part of a line. Arguments: method : One of these possible values: EraseMethod.END or 0: Clear from cursor to the end of the line. EraseMethod.START or 1: C...
26.040079
33.136776
0.785836
codes = self.data.split(escape_sequence) if not codes: return '' return ''.join((escape_sequence, codes[-1]))
def last_code(self)
Return the last escape code in `self.data`. If no escape codes are found, '' is returned.
9.468235
5.166511
1.832617
return self.chained(move.pos(line=line, column=column))
def move_pos(self, line=1, column=1)
Move the cursor to a new position. Default: line 1, column 1
12.078508
14.922333
0.809425
# Subtracting one from the count means the code mentioned is # truly repeated exactly `count` times. # Control().move_up().repeat(3) == # Control().move_up().move_up().move_up() try: return self.__class__(''.join(( str(self), s...
def repeat(self, count=2)
Repeat the last control code a number of times. Returns a new Control with this one's data and the repeated code.
6.977489
6.191569
1.126934
try: return self.__class__(''.join(str(self) * count)) except TypeError: raise TypeError( '`count` must be an integer. Got: {!r}'.format(count) )
def repeat_all(self, count=2)
Repeat this entire Control code a number of times. Returns a new Control with this one's data repeated.
4.702276
4.168819
1.127964
if not hexval: raise ValueError( 'Expecting hex string (#RGB, #RRGGBB), got nothing: {!r}'.format( hexval ) ) try: hexval = hexval.strip().lstrip('#') except AttributeError: raise ValueError( 'Expecting hex string (#RGB...
def hex2rgb(hexval: str, allow_short: bool = False) -> RGB
Return a tuple of (R, G, B) from a hex color.
2.978774
2.912093
1.022898
return rgb2term(*hex2rgb(hexval, allow_short=allow_short))
def hex2term(hexval: str, allow_short: bool = False) -> str
Convert a hex value into the nearest terminal code number.
5.308904
4.174057
1.271881
return rgb2termhex(*hex2rgb(hexval, allow_short=allow_short))
def hex2termhex(hexval: str, allow_short: bool = False) -> str
Convert a hex value into the nearest terminal color matched hex.
5.610908
3.519236
1.594354
for code in sorted(term2hex_map): print(' '.join(( '\033[48;5;{code}m{code:<3}:{hexval:<6}\033[0m', '\033[38;5;{code}m{code:<3}:{hexval:<6}\033[0m' )).format(code=code, hexval=term2hex_map[code]))
def print_all() -> None
Print all 256 xterm color codes.
3.819411
2.994205
1.275601
return '{:02x}{:02x}{:02x}'.format(r, g, b)
def rgb2hex(r: int, g: int, b: int) -> str
Convert rgb values to a hex code.
2.83791
2.075357
1.367432
return hex2term_map[rgb2termhex(r, g, b)]
def rgb2term(r: int, g: int, b: int) -> str
Convert an rgb value to a terminal code.
14.516825
8.108134
1.790403
incs = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff] res = [] parts = r, g, b for part in parts: if (part < 0) or (part > 255): raise ValueError( 'Expecting 0-255 for RGB code, got: {!r}'.format(parts) ) i = 0 while i < len(incs) - 1: ...
def rgb2termhex(r: int, g: int, b: int) -> str
Convert an rgb value to the nearest hex value that matches a term code. The hex value will be one in `hex2term_map`.
3.365723
3.096089
1.087089
try: val = term2hex_map.get('{:02}'.format(int(code), default)) except ValueError: raise ValueError( 'Expecting an int or number string, got: {} ({})'.format( code, getattr(code, '__name__', type(code).__name__))) return val
def term2hex(code: Numeric, default: Optional[str] = None) -> str
Convenience function for term2hex_map.get(code, None). Accepts strs or ints in the form of: 1, 01, 123. Returns `default` if the code is not found.
5.959526
4.748889
1.254931
if -1 < code < 256: self.code = '{:02}'.format(code) self.hexval = term2hex(code) self.rgb = hex2rgb(self.hexval) else: raise ValueError(' '.join(( 'Code must be in the range 0-255, inclusive.', 'Got: {} ({})' ...
def _init_code(self, code: int) -> None
Initialize from an int terminal code.
3.900998
3.452839
1.129794
self.hexval = hex2termhex(fix_hex(hexval)) self.code = hex2term(self.hexval) self.rgb = hex2rgb(self.hexval)
def _init_hex(self, hexval: str) -> None
Initialize from a hex value string.
6.606351
5.531696
1.194272
if self.rgb_mode: self.rgb = (r, g, b) self.hexval = rgb2hex(r, g, b) else: self.rgb = hex2rgb(rgb2termhex(r, g, b)) self.hexval = rgb2termhex(r, g, b) self.code = hex2term(self.hexval)
def _init_rgb(self, r: int, g: int, b: int) -> None
Initialize from red, green, blue args.
3.182705
2.856157
1.114331
if self.rgb_mode: colorcode = '\033[38;2;{};{};{}m'.format(*self.rgb) else: colorcode = '\033[38;5;{}m'.format(self.code) return '{code}{s}\033[0m'.format(code=colorcode, s=self)
def example(self) -> str
Same as str(self), except the color codes are actually used.
3.022236
2.486077
1.215665
c = cls() c._init_code(code) return c
def from_code(cls, code: int) -> 'ColorCode'
Return a ColorCode from a terminal code.
7.522565
5.845274
1.286948
c = cls() c._init_hex(hexval) return c
def from_hex(cls, hexval: str) -> 'ColorCode'
Return a ColorCode from a hex string.
7.296002
5.792008
1.259667
c = cls() c._init_rgb(r, g, b) return c
def from_rgb(cls, r: int, g: int, b: int) -> 'ColorCode'
Return a ColorCode from a RGB tuple.
5.227483
4.116353
1.269931
'''Used as a decorator for automatically making session commits''' def wrap(**kwarg): with session_withcommit() as session: a = func(**kwarg) session.add(a) return session.query(songs).order_by( songs.song_id.desc()).first().song_id return wrap
def commit(func)
Used as a decorator for automatically making session commits
7.841915
5.855361
1.339271
with session_withcommit() as session: val = session.query(songs).all() for row in val: yield row
def get_songs()->Iterator
Return songs that have the fingerprinted flag set TRUE (1).
10.598174
8.878196
1.193731
try: hub = _local.hub except AttributeError: # The Hub can only be instantiated from the root fiber. No other fibers # can run until the Hub is there, so the root will always be the first # one to call get_hub(). assert fibers.current().parent is None hub = _...
def get_hub()
Return the instance of the hub.
7.827002
7.377745
1.060893
hub = get_hub() try: with switch_back(secs, hub): hub.switch() except Timeout: pass
def sleep(secs)
Sleep for *secs* seconds. The *secs* argument can be an int or a float.
13.019621
14.296601
0.910679
if self._hub is None or not self._fiber.is_alive(): return self._hub.run_callback(self._fiber.switch, value) self._hub = self._fiber = None
def switch(self, value=None)
Switch back to the origin fiber. The fiber is switch in next time the event loop runs.
6.788916
4.823166
1.407564
# The might seem redundant with self._fiber.cancel(exc), but it isn't # as self._fiber might be a "raw" fibers.Fiber() that doesn't have a # cancel() method. if self._hub is None or not self._fiber.is_alive(): return self._hub.run_callback(self._fiber.throw, ...
def throw(self, typ, val=None, tb=None)
Throw an exception into the origin fiber. The exception is thrown the next time the event loop runs.
8.427432
7.861089
1.072044
if self._loop is None: return if fibers.current().parent is not None: raise RuntimeError('close() may only be called in the root fiber') elif compat.get_thread_ident() != self._thread: raise RuntimeError('cannot close() from a different thread') ...
def close(self)
Close the hub and wait for it to be closed. This may only be called in the root fiber. After this call returned, Gruvi cannot be used anymore in the current thread. The main use case for calling this method is to clean up resources in a multi-threaded program where you want to exit a th...
10.715832
9.144408
1.171845
if self._loop is None or not self.is_alive(): raise RuntimeError('hub is closed/dead') elif fibers.current() is self: raise RuntimeError('cannot switch to myself') elif compat.get_thread_ident() != self._thread: raise RuntimeError('cannot switch from ...
def switch(self)
Switch to the hub. This method pauses the current fiber and runs the event loop. The caller should ensure that it has set up appropriate callbacks so that it will get scheduled again, preferably using :class:`switch_back`. In this case then return value of this method will be an ``(args...
6.222111
5.45582
1.140454
for i in range(len(self._callbacks)): callback, args = self._callbacks.popleft() try: callback(*args) except Exception: self._log.exception('Ignoring exception in callback:')
def _run_callbacks(self)
Run registered callbacks.
3.708784
3.459443
1.072075
if self._loop is None: raise RuntimeError('hub is closed') elif not callable(callback): raise TypeError('"callback": expecting a callable') self._callbacks.append((callback, args)) # thread-safe self._interrupt_loop()
def run_callback(self, callback, *args)
Queue a callback. The *callback* will be called with positional arguments *args* in the next iteration of the event loop. If you add multiple callbacks, they will be called in the order that you added them. The callback will run in the Hub's fiber. This method is thread-safe: i...
7.091252
6.533297
1.085402
method = message.get('method') msgid = message.get('id') error = message.get('error') if method and msgid is not None: return 'method call "{}", id = "{}"'.format(method, msgid) elif method: return 'notification "{}"'.format(method) elif error is not None and msgid is not No...
def message_info(message)
Return a string describing a message, for debugging purposes.
3.319474
3.13478
1.058918
msgid = self._id_template.format(self._next_id) self._next_id += 1 return msgid
def next_id(self)
Return a unique message ID.
4.806779
3.5808
1.342376
clsname = 'JsonRpcV{}'.format(version.rstrip('.0')) cls = globals()[clsname] return cls(version)
def create(version)
Return a new instance for *version*, which can be either `'1.0'` or `'2.0'`.
9.714378
8.650903
1.122932
if self._error: raise compat.saved_exc(self._error) elif self._transport is None: raise JsonRpcError('not connected') self._version.check_message(message) self._writer.write(serialize(message))
def send_message(self, message)
Send a raw JSON-RPC message. The *message* argument must be a dictionary containing a valid JSON-RPC message according to the version passed into the constructor.
8.633469
7.646422
1.129086
message = self._version.create_request(method, args) msgid = message['id'] try: with switch_back(self._timeout) as switcher: self._method_calls[msgid] = switcher self.send_message(message) args, _ = self._hub.switch() f...
def call_method(self, method, *args)
Call a JSON-RPC method and wait for its result. The *method* is called with positional arguments *args*. On success, the ``result`` field from the JSON-RPC response is returned. On error, a :class:`JsonRpcError` is raised, which you can use to access the ``error`` field of the JSON-RP...
4.717465
4.49833
1.048715
message = self._version.create_request(method, args, notification=True) self.send_message(message)
def send_notification(self, method, *args)
Send a JSON-RPC notification. The notification *method* is sent with positional arguments *args*.
6.376943
6.820117
0.93502
message = self._version.create_response(request, result, error) self.send_message(message)
def send_response(self, request, result=None, error=None)
Respond to a JSON-RPC method call. This is a response to the message in *request*. If *error* is not provided, then this is a succesful response, and the value in *result*, which may be ``None``, is passed back to the client. if *error* is provided and not ``None`` then an error is sent...
6.107928
6.30113
0.969339
sig = getattr(pobj, 'dbusSignature', None) if sig is not None: return sig elif isinstance(pobj, int): return 'i' elif isinstance(pobj, six.integer_types): return 'x' elif isinstance(pobj, float): return 'd' elif isinstance(pobj, six.string_types): return 's' ...
def sigFromPy( pobj )
Returns the DBus signature type for the argument. If the argument is an instance of one of the type wrapper classes, the exact type signature corresponding to the wrapper class will be used. If the object has a variable named 'dbusSignature', the value of that variable will be used. Otherwise, a generic...
2.323407
2.358946
0.984934
i = 0 start = 0 end = len(compoundSig) def find_end( idx, b, e ): depth = 1 while idx < end: subc = compoundSig[idx] if subc == b: depth += 1 elif subc == e: depth -= 1 if depth == 0: ...
def genCompleteTypes( compoundSig )
Generator function used to iterate over each complete, top-level type contained in in a signature. Ex:: "iii" => [ 'i', 'i', 'i' ] "i(ii)i" => [ 'i', '(ii)', 'i' ] "i(i(ii))i" => [ 'i', '(i(ii))', 'i' ]
2.548773
2.550318
0.999394
chunks = list() bstart = startByte if hasattr(variableList, 'dbusOrder'): order = getattr(variableList, 'dbusOrder') variableList = [ getattr(variableList, attr_name) for attr_name in order ] for ct, var in zip(genCompleteTypes( compoundSignature ), variableList): tcode ...
def marshal( compoundSignature, variableList, startByte = 0, lendian=True )
Encodes the Python objects in variableList into the DBus wire-format matching the supplied compoundSignature. This function retuns a list of binary strings is rather than a single string to simplify the recursive marshalling algorithm. A single string may be easily obtained from the result via: ''.join(...
5.921398
6.093809
0.971707
values = list() start_offset = offset for ct in genCompleteTypes( compoundSignature ): tcode = ct[0] offset += len(pad[tcode]( offset )) nbytes, value = unmarshallers[ tcode ]( ct, data, offset, lendian ) offset += nbytes values.append(...
def unmarshal( compoundSignature, data, offset = 0, lendian = True )
Unmarshals DBus encoded data. @type compoundSignature: C{string} @param compoundSignature: DBus signature specifying the encoded value types @type data: C{string} @param data: Binary data @type offset: C{int} @param offset: Offset within data at which data for compoundSignature ...
8.396681
9.319103
0.901018
fiber = Fiber(func, args, **kwargs) fiber.start() return fiber
def spawn(func, *args, **kwargs)
Spawn a new fiber. A new :class:`Fiber` is created with main function *func* and positional arguments *args*. The keyword arguments are passed to the :class:`Fiber` constructor, not to the main function. The fiber is then scheduled to start by calling its :meth:`~Fiber.start` method. The fiber ins...
6.587849
9.247536
0.71239
target = getattr(self._target, '__qualname__', self._target.__name__) self._log.debug('starting fiber {}, target {}', self.name, target) self._hub.run_callback(self.switch)
def start(self)
Schedule the fiber to be started in the next iteration of the event loop.
8.489883
6.768002
1.254415
if not self.is_alive(): return if message is None: message = 'cancelled by Fiber.cancel()' self._hub.run_callback(self.throw, Cancelled, Cancelled(message))
def cancel(self, message=None)
Schedule the fiber to be cancelled in the next iteration of the event loop. Cancellation works by throwing a :class:`~gruvi.Cancelled` exception into the fiber. If *message* is provided, it will be set as the value of the exception.
8.249596
7.140136
1.155384
# align by diffs diff_counter: dict = {} largest = 0 largest_count = 0 song_id = -1 for sid, diff in matches: if diff not in diff_counter: diff_counter[diff] = {} if sid not in diff_counter[diff]: diff_coun...
def align_matches(self, matches: list)->Optional[dict]
Finds hash matches that align in time with other matches and finds consensus about which hashes are "true" signal from the audio. Returns a dictionary with match information.
3.581374
3.665572
0.97703
if isinstance(address, six.string_types): return address elif isinstance(address, tuple) and len(address) >= 2 and ':' in address[0]: return '[{}]:{}'.format(address[0], address[1]) elif isinstance(address, tuple) and len(address) >= 2: return '{}:{}'.format(*address) else: ...
def saddr(address)
Return a string representation for an address. The *address* paramater can be a pipe name, an IP address tuple, or a socket address. The return value is always a ``str`` instance.
2.346036
2.429117
0.965798
if not isinstance(address, six.string_types): raise TypeError('expecting a string') if address.startswith('['): p1 = address.find(']:') if p1 == -1: raise ValueError return (address[1:p1], int(address[p1+2:])) elif ':' in address: p1 = address.find(':...
def paddr(address)
Parse a string representation of an address. This function is the inverse of :func:`saddr`.
2.228286
2.36068
0.943917
hub = get_hub() with switch_back(timeout) as switcher: request = pyuv.dns.getaddrinfo(hub.loop, node, service, family, socktype, protocol, flags, callback=switcher) switcher.add_cleanup(request.cancel) result = hub.switch() result, error = ...
def getaddrinfo(node, service=0, family=0, socktype=0, protocol=0, flags=0, timeout=30)
Resolve an Internet *node* name and *service* into a socket address. The *family*, *socktype* and *protocol* are optional arguments that specify the address family, socket type and protocol, respectively. The *flags* argument allows you to pass flags to further modify the resolution process. See the :f...
4.420155
5.159818
0.856649
hub = get_hub() with switch_back(timeout) as switcher: request = pyuv.dns.getnameinfo(hub.loop, sockaddr, flags, callback=switcher) switcher.add_cleanup(request.cancel) result = hub.switch() result, error = result[0] if error: message = pyuv.errno.strerror(error) ...
def getnameinfo(sockaddr, flags=0, timeout=30)
Resolve a socket address *sockaddr* back to a ``(node, service)`` tuple. The *flags* argument can be used to modify the resolution process. See the :func:`socket.getnameinfo` function for more information. The address resolution is performed in the libuv thread pool.
4.875609
5.56909
0.875477
return codegrabpat.findall(str(s))
def get_codes(s: Union[str, 'ChainedBase']) -> List[str]
Grab all escape codes from a string. Returns a list of all escape codes.
80.976723
61.245247
1.322172
indices = {} i = 0 codes = get_codes(s) for code in codes: codeindex = s.index(code) realindex = i + codeindex indices[realindex] = code codelen = len(code) i = realindex + codelen s = s[codeindex + codelen:] return indices
def get_code_indices(s: Union[str, 'ChainedBase']) -> Dict[int, str]
Retrieve a dict of {index: escape_code} for a given string. If no escape codes are found, an empty dict is returned.
3.142089
3.237846
0.970425
codes = get_code_indices(s) if not codes: # This function is not for non-escape-code stuff, but okay. return {i: c for i, c in enumerate(s)} indices = {} for codeindex in sorted(codes): code = codes[codeindex] if codeindex == 0: indices[codeindex] = code...
def get_indices(s: Union[str, 'ChainedBase']) -> Dict[int, str]
Retrieve a dict of characters and escape codes with their real index into the string as the key.
3.371908
3.27824
1.028573
return codepat.sub('', str(s) if (s or (s == 0)) else '')
def strip_codes(s: Union[str, 'ChainedBase']) -> str
Strip all color codes from a string. Returns empty string for "falsey" inputs (except 0).
22.404245
16.43046
1.36358
if self._poll is None: raise RuntimeError('poll instance is closed') if events & ~(READABLE|WRITABLE): raise ValueError('illegal event mask: {}'.format(events)) if events & READABLE: self._readers += 1 if events & WRITABLE: self._w...
def add_callback(self, events, callback)
Add a new callback.
3.992176
4.000916
0.997816