_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q14000
ParsedUrl.target
train
def target(self): """The "target" i.e. local part of the URL, consisting of the path and query.""" target = self.path or '/' if self.query: target = '{}?{}'.format(target, self.query) return target
python
{ "resource": "" }
q14001
HttpRequest.start_request
train
def start_request(self, method, url, headers=None, bodylen=None): """Start a new HTTP request. The optional *headers* argument contains the headers to send. It must be a sequence of ``(name, value)`` tuples. The optional *bodylen* parameter is a hint that specifies the length of ...
python
{ "resource": "" }
q14002
HttpRequest.end_request
train
def end_request(self): """End the request body.""" if not self._chunked: return trailers = [(n, get_header(self._headers, n)) for n in self._trailer] \ if self._trailer else None ending = create_chunked_body_end(trailers) self._protocol.writer....
python
{ "resource": "" }
q14003
HttpProtocol.request
train
def request(self, method, url, headers=None, body=None): """Make a new HTTP request. The *method* argument is the HTTP method as a string, for example ``'GET'`` or ``'POST'``. The *url* argument specifies the URL. The optional *headers* argument specifies extra HTTP headers to use in ...
python
{ "resource": "" }
q14004
HttpProtocol.getresponse
train
def getresponse(self): """Wait for and return a HTTP response. The return value will be a :class:`HttpMessage`. When this method returns only the response header has been read. The response body can be read using :meth:`~gruvi.Stream.read` and similar methods on the message :att...
python
{ "resource": "" }
q14005
unique_hash
train
def unique_hash(filepath: str, blocksize: int=80)->str: """ Small function to generate a hash to uniquely generate a file. Default blocksize is `500` """ s = sha1() with open(filepath, "rb") as f: buf = f.read(blocksize) s.update(buf) return s.hexdigest()
python
{ "resource": "" }
q14006
path_to_songname
train
def path_to_songname(path: str)->str: """ Extracts song name from a filepath. Used to identify which songs have already been fingerprinted on disk. """ return os.path.splitext(os.path.basename(path))[0]
python
{ "resource": "" }
q14007
create_server
train
def create_server(protocol_factory, address=None, ssl=False, family=0, flags=0, ipc=False, backlog=128): """ Create a new network server. This creates one or more :class:`pyuv.Handle` instances bound to *address*, puts them in listen mode and starts accepting new connections. For each...
python
{ "resource": "" }
q14008
Server.close
train
def close(self): """Close the listening sockets and all accepted connections.""" for handle in self._handles: if not handle.closed: handle.close() del self._handles[:] for transport, _ in self.connections: transport.close() self._all_closed...
python
{ "resource": "" }
q14009
dict_pop_or
train
def dict_pop_or(d, key, default=None): """ Try popping a key from a dict. Instead of raising KeyError, just return the default value. """ val = default with suppress(KeyError): val = d.pop(key) return val
python
{ "resource": "" }
q14010
get_colr
train
def get_colr(txt, argd): """ Return a Colr instance based on user args. """ fore = parse_colr_arg( get_name_arg(argd, '--fore', 'FORE', default=None), rgb_mode=argd['--truecolor'], ) back = parse_colr_arg( get_name_arg(argd, '--back', 'BACK', default=None), rgb_mode=argd[...
python
{ "resource": "" }
q14011
get_name_arg
train
def get_name_arg(argd, *argnames, default=None): """ Return the first argument value given in a docopt arg dict. When not given, return default. """ val = None for argname in argnames: if argd[argname]: val = argd[argname].lower().strip() break return val if v...
python
{ "resource": "" }
q14012
list_known_codes
train
def list_known_codes(s, unique=True, rgb_mode=False): """ Find and print all known escape codes in a string, using get_known_codes. """ total = 0 for codedesc in get_known_codes(s, unique=unique, rgb_mode=rgb_mode): total += 1 print(codedesc) plural = 'code' if total == 1 els...
python
{ "resource": "" }
q14013
list_names
train
def list_names(): """ List all known color names. """ names = get_all_names() # This is 375 right now. Probably won't ever change, but I'm not sure. nameslen = len(names) print('\nListing {} names:\n'.format(nameslen)) # Using 3 columns of names, still alphabetically sorted from the top down. ...
python
{ "resource": "" }
q14014
read_stdin
train
def read_stdin(): """ Read text from stdin, and print a helpful message for ttys. """ if sys.stdin.isatty() and sys.stdout.isatty(): print('\nReading from stdin until end of file (Ctrl + D)...') return sys.stdin.read()
python
{ "resource": "" }
q14015
translate
train
def translate(usercodes, rgb_mode=False): """ Translate one or more hex, term, or rgb value into the others. Yields strings with the results for each code translated. """ for code in usercodes: code = code.strip().lower() if code.isalpha() and (code in codes['fore']): # B...
python
{ "resource": "" }
q14016
translate_basic
train
def translate_basic(usercode): """ Translate a basic color name to color with explanation. """ codenum = get_code_num(codes['fore'][usercode]) colorcode = codeformat(codenum) msg = 'Name: {:>10}, Number: {:>3}, EscapeCode: {!r}'.format( usercode, codenum, colorcode ) if d...
python
{ "resource": "" }
q14017
try_float
train
def try_float(s, default=None, minimum=None): """ Try parsing a string into a float. If None is passed, default is returned. On failure, InvalidFloat is raised. """ if not s: return default try: val = float(s) except (TypeError, ValueError): raise InvalidNumbe...
python
{ "resource": "" }
q14018
try_int
train
def try_int(s, default=None, minimum=None): """ Try parsing a string into an integer. If None is passed, default is returned. On failure, InvalidNumber is raised. """ if not s: return default try: val = int(s) except (TypeError, ValueError): raise InvalidNumbe...
python
{ "resource": "" }
q14019
ContextLogger.thread_info
train
def thread_info(self): """Return a string identifying the current thread and fiber.""" tid = threading.current_thread().name if tid == 'MainThread': tid = 'Main' current = fibers.current() fid = getattr(current, 'name') if current.parent else 'Root' return '{}...
python
{ "resource": "" }
q14020
ContextLogger.frame_info
train
def frame_info(self): """Return a string identifying the current frame.""" if not self._logger.isEnabledFor(logging.DEBUG): return '' f = sys._getframe(3) fname = os.path.split(f.f_code.co_filename)[1] return '{}:{}'.format(fname, f.f_lineno)
python
{ "resource": "" }
q14021
StreamBuffer.set_buffer_limits
train
def set_buffer_limits(self, high=None, low=None): """Set the low and high watermarks for the read buffer.""" if high is None: high = self.default_buffer_size if low is None: low = high // 2 self._buffer_high = high self._buffer_low = low
python
{ "resource": "" }
q14022
Stream.readline
train
def readline(self, limit=-1, delim=b'\n'): """Read a single line. If EOF is reached before a full line can be read, a partial line is returned. If *limit* is specified, at most this many bytes will be read. """ self._check_readable() chunks = [] while True: ...
python
{ "resource": "" }
q14023
Stream.readlines
train
def readlines(self, hint=-1): """Read lines until EOF, and return them as a list. If *hint* is specified, then stop reading lines as soon as the total size of all lines exceeds *hint*. """ self._check_readable() lines = [] chunks = [] bytes_read = 0 ...
python
{ "resource": "" }
q14024
Stream.write_eof
train
def write_eof(self): """Close the write direction of the transport. This method will block if the transport's write buffer is at capacity. """ self._check_writable() self._transport._can_write.wait() self._transport.write_eof()
python
{ "resource": "" }
q14025
blocking
train
def blocking(func, *args, **kwargs): """Run a function that uses blocking IO. The function is run in the IO thread pool. """ pool = get_io_pool() fut = pool.submit(func, *args, **kwargs) return fut.result()
python
{ "resource": "" }
q14026
as_completed
train
def as_completed(objects, count=None, timeout=None): """Wait for one or more waitable objects, yielding them as they become ready. This is the iterator/generator version of :func:`wait`. """ for obj in objects: if not hasattr(obj, 'add_done_callback'): raise TypeError('Expecting...
python
{ "resource": "" }
q14027
wait
train
def wait(objects, count=None, timeout=None): """Wait for one or more waitable objects. This method waits until *count* elements from the sequence of waitable objects *objects* have become ready. If *count* is ``None`` (the default), then wait for all objects to become ready. What "ready" is means ...
python
{ "resource": "" }
q14028
Future.cancelled
train
def cancelled(self): """Return whether this future was successfully cancelled.""" return self._state == self.S_EXCEPTION and isinstance(self._result, Cancelled)
python
{ "resource": "" }
q14029
Future.cancel
train
def cancel(self): """Cancel the execution of the async function, if possible. This method marks the future as done and sets the :class:`Cancelled` exception. A future that is not running can always be cancelled. However when a future is running, the ability to cancel it depends...
python
{ "resource": "" }
q14030
Future.result
train
def result(self, timeout=None): """Wait for the future to complete and return its result. If the function returned normally, its return value is returned here. If the function raised an exception, the exception is re-raised here. """ if not self._done.wait(timeout): ...
python
{ "resource": "" }
q14031
Future.exception
train
def exception(self, timeout=None): """Wait for the async function to complete and return its exception. If the function did not raise an exception this returns ``None``. """ if not self._done.wait(timeout): raise Timeout('timeout waiting for future') if self._state =...
python
{ "resource": "" }
q14032
Future.add_done_callback
train
def add_done_callback(self, callback, *args): """Add a callback that gets called when the future completes. The callback will be called in the context of the fiber that sets the future's result. The callback is called with the positional arguments *args* provided to this method. ...
python
{ "resource": "" }
q14033
PoolBase.close
train
def close(self): """Close the pool and wait for all workers to exit. New submissions will be blocked. Workers will exit once their current job is finished. This method will return after all workers have exited. """ with self._lock: if self._closing: r...
python
{ "resource": "" }
q14034
SslPipe.do_handshake
train
def do_handshake(self, callback=None): """Start the SSL handshake. Return a list of ssldata. The optional *callback* argument can be used to install a callback that will be called when the handshake is complete. The callback will be called without arguments. """ if self....
python
{ "resource": "" }
q14035
SslPipe.shutdown
train
def shutdown(self, callback=None): """Start the SSL shutdown sequence. Return a list of ssldata. The optional *callback* argument can be used to install a callback that will be called when the shutdown is complete. The callback will be called without arguments. """ if se...
python
{ "resource": "" }
q14036
SslPipe.feed_eof
train
def feed_eof(self): """Send a potentially "ragged" EOF. This method will raise an SSL_ERROR_EOF exception if the EOF is unexpected. """ self._incoming.write_eof() ssldata, appdata = self.feed_ssldata(b'') assert appdata == [] or appdata == [b'']
python
{ "resource": "" }
q14037
SslPipe.feed_ssldata
train
def feed_ssldata(self, data): """Feed SSL record level data into the pipe. The data must be a bytes instance. It is OK to send an empty bytes instance. This can be used to get ssldata for a handshake initiated by this endpoint. Return a (ssldata, appdata) tuple. The ssldata ele...
python
{ "resource": "" }
q14038
SslPipe.feed_appdata
train
def feed_appdata(self, data, offset=0): """Feed plaintext data into the pipe. Return an (ssldata, offset) tuple. The ssldata element is a list of buffers containing record level data that needs to be sent to the remote SSL instance. The offset is the number of plaintext bytes that ...
python
{ "resource": "" }
q14039
SslTransport.get_extra_info
train
def get_extra_info(self, name, default=None): """Return transport specific data. The following fields are available, in addition to the information exposed by :meth:`Transport.get_extra_info`. ====================== =============================================== Name ...
python
{ "resource": "" }
q14040
SslTransport.do_handshake
train
def do_handshake(self): """Start the SSL handshake. This method only needs to be called if this transport was created with *do_handshake_on_connect* set to False (the default is True). The handshake needs to be synchronized between the both endpoints, so that SSL record level d...
python
{ "resource": "" }
q14041
SslTransport.unwrap
train
def unwrap(self): """Remove the security layer. Use this method only if you want to send plaintext data on the connection after the security layer has been removed. In all other cases, use :meth:`close`. If the unwrap is initiated by us, then any data sent after it will be ...
python
{ "resource": "" }
q14042
SslTransport.close
train
def close(self): """Cleanly shut down the SSL protocol and close the transport.""" if self._closing or self._handle.closed: return self._closing = True self._write_backlog.append([b'', False]) self._process_write_backlog()
python
{ "resource": "" }
q14043
is_locked
train
def is_locked(lock): """Return whether a lock is locked. Suppors :class:`Lock`, :class:`RLock`, :class:`threading.Lock` and :class:`threading.RLock` instances. """ if hasattr(lock, 'locked'): return lock.locked() elif hasattr(lock, '_is_owned'): return lock._is_owned() else:...
python
{ "resource": "" }
q14044
acquire_restore
train
def acquire_restore(lock, state): """Acquire a lock and restore its state.""" if hasattr(lock, '_acquire_restore'): lock._acquire_restore(state) elif hasattr(lock, 'acquire'): lock.acquire() else: raise TypeError('expecting Lock/RLock')
python
{ "resource": "" }
q14045
release_save
train
def release_save(lock): """Release a lock and return its state.""" if hasattr(lock, '_release_save'): return lock._release_save() elif hasattr(lock, 'release'): lock.release() else: raise TypeError('expecting Lock/RLock')
python
{ "resource": "" }
q14046
Condition.notify
train
def notify(self, n=1): """Raise the condition and wake up fibers waiting on it. The optional *n* parameter specifies how many fibers will be notified. By default, one fiber is notified. """ if not is_locked(self._lock): raise RuntimeError('lock is not locked') ...
python
{ "resource": "" }
q14047
Queue.get
train
def get(self, block=True, timeout=None): """Pop an item from the queue. If the queue is not empty, an item is returned immediately. Otherwise, if *block* is True (the default), wait up to *timeout* seconds for an item to become available. If not timeout is provided, then wait in...
python
{ "resource": "" }
q14048
Queue.task_done
train
def task_done(self): """Mark a task as done.""" with self._lock: unfinished = self._unfinished_tasks - 1 if unfinished < 0: raise RuntimeError('task_done() called too many times') elif unfinished == 0: self._alldone.notify() ...
python
{ "resource": "" }
q14049
Process.spawn
train
def spawn(self, args, executable=None, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, env=None, flags=0, extra_handles=None): """Spawn a new child process. The executable to spawn and its arguments are determined by *args*, *executable* and *shell*. When *sh...
python
{ "resource": "" }
q14050
Process.close
train
def close(self): """Close the process and frees its associated resources. This method waits for the resources to be freed by the event loop. """ if self._process is None: return waitfor = [] if not self._process.closed: self._process.close(self._o...
python
{ "resource": "" }
q14051
Process.terminate
train
def terminate(self): """Terminate the child process. It is not an error to call this method when the child has already exited. """ try: self.send_signal(signal.SIGTERM) except pyuv.error.ProcessError as e: if e.args[0] != pyuv.errno.UV_ESRCH: ...
python
{ "resource": "" }
q14052
Process.wait
train
def wait(self, timeout=-1): """Wait for the child to exit. Wait for at most *timeout* seconds, or indefinitely if *timeout* is None. Return the value of the :attr:`returncode` attribute. """ if self._process is None: raise RuntimeError('no child process') if ...
python
{ "resource": "" }
q14053
Process.communicate
train
def communicate(self, input=None, timeout=-1): """Communicate with the child and return its output. If *input* is provided, it is sent to the client. Concurrent with sending the input, the child's standard output and standard error are read, until the child exits. The return va...
python
{ "resource": "" }
q14054
get_requirements
train
def get_requirements(): """Parse a requirements.txt file and return as a list.""" with open(os.path.join(topdir, 'requirements.txt')) as fin: lines = fin.readlines() lines = [line.strip() for line in lines] return lines
python
{ "resource": "" }
q14055
dllist.insert
train
def insert(self, node, before=None): """Insert a new node in the list. If *before* is specified, the new node is inserted before this node. Otherwise, the node is inserted at the end of the list. """ node._list = self if self._first is None: self._first = sel...
python
{ "resource": "" }
q14056
dllist.clear
train
def clear(self): """Remove all nodes from the list.""" node = self._first while node is not None: next_node = node._next node._list = node._prev = node._next = None node = next_node self._size = 0
python
{ "resource": "" }
q14057
_build_codes
train
def _build_codes() -> Dict[str, Dict[str, str]]: """ Build code map, encapsulated to reduce module-level globals. """ built = { 'fore': {}, 'back': {}, 'style': {}, } # type: Dict[str, Dict[str, str]] # Set codes for forecolors (30-37) and backcolors (40-47) # Names are giv...
python
{ "resource": "" }
q14058
_build_codes_reverse
train
def _build_codes_reverse( codes: Dict[str, Dict[str, str]]) -> Dict[str, Dict[str, str]]: """ Build a reverse escape-code to name map, based on an existing name to escape-code map. """ built = {} # type: Dict[str, Dict[str, str]] for codetype, codemap in codes.items(): for name,...
python
{ "resource": "" }
q14059
auto_disable
train
def auto_disable( enabled: Optional[bool] = True, fds: Optional[Sequence[IO]] = (sys.stdout, sys.stderr)) -> None: """ Automatically decide whether to disable color codes if stdout or stderr are not ttys. Arguments: enabled : Whether to automatically disable color codes...
python
{ "resource": "" }
q14060
format_back
train
def format_back( number: FormatArg, light: Optional[bool] = False, extended: Optional[bool] = False) -> str: """ Return an escape code for a back color, by number. This is a convenience method for handling the different code types all in one shot. It also handles some...
python
{ "resource": "" }
q14061
format_fore
train
def format_fore( number: FormatArg, light: Optional[bool] = False, extended: Optional[bool] = False) -> str: """ Return an escape code for a fore color, by number. This is a convenience method for handling the different code types all in one shot. It also handles some...
python
{ "resource": "" }
q14062
format_style
train
def format_style(number: int) -> str: """ Return an escape code for a style, by number. This handles invalid style numbers. """ if str(number) not in _stylenums: raise InvalidStyle(number) return codeformat(number)
python
{ "resource": "" }
q14063
get_all_names
train
def get_all_names() -> Tuple[str]: """ Retrieve a tuple of all known color names, basic and 'known names'. """ names = list(basic_names) names.extend(name_data) return tuple(sorted(set(names)))
python
{ "resource": "" }
q14064
get_code_num
train
def get_code_num(s: str) -> Optional[int]: """ Get code number from an escape code. Raises InvalidEscapeCode if an invalid number is found. """ if ';' in s: # Extended fore/back codes. numberstr = s.rpartition(';')[-1][:-1] else: # Fore, back, style, codes. number...
python
{ "resource": "" }
q14065
get_code_num_rgb
train
def get_code_num_rgb(s: str) -> Optional[Tuple[int, int, int]]: """ Get rgb code numbers from an RGB escape code. Raises InvalidRgbEscapeCode if an invalid number is found. """ parts = s.split(';') if len(parts) != 5: raise InvalidRgbEscapeCode(s, reason='Count is off.') rgbparts = p...
python
{ "resource": "" }
q14066
get_known_codes
train
def get_known_codes( s: Union[str, 'Colr'], unique: Optional[bool] = True, rgb_mode: Optional[bool] = False): """ Get all known escape codes from a string, and yield the explanations. """ isdisabled = disabled() orderedcodes = tuple((c, get_known_name(c)) for c in get_codes(s)) ...
python
{ "resource": "" }
q14067
try_parse_int
train
def try_parse_int( s: str, default: Optional[Any] = None, minimum: Optional[int] = None, maximum: Optional[int] = None) -> Optional[Any]: """ Try parsing a string into an integer. On failure, return `default`. If the number is less then `minimum` or greater than `maxi...
python
{ "resource": "" }
q14068
Colr._ext_attr_to_partial
train
def _ext_attr_to_partial(self, name, kwarg_key): """ Convert a string like '233' or 'aliceblue' into partial for self.chained. """ try: intval = int(name) except ValueError: # Try as an extended name_data name. info = name_data.get(name, No...
python
{ "resource": "" }
q14069
Colr._gradient_black_line
train
def _gradient_black_line( self, text, start, step=1, fore=None, back=None, style=None, reverse=False, rgb_mode=False): """ Yield colorized characters, within the 24-length black gradient. """ if start < 232: start = 232 elif start > 255: ...
python
{ "resource": "" }
q14070
Colr._gradient_black_lines
train
def _gradient_black_lines( self, text, start, step=1, fore=None, back=None, style=None, reverse=False, movefactor=2, rgb_mode=False): """ Yield colorized characters, within the 24-length black gradient, treating each line separately. """ ...
python
{ "resource": "" }
q14071
Colr._gradient_rgb_lines
train
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. """ morphlist = list(self._morph_rgb(start, ...
python
{ "resource": "" }
q14072
Colr._morph_rgb
train
def _morph_rgb(self, rgb1, rgb2, step=1): """ Morph an rgb value into another, yielding each step along the way. """ pos1, pos2 = list(rgb1), list(rgb2) indexes = [i for i, _ in enumerate(pos1)] def step_value(a, b): """ Returns the amount to add to `a` to make it cl...
python
{ "resource": "" }
q14073
Colr.chained
train
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...
python
{ "resource": "" }
q14074
Colr.color
train
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. """ has_args = ( ...
python
{ "resource": "" }
q14075
Colr.format
train
def format(self, *args, **kwargs): """ Like str.format, except it returns a Colr. """ return self.__class__(self.data.format(*args, **kwargs))
python
{ "resource": "" }
q14076
Colr.get_escape_code
train
def get_escape_code(self, codetype, value): """ Convert user arg to escape code. """ valuefmt = str(value).lower() code = codes[codetype].get(valuefmt, None) if code: # Basic code from fore, back, or style. return code named_funcs = { 'fore': ...
python
{ "resource": "" }
q14077
Colr.lstrip
train
def lstrip(self, chars=None): """ Like str.lstrip, except it returns the Colr instance. """ return self.__class__( self._str_strip('lstrip', chars), no_closing=chars and (closing_code in chars), )
python
{ "resource": "" }
q14078
Colr.print
train
def print(self, *args, **kwargs): """ Chainable print method. Prints self.data and then clears it. """ print(self, *args, **kwargs) self.data = '' return self
python
{ "resource": "" }
q14079
Colr.rstrip
train
def rstrip(self, chars=None): """ Like str.rstrip, except it returns the Colr instance. """ return self.__class__( self._str_strip('rstrip', chars), no_closing=chars and (closing_code in chars), )
python
{ "resource": "" }
q14080
Colr.strip
train
def strip(self, chars=None): """ Like str.strip, except it returns the Colr instance. """ return self.__class__( self._str_strip('strip', chars), no_closing=chars and (closing_code in chars), )
python
{ "resource": "" }
q14081
ensure_tty
train
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. """ isatty = getattr(file, 'isatty', None) if isatty is None: raise TypeError( 'Ca...
python
{ "resource": "" }
q14082
move_back
train
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. """ move...
python
{ "resource": "" }
q14083
move_column
train
def move_column(column=1, file=sys.stdout): """ Move the cursor to the specified column, default 1. Esc[<column>G """ move.column(column).write(file=file)
python
{ "resource": "" }
q14084
move_down
train
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. """ move.down(line...
python
{ "resource": "" }
q14085
move_forward
train
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. ""...
python
{ "resource": "" }
q14086
move_pos
train
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 """ move.pos(line=line, col=column).write(file=file)
python
{ "resource": "" }
q14087
move_up
train
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. """ move.up(lines).write(file...
python
{ "resource": "" }
q14088
scroll_down
train
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 """ scroll.down(lines).write(file=file)
python
{ "resource": "" }
q14089
scroll_up
train
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 """ scroll.up(lines).write(file=file)
python
{ "resource": "" }
q14090
Control.last_code
train
def last_code(self): """ Return the last escape code in `self.data`. If no escape codes are found, '' is returned. """ codes = self.data.split(escape_sequence) if not codes: return '' return ''.join((escape_sequence, codes[-1]))
python
{ "resource": "" }
q14091
Control.repeat
train
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. """ # Subtracting one from the count means the code mentioned is # truly repeated exactly `count` times. # Control().move_u...
python
{ "resource": "" }
q14092
Control.repeat_all
train
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. """ try: return self.__class__(''.join(str(self) * count)) except TypeError: raise TypeError( '`c...
python
{ "resource": "" }
q14093
hex2term
train
def hex2term(hexval: str, allow_short: bool = False) -> str: """ Convert a hex value into the nearest terminal code number. """ return rgb2term(*hex2rgb(hexval, allow_short=allow_short))
python
{ "resource": "" }
q14094
hex2termhex
train
def hex2termhex(hexval: str, allow_short: bool = False) -> str: """ Convert a hex value into the nearest terminal color matched hex. """ return rgb2termhex(*hex2rgb(hexval, allow_short=allow_short))
python
{ "resource": "" }
q14095
print_all
train
def print_all() -> None: """ Print all 256 xterm color codes. """ 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]))
python
{ "resource": "" }
q14096
rgb2hex
train
def rgb2hex(r: int, g: int, b: int) -> str: """ Convert rgb values to a hex code. """ return '{:02x}{:02x}{:02x}'.format(r, g, b)
python
{ "resource": "" }
q14097
rgb2term
train
def rgb2term(r: int, g: int, b: int) -> str: """ Convert an rgb value to a terminal code. """ return hex2term_map[rgb2termhex(r, g, b)]
python
{ "resource": "" }
q14098
rgb2termhex
train
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`. """ incs = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff] res = [] parts = r, g, b for part in parts: if (part < 0) or (...
python
{ "resource": "" }
q14099
ColorCode._init_code
train
def _init_code(self, code: int) -> None: """ Initialize from an int terminal code. """ if -1 < code < 256: self.code = '{:02}'.format(code) self.hexval = term2hex(code) self.rgb = hex2rgb(self.hexval) else: raise ValueError(' '.join(( ...
python
{ "resource": "" }