_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q276400 | _transform_result | test | def _transform_result(typ, result):
"""Convert the result back into the input type.
"""
if issubclass(typ, bytes):
return tostring(result, encoding='utf-8')
elif issubclass(typ, unicode):
return tostring(result, encoding='unicode')
else:
return result | python | {
"resource": ""
} |
q276401 | html_to_xhtml | test | def html_to_xhtml(html):
"""Convert all tags in an HTML tree to XHTML by moving them to the
XHTML namespace.
"""
try:
html = html.getroot()
except AttributeError:
pass
prefix = "{%s}" % XHTML_NAMESPACE
for el in html.iter(etree.Element):
tag = el.tag
if tag[0]... | python | {
"resource": ""
} |
q276402 | xhtml_to_html | test | def xhtml_to_html(xhtml):
"""Convert all tags in an XHTML tree to HTML by removing their
XHTML namespace.
"""
try:
xhtml = xhtml.getroot()
except AttributeError:
pass
prefix = "{%s}" % XHTML_NAMESPACE
prefix_len = len(prefix)
for el in xhtml.iter(prefix + "*"):
el... | python | {
"resource": ""
} |
q276403 | tostring | test | def tostring(doc, pretty_print=False, include_meta_content_type=False,
encoding=None, method="html", with_tail=True, doctype=None):
"""Return an HTML string representation of the document.
Note: if include_meta_content_type is true this will create a
``<meta http-equiv="Content-Type" ...>`` ta... | python | {
"resource": ""
} |
q276404 | open_in_browser | test | def open_in_browser(doc, encoding=None):
"""
Open the HTML document in a web browser, saving it to a temporary
file to open it. Note that this does not delete the file after
use. This is mainly meant for debugging.
"""
import os
import webbrowser
import tempfile
if not isinstance(d... | python | {
"resource": ""
} |
q276405 | HtmlMixin.drop_tree | test | def drop_tree(self):
"""
Removes this element from the tree, including its children and
text. The tail text is joined to the previous element or
parent.
"""
parent = self.getparent()
assert parent is not None
if self.tail:
previous = self.getp... | python | {
"resource": ""
} |
q276406 | HtmlMixin.drop_tag | test | def drop_tag(self):
"""
Remove the tag, but not its children or text. The children and text
are merged into the parent.
Example::
>>> h = fragment_fromstring('<div>Hello <b>World!</b></div>')
>>> h.find('.//b').drop_tag()
>>> print(tostring(h, encod... | python | {
"resource": ""
} |
q276407 | HtmlMixin.get_element_by_id | test | def get_element_by_id(self, id, *default):
"""
Get the first element in a document with the given id. If none is
found, return the default argument if provided or raise KeyError
otherwise.
Note that there can be more than one element with the same id,
and this isn't unc... | python | {
"resource": ""
} |
q276408 | HtmlMixin.cssselect | test | def cssselect(self, expr, translator='html'):
"""
Run the CSS expression on this element and its children,
returning a list of the results.
Equivalent to lxml.cssselect.CSSSelect(expr, translator='html')(self)
-- note that pre-compiling the expression can provide a substantial
... | python | {
"resource": ""
} |
q276409 | loghandler_members | test | def loghandler_members():
"""iterate through the attributes of every logger's handler
this is used to switch out stderr and stdout in tests when buffer is True
:returns: generator of tuples, each tuple has (name, handler, member_name, member_val)
"""
Members = namedtuple("Members", ["name", "handl... | python | {
"resource": ""
} |
q276410 | get_counts | test | def get_counts():
"""return test counts that are set via pyt environment variables when pyt
runs the test
:returns: dict, 3 keys (classes, tests, modules) and how many tests of each
were found by pyt
"""
counts = {}
ks = [
('PYT_TEST_CLASS_COUNT', "classes"),
('PYT_TEST... | python | {
"resource": ""
} |
q276411 | is_single_class | test | def is_single_class():
"""Returns True if only a single class is being run or some tests within a single class"""
ret = False
counts = get_counts()
if counts["classes"] < 1 and counts["modules"] < 1:
ret = counts["tests"] > 0
else:
ret = counts["classes"] <= 1 and counts["modules"] <... | python | {
"resource": ""
} |
q276412 | is_single_module | test | def is_single_module():
"""Returns True if only a module is being run"""
ret = False
counts = get_counts()
if counts["modules"] == 1:
ret = True
elif counts["modules"] < 1:
ret = is_single_class()
return ret | python | {
"resource": ""
} |
q276413 | validate_params | test | def validate_params(request):
"""Validate request params."""
if 'params' in request:
correct_params = isinstance(request['params'], (list, dict))
error = 'Incorrect parameter values'
assert correct_params, error | python | {
"resource": ""
} |
q276414 | validate_id | test | def validate_id(request):
"""Validate request id."""
if 'id' in request:
correct_id = isinstance(
request['id'],
(string_types, int, None),
)
error = 'Incorrect identifier'
assert correct_id, error | python | {
"resource": ""
} |
q276415 | filesys_decode | test | def filesys_decode(path):
"""
Ensure that the given path is decoded,
NONE when no expected encoding works
"""
fs_enc = sys.getfilesystemencoding()
if isinstance(path, decoded_string):
return path
for enc in (fs_enc, "utf-8"):
try:
return path.decode(enc)
... | python | {
"resource": ""
} |
q276416 | _escape_argspec | test | def _escape_argspec(obj, iterable, escape):
"""Helper for various string-wrapped functions."""
for key, value in iterable:
if hasattr(value, '__html__') or isinstance(value, string_types):
obj[key] = escape(value)
return obj | python | {
"resource": ""
} |
q276417 | codecName | test | def codecName(encoding):
"""Return the python codec name corresponding to an encoding or None if the
string doesn't correspond to a valid encoding."""
if isinstance(encoding, bytes):
try:
encoding = encoding.decode("ascii")
except UnicodeDecodeError:
return None
i... | python | {
"resource": ""
} |
q276418 | HTMLBinaryInputStream.detectBOM | test | def detectBOM(self):
"""Attempts to detect at BOM at the start of the stream. If
an encoding can be determined from the BOM return the name of the
encoding otherwise return None"""
bomDict = {
codecs.BOM_UTF8: 'utf-8',
codecs.BOM_UTF16_LE: 'utf-16-le', codecs.BOM_... | python | {
"resource": ""
} |
q276419 | ProxyFix.get_remote_addr | test | def get_remote_addr(self, forwarded_for):
"""Selects the new remote addr from the given list of ips in
X-Forwarded-For. By default it picks the one that the `num_proxies`
proxy server provides. Before 0.9 it would always pick the first.
.. versionadded:: 0.8
"""
if len... | python | {
"resource": ""
} |
q276420 | amount_converter | test | def amount_converter(obj):
"""Converts amount value from several types into Decimal."""
if isinstance(obj, Decimal):
return obj
elif isinstance(obj, (str, int, float)):
return Decimal(str(obj))
else:
raise ValueError('do not know how to convert: {}'.format(type(obj))) | python | {
"resource": ""
} |
q276421 | fromstring | test | def fromstring(data, beautifulsoup=None, makeelement=None, **bsargs):
"""Parse a string of HTML data into an Element tree using the
BeautifulSoup parser.
Returns the root ``<html>`` Element of the tree.
You can pass a different BeautifulSoup parser through the
`beautifulsoup` keyword, and a diffen... | python | {
"resource": ""
} |
q276422 | parse | test | def parse(file, beautifulsoup=None, makeelement=None, **bsargs):
"""Parse a file into an ElemenTree using the BeautifulSoup parser.
You can pass a different BeautifulSoup parser through the
`beautifulsoup` keyword, and a diffent Element factory function
through the `makeelement` keyword. By default, t... | python | {
"resource": ""
} |
q276423 | convert_tree | test | def convert_tree(beautiful_soup_tree, makeelement=None):
"""Convert a BeautifulSoup tree to a list of Element trees.
Returns a list instead of a single root Element to support
HTML-like soup with more than one root element.
You can pass a different Element factory through the `makeelement`
keyword... | python | {
"resource": ""
} |
q276424 | get_current_traceback | test | def get_current_traceback(ignore_system_exceptions=False,
show_hidden_frames=False, skip=0):
"""Get the current exception info as `Traceback` object. Per default
calling this method will reraise system exceptions such as generator exit,
system exit or others. This behavior can be... | python | {
"resource": ""
} |
q276425 | Traceback.exception | test | def exception(self):
"""String representation of the exception."""
buf = traceback.format_exception_only(self.exc_type, self.exc_value)
rv = ''.join(buf).strip()
return rv.decode('utf-8', 'replace') if PY2 else rv | python | {
"resource": ""
} |
q276426 | Traceback.render_summary | test | def render_summary(self, include_title=True):
"""Render the traceback for the interactive console."""
title = ''
frames = []
classes = ['traceback']
if not self.frames:
classes.append('noframe-traceback')
if include_title:
if self.is_syntax_error:... | python | {
"resource": ""
} |
q276427 | Traceback.generate_plaintext_traceback | test | def generate_plaintext_traceback(self):
"""Like the plaintext attribute but returns a generator"""
yield u'Traceback (most recent call last):'
for frame in self.frames:
yield u' File "%s", line %s, in %s' % (
frame.filename,
frame.lineno,
... | python | {
"resource": ""
} |
q276428 | Frame.get_annotated_lines | test | def get_annotated_lines(self):
"""Helper function that returns lines with extra information."""
lines = [Line(idx + 1, x) for idx, x in enumerate(self.sourcelines)]
# find function definition and mark lines
if hasattr(self.code, 'co_firstlineno'):
lineno = self.code.co_first... | python | {
"resource": ""
} |
q276429 | Frame.render_source | test | def render_source(self):
"""Render the sourcecode."""
return SOURCE_TABLE_HTML % u'\n'.join(line.render() for line in
self.get_annotated_lines()) | python | {
"resource": ""
} |
q276430 | egg_info_matches | test | def egg_info_matches(
egg_info, search_name, link,
_egg_info_re=re.compile(r'([a-z0-9_.]+)-([a-z0-9_.!+-]+)', re.I)):
"""Pull the version part out of a string.
:param egg_info: The string to parse. E.g. foo-2.1
:param search_name: The name of the package this belongs to. None to
inf... | python | {
"resource": ""
} |
q276431 | PackageFinder._get_index_urls_locations | test | def _get_index_urls_locations(self, project_name):
"""Returns the locations found via self.index_urls
Checks the url_name on the main (first in the list) index and
use this url_name to produce all locations
"""
def mkurl_pypi_url(url):
loc = posixpath.join(url, proj... | python | {
"resource": ""
} |
q276432 | PackageFinder._find_all_versions | test | def _find_all_versions(self, project_name):
"""Find all available versions for project_name
This checks index_urls, find_links and dependency_links
All versions found are returned
See _link_package_versions for details on which files are accepted
"""
index_locations = s... | python | {
"resource": ""
} |
q276433 | PackageFinder.find_requirement | test | def find_requirement(self, req, upgrade):
"""Try to find an InstallationCandidate for req
Expects req, an InstallRequirement and upgrade, a boolean
Returns an InstallationCandidate or None
May raise DistributionNotFound or BestVersionAlreadyInstalled
"""
all_versions = s... | python | {
"resource": ""
} |
q276434 | PackageFinder._sort_links | test | def _sort_links(self, links):
"""
Returns elements of links in order, non-egg links first, egg links
second, while eliminating duplicates
"""
eggs, no_eggs = [], []
seen = set()
for link in links:
if link not in seen:
seen.add(link)
... | python | {
"resource": ""
} |
q276435 | HTMLPage._get_content_type | test | def _get_content_type(url, session):
"""Get the Content-Type of the given url, using a HEAD request"""
scheme, netloc, path, query, fragment = urllib_parse.urlsplit(url)
if scheme not in ('http', 'https'):
# FIXME: some warning or something?
# assertion error?
... | python | {
"resource": ""
} |
q276436 | HTMLPage.links | test | def links(self):
"""Yields all links in the page"""
for anchor in self.parsed.findall(".//a"):
if anchor.get("href"):
href = anchor.get("href")
url = self.clean_link(
urllib_parse.urljoin(self.base_url, href)
)
... | python | {
"resource": ""
} |
q276437 | Link.verifiable | test | def verifiable(self):
"""
Returns True if this link can be verified after download, False if it
cannot, and None if we cannot determine.
"""
trusted = self.trusted or getattr(self.comes_from, "trusted", None)
if trusted is not None and trusted:
# This link cam... | python | {
"resource": ""
} |
q276438 | build_py.find_data_files | test | def find_data_files(self, package, src_dir):
"""Return filenames for package's data files in 'src_dir'"""
globs = (self.package_data.get('', [])
+ self.package_data.get(package, []))
files = self.manifest_files.get(package, [])[:]
for pattern in globs:
# Each... | python | {
"resource": ""
} |
q276439 | build_py.exclude_data_files | test | def exclude_data_files(self, package, src_dir, files):
"""Filter filenames for package's data files in 'src_dir'"""
globs = (self.exclude_package_data.get('', [])
+ self.exclude_package_data.get(package, []))
bad = []
for pattern in globs:
bad.extend(
... | python | {
"resource": ""
} |
q276440 | parse_requirements | test | def parse_requirements(filename, finder=None, comes_from=None, options=None,
session=None, wheel_cache=None):
"""
Parse a requirements file and yield InstallRequirement instances.
:param filename: Path or url of requirements file.
:param finder: Instance of pip.index.Pack... | python | {
"resource": ""
} |
q276441 | join_lines | test | def join_lines(iterator):
"""
Joins a line ending in '\' with the previous line.
"""
lines = []
for line in iterator:
if not line.endswith('\\'):
if lines:
lines.append(line)
yield ''.join(lines)
lines = []
else:
... | python | {
"resource": ""
} |
q276442 | ignore_comments | test | def ignore_comments(iterator):
"""
Strips and filters empty or commented lines.
"""
for line in iterator:
line = COMMENT_RE.sub('', line)
line = line.strip()
if line:
yield line | python | {
"resource": ""
} |
q276443 | compile | test | def compile(marker):
"""Return compiled marker as a function accepting an environment dict."""
try:
return _cache[marker]
except KeyError:
pass
if not marker.strip():
def marker_fn(environment=None, override=None):
""""""
return True
else:
comp... | python | {
"resource": ""
} |
q276444 | ASTWhitelist.visit | test | def visit(self, node):
"""Ensure statement only contains allowed nodes."""
if not isinstance(node, self.ALLOWED):
raise SyntaxError('Not allowed in environment markers.\n%s\n%s' %
(self.statement,
(' ' * node.col_offset) + '^'))
... | python | {
"resource": ""
} |
q276445 | ASTWhitelist.visit_Attribute | test | def visit_Attribute(self, node):
"""Flatten one level of attribute access."""
new_node = ast.Name("%s.%s" % (node.value.id, node.attr), node.ctx)
return ast.copy_location(new_node, node) | python | {
"resource": ""
} |
q276446 | coerce | test | def coerce(value):
"""
coerce takes a value and attempts to convert it to a float,
or int.
If none of the conversions are successful, the original value is
returned.
>>> coerce('3')
3
>>> coerce('3.0')
3.0
>>> coerce('foo')
'foo'
>>> coerce({})
{}
>>> coerce('{}')
'{}'
"""
with contextlib2.suppre... | python | {
"resource": ""
} |
q276447 | copy_current_request_context | test | def copy_current_request_context(f):
"""A helper function that decorates a function to retain the current
request context. This is useful when working with greenlets. The moment
the function is decorated a copy of the request context is created and
then pushed when the function is called.
Example... | python | {
"resource": ""
} |
q276448 | AppContext.push | test | def push(self):
"""Binds the app context to the current context."""
self._refcnt += 1
_app_ctx_stack.push(self)
appcontext_pushed.send(self.app) | python | {
"resource": ""
} |
q276449 | AppContext.pop | test | def pop(self, exc=None):
"""Pops the app context."""
self._refcnt -= 1
if self._refcnt <= 0:
if exc is None:
exc = sys.exc_info()[1]
self.app.do_teardown_appcontext(exc)
rv = _app_ctx_stack.pop()
assert rv is self, 'Popped wrong app context... | python | {
"resource": ""
} |
q276450 | RequestContext.copy | test | def copy(self):
"""Creates a copy of this request context with the same request object.
This can be used to move a request context to a different greenlet.
Because the actual request object is the same this cannot be used to
move a request context to a different thread unless access to t... | python | {
"resource": ""
} |
q276451 | RequestContext.match_request | test | def match_request(self):
"""Can be overridden by a subclass to hook into the matching
of the request.
"""
try:
url_rule, self.request.view_args = \
self.url_adapter.match(return_rule=True)
self.request.url_rule = url_rule
except HTTPExcepti... | python | {
"resource": ""
} |
q276452 | RequestContext.push | test | def push(self):
"""Binds the request context to the current context."""
# If an exception occurs in debug mode or if context preservation is
# activated under exception situations exactly one context stays
# on the stack. The rationale is that you want to access that
# informati... | python | {
"resource": ""
} |
q276453 | make_path_relative | test | def make_path_relative(path, rel_to):
"""
Make a filename relative, where the filename path, and it is
relative to rel_to
>>> make_path_relative('/usr/share/something/a-file.pth',
... '/usr/share/another-place/src/Directory')
'../../../something/a-file.pth'
... | python | {
"resource": ""
} |
q276454 | dist_is_editable | test | def dist_is_editable(dist):
"""Is distribution an editable install?"""
# TODO: factor out determining editableness out of FrozenRequirement
from pip import FrozenRequirement
req = FrozenRequirement.from_dist(dist, [])
return req.editable | python | {
"resource": ""
} |
q276455 | Blueprint.url_value_preprocessor | test | def url_value_preprocessor(self, f):
"""Registers a function as URL value preprocessor for this
blueprint. It's called before the view functions are called and
can modify the url values provided.
"""
self.record_once(lambda s: s.app.url_value_preprocessors
.setdefaul... | python | {
"resource": ""
} |
q276456 | Blueprint.url_defaults | test | def url_defaults(self, f):
"""Callback function for URL defaults for this blueprint. It's called
with the endpoint and values and should update the values passed
in place.
"""
self.record_once(lambda s: s.app.url_default_functions
.setdefault(self.name, []).append(f)... | python | {
"resource": ""
} |
q276457 | Blueprint.errorhandler | test | def errorhandler(self, code_or_exception):
"""Registers an error handler that becomes active for this blueprint
only. Please be aware that routing does not happen local to a
blueprint so an error handler for 404 usually is not handled by
a blueprint unless it is caused inside a view fun... | python | {
"resource": ""
} |
q276458 | stream_with_context | test | def stream_with_context(generator_or_function):
"""Request contexts disappear when the response is started on the server.
This is done for efficiency reasons and to make it less likely to encounter
memory leaks with badly written WSGI middlewares. The downside is that if
you are using streamed response... | python | {
"resource": ""
} |
q276459 | make_response | test | def make_response(*args):
"""Sometimes it is necessary to set additional headers in a view. Because
views do not have to return response objects but can return a value that
is converted into a response object by Flask itself, it becomes tricky to
add headers to it. This function can be called instead ... | python | {
"resource": ""
} |
q276460 | url_for | test | def url_for(endpoint, **values):
"""Generates a URL to the given endpoint with the method provided.
Variable arguments that are unknown to the target endpoint are appended
to the generated URL as query arguments. If the value of a query argument
is `None`, the whole pair is skipped. In case blueprint... | python | {
"resource": ""
} |
q276461 | safe_join | test | def safe_join(directory, filename):
"""Safely join `directory` and `filename`.
Example usage::
@app.route('/wiki/<path:filename>')
def wiki_page(filename):
filename = safe_join(app.config['WIKI_FOLDER'], filename)
with open(filename, 'rb') as fd:
content... | python | {
"resource": ""
} |
q276462 | get_root_path | test | def get_root_path(import_name):
"""Returns the path to a package or cwd if that cannot be found. This
returns the path of a package or the folder that contains a module.
Not to be confused with the package path returned by :func:`find_package`.
"""
# Module already imported and has a file attribut... | python | {
"resource": ""
} |
q276463 | _PackageBoundObject.jinja_loader | test | def jinja_loader(self):
"""The Jinja loader for this package bound object.
.. versionadded:: 0.5
"""
if self.template_folder is not None:
return FileSystemLoader(os.path.join(self.root_path,
self.template_folder)) | python | {
"resource": ""
} |
q276464 | CompletionCommand.run | test | def run(self, options, args):
"""Prints the completion code of the given shell"""
shells = COMPLETION_SCRIPTS.keys()
shell_options = ['--' + shell for shell in sorted(shells)]
if options.shell in shells:
script = COMPLETION_SCRIPTS.get(options.shell, '')
print(BAS... | python | {
"resource": ""
} |
q276465 | SessionInterface.get_cookie_domain | test | def get_cookie_domain(self, app):
"""Helpful helper method that returns the cookie domain that should
be used for the session cookie if session cookies are used.
"""
if app.config['SESSION_COOKIE_DOMAIN'] is not None:
return app.config['SESSION_COOKIE_DOMAIN']
if app.... | python | {
"resource": ""
} |
q276466 | _cache_for_link | test | def _cache_for_link(cache_dir, link):
"""
Return a directory to store cached wheels in for link.
Because there are M wheels for any one sdist, we provide a directory
to cache them in, and then consult that directory when looking up
cache hits.
We only insert things into the cache if they have ... | python | {
"resource": ""
} |
q276467 | root_is_purelib | test | def root_is_purelib(name, wheeldir):
"""
Return True if the extracted wheel in wheeldir should go into purelib.
"""
name_folded = name.replace("-", "_")
for item in os.listdir(wheeldir):
match = dist_info_re.match(item)
if match and match.group('name') == name_folded:
wit... | python | {
"resource": ""
} |
q276468 | uninstallation_paths | test | def uninstallation_paths(dist):
"""
Yield all the uninstallation paths for dist based on RECORD-without-.pyc
Yield paths to all the files in RECORD. For each .py file in RECORD, add
the .pyc in the same directory.
UninstallPathSet.add() takes care of the __pycache__ .pyc.
"""
from pip.util... | python | {
"resource": ""
} |
q276469 | check_compatibility | test | def check_compatibility(version, name):
"""
Raises errors or warns if called with an incompatible Wheel-Version.
Pip should refuse to install a Wheel-Version that's a major series
ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when
installing a version only minor version ahead (e.g 1.... | python | {
"resource": ""
} |
q276470 | WheelBuilder._build_one | test | def _build_one(self, req, output_dir):
"""Build one wheel.
:return: The filename of the built wheel, or None if the build failed.
"""
tempd = tempfile.mkdtemp('pip-wheel-')
try:
if self.__build_one(req, tempd):
try:
wheel_name = os... | python | {
"resource": ""
} |
q276471 | iter_symbols | test | def iter_symbols(code):
"""Yield names and strings used by `code` and its nested code objects"""
for name in code.co_names:
yield name
for const in code.co_consts:
if isinstance(const, basestring):
yield const
elif isinstance(const, CodeType):
for name in iter... | python | {
"resource": ""
} |
q276472 | ensure_fresh_rates | test | def ensure_fresh_rates(func):
"""Decorator for Backend that ensures rates are fresh within last 5 mins"""
def wrapper(self, *args, **kwargs):
if self.last_updated + timedelta(minutes=5) < zulu.now():
self.refresh()
return func(self, *args, **kwargs)
return wrapper | python | {
"resource": ""
} |
q276473 | manifest_maker._add_egg_info | test | def _add_egg_info(self, cmd):
"""
Add paths for egg-info files for an external egg-base.
The egg-info files are written to egg-base. If egg-base is
outside the current working directory, this method
searchs the egg-base directory for files to include
in the manifest. Use... | python | {
"resource": ""
} |
q276474 | write_delete_marker_file | test | def write_delete_marker_file(directory):
"""
Write the pip delete marker file into this directory.
"""
filepath = os.path.join(directory, PIP_DELETE_MARKER_FILENAME)
with open(filepath, 'w') as marker_fp:
marker_fp.write(DELETE_MARKER_MESSAGE) | python | {
"resource": ""
} |
q276475 | running_under_virtualenv | test | def running_under_virtualenv():
"""
Return True if we're running inside a virtualenv, False otherwise.
"""
if hasattr(sys, 'real_prefix'):
return True
elif sys.prefix != getattr(sys, "base_prefix", sys.prefix):
return True
return False | python | {
"resource": ""
} |
q276476 | __get_username | test | def __get_username():
""" Returns the effective username of the current process. """
if WINDOWS:
return getpass.getuser()
import pwd
return pwd.getpwuid(os.geteuid()).pw_name | python | {
"resource": ""
} |
q276477 | distutils_scheme | test | def distutils_scheme(dist_name, user=False, home=None, root=None,
isolated=False):
"""
Return a distutils install scheme
"""
from distutils.dist import Distribution
scheme = {}
if isolated:
extra_dist_args = {"script_args": ["--no-user-cfg"]}
else:
extr... | python | {
"resource": ""
} |
q276478 | CacheController.parse_cache_control | test | def parse_cache_control(self, headers):
"""
Parse the cache control headers returning a dictionary with values
for the different directives.
"""
retval = {}
cc_header = 'cache-control'
if 'Cache-Control' in headers:
cc_header = 'Cache-Control'
... | python | {
"resource": ""
} |
q276479 | CacheController.cached_request | test | def cached_request(self, request):
"""
Return a cached response if it exists in the cache, otherwise
return False.
"""
cache_url = self.cache_url(request.url)
cc = self.parse_cache_control(request.headers)
# non-caching states
no_cache = True if 'no-cache... | python | {
"resource": ""
} |
q276480 | CacheController.cache_response | test | def cache_response(self, request, response, body=None):
"""
Algorithm for caching requests.
This assumes a requests Response object.
"""
# From httplib2: Don't cache 206's since we aren't going to
# handle byte range requests
if response.status not... | python | {
"resource": ""
} |
q276481 | _update_zipimporter_cache | test | def _update_zipimporter_cache(normalized_path, cache, updater=None):
"""
Update zipimporter cache data for a given normalized path.
Any sub-path entries are processed as well, i.e. those corresponding to zip
archives embedded in other zip archives.
Given updater is a callable taking a cache entry ... | python | {
"resource": ""
} |
q276482 | easy_install._load_template | test | def _load_template(dev_path):
"""
There are a couple of template scripts in the package. This
function loads one of them and prepares it for use.
"""
# See https://bitbucket.org/pypa/setuptools/issue/134 for info
# on script file naming and downstream issues with SVR4
... | python | {
"resource": ""
} |
q276483 | easy_install.install_site_py | test | def install_site_py(self):
"""Make sure there's a site.py in the target dir, if needed"""
if self.sitepy_installed:
return # already did it, or don't need to
sitepy = os.path.join(self.install_dir, "site.py")
source = resource_string("setuptools", "site-patch.py")
... | python | {
"resource": ""
} |
q276484 | PthDistributions.save | test | def save(self):
"""Write changed .pth file back to disk"""
if not self.dirty:
return
data = '\n'.join(map(self.make_relative, self.paths))
if data:
log.debug("Saving %s", self.filename)
data = (
"import sys; sys.__plen = len(sys.path)\... | python | {
"resource": ""
} |
q276485 | BaseConfigurator.convert | test | def convert(self, value):
"""
Convert values to an appropriate type. dicts, lists and tuples are
replaced by their converting alternatives. Strings are checked to
see if they have a conversion format and are converted if they do.
"""
if not isinstance(value, ConvertingDic... | python | {
"resource": ""
} |
q276486 | DictConfigurator.add_filters | test | def add_filters(self, filterer, filters):
"""Add filters to a filterer from a list of names."""
for f in filters:
try:
filterer.addFilter(self.config['filters'][f])
except StandardError as e:
raise ValueError('Unable to add filter %r: %s' % (f, e)) | python | {
"resource": ""
} |
q276487 | DictConfigurator.configure_handler | test | def configure_handler(self, config):
"""Configure a handler from a dictionary."""
formatter = config.pop('formatter', None)
if formatter:
try:
formatter = self.config['formatters'][formatter]
except StandardError as e:
raise ValueError('Una... | python | {
"resource": ""
} |
q276488 | DictConfigurator.add_handlers | test | def add_handlers(self, logger, handlers):
"""Add handlers to a logger from a list of names."""
for h in handlers:
try:
logger.addHandler(self.config['handlers'][h])
except StandardError as e:
raise ValueError('Unable to add handler %r: %s' % (h, e)... | python | {
"resource": ""
} |
q276489 | DictConfigurator.common_logger_config | test | def common_logger_config(self, logger, config, incremental=False):
"""
Perform configuration which is common to root and non-root loggers.
"""
level = config.get('level', None)
if level is not None:
logger.setLevel(_checkLevel(level))
if not incremental:
... | python | {
"resource": ""
} |
q276490 | _execfile | test | def _execfile(filename, globals, locals=None):
"""
Python 3 implementation of execfile.
"""
mode = 'rb'
with open(filename, mode) as stream:
script = stream.read()
# compile() function in Python 2.6 and 3.1 requires LF line endings.
if sys.version_info[:2] < (2, 7) or sys.version_inf... | python | {
"resource": ""
} |
q276491 | override_temp | test | def override_temp(replacement):
"""
Monkey-patch tempfile.tempdir with replacement, ensuring it exists
"""
if not os.path.isdir(replacement):
os.makedirs(replacement)
saved = tempfile.tempdir
tempfile.tempdir = replacement
try:
yield
finally:
tempfile.tempdir =... | python | {
"resource": ""
} |
q276492 | Git.get_url_rev | test | def get_url_rev(self):
"""
Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
That's required because although they use SSH they sometimes doesn't
work with a ssh:// scheme (e.g. Github). But we need a scheme for
parsing. Hence we remove it again afterwards and ... | python | {
"resource": ""
} |
q276493 | Environment.getitem | test | def getitem(self, obj, argument):
"""Get an item or attribute of an object but prefer the item."""
try:
return obj[argument]
except (TypeError, LookupError):
if isinstance(argument, string_types):
try:
attr = str(argument)
... | python | {
"resource": ""
} |
q276494 | Environment._generate | test | def _generate(self, source, name, filename, defer_init=False):
"""Internal hook that can be overridden to hook a different generate
method in.
.. versionadded:: 2.5
"""
return generate(source, self, name, filename, defer_init=defer_init) | python | {
"resource": ""
} |
q276495 | Environment.compile_templates | test | def compile_templates(self, target, extensions=None, filter_func=None,
zip='deflated', log_function=None,
ignore_errors=True, py_compile=False):
"""Finds all the templates the loader can find, compiles them
and stores them in `target`. If `zip` is `No... | python | {
"resource": ""
} |
q276496 | get_default_cache | test | def get_default_cache():
"""Determine the default cache location
This returns the ``PYTHON_EGG_CACHE`` environment variable, if set.
Otherwise, on Windows, it returns a "Python-Eggs" subdirectory of the
"Application Data" directory. On all other systems, it's "~/.python-eggs".
"""
try:
... | python | {
"resource": ""
} |
q276497 | find_eggs_in_zip | test | def find_eggs_in_zip(importer, path_item, only=False):
"""
Find eggs in zip files; possibly multiple nested eggs.
"""
if importer.archive.endswith('.whl'):
# wheels are not supported with this finder
# they don't have PKG-INFO metadata, and won't ever contain eggs
return
meta... | python | {
"resource": ""
} |
q276498 | find_on_path | test | def find_on_path(importer, path_item, only=False):
"""Yield distributions accessible on a sys.path directory"""
path_item = _normalize_cached(path_item)
if os.path.isdir(path_item) and os.access(path_item, os.R_OK):
if path_item.lower().endswith('.egg'):
# unpacked egg
yield... | python | {
"resource": ""
} |
q276499 | declare_namespace | test | def declare_namespace(packageName):
"""Declare that package 'packageName' is a namespace package"""
imp.acquire_lock()
try:
if packageName in _namespace_packages:
return
path, parent = sys.path, None
if '.' in packageName:
parent = '.'.join(packageName.split... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.