Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
if cookiejar is None:
cookiejar = RequestsCookieJar()
if cookie_dict is not None:
names_from_jar = [cookie.name for cookie in cookiejar]
for name in cookie_dict:
... | [
"Returns a CookieJar from a key/value dictionary.\n\n :param cookie_dict: Dict of key/values to insert into CookieJar.\n :param cookiejar: (optional) A cookiejar to add the cookies to.\n :param overwrite: (optional) If False, will not replace cookies\n already in the jar with new ones.\n :rtype: ... |
Please provide a description of the function:def merge_cookies(cookiejar, cookies):
if not isinstance(cookiejar, cookielib.CookieJar):
raise ValueError('You can only merge into CookieJar')
if isinstance(cookies, dict):
cookiejar = cookiejar_from_dict(
cookies, cookiejar=cookiej... | [
"Add cookies to cookiejar and returns a merged CookieJar.\n\n :param cookiejar: CookieJar object to add the cookies to.\n :param cookies: Dictionary or CookieJar object to be added.\n :rtype: CookieJar\n "
] |
Please provide a description of the function:def get(self, name, default=None, domain=None, path=None):
try:
return self._find_no_duplicates(name, domain, path)
except KeyError:
return default | [
"Dict-like get() that also supports optional domain and path args in\n order to resolve naming collisions from using one cookie jar over\n multiple domains.\n\n .. warning:: operation is O(n), not O(1).\n "
] |
Please provide a description of the function:def set(self, name, value, **kwargs):
# support client code that unsets cookies by assignment of a None value:
if value is None:
remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))
return
... | [
"Dict-like set() that also supports optional domain and path args in\n order to resolve naming collisions from using one cookie jar over\n multiple domains.\n "
] |
Please provide a description of the function:def list_domains(self):
domains = []
for cookie in iter(self):
if cookie.domain not in domains:
domains.append(cookie.domain)
return domains | [
"Utility method to list all the domains in the jar."
] |
Please provide a description of the function:def list_paths(self):
paths = []
for cookie in iter(self):
if cookie.path not in paths:
paths.append(cookie.path)
return paths | [
"Utility method to list all the paths in the jar."
] |
Please provide a description of the function:def multiple_domains(self):
domains = []
for cookie in iter(self):
if cookie.domain is not None and cookie.domain in domains:
return True
domains.append(cookie.domain)
return False | [
"Returns True if there are multiple domains in the jar.\n Returns False otherwise.\n\n :rtype: bool\n "
] |
Please provide a description of the function:def update(self, other):
if isinstance(other, cookielib.CookieJar):
for cookie in other:
self.set_cookie(copy.copy(cookie))
else:
super(RequestsCookieJar, self).update(other) | [
"Updates this jar with cookies from another CookieJar or dict-like"
] |
Please provide a description of the function:def _find(self, name, domain=None, path=None):
for cookie in iter(self):
if cookie.name == name:
if domain is None or cookie.domain == domain:
if path is None or cookie.path == path:
ret... | [
"Requests uses this method internally to get cookie values.\n\n If there are conflicting cookies, _find arbitrarily chooses one.\n See _find_no_duplicates if you want an exception thrown if there are\n conflicting cookies.\n\n :param name: a string containing name of cookie\n :par... |
Please provide a description of the function:def _find_no_duplicates(self, name, domain=None, path=None):
toReturn = None
for cookie in iter(self):
if cookie.name == name:
if domain is None or cookie.domain == domain:
if path is None or cookie.pat... | [
"Both ``__get_item__`` and ``get`` call this function: it's never\n used elsewhere in Requests.\n\n :param name: a string containing name of cookie\n :param domain: (optional) string containing domain of cookie\n :param path: (optional) string containing path of cookie\n :raises K... |
Please provide a description of the function:def copy(self):
new_cj = RequestsCookieJar()
new_cj.set_policy(self.get_policy())
new_cj.update(self)
return new_cj | [
"Return a copy of this RequestsCookieJar."
] |
Please provide a description of the function: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 | [] |
Please provide a description of the function: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("... | [] |
Please provide a description of the function: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 ... | [] |
Please provide a description of the function: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 ]) | [] |
Please provide a description of the function: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'
... | [] |
Please provide a description of the function: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() | [] |
Please provide a description of the function: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]
se... | [] |
Please provide a description of the function: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) | [] |
Please provide a description of the function: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._deco... | [] |
Please provide a description of the function: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, sel... | [] |
Please provide a description of the function: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) | [] |
Please provide a description of the function: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 | [] |
Please provide a description of the function: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 | [] |
Please provide a description of the function: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() | [] |
Please provide a description of the function: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]) | [] |
Please provide a description of the function: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) | [] |
Please provide a description of the function: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) | [] |
Please provide a description of the function:def erase_line (self): # <ESC>[2K
'''Erases the entire current line.'''
self.fill_region (self.cur_r, 1, self.cur_r, self.cols) | [] |
Please provide a description of the function: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) | [] |
Please provide a description of the function: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) | [] |
Please provide a description of the function:def to_int(d, key, default_to_zero=False, default=None, required=True):
value = d.get(key) or default
if (value in ["", None]) and default_to_zero:
return 0
if value is None:
if required:
raise ParseError("Unable to read %s from %... | [
"Pull a value from the dict and convert to int\n\n :param default_to_zero: If the value is None or empty, treat it as zero\n :param default: If the value is missing in the dict use this default\n\n "
] |
Please provide a description of the function:def parse_timezone(matches, default_timezone=UTC):
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).
# Addresses is... | [
"Parses ISO 8601 time zone specs into tzinfo offsets\n\n "
] |
Please provide a description of the function:def parse_date(datestring, default_timezone=UTC):
if not isinstance(datestring, _basestring):
raise ParseError("Expecting a string %r" % datestring)
m = ISO8601_REGEX.match(datestring)
if not m:
raise ParseError("Unable to parse date string %... | [
"Parses ISO 8601 dates into datetime objects\n\n The timezone is parsed from the date string. However it is quite common to\n have dates without a timezone (not strictly correct). In this case the\n default timezone specified in default_timezone is used. This is UTC by\n default.\n\n :param datestrin... |
Please provide a description of the function:def default_handler(signum, frame, spinner):
spinner.fail()
spinner.stop()
sys.exit(0) | [
"Signal handler, used to gracefully shut down the ``spinner`` instance\n when specified signal is received by the process running the ``spinner``.\n\n ``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``\n function for more details.\n "
] |
Please provide a description of the function:def fancy_handler(signum, frame, spinner):
spinner.red.fail("✘")
spinner.stop()
sys.exit(0) | [
"Signal handler, used to gracefully shut down the ``spinner`` instance\n when specified signal is received by the process running the ``spinner``.\n\n ``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal``\n function for more details.\n "
] |
Please provide a description of the function:def uts46_remap(domain, std3_rules=True, transitional=False):
from .uts46data import uts46data
output = u""
try:
for pos, char in enumerate(domain):
code_point = ord(char)
uts46row = uts46data[code_point if code_point < 256 el... | [
"Re-map the characters in the string according to UTS46 processing."
] |
Please provide a description of the function:def _implementation():
implementation = platform.python_implementation()
if implementation == 'CPython':
implementation_version = platform.python_version()
elif implementation == 'PyPy':
implementation_version = '%s.%s.%s' % (sys.pypy_versio... | [
"Return a dict with the Python implementation and version.\n\n Provide both the name and the version of the Python implementation\n currently running. For example, on CPython 2.7.5 it will return\n {'name': 'CPython', 'version': '2.7.5'}.\n\n This function works best on CPython and PyPy: in particular, ... |
Please provide a description of the function:def info():
try:
platform_info = {
'system': platform.system(),
'release': platform.release(),
}
except IOError:
platform_info = {
'system': 'Unknown',
'release': 'Unknown',
}
i... | [
"Generate information for a bug report."
] |
Please provide a description of the function:def package_type(self):
mapping = {'bdist_egg': u'egg', 'bdist_wheel': u'wheel',
'sdist': u'source'}
ptype = self._release['packagetype']
if ptype in mapping.keys():
return mapping[ptype]
return ptype | [
"\n >>> package = yarg.get('yarg')\n >>> v = \"0.1.0\"\n >>> r = package.release(v)\n >>> r.package_type\n u'wheel'\n "
] |
Please provide a description of the function:def process (self, c):
if isinstance(c, bytes):
c = self._decode(c)
self.state.process(c) | [
"Process a single character. Called by :meth:`write`."
] |
Please provide a description of the function:def write (self, s):
if isinstance(s, bytes):
s = self._decode(s)
for c in s:
self.process(c) | [
"Process text, writing it to the virtual screen while handling\n ANSI escape codes.\n "
] |
Please provide a description of the function: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, b... | [] |
Please provide a description of the function:def get_best_encoding(stream):
rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding()
if is_ascii_encoding(rv):
return 'utf-8'
return rv | [
"Returns the default stream encoding if not found."
] |
Please provide a description of the function:def get_terminal_size(fallback=(80, 24)):
# Try the environment first
try:
columns = int(os.environ["COLUMNS"])
except (KeyError, ValueError):
columns = 0
try:
lines = int(os.environ["LINES"])
except (KeyError, ValueError):
... | [
"Get the size of the terminal window.\n\n For each of the two dimensions, the environment variable, COLUMNS\n and LINES respectively, is checked. If the variable is defined and\n the value is a positive integer, it is used.\n\n When COLUMNS or LINES is not defined, which is the common case,\n the ter... |
Please provide a description of the function:def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,
basic_auth=None, proxy_basic_auth=None, disable_cache=None):
headers = {}
if accept_encoding:
if isinstance(accept_encoding, str):
pass
elif isi... | [
"\n Shortcuts for generating request headers.\n\n :param keep_alive:\n If ``True``, adds 'connection: keep-alive' header.\n\n :param accept_encoding:\n Can be a boolean, list, or string.\n ``True`` translates to 'gzip,deflate'.\n List will get joined by comma.\n String wi... |
Please provide a description of the function:def set_file_position(body, pos):
if pos is not None:
rewind_body(body, pos)
elif getattr(body, 'tell', None) is not None:
try:
pos = body.tell()
except (IOError, OSError):
# This differentiates from None, allowing... | [
"\n If a position is provided, move file to that point.\n Otherwise, we'll attempt to record a position for future use.\n "
] |
Please provide a description of the function:def rewind_body(body, body_pos):
body_seek = getattr(body, 'seek', None)
if body_seek is not None and isinstance(body_pos, integer_types):
try:
body_seek(body_pos)
except (IOError, OSError):
raise UnrewindableBodyError("An... | [
"\n Attempt to rewind body to a certain position.\n Primarily used for request redirects and retries.\n\n :param body:\n File-like object that supports seek.\n\n :param int pos:\n Position to seek to in file.\n "
] |
Please provide a description of the function:def _copy_jsonsafe(value):
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, col... | [
"Deep-copy a value into JSON-safe types.\n "
] |
Please provide a description of the function:def clear(self):
for key in self.conn.keys():
self.conn.delete(key) | [
"Helper for clearing all the keys in a database. Use with\n caution!"
] |
Please provide a description of the function:def mapping_to_frozenset(mapping):
mapping = mapping.copy()
for key, value in mapping.items():
if isinstance(value, Mapping):
mapping[key] = mapping_to_frozenset(value)
elif isinstance(value, Sequence):
value = list(value)... | [
" Be aware that this treats any sequence type with the equal members as\n equal. As it is used to identify equality of schemas, this can be\n considered okay as definitions are semantically equal regardless the\n container type. "
] |
Please provide a description of the function:def validator_factory(name, bases=None, namespace={}):
Validator = get_Validator_class()
if bases is None:
bases = (Validator,)
elif isinstance(bases, tuple):
bases += (Validator,)
else:
bases = (bases, Validator)
docstrings... | [
" Dynamically create a :class:`~cerberus.Validator` subclass.\n Docstrings of mixin-classes will be added to the resulting\n class' one if ``__doc__`` is not in :obj:`namespace`.\n\n :param name: The name of the new class.\n :type name: :class:`str`\n :param bases: Class(es) with additional a... |
Please provide a description of the function:def cmdify(self):
return " ".join(
itertools.chain(
[_quote_if_contains(self.command, r"[\s^()]")],
(_quote_if_contains(arg, r"[\s^]") for arg in self.args),
)
) | [
"Encode into a cmd-executable string.\n\n This re-implements CreateProcess's quoting logic to turn a list of\n arguments into one single string for the shell to interpret.\n\n * All double quotes are escaped with a backslash.\n * Existing backslashes before a quote are doubled, so they a... |
Please provide a description of the function:def _split_what(what):
return (
frozenset(cls for cls in what if isclass(cls)),
frozenset(cls for cls in what if isinstance(cls, Attribute)),
) | [
"\n Returns a tuple of `frozenset`s of classes and attributes.\n "
] |
Please provide a description of the function:def include(*what):
cls, attrs = _split_what(what)
def include_(attribute, value):
return value.__class__ in cls or attribute in attrs
return include_ | [
"\n Whitelist *what*.\n\n :param what: What to whitelist.\n :type what: :class:`list` of :class:`type` or :class:`attr.Attribute`\\\\ s\n\n :rtype: :class:`callable`\n "
] |
Please provide a description of the function:def exclude(*what):
cls, attrs = _split_what(what)
def exclude_(attribute, value):
return value.__class__ not in cls and attribute not in attrs
return exclude_ | [
"\n Blacklist *what*.\n\n :param what: What to blacklist.\n :type what: :class:`list` of classes or :class:`attr.Attribute`\\\\ s.\n\n :rtype: :class:`callable`\n "
] |
Please provide a description of the function:def asdict(
inst,
recurse=True,
filter=None,
dict_factory=dict,
retain_collection_types=False,
):
attrs = fields(inst.__class__)
rv = dict_factory()
for a in attrs:
v = getattr(inst, a.name)
if filter is not None and not f... | [
"\n Return the ``attrs`` attribute values of *inst* as a dict.\n\n Optionally recurse into other ``attrs``-decorated classes.\n\n :param inst: Instance of an ``attrs``-decorated class.\n :param bool recurse: Recurse into classes that are also\n ``attrs``-decorated.\n :param callable filter: A ... |
Please provide a description of the function:def _asdict_anything(val, filter, dict_factory, retain_collection_types):
if getattr(val.__class__, "__attrs_attrs__", None) is not None:
# Attrs class.
rv = asdict(val, True, filter, dict_factory, retain_collection_types)
elif isinstance(val, (t... | [
"\n ``asdict`` only works on attrs instances, this works on anything.\n "
] |
Please provide a description of the function:def astuple(
inst,
recurse=True,
filter=None,
tuple_factory=tuple,
retain_collection_types=False,
):
attrs = fields(inst.__class__)
rv = []
retain = retain_collection_types # Very long. :/
for a in attrs:
v = getattr(inst, a.... | [
"\n Return the ``attrs`` attribute values of *inst* as a tuple.\n\n Optionally recurse into other ``attrs``-decorated classes.\n\n :param inst: Instance of an ``attrs``-decorated class.\n :param bool recurse: Recurse into classes that are also\n ``attrs``-decorated.\n :param callable filter: A... |
Please provide a description of the function:def assoc(inst, **changes):
import warnings
warnings.warn(
"assoc is deprecated and will be removed after 2018/01.",
DeprecationWarning,
stacklevel=2,
)
new = copy.copy(inst)
attrs = fields(inst.__class__)
for k, v in ite... | [
"\n Copy *inst* and apply *changes*.\n\n :param inst: Instance of a class with ``attrs`` attributes.\n :param changes: Keyword changes in the new copy.\n\n :return: A copy of inst with *changes* incorporated.\n\n :raise attr.exceptions.AttrsAttributeNotFoundError: If *attr_name* couldn't\n be ... |
Please provide a description of the function:def evolve(inst, **changes):
cls = inst.__class__
attrs = fields(cls)
for a in attrs:
if not a.init:
continue
attr_name = a.name # To deal with private attributes.
init_name = attr_name if attr_name[0] != "_" else attr_na... | [
"\n Create a new instance, based on *inst* with *changes* applied.\n\n :param inst: Instance of a class with ``attrs`` attributes.\n :param changes: Keyword changes in the new copy.\n\n :return: A copy of inst with *changes* incorporated.\n\n :raise TypeError: If *attr_name* couldn't be found in the ... |
Please provide a description of the function:def get(package_name, pypi_server="https://pypi.python.org/pypi/"):
if not pypi_server.endswith("/"):
pypi_server = pypi_server + "/"
response = requests.get("{0}{1}/json".format(pypi_server,
package_name)... | [
"\n Constructs a request to the PyPI server and returns a\n :class:`yarg.package.Package`.\n\n :param package_name: case sensitive name of the package on the PyPI server.\n :param pypi_server: (option) URL to the PyPI server.\n\n >>> import yarg\n >>> package = yarg.get('yarg')\n <P... |
Please provide a description of the function:def resolve_ctx(cli, prog_name, args):
ctx = cli.make_context(prog_name, args, resilient_parsing=True)
args = ctx.protected_args + ctx.args
while args:
if isinstance(ctx.command, MultiCommand):
if not ctx.command.chain:
cm... | [
"\n Parse into a hierarchy of contexts. Contexts are connected through the parent variable.\n :param cli: command definition\n :param prog_name: the program that is running\n :param args: full list of args\n :return: the final context/command parsed\n "
] |
Please provide a description of the function:def is_incomplete_option(all_args, cmd_param):
if not isinstance(cmd_param, Option):
return False
if cmd_param.is_flag:
return False
last_option = None
for index, arg_str in enumerate(reversed([arg for arg in all_args if arg != WORDBREAK]... | [
"\n :param all_args: the full original list of args supplied\n :param cmd_param: the current command paramter\n :return: whether or not the last option declaration (i.e. starts \"-\" or \"--\") is incomplete and\n corresponds to this cmd_param. In other words whether this cmd_param option can still acce... |
Please provide a description of the function:def is_incomplete_argument(current_params, cmd_param):
if not isinstance(cmd_param, Argument):
return False
current_param_values = current_params[cmd_param.name]
if current_param_values is None:
return True
if cmd_param.nargs == -1:
... | [
"\n :param current_params: the current params and values for this argument as already entered\n :param cmd_param: the current command parameter\n :return: whether or not the last argument is incomplete and corresponds to this cmd_param. In\n other words whether or not the this cmd_param argument can sti... |
Please provide a description of the function:def get_user_autocompletions(ctx, args, incomplete, cmd_param):
results = []
if isinstance(cmd_param.type, Choice):
# Choices don't support descriptions.
results = [(c, None)
for c in cmd_param.type.choices if str(c).startswith... | [
"\n :param ctx: context associated with the parsed command\n :param args: full list of args\n :param incomplete: the incomplete text to autocomplete\n :param cmd_param: command definition\n :return: all the possible user-specified completions for the param\n "
] |
Please provide a description of the function:def get_visible_commands_starting_with(ctx, starts_with):
for c in ctx.command.list_commands(ctx):
if c.startswith(starts_with):
command = ctx.command.get_command(ctx, c)
if not command.hidden:
yield command | [
"\n :param ctx: context associated with the parsed command\n :starts_with: string that visible commands must start with.\n :return: all visible (not hidden) commands that start with starts_with.\n "
] |
Please provide a description of the function:def get_choices(cli, prog_name, args, incomplete):
all_args = copy.deepcopy(args)
ctx = resolve_ctx(cli, prog_name, args)
if ctx is None:
return []
# In newer versions of bash long opts with '='s are partitioned, but it's easier to parse
# ... | [
"\n :param cli: command definition\n :param prog_name: the program that is running\n :param args: full list of args\n :param incomplete: the incomplete text to autocomplete\n :return: all the possible completions for the incomplete\n "
] |
Please provide a description of the function:def interpret(marker, execution_context=None):
try:
expr, rest = parse_marker(marker)
except Exception as e:
raise SyntaxError('Unable to interpret marker syntax: %s: %s' % (marker, e))
if rest and rest[0] != '#':
raise SyntaxError('u... | [
"\n Interpret a marker and return a result depending on environment.\n\n :param marker: The marker to interpret.\n :type marker: str\n :param execution_context: The context used for name lookup.\n :type execution_context: mapping\n "
] |
Please provide a description of the function:def evaluate(self, expr, context):
if isinstance(expr, string_types):
if expr[0] in '\'"':
result = expr[1:-1]
else:
if expr not in context:
raise SyntaxError('unknown variable: %s' ... | [
"\n Evaluate a marker expression returned by the :func:`parse_requirement`\n function in the specified context.\n "
] |
Please provide a description of the function:def colored(text, color=None, on_color=None, attrs=None):
if os.getenv("ANSI_COLORS_DISABLED") is None:
style = "NORMAL"
if "bold" in attrs:
style = "BRIGHT"
attrs.remove("bold")
if color is not None:
color... | [
"Colorize text using a reimplementation of the colorizer from\n https://github.com/pavdmyt/yaspin so that it works on windows.\n\n Available text colors:\n red, green, yellow, blue, magenta, cyan, white.\n\n Available text highlights:\n on_red, on_green, on_yellow, on_blue, on_magenta, on_cya... |
Please provide a description of the function:def inc_n(self, n, exception=None): # type: (int, Optional[ParseError]) -> bool
return self._src.inc_n(n=n, exception=exception) | [
"\n Increments the parser by n characters\n if the end of the input has not been reached.\n "
] |
Please provide a description of the function:def consume(self, chars, min=0, max=-1):
return self._src.consume(chars=chars, min=min, max=max) | [
"\n Consume chars until min/max is satisfied is valid.\n "
] |
Please provide a description of the function:def parse_error(self, exception=ParseError, *args):
return self._src.parse_error(exception, *args) | [
"\n Creates a generic \"parse error\" at the current position.\n "
] |
Please provide a description of the function:def _merge_ws(self, item, container): # type: (Item, Container) -> bool
last = container.last_item()
if not last:
return False
if not isinstance(item, Whitespace) or not isinstance(last, Whitespace):
return False
... | [
"\n Merges the given Item with the last one currently in the given Container if\n both are whitespace items.\n\n Returns True if the items were merged.\n "
] |
Please provide a description of the function:def _is_child(self, parent, child): # type: (str, str) -> bool
parent_parts = tuple(self._split_table_name(parent))
child_parts = tuple(self._split_table_name(child))
if parent_parts == child_parts:
return False
return ... | [
"\n Returns whether a key is strictly a child of another key.\n AoT siblings are not considered children of one another.\n "
] |
Please provide a description of the function:def _parse_item(self): # type: () -> Optional[Tuple[Optional[Key], Item]]
self.mark()
with self._state as state:
while True:
c = self._current
if c == "\n":
# Found a newline; Return al... | [
"\n Attempts to parse the next item and returns it, along with its key\n if the item is value-like.\n "
] |
Please provide a description of the function:def _parse_comment_trail(self): # type: () -> Tuple[str, str, str]
if self.end():
return "", "", ""
comment = ""
comment_ws = ""
self.mark()
while True:
c = self._current
if c == "\n":
... | [
"\n Returns (comment_ws, comment, trail)\n If there is no comment, comment_ws and comment will\n simply be empty.\n "
] |
Please provide a description of the function:def _parse_quoted_key(self): # type: () -> Key
quote_style = self._current
key_type = None
dotted = False
for t in KeyType:
if t.value == quote_style:
key_type = t
break
if key_typ... | [
"\n Parses a key enclosed in either single or double quotes.\n "
] |
Please provide a description of the function:def _parse_bare_key(self): # type: () -> 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 == ".":
... | [
"\n Parses a bare key.\n "
] |
Please provide a description of the function:def _parse_value(self): # type: () -> Item
self.mark()
c = self._current
trivia = Trivia()
if c == StringType.SLB.value:
return self._parse_basic_string()
elif c == StringType.SLL.value:
return self._... | [
"\n Attempts to parse a value at the current position.\n "
] |
Please provide a description of the function:def _parse_table(
self, parent_name=None
): # type: (Optional[str]) -> Tuple[Key, Union[Table, AoT]]
if self._current != "[":
raise self.parse_error(
InternalParserError, "_parse_table() called on non-bracket characte... | [
"\n Parses a table element.\n "
] |
Please provide a description of the function:def _peek_table(self): # type: () -> Tuple[bool, str]
# we always want to restore after exiting this scope
with self._state(save_marker=True, restore=True):
if self._current != "[":
raise self.parse_error(
... | [
"\n Peeks ahead non-intrusively by cloning then restoring the\n initial state of the parser.\n\n Returns the name of the table about to be parsed,\n as well as whether it is part of an AoT.\n "
] |
Please provide a description of the function:def _parse_aot(self, first, name_first): # type: (Table, str) -> AoT
payload = [first]
self._aot_stack.append(name_first)
while not self.end():
is_aot_next, name_next = self._peek_table()
if is_aot_next and name_next ... | [
"\n Parses all siblings of the provided table first and bundles them into\n an AoT.\n "
] |
Please provide a description of the function:def _peek(self, n): # type: (int) -> str
# we always want to restore after exiting this scope
with self._state(restore=True):
buf = ""
for _ in range(n):
if self._current not in " \t\n\r#,]}":
... | [
"\n Peeks ahead n characters.\n\n n is the max number of characters that will be peeked.\n "
] |
Please provide a description of the function:def _peek_unicode(
self, is_long
): # type: (bool) -> Tuple[Optional[str], Optional[str]]
# we always want to restore after exiting this scope
with self._state(save_marker=True, restore=True):
if self._current not in {"u", "U... | [
"\n Peeks ahead non-intrusively by cloning then restoring the\n initial state of the parser.\n\n Returns the unicode value is it's a valid one else None.\n "
] |
Please provide a description of the function:def split_first(s, delims):
min_idx = None
min_delim = None
for d in delims:
idx = s.find(d)
if idx < 0:
continue
if min_idx is None or idx < min_idx:
min_idx = idx
min_delim = d
if min_idx is... | [
"\n Given a string and an iterable of delimiters, split on the first found\n delimiter. Return two split parts and the matched delimiter.\n\n If not found, then the first part is the full input string.\n\n Example::\n\n >>> split_first('foo/bar?baz', '?/=')\n ('foo', 'bar?baz', '/')\n ... |
Please provide a description of the function:def parse_url(url):
# While this code has overlap with stdlib's urlparse, it is much
# simplified for our needs and less annoying.
# Additionally, this implementations does silly things to be optimal
# on CPython.
if not url:
# Empty
... | [
"\n Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is\n performed to parse incomplete urls. Fields not provided will be None.\n\n Partly backwards-compatible with :mod:`urlparse`.\n\n Example::\n\n >>> parse_url('http://google.com/mail/')\n Url(scheme='http', host='goog... |
Please provide a description of the function:def get_host(url):
p = parse_url(url)
return p.scheme or 'http', p.hostname, p.port | [
"\n Deprecated. Use :func:`parse_url` instead.\n "
] |
Please provide a description of the function:def request_uri(self):
uri = self.path or '/'
if self.query is not None:
uri += '?' + self.query
return uri | [
"Absolute path including the query string."
] |
Please provide a description of the function:def netloc(self):
if self.port:
return '%s:%d' % (self.host, self.port)
return self.host | [
"Network location including host and port"
] |
Please provide a description of the function:def url(self):
scheme, auth, host, port, path, query, fragment = self
url = ''
# We use "is not None" we want things to happen with empty strings (or 0 port)
if scheme is not None:
url += scheme + '://'
if auth is... | [
"\n Convert self into a url\n\n This function should more or less round-trip with :func:`.parse_url`. The\n returned url may not be exactly the same as the url inputted to\n :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls\n with a blank port will have : remo... |
Please provide a description of the function:def split_template_path(template):
pieces = []
for piece in template.split('/'):
if path.sep in piece \
or (path.altsep and path.altsep in piece) or \
piece == path.pardir:
raise TemplateNotFound(template)
elif p... | [
"Split a path into segments and perform a sanity check. If it detects\n '..' in the path it will raise a `TemplateNotFound` error.\n "
] |
Please provide a description of the function:def get_source(self, environment, template):
if not self.has_source_access:
raise RuntimeError('%s cannot provide access to the source' %
self.__class__.__name__)
raise TemplateNotFound(template) | [
"Get the template source, filename and reload helper for a template.\n It's passed the environment and template name and has to return a\n tuple in the form ``(source, filename, uptodate)`` or raise a\n `TemplateNotFound` error if it can't locate the template.\n\n The source part of the ... |
Please provide a description of the function:def load(self, environment, name, globals=None):
code = None
if globals is None:
globals = {}
# first we try to get the source for this template together
# with the filename and the uptodate function.
source, file... | [
"Loads a template. This method looks up the template in the cache\n or loads one by calling :meth:`get_source`. Subclasses should not\n override this method as loaders working on collections of other\n loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)\n will not call thi... |
Please provide a description of the function:def description_of(lines, name='stdin'):
u = UniversalDetector()
for line in lines:
line = bytearray(line)
u.feed(line)
# shortcut out of the loop to save reading further - particularly useful if we read a BOM.
if u.done:
... | [
"\n Return a string describing the probable encoding of a file or\n list of strings.\n\n :param lines: The lines to get the encoding of.\n :type lines: Iterable of bytes\n :param name: Name of file or collection of lines\n :type name: str\n "
] |
Please provide a description of the function:def to_genshi(walker):
text = []
for token in walker:
type = token["type"]
if type in ("Characters", "SpaceCharacters"):
text.append(token["data"])
elif text:
yield TEXT, "".join(text), (None, -1, -1)
t... | [
"Convert a tree to a genshi tree\n\n :arg walker: the treewalker to use to walk the tree to convert it\n\n :returns: generator of genshi nodes\n\n "
] |
Please provide a description of the function:def parse_requirements(file_):
modules = []
delim = ["<", ">", "=", "!", "~"] # https://www.python.org/dev/peps/pep-0508/#complete-grammar
try:
f = open_func(file_, "r")
except OSError:
logging.error("Failed on file: {}".format(file_))
... | [
"Parse a requirements formatted file.\n\n Traverse a string until a delimiter is detected, then split at said\n delimiter, get module name by element index, create a dict consisting of\n module:version, and add dict to list of parsed modules.\n\n Args:\n file_: File to parse.\n\n Raises:\n ... |
Please provide a description of the function:def compare_modules(file_, imports):
modules = parse_requirements(file_)
imports = [imports[i]["name"] for i in range(len(imports))]
modules = [modules[i]["name"] for i in range(len(modules))]
modules_not_imported = set(modules) - set(imports)
retu... | [
"Compare modules in a file to imported modules in a project.\n\n Args:\n file_ (str): File to parse for modules to be compared.\n imports (tuple): Modules being imported in the project.\n\n Returns:\n tuple: The modules not imported in the project, but do exist in the\n spec... |
Please provide a description of the function:def diff(file_, imports):
modules_not_imported = compare_modules(file_, imports)
logging.info("The following modules are in {} but do not seem to be imported: "
"{}".format(file_, ", ".join(x for x in modules_not_imported))) | [
"Display the difference between modules in a file and imported modules."
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.