desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Returns true if a message at this level will go to stdout'
| def stdout_level_matches(self, level):
| return self.level_matches(level, self._stdout_level())
|
'Returns the level that stdout runs at'
| def _stdout_level(self):
| for (level, consumer) in self.consumers:
if (consumer is sys.stdout):
return level
return self.FATAL
|
'>>> l = Logger()
>>> l.level_matches(3, 4)
False
>>> l.level_matches(3, 2)
True
>>> l.level_matches(slice(None, 3), 3)
False
>>> l.level_matches(slice(None, 3), 2)
True
>>> l.level_matches(slice(1, 3), 1)
True
>>> l.level_matches(slice(2, 3), 1)
False'
| def level_matches(self, level, consumer_level):
| if isinstance(level, slice):
(start, stop) = (level.start, level.stop)
if ((start is not None) and (start > consumer_level)):
return False
if ((stop is not None) or (stop <= consumer_level)):
return False
return True
else:
return (level >= consumer... |
'Sort locations into "files" (archives) and "urls", and return
a pair of lists (files,urls)'
| def _sort_locations(self, locations):
| files = []
urls = []
def sort_path(path):
url = path_to_url(path)
if (mimetypes.guess_type(url, strict=False)[0] == 'text/html'):
urls.append(url)
else:
files.append(url)
for url in locations:
is_local_path = os.path.exists(url)
is_file_url... |
'Function used to generate link sort key for link tuples.
The greater the return value, the more preferred it is.
If not finding wheels, then sorted by version only.
If finding wheels, then the sort order is by version, then:
1. existing installs
2. wheels ordered via Wheel.support_index_min()
3. source archives
Note: ... | def _link_sort_key(self, link_tuple):
| (parsed_version, link, _) = link_tuple
if self.use_wheel:
support_num = len(supported_tags)
if (link == INSTALLED_VERSION):
pri = 1
elif (link.ext == wheel_ext):
wheel = Wheel(link.filename)
if (not wheel.supported()):
raise Unsupported... |
'Bring the latest version (and wheels) to the front, but maintain the existing ordering as secondary.
See the docstring for `_link_sort_key` for details.
This function is isolated for easier unit testing.'
| def _sort_versions(self, applicable_versions):
| return sorted(applicable_versions, key=self._link_sort_key, reverse=True)
|
'Finds the true URL name of a package, when the given name isn\'t quite correct.
This is usually used to implement case-insensitivity.'
| def _find_url_name(self, index_url, url_name, req):
| if (not index_url.url.endswith('/')):
index_url.url += '/'
page = self._get_page(index_url, req)
if (page is None):
logger.fatal(('Cannot fetch index base URL %s' % index_url))
return
norm_name = normalize_name(req.url_name)
for link in page.links:
base... |
'Yields (page, page_url) from the given locations, skipping
locations that have errors, and adding download/homepage links'
| def _get_pages(self, locations, req):
| all_locations = list(locations)
seen = set()
while all_locations:
location = all_locations.pop(0)
if (location in seen):
continue
seen.add(location)
page = self._get_page(location, req)
if (page is None):
continue
(yield page)
f... |
'Returns elements of links in order, non-egg links first, egg links second, while eliminating duplicates'
| def _sort_links(self, links):
| (eggs, no_eggs) = ([], [])
seen = set()
for link in links:
if (link not in seen):
seen.add(link)
if link.egg_fragment:
eggs.append(link)
else:
no_eggs.append(link)
return (no_eggs + eggs)
|
'Return an iterable of triples (pkg_resources_version_key,
link, python_version) that can be extracted from the given
link.
Meant to be overridden by subclasses, not called by clients.'
| def _link_package_versions(self, link, search_name):
| platform = get_platform()
version = None
if link.egg_fragment:
egg_info = link.egg_fragment
else:
(egg_info, ext) = link.splitext()
if (not ext):
if (link not in self.logged_links):
logger.debug(('Skipping link %s; not a file' % link))
... |
'Get the Content-Type of the given url, using a HEAD request'
| @staticmethod
def _get_content_type(url, session=None):
| if (session is None):
session = PipSession()
(scheme, netloc, path, query, fragment) = urlparse.urlsplit(url)
if (not (scheme in ('http', 'https', 'ftp', 'ftps'))):
return ''
resp = session.head(url, allow_redirects=True)
resp.raise_for_status()
return resp.headers.get('Content-T... |
'Yields all links in the page'
| @property
def links(self):
| for anchor in self.parsed.findall('.//a'):
if anchor.get('href'):
href = anchor.get('href')
url = self.clean_link(urlparse.urljoin(self.base_url, href))
internal = None
if (self.api_version and (self.api_version >= 2)):
internal = bool((anchor.... |
'Yields all links with the given relations'
| def explicit_rel_links(self, rels=('homepage', 'download')):
| rels = set(rels)
for anchor in self.parsed.findall('.//a'):
if (anchor.get('rel') and anchor.get('href')):
found_rels = set(anchor.get('rel').split())
if (found_rels & rels):
href = anchor.get('href')
url = self.clean_link(urlparse.urljoin(self.bas... |
'Makes sure a link is fully encoded. That is, if a \' \' shows up in
the link, it will be rewritten to %20 (while not over-quoting
% or other characters).'
| def clean_link(self, url):
| return self._clean_re.sub((lambda match: ('%%%2x' % ord(match.group(0)))), url)
|
'Returns True if this link can be verified after download, False if it
cannot, and None if we cannot determine.'
| @property
def verifiable(self):
| trusted = (self.trusted or getattr(self.comes_from, 'trusted', None))
if ((trusted is not None) and trusted):
try:
api_version = getattr(self.comes_from, 'api_version', None)
api_version = int(api_version)
except (ValueError, TypeError):
api_version = None
... |
'Create a package finder appropriate to this install command.
This method is meant to be overridden by subclasses, not
called directly.'
| def _build_package_finder(self, options, index_urls, session):
| return PackageFinder(find_links=options.find_links, index_urls=index_urls, use_wheel=options.use_wheel, allow_external=options.allow_external, allow_unverified=options.allow_unverified, allow_all_external=options.allow_all_external, allow_all_prereleases=options.pre, process_dependency_links=options.process_depende... |
'Prints the completion code of the given shell'
| def run(self, options, args):
| shells = COMPLETION_SCRIPTS.keys()
shell_options = [('--' + shell) for shell in sorted(shells)]
if (options.shell in shells):
script = COMPLETION_SCRIPTS.get(options.shell, '')
print (BASE_COMPLETION % {'script': script, 'shell': options.shell})
else:
sys.stderr.write(('ERROR: ... |
'Create a package finder appropriate to this list command.'
| def _build_package_finder(self, options, index_urls, session):
| return PackageFinder(find_links=options.find_links, index_urls=index_urls, allow_external=options.allow_external, allow_unverified=options.allow_unverified, allow_all_external=options.allow_all_external, allow_all_prereleases=options.pre, process_dependency_links=options.process_dependency_links, session=session)
|
'All the entries of sys.path, possibly restricted by --path'
| def paths(self):
| if (not self.select_paths):
return sys.path
result = []
match_any = set()
for path in sys.path:
path = os.path.normcase(os.path.abspath(path))
for match in self.select_paths:
match = os.path.normcase(os.path.abspath(match))
if ('*' in match):
... |
'Return the name of the version control backend if found at given
location, e.g. vcs.get_backend_name(\'/path/to/vcs/checkout\')'
| def get_backend_name(self, location):
| for vc_type in self._registry.values():
path = os.path.join(location, vc_type.dirname)
if os.path.exists(path):
return vc_type.name
return None
|
'posix absolute paths start with os.path.sep,
win32 ones ones start with drive (like c:\folder)'
| def _is_local_repository(self, repo):
| (drive, tail) = os.path.splitdrive(repo)
return (repo.startswith(os.path.sep) or drive)
|
'Returns the correct repository URL and revision by parsing the given
repository URL'
| def get_url_rev(self):
| error_message = "Sorry, '%s' is a malformed VCS url. The format is <vcs>+<protocol>://<url>, e.g. svn+http://myrepo/svn/MyApp#egg=MyApp"
assert ('+' in self.url), (error_message % self.url)
url = self.url.split('+', 1)[1]
(scheme, netloc, path, query, frag) = urlparse... |
'Returns (url, revision), where both are strings'
| def get_info(self, location):
| assert (not location.rstrip('/').endswith(self.dirname)), ('Bad directory: %s' % location)
return (self.get_url(location), self.get_revision(location))
|
'Normalize a URL for comparison by unquoting it and removing any trailing slash.'
| def normalize_url(self, url):
| return urllib.unquote(url).rstrip('/')
|
'Compare two repo URLs for identity, ignoring incidental differences.'
| def compare_urls(self, url1, url2):
| return (self.normalize_url(url1) == self.normalize_url(url2))
|
'Takes the contents of the bundled text file that explains how to revert
the stripped off version control data of the given package and returns
the URL and revision of it.'
| def parse_vcs_bundle_file(self, content):
| raise NotImplementedError
|
'Called when installing or updating an editable package, takes the
source path of the checkout.'
| def obtain(self, dest):
| raise NotImplementedError
|
'Switch the repo at ``dest`` to point to ``URL``.'
| def switch(self, dest, url, rev_options):
| raise NotImplemented
|
'Update an already-existing repo to the given ``rev_options``.'
| def update(self, dest, rev_options):
| raise NotImplementedError
|
'Prepare a location to receive a checkout/clone.
Return True if the location is ready for (and requires) a
checkout/clone, False otherwise.'
| def check_destination(self, dest, url, rev_options, rev_display):
| checkout = True
prompt = False
if os.path.exists(dest):
checkout = False
if os.path.exists(os.path.join(dest, self.dirname)):
existing_url = self.get_url(dest)
if self.compare_urls(existing_url, url):
logger.info(('%s in %s exists, and h... |
'Export the Hg repository at the url to the destination location'
| def export(self, location):
| temp_dir = tempfile.mkdtemp('-export', 'pip-')
self.unpack(temp_dir)
try:
call_subprocess([self.cmd, 'archive', location], filter_stdout=self._filter, show_stdout=False, cwd=temp_dir)
finally:
rmtree(temp_dir)
|
'Returns (url, revision), where both are strings'
| def get_info(self, location):
| assert (not location.rstrip('/').endswith(self.dirname)), ('Bad directory: %s' % location)
output = call_subprocess([self.cmd, 'info', location], show_stdout=False, extra_environ={'LANG': 'C'})
match = _svn_url_re.search(output)
if (not match):
logger.warn(('Cannot determine URL o... |
'Export the svn repository at the url to the destination location'
| def export(self, location):
| (url, rev) = self.get_url_rev()
rev_options = get_rev_options(url, rev)
logger.notify(('Exporting svn repository %s to %s' % (url, location)))
logger.indent += 2
try:
if os.path.exists(location):
rmtree(location)
call_subprocess((([self.cmd, 'export'] + rev... |
'Return the maximum revision for all files under a given location'
| def get_revision(self, location):
| revision = 0
for (base, dirs, files) in os.walk(location):
if (self.dirname not in dirs):
dirs[:] = []
continue
dirs.remove(self.dirname)
entries_fn = os.path.join(base, self.dirname, 'entries')
if (not os.path.exists(entries_fn)):
continue
... |
'Export the Bazaar repository at the url to the destination location'
| def export(self, location):
| temp_dir = tempfile.mkdtemp('-export', 'pip-')
self.unpack(temp_dir)
if os.path.exists(location):
rmtree(location)
try:
call_subprocess([self.cmd, 'export', location], cwd=temp_dir, filter_stdout=self._filter, show_stdout=False)
finally:
rmtree(temp_dir)
|
'Export the Git repository at the url to the destination location'
| def export(self, location):
| temp_dir = tempfile.mkdtemp('-export', 'pip-')
self.unpack(temp_dir)
try:
if (not location.endswith('/')):
location = (location + '/')
call_subprocess([self.cmd, 'checkout-index', '-a', '-f', '--prefix', location], filter_stdout=self._filter, show_stdout=False, cwd=temp_dir)
... |
'Check the revision options before checkout to compensate that tags
and branches may need origin/ as a prefix.
Returns the SHA1 of the branch or tag if found.'
| def check_rev_options(self, rev, dest, rev_options):
| revisions = self.get_refs(dest)
origin_rev = ('origin/%s' % rev)
if (origin_rev in revisions):
return [revisions[origin_rev]]
elif (rev in revisions):
return [revisions[rev]]
else:
logger.warn(("Could not find a tag or branch '%s', assuming commit."... |
'Return map of named refs (branches or tags) to commit hashes.'
| def get_refs(self, location):
| output = call_subprocess([self.cmd, 'show-ref'], show_stdout=False, cwd=location)
rv = {}
for line in output.strip().splitlines():
(commit, ref) = line.split(' ', 1)
ref = ref.strip()
ref_name = None
if ref.startswith('refs/remotes/'):
ref_name = ref[len('refs/... |
'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 return it as a stub.'
| def get_url_rev(self):
| if (not ('://' in self.url)):
assert (not ('file:' in self.url))
self.url = self.url.replace('git+', 'git+ssh://')
(url, rev) = super(Git, self).get_url_rev()
url = url.replace('ssh://', '')
else:
(url, rev) = super(Git, self).get_url_rev()
return (url, rev)
|
'cookielib has no legitimate use for this method; add it back if you find one.'
| def add_header(self, key, val):
| raise NotImplementedError('Cookie headers should be added with add_unredirected_header()')
|
'Make a MockResponse for `cookielib` to read.
:param headers: a httplib.HTTPMessage or analogous carrying the headers'
| def __init__(self, headers):
| self._headers = headers
|
'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. Caution: operation is O(n), not O(1).'
| 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 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):
| if (value is None):
remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))
return
if isinstance(value, Morsel):
c = morsel_to_cookie(value)
else:
c = create_cookie(name, value, **kwargs)
self.set_cookie(c)
return c
|
'Dict-like iterkeys() that returns an iterator of names of cookies from the jar.
See itervalues() and iteritems().'
| def iterkeys(self):
| for cookie in iter(self):
(yield cookie.name)
|
'Dict-like keys() that returns a list of names of cookies from the jar.
See values() and items().'
| def keys(self):
| return list(self.iterkeys())
|
'Dict-like itervalues() that returns an iterator of values of cookies from the jar.
See iterkeys() and iteritems().'
| def itervalues(self):
| for cookie in iter(self):
(yield cookie.value)
|
'Dict-like values() that returns a list of values of cookies from the jar.
See keys() and items().'
| def values(self):
| return list(self.itervalues())
|
'Dict-like iteritems() that returns an iterator of name-value tuples from the jar.
See iterkeys() and itervalues().'
| def iteritems(self):
| for cookie in iter(self):
(yield (cookie.name, cookie.value))
|
'Dict-like items() that returns a list of name-value tuples from the jar.
See keys() and values(). Allows client-code to call "dict(RequestsCookieJar)
and get a vanilla python dict of key value pairs.'
| def items(self):
| return list(self.iteritems())
|
'Utility method to list all the domains in the jar.'
| 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 paths in the jar.'
| def list_paths(self):
| 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):
| 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
|
'Takes as an argument an optional domain and path and returns a plain old
Python dict of name-value pairs of cookies that meet the requirements.'
| def get_dict(self, domain=None, path=None):
| dictionary = {}
for cookie in iter(self):
if (((domain is None) or (cookie.domain == domain)) and ((path is None) or (cookie.path == path))):
dictionary[cookie.name] = cookie.value
return dictionary
|
'Dict-like __getitem__() for compatibility with client code. Throws exception
if there are more than one cookie with name. In that case, use the more
explicit get() method instead. Caution: operation is O(n), not O(1).'
| def __getitem__(self, name):
| return self._find_no_duplicates(name)
|
'Dict-like __setitem__ for compatibility with client code. Throws exception
if there is already a cookie of that name in the jar. In that case, use the more
explicit set() method instead.'
| def __setitem__(self, name, value):
| self.set(name, value)
|
'Deletes a cookie given a name. Wraps cookielib.CookieJar\'s remove_cookie_by_name().'
| def __delitem__(self, name):
| remove_cookie_by_name(self, name)
|
'Updates this jar with cookies from another CookieJar or dict-like'
| def update(self, other):
| if isinstance(other, cookielib.CookieJar):
for cookie in other:
self.set_cookie(cookie)
else:
super(RequestsCookieJar, self).update(other)
|
'Requests uses this method internally to get cookie values. Takes as args name
and optional domain and path. Returns a cookie.value. If there are conflicting cookies,
_find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown
if there are conflicting cookies.'
| 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)):
return cookie.value
raise KeyError(('name=%r, domain=%r, path=%r' % (name, domain, path)))
|
'__get_item__ and get call _find_no_duplicates -- never used in Requests internally.
Takes as args name and optional domain and path. Returns a cookie.value.
Throws KeyError if cookie is not found and CookieConflictError if there are
multiple cookies that match name and optionally domain and path.'
| 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.path == path)):
if (toReturn is not None):
raise CookieConflictError(('There ar... |
'Unlike a normal CookieJar, this class is pickleable.'
| def __getstate__(self):
| state = self.__dict__.copy()
state.pop('_cookies_lock')
return state
|
'Unlike a normal CookieJar, this class is pickleable.'
| def __setstate__(self, state):
| self.__dict__.update(state)
if ('_cookies_lock' not in self.__dict__):
self._cookies_lock = threading.RLock()
|
'Return a copy of this RequestsCookieJar.'
| def copy(self):
| new_cj = RequestsCookieJar()
new_cj.update(self)
return new_cj
|
'reset analyser, clear any state'
| def reset(self):
| self._mDone = False
self._mTotalChars = 0
self._mFreqChars = 0
|
'feed a character with known length'
| def feed(self, aBuf, aCharLen):
| if (aCharLen == 2):
order = self.get_order(aBuf)
else:
order = (-1)
if (order >= 0):
self._mTotalChars += 1
if (order < self._mTableSize):
if (512 > self._mCharToFreqOrder[order]):
self._mFreqChars += 1
|
'return confidence based on existing data'
| def get_confidence(self):
| if ((self._mTotalChars <= 0) or (self._mFreqChars <= MINIMUM_DATA_THRESHOLD)):
return SURE_NO
if (self._mTotalChars != self._mFreqChars):
r = (self._mFreqChars / ((self._mTotalChars - self._mFreqChars) * self._mTypicalDistributionRatio))
if (r < SURE_YES):
return r
return... |
'Should we redirect and where to?
:returns: Truthy redirect location string if we got a redirect status
code and valid location. ``None`` if redirect status and no
location. ``False`` if not a redirect status code.'
| def get_redirect_location(self):
| if (self.status in self.REDIRECT_STATUSES):
return self.headers.get('location')
return False
|
'Obtain the number of bytes pulled over the wire so far. May differ from
the amount of content returned by :meth:``HTTPResponse.read`` if bytes
are encoded on the wire (e.g, compressed).'
| def tell(self):
| return self._fp_bytes_read
|
'Similar to :meth:`httplib.HTTPResponse.read`, but with two additional
parameters: ``decode_content`` and ``cache_content``.
:param amt:
How much of the content to read. If specified, caching is skipped
because it doesn\'t make sense to cache partial content as the full
response.
:param decode_content:
If True, will at... | def read(self, amt=None, decode_content=None, cache_content=False):
| content_encoding = self.headers.get('content-encoding', '').lower()
if (self._decoder is None):
if (content_encoding in self.CONTENT_DECODERS):
self._decoder = _get_decoder(content_encoding)
if (decode_content is None):
decode_content = self.decode_content
if (self._fp is Non... |
'A generator wrapper for the read() method. A call will block until
``amt`` bytes have been read from the connection or until the
connection is closed.
:param amt:
How much of the content to read. The generator will return up to
much data per iteration, but may return less. This is particularly
likely when using compre... | def stream(self, amt=(2 ** 16), decode_content=None):
| while (not is_fp_closed(self._fp)):
data = self.read(amt=amt, decode_content=decode_content)
if data:
(yield data)
|
'Given an :class:`httplib.HTTPResponse` instance ``r``, return a
corresponding :class:`urllib3.response.HTTPResponse` object.
Remaining parameters are passed to the HTTPResponse constructor, along
with ``original_response=r``.'
| @classmethod
def from_httplib(ResponseCls, r, **response_kw):
| headers = HTTPHeaderDict()
for (k, v) in r.getheaders():
headers.add(k, v)
strict = getattr(r, 'strict', 0)
return ResponseCls(body=r, headers=headers, status=r.status, version=r.version, reason=r.reason, strict=strict, original_response=r, **response_kw)
|
'Create a new :class:`ConnectionPool` based on host, port and scheme.
This method is used to actually create the connection pools handed out
by :meth:`connection_from_url` and companion methods. It is intended
to be overridden for customization.'
| def _new_pool(self, scheme, host, port):
| pool_cls = pool_classes_by_scheme[scheme]
kwargs = self.connection_pool_kw
if (scheme == 'http'):
kwargs = self.connection_pool_kw.copy()
for kw in SSL_KEYWORDS:
kwargs.pop(kw, None)
return pool_cls(host, port, **kwargs)
|
'Empty our store of pools and direct them all to close.
This will not affect in-flight connections, but they will not be
re-used after completion.'
| def clear(self):
| self.pools.clear()
|
'Get a :class:`ConnectionPool` based on the host, port, and scheme.
If ``port`` isn\'t given, it will be derived from the ``scheme`` using
``urllib3.connectionpool.port_by_scheme``.'
| def connection_from_host(self, host, port=None, scheme='http'):
| scheme = (scheme or 'http')
port = (port or port_by_scheme.get(scheme, 80))
pool_key = (scheme, host, port)
with self.pools.lock:
pool = self.pools.get(pool_key)
if pool:
return pool
pool = self._new_pool(scheme, host, port)
self.pools[pool_key] = pool
ret... |
'Similar to :func:`urllib3.connectionpool.connection_from_url` but
doesn\'t pass any additional parameters to the
:class:`urllib3.connectionpool.ConnectionPool` constructor.
Additional parameters are taken from the :class:`.PoolManager`
constructor.'
| def connection_from_url(self, url):
| u = parse_url(url)
return self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
|
'Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`
with custom cross-host redirect logic and only sends the request-uri
portion of the ``url``.
The given ``url`` parameter must be absolute, such that an appropriate
:class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.'
| def urlopen(self, method, url, redirect=True, **kw):
| u = parse_url(url)
conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
kw['assert_same_host'] = False
kw['redirect'] = False
if ('headers' not in kw):
kw['headers'] = self.headers
if ((self.proxy is not None) and (u.scheme == 'http')):
response = conn.urlopen(m... |
'Sets headers needed by proxies: specifically, the Accept and Host
headers. Only sets headers not provided by the user.'
| def _set_proxy_headers(self, url, headers=None):
| headers_ = {'Accept': '*/*'}
netloc = parse_url(url).netloc
if netloc:
headers_['Host'] = netloc
if headers:
headers_.update(headers)
return headers_
|
'Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute.'
| def urlopen(self, method, url, redirect=True, **kw):
| u = parse_url(url)
if (u.scheme == 'http'):
kw['headers'] = self._set_proxy_headers(url, kw.get('headers', self.headers))
return super(ProxyManager, self).urlopen(method, url, redirect, **kw)
|
'Initialize an ordered dictionary. Signature is the same as for
regular dictionaries, but keyword arguments are not recommended
because their insertion order is arbitrary.'
| def __init__(self, *args, **kwds):
| if (len(args) > 1):
raise TypeError(('expected at most 1 arguments, got %d' % len(args)))
try:
self.__root
except AttributeError:
self.__root = root = []
root[:] = [root, root, None]
self.__map = {}
self.__update(*args, **kwds)
|
'od.__setitem__(i, y) <==> od[i]=y'
| def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
| if (key not in self):
root = self.__root
last = root[0]
last[1] = root[0] = self.__map[key] = [last, root, key]
dict_setitem(self, key, value)
|
'od.__delitem__(y) <==> del od[y]'
| def __delitem__(self, key, dict_delitem=dict.__delitem__):
| dict_delitem(self, key)
(link_prev, link_next, key) = self.__map.pop(key)
link_prev[1] = link_next
link_next[0] = link_prev
|
'od.__iter__() <==> iter(od)'
| def __iter__(self):
| root = self.__root
curr = root[1]
while (curr is not root):
(yield curr[2])
curr = curr[1]
|
'od.__reversed__() <==> reversed(od)'
| def __reversed__(self):
| root = self.__root
curr = root[0]
while (curr is not root):
(yield curr[2])
curr = curr[0]
|
'od.clear() -> None. Remove all items from od.'
| def clear(self):
| try:
for node in self.__map.itervalues():
del node[:]
root = self.__root
root[:] = [root, root, None]
self.__map.clear()
except AttributeError:
pass
dict.clear(self)
|
'od.popitem() -> (k, v), return and remove a (key, value) pair.
Pairs are returned in LIFO order if last is true or FIFO order if false.'
| def popitem(self, last=True):
| if (not self):
raise KeyError('dictionary is empty')
root = self.__root
if last:
link = root[0]
link_prev = link[0]
link_prev[1] = root
root[0] = link_prev
else:
link = root[1]
link_next = link[1]
root[1] = link_next
link_next... |
'od.keys() -> list of keys in od'
| def keys(self):
| return list(self)
|
'od.values() -> list of values in od'
| def values(self):
| return [self[key] for key in self]
|
'od.items() -> list of (key, value) pairs in od'
| def items(self):
| return [(key, self[key]) for key in self]
|
'od.iterkeys() -> an iterator over the keys in od'
| def iterkeys(self):
| return iter(self)
|
'od.itervalues -> an iterator over the values in od'
| def itervalues(self):
| for k in self:
(yield self[k])
|
'od.iteritems -> an iterator over the (key, value) items in od'
| def iteritems(self):
| for k in self:
(yield (k, self[k]))
|
'od.update(E, **F) -> None. Update od from dict/iterable E and F.
If E is a dict instance, does: for k in E: od[k] = E[k]
If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]
Or if E is an iterable of items, does: for k, v in E: od[k] = v
In either case, this is followed by: for k, ... | def update(*args, **kwds):
| if (len(args) > 2):
raise TypeError(('update() takes at most 2 positional arguments (%d given)' % (len(args),)))
elif (not args):
raise TypeError('update() takes at least 1 argument (0 given)')
self = args[0]
other = ()
if (len(args) == 2)... |
'od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised.'
| def pop(self, key, default=__marker):
| if (key in self):
result = self[key]
del self[key]
return result
if (default is self.__marker):
raise KeyError(key)
return default
|
'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
| def setdefault(self, key, default=None):
| if (key in self):
return self[key]
self[key] = default
return default
|
'od.__repr__() <==> repr(od)'
| def __repr__(self, _repr_running={}):
| call_key = (id(self), _get_ident())
if (call_key in _repr_running):
return '...'
_repr_running[call_key] = 1
try:
if (not self):
return ('%s()' % (self.__class__.__name__,))
return ('%s(%r)' % (self.__class__.__name__, self.items()))
finally:
del _repr_run... |
'Return state information for pickling'
| def __reduce__(self):
| items = [[k, self[k]] for k in self]
inst_dict = vars(self).copy()
for k in vars(OrderedDict()):
inst_dict.pop(k, None)
if inst_dict:
return (self.__class__, (items,), inst_dict)
return (self.__class__, (items,))
|
'od.copy() -> a shallow copy of od'
| def copy(self):
| return self.__class__(self)
|
'OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
and values equal to v (which defaults to None).'
| @classmethod
def fromkeys(cls, iterable, value=None):
| d = cls()
for key in iterable:
d[key] = value
return d
|
'od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
while comparison to a regular mapping is order-insensitive.'
| def __eq__(self, other):
| if isinstance(other, OrderedDict):
return ((len(self) == len(other)) and (self.items() == other.items()))
return dict.__eq__(self, other)
|
'od.viewkeys() -> a set-like object providing a view on od\'s keys'
| def viewkeys(self):
| return KeysView(self)
|
'od.viewvalues() -> an object providing a view on od\'s values'
| def viewvalues(self):
| return ValuesView(self)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.