INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Blocking expect | def expect_loop(self, timeout=-1):
"""Blocking expect"""
spawn = self.spawn
if timeout is not None:
end_time = time.time() + timeout
try:
incoming = spawn.buffer
spawn._buffer = spawn.buffer_type()
spawn._before = spawn.buffer_type()
... |
Adds a ( name value ) pair doesn t overwrite the value if it already exists. | def add(self, key, val):
"""Adds a (name, value) pair, doesn't overwrite the value if it already
exists.
>>> headers = HTTPHeaderDict(foo='bar')
>>> headers.add('Foo', 'baz')
>>> headers['foo']
'bar, baz'
"""
key_lower = key.lower()
new_vals = [ke... |
Generic import function for any type of header - like object. Adapted version of MutableMapping. update in order to insert items with self. add instead of self. __setitem__ | def extend(self, *args, **kwargs):
"""Generic import function for any type of header-like object.
Adapted version of MutableMapping.update in order to insert items
with self.add instead of self.__setitem__
"""
if len(args) > 1:
raise TypeError("extend() takes at most ... |
Returns a list of all the values for the named field. Returns an empty list if the key doesn t exist. | def getlist(self, key, default=__marker):
"""Returns a list of all the values for the named field. Returns an
empty list if the key doesn't exist."""
try:
vals = self._container[key.lower()]
except KeyError:
if default is self.__marker:
return []
... |
Iterate over all header lines including duplicate ones. | def iteritems(self):
"""Iterate over all header lines, including duplicate ones."""
for key in self:
vals = self._container[key.lower()]
for val in vals[1:]:
yield vals[0], val |
Iterate over all headers merging duplicate ones together. | def itermerged(self):
"""Iterate over all headers, merging duplicate ones together."""
for key in self:
val = self._container[key.lower()]
yield val[0], ', '.join(val[1:]) |
Read headers from a Python 2 httplib message object. | def from_httplib(cls, message): # Python 2
"""Read headers from a Python 2 httplib message object."""
# python2.7 does not expose a proper API for exporting multiheaders
# efficiently. This function re-reads raw lines from the message
# object and extracts the multiheaders properly.
... |
Extract the cookies from the response into a CookieJar. | def extract_cookies_to_jar(jar, request, response):
"""Extract the cookies from the response into a CookieJar.
:param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)
:param request: our own requests.Request object
:param response: urllib3.HTTPResponse object
"""
if not (hasattr(r... |
Produce an appropriate Cookie header string to be sent with request or None. | def get_cookie_header(jar, request):
"""
Produce an appropriate Cookie header string to be sent with `request`, or None.
:rtype: str
"""
r = MockRequest(request)
jar.add_cookie_header(r)
return r.get_new_headers().get('Cookie') |
Unsets a cookie by name by default over all domains and paths. | def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
"""Unsets a cookie by name, by default over all domains and paths.
Wraps CookieJar.clear(), is O(n).
"""
clearables = []
for cookie in cookiejar:
if cookie.name != name:
continue
if domain is not None an... |
Make a cookie from underspecified parameters. | def create_cookie(name, value, **kwargs):
"""Make a cookie from underspecified parameters.
By default, the pair of `name` and `value` will be set for the domain ''
and sent on every request (this is sometimes called a "supercookie").
"""
result = {
'version': 0,
'name': name,
... |
Convert a Morsel object into a Cookie containing the one k/ v pair. | def morsel_to_cookie(morsel):
"""Convert a Morsel object into a Cookie containing the one k/v pair."""
expires = None
if morsel['max-age']:
try:
expires = int(time.time() + int(morsel['max-age']))
except ValueError:
raise TypeError('max-age: %s must be integer' % mor... |
Returns a CookieJar from a key/ value dictionary. | def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
"""Returns a CookieJar from a key/value dictionary.
:param cookie_dict: Dict of key/values to insert into CookieJar.
:param cookiejar: (optional) A cookiejar to add the cookies to.
:param overwrite: (optional) If False, will not repl... |
Add cookies to cookiejar and returns a merged CookieJar. | def merge_cookies(cookiejar, cookies):
"""Add cookies to cookiejar and returns a merged CookieJar.
:param cookiejar: CookieJar object to add the cookies to.
:param cookies: Dictionary or CookieJar object to be added.
:rtype: CookieJar
"""
if not isinstance(cookiejar, cookielib.CookieJar):
... |
Dict - like get () that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. | def get(self, name, default=None, domain=None, path=None):
"""Dict-like get() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
.. warning:: operation is O(n), not O(1).
"""
try:
... |
Dict - like set () that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. | def set(self, name, value, **kwargs):
"""Dict-like set() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
"""
# support client code that unsets cookies by assignment of a None value:
if... |
Utility method to list all the domains in the jar. | def list_domains(self):
"""Utility method to list all the domains in the jar."""
domains = []
for cookie in iter(self):
if cookie.domain not in domains:
domains.append(cookie.domain)
return domains |
Utility method to list all the paths in the jar. | def list_paths(self):
"""Utility method to list all the paths in the jar."""
paths = []
for cookie in iter(self):
if cookie.path not in paths:
paths.append(cookie.path)
return paths |
Returns True if there are multiple domains in the jar. Returns False otherwise. | def multiple_domains(self):
"""Returns True if there are multiple domains in the jar.
Returns False otherwise.
:rtype: bool
"""
domains = []
for cookie in iter(self):
if cookie.domain is not None and cookie.domain in domains:
return True
... |
Updates this jar with cookies from another CookieJar or dict - like | def update(self, other):
"""Updates this jar with cookies from another CookieJar or dict-like"""
if isinstance(other, cookielib.CookieJar):
for cookie in other:
self.set_cookie(copy.copy(cookie))
else:
super(RequestsCookieJar, self).update(other) |
Requests uses this method internally to get cookie values. | def _find(self, name, domain=None, path=None):
"""Requests uses this method internally to get cookie values.
If there are conflicting cookies, _find arbitrarily chooses one.
See _find_no_duplicates if you want an exception thrown if there are
conflicting cookies.
:param name: a... |
Both __get_item__ and get call this function: it s never used elsewhere in Requests. | def _find_no_duplicates(self, name, domain=None, path=None):
"""Both ``__get_item__`` and ``get`` call this function: it's never
used elsewhere in Requests.
:param name: a string containing name of cookie
:param domain: (optional) string containing domain of cookie
:param path: ... |
Return a copy of this RequestsCookieJar. | def copy(self):
"""Return a copy of this RequestsCookieJar."""
new_cj = RequestsCookieJar()
new_cj.set_policy(self.get_policy())
new_cj.update(self)
return new_cj |
This returns a number n constrained to the min and max bounds. | def constrain (n, min, max):
'''This returns a number, n constrained to the min and max bounds. '''
if n < min:
return min
if n > max:
return max
return n |
This converts from the external coding system ( as passed to the constructor ) to the internal one ( unicode ). | def _decode(self, s):
'''This converts from the external coding system (as passed to
the constructor) to the internal one (unicode). '''
if self.decoder is not None:
return self.decoder.decode(s)
else:
raise TypeError("This screen was constructed with encoding=Non... |
This returns a printable representation of the screen as a unicode string ( which under Python 3. x is the same as str ). The end of each screen line is terminated by a newline. | def _unicode(self):
'''This returns a printable representation of the screen as a unicode
string (which, under Python 3.x, is the same as 'str'). The end of each
screen line is terminated by a newline.'''
return u'\n'.join ([ u''.join(c) for c in self.w ]) |
This returns a copy of the screen as a unicode string. This is similar to __str__/ __unicode__ except that lines are not terminated with line feeds. | def dump (self):
'''This returns a copy of the screen as a unicode string. This is similar to
__str__/__unicode__ except that lines are not terminated with line
feeds.'''
return u''.join ([ u''.join(c) for c in self.w ]) |
This returns a copy of the screen as a unicode string with an ASCII text box around the screen border. This is similar to __str__/ __unicode__ except that it adds a box. | def pretty (self):
'''This returns a copy of the screen as a unicode string with an ASCII
text box around the screen border. This is similar to
__str__/__unicode__ except that it adds a box.'''
top_bot = u'+' + u'-'*self.cols + u'+\n'
return top_bot + u'\n'.join([u'|'+line+u'|' ... |
This moves the cursor down with scrolling. | def lf (self):
'''This moves the cursor down with scrolling.
'''
old_r = self.cur_r
self.cursor_down()
if old_r == self.cur_r:
self.scroll_up ()
self.erase_line() |
Screen array starts at 1 index. | def put_abs (self, r, c, ch):
'''Screen array starts at 1 index.'''
r = constrain (r, 1, self.rows)
c = constrain (c, 1, self.cols)
if isinstance(ch, bytes):
ch = self._decode(ch)[0]
else:
ch = ch[0]
self.w[r-1][c-1] = ch |
This puts a characters at the current cursor position. | def put (self, ch):
'''This puts a characters at the current cursor position.
'''
if isinstance(ch, bytes):
ch = self._decode(ch)
self.put_abs (self.cur_r, self.cur_c, ch) |
This inserts a character at ( r c ). Everything under and to the right is shifted right one character. The last character of the line is lost. | def insert_abs (self, r, c, ch):
'''This inserts a character at (r,c). Everything under
and to the right is shifted right one character.
The last character of the line is lost.
'''
if isinstance(ch, bytes):
ch = self._decode(ch)
r = constrain (r, 1, self.row... |
This returns a list of lines representing the region. | def get_region (self, rs,cs, re,ce):
'''This returns a list of lines representing the region.
'''
rs = constrain (rs, 1, self.rows)
re = constrain (re, 1, self.rows)
cs = constrain (cs, 1, self.cols)
ce = constrain (ce, 1, self.cols)
if rs > re:
rs, r... |
This keeps the cursor within the screen area. | def cursor_constrain (self):
'''This keeps the cursor within the screen area.
'''
self.cur_r = constrain (self.cur_r, 1, self.rows)
self.cur_c = constrain (self.cur_c, 1, self.cols) |
Save current cursor position. | def cursor_save_attrs (self): # <ESC>7
'''Save current cursor position.'''
self.cur_saved_r = self.cur_r
self.cur_saved_c = self.cur_c |
This keeps the scroll region within the screen region. | def scroll_constrain (self):
'''This keeps the scroll region within the screen region.'''
if self.scroll_row_start <= 0:
self.scroll_row_start = 1
if self.scroll_row_end > self.rows:
self.scroll_row_end = self.rows |
Enable scrolling from row { start } to row { end }. | def scroll_screen_rows (self, rs, re): # <ESC>[{start};{end}r
'''Enable scrolling from row {start} to row {end}.'''
self.scroll_row_start = rs
self.scroll_row_end = re
self.scroll_constrain() |
Scroll display down one line. | def scroll_down (self): # <ESC>D
'''Scroll display down one line.'''
# Screen is indexed from 1, but arrays are indexed from 0.
s = self.scroll_row_start - 1
e = self.scroll_row_end - 1
self.w[s+1:e+1] = copy.deepcopy(self.w[s:e]) |
Erases from the current cursor position to the end of the current line. | def erase_end_of_line (self): # <ESC>[0K -or- <ESC>[K
'''Erases from the current cursor position to the end of the current
line.'''
self.fill_region (self.cur_r, self.cur_c, self.cur_r, self.cols) |
Erases from the current cursor position to the start of the current line. | def erase_start_of_line (self): # <ESC>[1K
'''Erases from the current cursor position to the start of the current
line.'''
self.fill_region (self.cur_r, 1, self.cur_r, self.cur_c) |
Erases the entire current line. | def erase_line (self): # <ESC>[2K
'''Erases the entire current line.'''
self.fill_region (self.cur_r, 1, self.cur_r, self.cols) |
Erases the screen from the current line down to the bottom of the screen. | def erase_down (self): # <ESC>[0J -or- <ESC>[J
'''Erases the screen from the current line down to the bottom of the
screen.'''
self.erase_end_of_line ()
self.fill_region (self.cur_r + 1, 1, self.rows, self.cols) |
Erases the screen from the current line up to the top of the screen. | def erase_up (self): # <ESC>[1J
'''Erases the screen from the current line up to the top of the
screen.'''
self.erase_start_of_line ()
self.fill_region (self.cur_r-1, 1, 1, self.cols) |
Pull a value from the dict and convert to int | def to_int(d, key, default_to_zero=False, default=None, required=True):
"""Pull a value from the dict and convert to int
:param default_to_zero: If the value is None or empty, treat it as zero
:param default: If the value is missing in the dict use this default
"""
value = d.get(key) or default
... |
Parses ISO 8601 time zone specs into tzinfo offsets | def parse_timezone(matches, default_timezone=UTC):
"""Parses ISO 8601 time zone specs into tzinfo offsets
"""
if matches["timezone"] == "Z":
return UTC
# This isn't strictly correct, but it's common to encounter dates without
# timezones so I'll assume the default (which defaults to UTC).
... |
Parses ISO 8601 dates into datetime objects | def parse_date(datestring, default_timezone=UTC):
"""Parses ISO 8601 dates into datetime objects
The timezone is parsed from the date string. However it is quite common to
have dates without a timezone (not strictly correct). In this case the
default timezone specified in default_timezone is used. This... |
Signal handler used to gracefully shut down the spinner instance when specified signal is received by the process running the spinner. | def default_handler(signum, frame, spinner):
"""Signal handler, used to gracefully shut down the ``spinner`` instance
when specified signal is received by the process running the ``spinner``.
``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``
function for more details.
"""
... |
Signal handler used to gracefully shut down the spinner instance when specified signal is received by the process running the spinner. | def fancy_handler(signum, frame, spinner):
"""Signal handler, used to gracefully shut down the ``spinner`` instance
when specified signal is received by the process running the ``spinner``.
``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``
function for more details.
"""
... |
Re - map the characters in the string according to UTS46 processing. | def uts46_remap(domain, std3_rules=True, transitional=False):
"""Re-map the characters in the string according to UTS46 processing."""
from .uts46data import uts46data
output = u""
try:
for pos, char in enumerate(domain):
code_point = ord(char)
uts46row = uts46data[code_p... |
Return a dict with the Python implementation and version. | def _implementation():
"""Return a dict with the Python implementation and version.
Provide both the name and the version of the Python implementation
currently running. For example, on CPython 2.7.5 it will return
{'name': 'CPython', 'version': '2.7.5'}.
This function works best on CPython and Py... |
Generate information for a bug report. | def info():
"""Generate information for a bug report."""
try:
platform_info = {
'system': platform.system(),
'release': platform.release(),
}
except IOError:
platform_info = {
'system': 'Unknown',
'release': 'Unknown',
}
im... |
>>> package = yarg. get ( yarg ) >>> v = 0. 1. 0 >>> r = package. release ( v ) >>> r. package_type u wheel | def package_type(self):
"""
>>> package = yarg.get('yarg')
>>> v = "0.1.0"
>>> r = package.release(v)
>>> r.package_type
u'wheel'
"""
mapping = {'bdist_egg': u'egg', 'bdist_wheel': u'wheel',
'sdist': u'source'}
... |
Process a single character. Called by: meth: write. | def process (self, c):
"""Process a single character. Called by :meth:`write`."""
if isinstance(c, bytes):
c = self._decode(c)
self.state.process(c) |
Process text writing it to the virtual screen while handling ANSI escape codes. | def write (self, s):
"""Process text, writing it to the virtual screen while handling
ANSI escape codes.
"""
if isinstance(s, bytes):
s = self._decode(s)
for c in s:
self.process(c) |
This puts a character at the current cursor position. The cursor position is moved forward with wrap - around but no scrolling is done if the cursor hits the lower - right corner of the screen. | def write_ch (self, ch):
'''This puts a character at the current cursor position. The cursor
position is moved forward with wrap-around, but no scrolling is done if
the cursor hits the lower-right corner of the screen. '''
if isinstance(ch, bytes):
ch = self._decode(ch)
... |
Returns the default stream encoding if not found. | def get_best_encoding(stream):
"""Returns the default stream encoding if not found."""
rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding()
if is_ascii_encoding(rv):
return 'utf-8'
return rv |
Get the size of the terminal window. | def get_terminal_size(fallback=(80, 24)):
"""Get the size of the terminal window.
For each of the two dimensions, the environment variable, COLUMNS
and LINES respectively, is checked. If the variable is defined and
the value is a positive integer, it is used.
When COLUMNS or LINES is not defined, ... |
Shortcuts for generating request headers. | def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,
basic_auth=None, proxy_basic_auth=None, disable_cache=None):
"""
Shortcuts for generating request headers.
:param keep_alive:
If ``True``, adds 'connection: keep-alive' header.
:param accept_encoding:
... |
If a position is provided move file to that point. Otherwise we ll attempt to record a position for future use. | def set_file_position(body, pos):
"""
If a position is provided, move file to that point.
Otherwise, we'll attempt to record a position for future use.
"""
if pos is not None:
rewind_body(body, pos)
elif getattr(body, 'tell', None) is not None:
try:
pos = body.tell()
... |
Attempt to rewind body to a certain position. Primarily used for request redirects and retries. | def rewind_body(body, body_pos):
"""
Attempt to rewind body to a certain position.
Primarily used for request redirects and retries.
:param body:
File-like object that supports seek.
:param int pos:
Position to seek to in file.
"""
body_seek = getattr(body, 'seek', None)
... |
Deep - copy a value into JSON - safe types. | def _copy_jsonsafe(value):
"""Deep-copy a value into JSON-safe types.
"""
if isinstance(value, six.string_types + (numbers.Number,)):
return value
if isinstance(value, collections_abc.Mapping):
return {six.text_type(k): _copy_jsonsafe(v) for k, v in value.items()}
if isinstance(value... |
Helper for clearing all the keys in a database. Use with caution! | def clear(self):
"""Helper for clearing all the keys in a database. Use with
caution!"""
for key in self.conn.keys():
self.conn.delete(key) |
Be aware that this treats any sequence type with the equal members as equal. As it is used to identify equality of schemas this can be considered okay as definitions are semantically equal regardless the container type. | def mapping_to_frozenset(mapping):
""" Be aware that this treats any sequence type with the equal members as
equal. As it is used to identify equality of schemas, this can be
considered okay as definitions are semantically equal regardless the
container type. """
mapping = mapping.copy()... |
Dynamically create a: class: ~cerberus. Validator subclass. Docstrings of mixin - classes will be added to the resulting class one if __doc__ is not in: obj: namespace. | def validator_factory(name, bases=None, namespace={}):
""" Dynamically create a :class:`~cerberus.Validator` subclass.
Docstrings of mixin-classes will be added to the resulting
class' one if ``__doc__`` is not in :obj:`namespace`.
:param name: The name of the new class.
:type name: :class:... |
Encode into a cmd - executable string. | def cmdify(self):
"""Encode into a cmd-executable string.
This re-implements CreateProcess's quoting logic to turn a list of
arguments into one single string for the shell to interpret.
* All double quotes are escaped with a backslash.
* Existing backslashes before a quote are ... |
Returns a tuple of frozenset s of classes and attributes. | def _split_what(what):
"""
Returns a tuple of `frozenset`s of classes and attributes.
"""
return (
frozenset(cls for cls in what if isclass(cls)),
frozenset(cls for cls in what if isinstance(cls, Attribute)),
) |
Whitelist * what *. | def include(*what):
"""
Whitelist *what*.
:param what: What to whitelist.
:type what: :class:`list` of :class:`type` or :class:`attr.Attribute`\\ s
:rtype: :class:`callable`
"""
cls, attrs = _split_what(what)
def include_(attribute, value):
return value.__class__ in cls or att... |
Blacklist * what *. | def exclude(*what):
"""
Blacklist *what*.
:param what: What to blacklist.
:type what: :class:`list` of classes or :class:`attr.Attribute`\\ s.
:rtype: :class:`callable`
"""
cls, attrs = _split_what(what)
def exclude_(attribute, value):
return value.__class__ not in cls and att... |
Return the attrs attribute values of * inst * as a dict. | def asdict(
inst,
recurse=True,
filter=None,
dict_factory=dict,
retain_collection_types=False,
):
"""
Return the ``attrs`` attribute values of *inst* as a dict.
Optionally recurse into other ``attrs``-decorated classes.
:param inst: Instance of an ``attrs``-decorated class.
:pa... |
asdict only works on attrs instances this works on anything. | def _asdict_anything(val, filter, dict_factory, retain_collection_types):
"""
``asdict`` only works on attrs instances, this works on anything.
"""
if getattr(val.__class__, "__attrs_attrs__", None) is not None:
# Attrs class.
rv = asdict(val, True, filter, dict_factory, retain_collectio... |
Return the attrs attribute values of * inst * as a tuple. | def astuple(
inst,
recurse=True,
filter=None,
tuple_factory=tuple,
retain_collection_types=False,
):
"""
Return the ``attrs`` attribute values of *inst* as a tuple.
Optionally recurse into other ``attrs``-decorated classes.
:param inst: Instance of an ``attrs``-decorated class.
... |
Copy * inst * and apply * changes *. | def assoc(inst, **changes):
"""
Copy *inst* and apply *changes*.
:param inst: Instance of a class with ``attrs`` attributes.
:param changes: Keyword changes in the new copy.
:return: A copy of inst with *changes* incorporated.
:raise attr.exceptions.AttrsAttributeNotFoundError: If *attr_name*... |
Create a new instance based on * inst * with * changes * applied. | def evolve(inst, **changes):
"""
Create a new instance, based on *inst* with *changes* applied.
:param inst: Instance of a class with ``attrs`` attributes.
:param changes: Keyword changes in the new copy.
:return: A copy of inst with *changes* incorporated.
:raise TypeError: If *attr_name* co... |
Constructs a request to the PyPI server and returns a: class: yarg. package. Package. | def get(package_name, pypi_server="https://pypi.python.org/pypi/"):
"""
Constructs a request to the PyPI server and returns a
:class:`yarg.package.Package`.
:param package_name: case sensitive name of the package on the PyPI server.
:param pypi_server: (option) URL to the PyPI server.
>>> ... |
Parse into a hierarchy of contexts. Contexts are connected through the parent variable.: param cli: command definition: param prog_name: the program that is running: param args: full list of args: return: the final context/ command parsed | def resolve_ctx(cli, prog_name, args):
"""
Parse into a hierarchy of contexts. Contexts are connected through the parent variable.
:param cli: command definition
:param prog_name: the program that is running
:param args: full list of args
:return: the final context/command parsed
"""
ctx... |
: param all_args: the full original list of args supplied: param cmd_param: the current command paramter: return: whether or not the last option declaration ( i. e. starts - or -- ) is incomplete and corresponds to this cmd_param. In other words whether this cmd_param option can still accept values | def is_incomplete_option(all_args, cmd_param):
"""
:param all_args: the full original list of args supplied
:param cmd_param: the current command paramter
:return: whether or not the last option declaration (i.e. starts "-" or "--") is incomplete and
corresponds to this cmd_param. In other words whe... |
: param current_params: the current params and values for this argument as already entered: param cmd_param: the current command parameter: return: whether or not the last argument is incomplete and corresponds to this cmd_param. In other words whether or not the this cmd_param argument can still accept values | def is_incomplete_argument(current_params, cmd_param):
"""
:param current_params: the current params and values for this argument as already entered
:param cmd_param: the current command parameter
:return: whether or not the last argument is incomplete and corresponds to this cmd_param. In
other wor... |
: param ctx: context associated with the parsed command: param args: full list of args: param incomplete: the incomplete text to autocomplete: param cmd_param: command definition: return: all the possible user - specified completions for the param | def get_user_autocompletions(ctx, args, incomplete, cmd_param):
"""
:param ctx: context associated with the parsed command
:param args: full list of args
:param incomplete: the incomplete text to autocomplete
:param cmd_param: command definition
:return: all the possible user-specified completio... |
: param ctx: context associated with the parsed command: starts_with: string that visible commands must start with.: return: all visible ( not hidden ) commands that start with starts_with. | def get_visible_commands_starting_with(ctx, starts_with):
"""
:param ctx: context associated with the parsed command
:starts_with: string that visible commands must start with.
:return: all visible (not hidden) commands that start with starts_with.
"""
for c in ctx.command.list_commands(ctx):
... |
: param cli: command definition: param prog_name: the program that is running: param args: full list of args: param incomplete: the incomplete text to autocomplete: return: all the possible completions for the incomplete | def get_choices(cli, prog_name, args, incomplete):
"""
:param cli: command definition
:param prog_name: the program that is running
:param args: full list of args
:param incomplete: the incomplete text to autocomplete
:return: all the possible completions for the incomplete
"""
all_args ... |
Interpret a marker and return a result depending on environment. | def interpret(marker, execution_context=None):
"""
Interpret a marker and return a result depending on environment.
:param marker: The marker to interpret.
:type marker: str
:param execution_context: The context used for name lookup.
:type execution_context: mapping
"""
try:
exp... |
Evaluate a marker expression returned by the: func: parse_requirement function in the specified context. | def evaluate(self, expr, context):
"""
Evaluate a marker expression returned by the :func:`parse_requirement`
function in the specified context.
"""
if isinstance(expr, string_types):
if expr[0] in '\'"':
result = expr[1:-1]
else:
... |
Colorize text using a reimplementation of the colorizer from https:// github. com/ pavdmyt/ yaspin so that it works on windows. | def colored(text, color=None, on_color=None, attrs=None):
"""Colorize text using a reimplementation of the colorizer from
https://github.com/pavdmyt/yaspin so that it works on windows.
Available text colors:
red, green, yellow, blue, magenta, cyan, white.
Available text highlights:
on_... |
Increments the parser by n characters if the end of the input has not been reached. | def inc_n(self, n, exception=None): # type: (int, Optional[ParseError]) -> bool
"""
Increments the parser by n characters
if the end of the input has not been reached.
"""
return self._src.inc_n(n=n, exception=exception) |
Consume chars until min/ max is satisfied is valid. | def consume(self, chars, min=0, max=-1):
"""
Consume chars until min/max is satisfied is valid.
"""
return self._src.consume(chars=chars, min=min, max=max) |
Creates a generic parse error at the current position. | def parse_error(self, exception=ParseError, *args):
"""
Creates a generic "parse error" at the current position.
"""
return self._src.parse_error(exception, *args) |
Merges the given Item with the last one currently in the given Container if both are whitespace items. | def _merge_ws(self, item, container): # type: (Item, Container) -> bool
"""
Merges the given Item with the last one currently in the given Container if
both are whitespace items.
Returns True if the items were merged.
"""
last = container.last_item()
if not last... |
Returns whether a key is strictly a child of another key. AoT siblings are not considered children of one another. | def _is_child(self, parent, child): # type: (str, str) -> bool
"""
Returns whether a key is strictly a child of another key.
AoT siblings are not considered children of one another.
"""
parent_parts = tuple(self._split_table_name(parent))
child_parts = tuple(self._split_... |
Attempts to parse the next item and returns it along with its key if the item is value - like. | def _parse_item(self): # type: () -> Optional[Tuple[Optional[Key], Item]]
"""
Attempts to parse the next item and returns it, along with its key
if the item is value-like.
"""
self.mark()
with self._state as state:
while True:
c = self._curren... |
Returns ( comment_ws comment trail ) If there is no comment comment_ws and comment will simply be empty. | def _parse_comment_trail(self): # type: () -> Tuple[str, str, str]
"""
Returns (comment_ws, comment, trail)
If there is no comment, comment_ws and comment will
simply be empty.
"""
if self.end():
return "", "", ""
comment = ""
comment_ws = ""... |
Parses a key enclosed in either single or double quotes. | def _parse_quoted_key(self): # type: () -> Key
"""
Parses a key enclosed in either single or double quotes.
"""
quote_style = self._current
key_type = None
dotted = False
for t in KeyType:
if t.value == quote_style:
key_type = t
... |
Parses a bare key. | def _parse_bare_key(self): # type: () -> Key
"""
Parses a bare key.
"""
key_type = None
dotted = False
self.mark()
while self._current.is_bare_key_char() and self.inc():
pass
key = self.extract()
if self._current == ".":
... |
Attempts to parse a value at the current position. | def _parse_value(self): # type: () -> Item
"""
Attempts to parse a value at the current position.
"""
self.mark()
c = self._current
trivia = Trivia()
if c == StringType.SLB.value:
return self._parse_basic_string()
elif c == StringType.SLL.val... |
Parses a table element. | def _parse_table(
self, parent_name=None
): # type: (Optional[str]) -> Tuple[Key, Union[Table, AoT]]
"""
Parses a table element.
"""
if self._current != "[":
raise self.parse_error(
InternalParserError, "_parse_table() called on non-bracket charac... |
Peeks ahead non - intrusively by cloning then restoring the initial state of the parser. | def _peek_table(self): # type: () -> Tuple[bool, str]
"""
Peeks ahead non-intrusively by cloning then restoring the
initial state of the parser.
Returns the name of the table about to be parsed,
as well as whether it is part of an AoT.
"""
# we always want to re... |
Parses all siblings of the provided table first and bundles them into an AoT. | def _parse_aot(self, first, name_first): # type: (Table, str) -> AoT
"""
Parses all siblings of the provided table first and bundles them into
an AoT.
"""
payload = [first]
self._aot_stack.append(name_first)
while not self.end():
is_aot_next, name_nex... |
Peeks ahead n characters. | def _peek(self, n): # type: (int) -> str
"""
Peeks ahead n characters.
n is the max number of characters that will be peeked.
"""
# we always want to restore after exiting this scope
with self._state(restore=True):
buf = ""
for _ in range(n):
... |
Peeks ahead non - intrusively by cloning then restoring the initial state of the parser. | def _peek_unicode(
self, is_long
): # type: (bool) -> Tuple[Optional[str], Optional[str]]
"""
Peeks ahead non-intrusively by cloning then restoring the
initial state of the parser.
Returns the unicode value is it's a valid one else None.
"""
# we always want... |
Given a string and an iterable of delimiters split on the first found delimiter. Return two split parts and the matched delimiter. | def split_first(s, delims):
"""
Given a string and an iterable of delimiters, split on the first found
delimiter. Return two split parts and the matched delimiter.
If not found, then the first part is the full input string.
Example::
>>> split_first('foo/bar?baz', '?/=')
('foo', '... |
Given a url return a parsed: class:. Url namedtuple. Best - effort is performed to parse incomplete urls. Fields not provided will be None. | def parse_url(url):
"""
Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is
performed to parse incomplete urls. Fields not provided will be None.
Partly backwards-compatible with :mod:`urlparse`.
Example::
>>> parse_url('http://google.com/mail/')
Url(scheme='http... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.