nwo
stringlengths
10
28
sha
stringlengths
40
40
path
stringlengths
11
97
identifier
stringlengths
1
64
parameters
stringlengths
2
2.24k
return_statement
stringlengths
0
2.17k
docstring
stringlengths
0
5.45k
docstring_summary
stringlengths
0
3.83k
func_begin
int64
1
13.4k
func_end
int64
2
13.4k
function
stringlengths
28
56.4k
url
stringlengths
106
209
project
int64
1
48
executed_lines
list
executed_lines_pc
float64
0
153
missing_lines
list
missing_lines_pc
float64
0
100
covered
bool
2 classes
filecoverage
float64
2.53
100
function_lines
int64
2
1.46k
mccabe
int64
1
253
coverage
float64
0
100
docstring_lines
int64
0
112
function_nodoc
stringlengths
9
56.4k
id
int64
0
29.8k
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar.keys
(self)
return list(self.iterkeys())
Dict-like keys() that returns a list of names of cookies from the jar. .. seealso:: values() and items().
Dict-like keys() that returns a list of names of cookies from the jar.
234
240
def keys(self): """Dict-like keys() that returns a list of names of cookies from the jar. .. seealso:: values() and items(). """ return list(self.iterkeys())
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L234-L240
33
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
77.824268
7
1
100
4
def keys(self): return list(self.iterkeys())
22,185
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar.itervalues
(self)
Dict-like itervalues() that returns an iterator of values of cookies from the jar. .. seealso:: iterkeys() and iteritems().
Dict-like itervalues() that returns an iterator of values of cookies from the jar.
242
249
def itervalues(self): """Dict-like itervalues() that returns an iterator of values of cookies from the jar. .. seealso:: iterkeys() and iteritems(). """ for cookie in iter(self): yield cookie.value
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L242-L249
33
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
77.824268
8
2
100
4
def itervalues(self): for cookie in iter(self): yield cookie.value
22,186
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar.values
(self)
return list(self.itervalues())
Dict-like values() that returns a list of values of cookies from the jar. .. seealso:: keys() and items().
Dict-like values() that returns a list of values of cookies from the jar.
251
257
def values(self): """Dict-like values() that returns a list of values of cookies from the jar. .. seealso:: keys() and items(). """ return list(self.itervalues())
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L251-L257
33
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
77.824268
7
1
100
4
def values(self): return list(self.itervalues())
22,187
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar.iteritems
(self)
Dict-like iteritems() that returns an iterator of name-value tuples from the jar. .. seealso:: iterkeys() and itervalues().
Dict-like iteritems() that returns an iterator of name-value tuples from the jar.
259
266
def iteritems(self): """Dict-like iteritems() that returns an iterator of name-value tuples from the jar. .. seealso:: iterkeys() and itervalues(). """ for cookie in iter(self): yield cookie.name, cookie.value
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L259-L266
33
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
77.824268
8
2
100
4
def iteritems(self): for cookie in iter(self): yield cookie.name, cookie.value
22,188
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar.items
(self)
return list(self.iteritems())
Dict-like items() that returns a list of name-value tuples from the jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a vanilla python dict of key value pairs. .. seealso:: keys() and values().
Dict-like items() that returns a list of name-value tuples from the jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a vanilla python dict of key value pairs.
268
275
def items(self): """Dict-like items() that returns a list of name-value tuples from the jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a vanilla python dict of key value pairs. .. seealso:: keys() and values(). """ return list(self.iteritems())
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L268-L275
33
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
77.824268
8
1
100
5
def items(self): return list(self.iteritems())
22,189
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar.list_domains
(self)
return domains
Utility method to list all the domains in the jar.
Utility method to list all the domains in the jar.
277
283
def list_domains(self): """Utility method to list all the domains in the jar.""" domains = [] for cookie in iter(self): if cookie.domain not in domains: domains.append(cookie.domain) return domains
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L277-L283
33
[ 0, 1 ]
28.571429
[ 2, 3, 4, 5, 6 ]
71.428571
false
77.824268
7
3
28.571429
1
def list_domains(self): domains = [] for cookie in iter(self): if cookie.domain not in domains: domains.append(cookie.domain) return domains
22,190
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar.list_paths
(self)
return paths
Utility method to list all the paths in the jar.
Utility method to list all the paths in the jar.
285
291
def list_paths(self): """Utility method to list all the paths in the jar.""" paths = [] for cookie in iter(self): if cookie.path not in paths: paths.append(cookie.path) return paths
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L285-L291
33
[ 0, 1 ]
28.571429
[ 2, 3, 4, 5, 6 ]
71.428571
false
77.824268
7
3
28.571429
1
def list_paths(self): paths = [] for cookie in iter(self): if cookie.path not in paths: paths.append(cookie.path) return paths
22,191
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar.multiple_domains
(self)
return False
Returns True if there are multiple domains in the jar. Returns False otherwise. :rtype: bool
Returns True if there are multiple domains in the jar. Returns False otherwise.
293
304
def multiple_domains(self): """Returns True if there are multiple domains in the jar. Returns False otherwise. :rtype: bool """ domains = [] for cookie in iter(self): if cookie.domain is not None and cookie.domain in domains: return True domains.append(cookie.domain) return False
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L293-L304
33
[ 0, 1, 2, 3, 4, 5 ]
50
[ 6, 7, 8, 9, 10, 11 ]
50
false
77.824268
12
4
50
4
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
22,192
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar.get_dict
(self, domain=None, path=None)
return dictionary
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. :rtype: dict
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.
306
319
def get_dict(self, domain=None, path=None): """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. :rtype: dict """ 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
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L306-L319
33
[ 0, 1, 2, 3, 4, 5, 6 ]
50
[ 7, 8, 9, 12, 13 ]
35.714286
false
77.824268
14
6
64.285714
5
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
22,193
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar.__contains__
(self, name)
321
325
def __contains__(self, name): try: return super().__contains__(name) except CookieConflictError: return True
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L321-L325
33
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
77.824268
5
2
100
0
def __contains__(self, name): try: return super().__contains__(name) except CookieConflictError: return True
22,194
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar.__getitem__
(self, name)
return self._find_no_duplicates(name)
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. .. warning:: operation is O(n), not O(1).
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.
327
334
def __getitem__(self, name): """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. .. warning:: operation is O(n), not O(1). """ return self._find_no_duplicates(name)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L327-L334
33
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
77.824268
8
1
100
5
def __getitem__(self, name): return self._find_no_duplicates(name)
22,195
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar.__setitem__
(self, name, value)
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.
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.
336
341
def __setitem__(self, name, value): """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. """ self.set(name, value)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L336-L341
33
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
77.824268
6
1
100
3
def __setitem__(self, name, value): self.set(name, value)
22,196
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar.__delitem__
(self, name)
Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s ``remove_cookie_by_name()``.
Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s ``remove_cookie_by_name()``.
343
347
def __delitem__(self, name): """Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s ``remove_cookie_by_name()``. """ remove_cookie_by_name(self, name)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L343-L347
33
[ 0, 1, 2, 3 ]
80
[ 4 ]
20
false
77.824268
5
1
80
2
def __delitem__(self, name): remove_cookie_by_name(self, name)
22,197
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar.set_cookie
(self, cookie, *args, **kwargs)
return super().set_cookie(cookie, *args, **kwargs)
349
356
def set_cookie(self, cookie, *args, **kwargs): if ( hasattr(cookie.value, "startswith") and cookie.value.startswith('"') and cookie.value.endswith('"') ): cookie.value = cookie.value.replace('\\"', "") return super().set_cookie(cookie, *args, **kwargs)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L349-L356
33
[ 0, 1, 6, 7 ]
50
[]
0
false
77.824268
8
4
100
0
def set_cookie(self, cookie, *args, **kwargs): if ( hasattr(cookie.value, "startswith") and cookie.value.startswith('"') and cookie.value.endswith('"') ): cookie.value = cookie.value.replace('\\"', "") return super().set_cookie(cookie, *args, **kwargs)
22,198
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar.update
(self, other)
Updates this jar with cookies from another CookieJar or dict-like
Updates this jar with cookies from another CookieJar or dict-like
358
364
def update(self, other): """Updates this jar with cookies from another CookieJar or dict-like""" if isinstance(other, cookielib.CookieJar): for cookie in other: self.set_cookie(copy.copy(cookie)) else: super().update(other)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L358-L364
33
[ 0, 1, 2, 3, 4, 5 ]
85.714286
[ 6 ]
14.285714
false
77.824268
7
3
85.714286
1
def update(self, other): if isinstance(other, cookielib.CookieJar): for cookie in other: self.set_cookie(copy.copy(cookie)) else: super().update(other)
22,199
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar._find
(self, name, domain=None, path=None)
Requests uses this method internally to get cookie values. If there are conflicting cookies, _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown if there are conflicting cookies. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :return: cookie.value
Requests uses this method internally to get cookie values.
366
384
def _find(self, name, domain=None, path=None): """Requests uses this method internally to get cookie values. If there are conflicting cookies, _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown if there are conflicting cookies. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :return: cookie.value """ 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(f"name={name!r}, domain={domain!r}, path={path!r}")
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L366-L384
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
63.157895
[ 12, 13, 14, 15, 16, 18 ]
31.578947
false
77.824268
19
7
68.421053
10
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(f"name={name!r}, domain={domain!r}, path={path!r}")
22,200
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar._find_no_duplicates
(self, name, domain=None, path=None)
Both ``__get_item__`` and ``get`` call this function: it's never used elsewhere in Requests. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :raises KeyError: if cookie is not found :raises CookieConflictError: if there are multiple cookies that match name and optionally domain and path :return: cookie.value
Both ``__get_item__`` and ``get`` call this function: it's never used elsewhere in Requests.
386
413
def _find_no_duplicates(self, name, domain=None, path=None): """Both ``__get_item__`` and ``get`` call this function: it's never used elsewhere in Requests. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :raises KeyError: if cookie is not found :raises CookieConflictError: if there are multiple cookies that match name and optionally domain and path :return: cookie.value """ 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: # if there are multiple cookies that meet passed in criteria raise CookieConflictError( f"There are multiple cookies with name, {name!r}" ) # we will eventually return this as long as no cookie conflict toReturn = cookie.value if toReturn: return toReturn raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L386-L413
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 ]
100
[]
0
true
77.824268
28
9
100
10
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: # if there are multiple cookies that meet passed in criteria raise CookieConflictError( f"There are multiple cookies with name, {name!r}" ) # we will eventually return this as long as no cookie conflict toReturn = cookie.value if toReturn: return toReturn raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")
22,201
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar.__getstate__
(self)
return state
Unlike a normal CookieJar, this class is pickleable.
Unlike a normal CookieJar, this class is pickleable.
415
420
def __getstate__(self): """Unlike a normal CookieJar, this class is pickleable.""" state = self.__dict__.copy() # remove the unpickleable RLock object state.pop("_cookies_lock") return state
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L415-L420
33
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
77.824268
6
1
100
1
def __getstate__(self): state = self.__dict__.copy() # remove the unpickleable RLock object state.pop("_cookies_lock") return state
22,202
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar.__setstate__
(self, state)
Unlike a normal CookieJar, this class is pickleable.
Unlike a normal CookieJar, this class is pickleable.
422
426
def __setstate__(self, state): """Unlike a normal CookieJar, this class is pickleable.""" self.__dict__.update(state) if "_cookies_lock" not in self.__dict__: self._cookies_lock = threading.RLock()
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L422-L426
33
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
77.824268
5
2
100
1
def __setstate__(self, state): self.__dict__.update(state) if "_cookies_lock" not in self.__dict__: self._cookies_lock = threading.RLock()
22,203
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar.copy
(self)
return new_cj
Return a copy of this RequestsCookieJar.
Return a copy of this RequestsCookieJar.
428
433
def copy(self): """Return a copy of this RequestsCookieJar.""" new_cj = RequestsCookieJar() new_cj.set_policy(self.get_policy()) new_cj.update(self) return new_cj
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L428-L433
33
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
77.824268
6
1
100
1
def copy(self): new_cj = RequestsCookieJar() new_cj.set_policy(self.get_policy()) new_cj.update(self) return new_cj
22,204
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/cookies.py
RequestsCookieJar.get_policy
(self)
return self._policy
Return the CookiePolicy instance used.
Return the CookiePolicy instance used.
435
437
def get_policy(self): """Return the CookiePolicy instance used.""" return self._policy
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/cookies.py#L435-L437
33
[ 0, 1, 2 ]
100
[]
0
true
77.824268
3
1
100
1
def get_policy(self): return self._policy
22,205
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/adapters.py
BaseAdapter.__init__
(self)
74
75
def __init__(self): super().__init__()
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/adapters.py#L74-L75
33
[ 0, 1 ]
100
[]
0
true
92.592593
2
1
100
0
def __init__(self): super().__init__()
22,206
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/adapters.py
BaseAdapter.send
( self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None )
Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request content. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: (optional) Any user-provided SSL certificate to be trusted. :param proxies: (optional) The proxies dictionary to apply to the request.
Sends PreparedRequest object. Returns Response object.
77
94
def send( self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None ): """Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request content. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: (optional) Any user-provided SSL certificate to be trusted. :param proxies: (optional) The proxies dictionary to apply to the request. """ raise NotImplementedError
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/adapters.py#L77-L94
33
[ 0 ]
5.555556
[ 17 ]
5.555556
false
92.592593
18
1
94.444444
13
def send( self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None ): raise NotImplementedError
22,207
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/adapters.py
BaseAdapter.close
(self)
Cleans up adapter specific items.
Cleans up adapter specific items.
96
98
def close(self): """Cleans up adapter specific items.""" raise NotImplementedError
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/adapters.py#L96-L98
33
[ 0, 1 ]
66.666667
[ 2 ]
33.333333
false
92.592593
3
1
66.666667
1
def close(self): raise NotImplementedError
22,208
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/adapters.py
HTTPAdapter.__init__
( self, pool_connections=DEFAULT_POOLSIZE, pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES, pool_block=DEFAULT_POOLBLOCK, )
136
156
def __init__( self, pool_connections=DEFAULT_POOLSIZE, pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES, pool_block=DEFAULT_POOLBLOCK, ): if max_retries == DEFAULT_RETRIES: self.max_retries = Retry(0, read=False) else: self.max_retries = Retry.from_int(max_retries) self.config = {} self.proxy_manager = {} super().__init__() self._pool_connections = pool_connections self._pool_maxsize = pool_maxsize self._pool_block = pool_block self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/adapters.py#L136-L156
33
[ 0, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]
66.666667
[]
0
false
92.592593
21
2
100
0
def __init__( self, pool_connections=DEFAULT_POOLSIZE, pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES, pool_block=DEFAULT_POOLBLOCK, ): if max_retries == DEFAULT_RETRIES: self.max_retries = Retry(0, read=False) else: self.max_retries = Retry.from_int(max_retries) self.config = {} self.proxy_manager = {} super().__init__() self._pool_connections = pool_connections self._pool_maxsize = pool_maxsize self._pool_block = pool_block self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)
22,209
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/adapters.py
HTTPAdapter.__getstate__
(self)
return {attr: getattr(self, attr, None) for attr in self.__attrs__}
158
159
def __getstate__(self): return {attr: getattr(self, attr, None) for attr in self.__attrs__}
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/adapters.py#L158-L159
33
[ 0, 1 ]
100
[]
0
true
92.592593
2
1
100
0
def __getstate__(self): return {attr: getattr(self, attr, None) for attr in self.__attrs__}
22,210
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/adapters.py
HTTPAdapter.__setstate__
(self, state)
161
172
def __setstate__(self, state): # Can't handle by adding 'proxy_manager' to self.__attrs__ because # self.poolmanager uses a lambda function, which isn't pickleable. self.proxy_manager = {} self.config = {} for attr, value in state.items(): setattr(self, attr, value) self.init_poolmanager( self._pool_connections, self._pool_maxsize, block=self._pool_block )
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/adapters.py#L161-L172
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
83.333333
[]
0
false
92.592593
12
2
100
0
def __setstate__(self, state): # Can't handle by adding 'proxy_manager' to self.__attrs__ because # self.poolmanager uses a lambda function, which isn't pickleable. self.proxy_manager = {} self.config = {} for attr, value in state.items(): setattr(self, attr, value) self.init_poolmanager( self._pool_connections, self._pool_maxsize, block=self._pool_block )
22,211
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/adapters.py
HTTPAdapter.init_poolmanager
( self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs )
Initializes a urllib3 PoolManager. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param connections: The number of urllib3 connection pools to cache. :param maxsize: The maximum number of connections to save in the pool. :param block: Block when no free connections are available. :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.
Initializes a urllib3 PoolManager.
174
199
def init_poolmanager( self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs ): """Initializes a urllib3 PoolManager. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param connections: The number of urllib3 connection pools to cache. :param maxsize: The maximum number of connections to save in the pool. :param block: Block when no free connections are available. :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager. """ # save these values for pickling self._pool_connections = connections self._pool_maxsize = maxsize self._pool_block = block self.poolmanager = PoolManager( num_pools=connections, maxsize=maxsize, block=block, strict=True, **pool_kwargs, )
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/adapters.py#L174-L199
33
[ 0, 14, 15, 16, 17, 18, 19 ]
26.923077
[]
0
false
92.592593
26
1
100
10
def init_poolmanager( self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs ): # save these values for pickling self._pool_connections = connections self._pool_maxsize = maxsize self._pool_block = block self.poolmanager = PoolManager( num_pools=connections, maxsize=maxsize, block=block, strict=True, **pool_kwargs, )
22,212
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/adapters.py
HTTPAdapter.proxy_manager_for
(self, proxy, **proxy_kwargs)
return manager
Return urllib3 ProxyManager for the given proxy. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The proxy to return a urllib3 ProxyManager for. :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager. :returns: ProxyManager :rtype: urllib3.ProxyManager
Return urllib3 ProxyManager for the given proxy.
201
237
def proxy_manager_for(self, proxy, **proxy_kwargs): """Return urllib3 ProxyManager for the given proxy. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The proxy to return a urllib3 ProxyManager for. :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager. :returns: ProxyManager :rtype: urllib3.ProxyManager """ if proxy in self.proxy_manager: manager = self.proxy_manager[proxy] elif proxy.lower().startswith("socks"): username, password = get_auth_from_url(proxy) manager = self.proxy_manager[proxy] = SOCKSProxyManager( proxy, username=username, password=password, num_pools=self._pool_connections, maxsize=self._pool_maxsize, block=self._pool_block, **proxy_kwargs, ) else: proxy_headers = self.proxy_headers(proxy) manager = self.proxy_manager[proxy] = proxy_from_url( proxy, proxy_headers=proxy_headers, num_pools=self._pool_connections, maxsize=self._pool_maxsize, block=self._pool_block, **proxy_kwargs, ) return manager
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/adapters.py#L201-L237
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36 ]
97.297297
[ 13 ]
2.702703
false
92.592593
37
3
97.297297
10
def proxy_manager_for(self, proxy, **proxy_kwargs): if proxy in self.proxy_manager: manager = self.proxy_manager[proxy] elif proxy.lower().startswith("socks"): username, password = get_auth_from_url(proxy) manager = self.proxy_manager[proxy] = SOCKSProxyManager( proxy, username=username, password=password, num_pools=self._pool_connections, maxsize=self._pool_maxsize, block=self._pool_block, **proxy_kwargs, ) else: proxy_headers = self.proxy_headers(proxy) manager = self.proxy_manager[proxy] = proxy_from_url( proxy, proxy_headers=proxy_headers, num_pools=self._pool_connections, maxsize=self._pool_maxsize, block=self._pool_block, **proxy_kwargs, ) return manager
22,213
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/adapters.py
HTTPAdapter.cert_verify
(self, conn, url, verify, cert)
Verify a SSL certificate. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param conn: The urllib3 connection object associated with the cert. :param url: The requested URL. :param verify: Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: The SSL certificate to verify.
Verify a SSL certificate. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
239
294
def cert_verify(self, conn, url, verify, cert): """Verify a SSL certificate. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param conn: The urllib3 connection object associated with the cert. :param url: The requested URL. :param verify: Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: The SSL certificate to verify. """ if url.lower().startswith("https") and verify: cert_loc = None # Allow self-specified cert location. if verify is not True: cert_loc = verify if not cert_loc: cert_loc = extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH) if not cert_loc or not os.path.exists(cert_loc): raise OSError( f"Could not find a suitable TLS CA certificate bundle, " f"invalid path: {cert_loc}" ) conn.cert_reqs = "CERT_REQUIRED" if not os.path.isdir(cert_loc): conn.ca_certs = cert_loc else: conn.ca_cert_dir = cert_loc else: conn.cert_reqs = "CERT_NONE" conn.ca_certs = None conn.ca_cert_dir = None if cert: if not isinstance(cert, basestring): conn.cert_file = cert[0] conn.key_file = cert[1] else: conn.cert_file = cert conn.key_file = None if conn.cert_file and not os.path.exists(conn.cert_file): raise OSError( f"Could not find the TLS certificate file, " f"invalid path: {conn.cert_file}" ) if conn.key_file and not os.path.exists(conn.key_file): raise OSError( f"Could not find the TLS key file, invalid path: {conn.key_file}" )
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/adapters.py#L239-L294
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55 ]
98.214286
[ 34 ]
1.785714
false
92.592593
56
14
98.214286
10
def cert_verify(self, conn, url, verify, cert): if url.lower().startswith("https") and verify: cert_loc = None # Allow self-specified cert location. if verify is not True: cert_loc = verify if not cert_loc: cert_loc = extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH) if not cert_loc or not os.path.exists(cert_loc): raise OSError( f"Could not find a suitable TLS CA certificate bundle, " f"invalid path: {cert_loc}" ) conn.cert_reqs = "CERT_REQUIRED" if not os.path.isdir(cert_loc): conn.ca_certs = cert_loc else: conn.ca_cert_dir = cert_loc else: conn.cert_reqs = "CERT_NONE" conn.ca_certs = None conn.ca_cert_dir = None if cert: if not isinstance(cert, basestring): conn.cert_file = cert[0] conn.key_file = cert[1] else: conn.cert_file = cert conn.key_file = None if conn.cert_file and not os.path.exists(conn.cert_file): raise OSError( f"Could not find the TLS certificate file, " f"invalid path: {conn.cert_file}" ) if conn.key_file and not os.path.exists(conn.key_file): raise OSError( f"Could not find the TLS key file, invalid path: {conn.key_file}" )
22,214
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/adapters.py
HTTPAdapter.build_response
(self, req, resp)
return response
Builds a :class:`Response <requests.Response>` object from a urllib3 response. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>` :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response. :param resp: The urllib3 response object. :rtype: requests.Response
Builds a :class:`Response <requests.Response>` object from a urllib3 response. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`
296
331
def build_response(self, req, resp): """Builds a :class:`Response <requests.Response>` object from a urllib3 response. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>` :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response. :param resp: The urllib3 response object. :rtype: requests.Response """ response = Response() # Fallback to None if there's no status_code, for whatever reason. response.status_code = getattr(resp, "status", None) # Make headers case-insensitive. response.headers = CaseInsensitiveDict(getattr(resp, "headers", {})) # Set encoding. response.encoding = get_encoding_from_headers(response.headers) response.raw = resp response.reason = response.raw.reason if isinstance(req.url, bytes): response.url = req.url.decode("utf-8") else: response.url = req.url # Add new cookies from the server. extract_cookies_to_jar(response.cookies, req, resp) # Give the Response some context. response.request = req response.connection = self return response
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/adapters.py#L296-L331
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35 ]
97.222222
[ 24 ]
2.777778
false
92.592593
36
2
97.222222
8
def build_response(self, req, resp): response = Response() # Fallback to None if there's no status_code, for whatever reason. response.status_code = getattr(resp, "status", None) # Make headers case-insensitive. response.headers = CaseInsensitiveDict(getattr(resp, "headers", {})) # Set encoding. response.encoding = get_encoding_from_headers(response.headers) response.raw = resp response.reason = response.raw.reason if isinstance(req.url, bytes): response.url = req.url.decode("utf-8") else: response.url = req.url # Add new cookies from the server. extract_cookies_to_jar(response.cookies, req, resp) # Give the Response some context. response.request = req response.connection = self return response
22,215
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/adapters.py
HTTPAdapter.get_connection
(self, url, proxies=None)
return conn
Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param url: The URL to connect to. :param proxies: (optional) A Requests-style dictionary of proxies used on this request. :rtype: urllib3.ConnectionPool
Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
333
360
def get_connection(self, url, proxies=None): """Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param url: The URL to connect to. :param proxies: (optional) A Requests-style dictionary of proxies used on this request. :rtype: urllib3.ConnectionPool """ proxy = select_proxy(url, proxies) if proxy: proxy = prepend_scheme_if_needed(proxy, "http") proxy_url = parse_url(proxy) if not proxy_url.host: raise InvalidProxyURL( "Please check proxy URL. It is malformed " "and could be missing the host." ) proxy_manager = self.proxy_manager_for(proxy) conn = proxy_manager.connection_from_url(url) else: # Only scheme should be lower case parsed = urlparse(url) url = parsed.geturl() conn = self.poolmanager.connection_from_url(url) return conn
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/adapters.py#L333-L360
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 ]
100
[]
0
true
92.592593
28
3
100
7
def get_connection(self, url, proxies=None): proxy = select_proxy(url, proxies) if proxy: proxy = prepend_scheme_if_needed(proxy, "http") proxy_url = parse_url(proxy) if not proxy_url.host: raise InvalidProxyURL( "Please check proxy URL. It is malformed " "and could be missing the host." ) proxy_manager = self.proxy_manager_for(proxy) conn = proxy_manager.connection_from_url(url) else: # Only scheme should be lower case parsed = urlparse(url) url = parsed.geturl() conn = self.poolmanager.connection_from_url(url) return conn
22,216
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/adapters.py
HTTPAdapter.close
(self)
Disposes of any internal state. Currently, this closes the PoolManager and any active ProxyManager, which closes any pooled connections.
Disposes of any internal state.
362
370
def close(self): """Disposes of any internal state. Currently, this closes the PoolManager and any active ProxyManager, which closes any pooled connections. """ self.poolmanager.clear() for proxy in self.proxy_manager.values(): proxy.clear()
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/adapters.py#L362-L370
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
100
[]
0
true
92.592593
9
2
100
4
def close(self): self.poolmanager.clear() for proxy in self.proxy_manager.values(): proxy.clear()
22,217
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/adapters.py
HTTPAdapter.request_url
(self, request, proxies)
return url
Obtain the url to use when making the final request. If the message is being sent through a HTTP proxy, the full URL has to be used. Otherwise, we should only use the path portion of the URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs. :rtype: str
Obtain the url to use when making the final request.
372
399
def request_url(self, request, proxies): """Obtain the url to use when making the final request. If the message is being sent through a HTTP proxy, the full URL has to be used. Otherwise, we should only use the path portion of the URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs. :rtype: str """ proxy = select_proxy(request.url, proxies) scheme = urlparse(request.url).scheme is_proxied_http_request = proxy and scheme != "https" using_socks_proxy = False if proxy: proxy_scheme = urlparse(proxy).scheme.lower() using_socks_proxy = proxy_scheme.startswith("socks") url = request.path_url if is_proxied_http_request and not using_socks_proxy: url = urldefragauth(request.url) return url
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/adapters.py#L372-L399
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 ]
100
[]
0
true
92.592593
28
5
100
12
def request_url(self, request, proxies): proxy = select_proxy(request.url, proxies) scheme = urlparse(request.url).scheme is_proxied_http_request = proxy and scheme != "https" using_socks_proxy = False if proxy: proxy_scheme = urlparse(proxy).scheme.lower() using_socks_proxy = proxy_scheme.startswith("socks") url = request.path_url if is_proxied_http_request and not using_socks_proxy: url = urldefragauth(request.url) return url
22,218
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/adapters.py
HTTPAdapter.add_headers
(self, request, **kwargs)
Add any headers needed by the connection. As of v2.0 this does nothing by default, but is left for overriding by users that subclass the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to. :param kwargs: The keyword arguments from the call to send().
Add any headers needed by the connection. As of v2.0 this does nothing by default, but is left for overriding by users that subclass the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
401
413
def add_headers(self, request, **kwargs): """Add any headers needed by the connection. As of v2.0 this does nothing by default, but is left for overriding by users that subclass the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to. :param kwargs: The keyword arguments from the call to send(). """ pass
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/adapters.py#L401-L413
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
92.592593
13
1
100
10
def add_headers(self, request, **kwargs): pass
22,219
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/adapters.py
HTTPAdapter.proxy_headers
(self, proxy)
return headers
Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The url of the proxy being used for this request. :rtype: dict
Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used.
415
434
def proxy_headers(self, proxy): """Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The url of the proxy being used for this request. :rtype: dict """ headers = {} username, password = get_auth_from_url(proxy) if username: headers["Proxy-Authorization"] = _basic_auth_str(username, password) return headers
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/adapters.py#L415-L434
33
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ]
100
[]
0
true
92.592593
20
2
100
11
def proxy_headers(self, proxy): headers = {} username, password = get_auth_from_url(proxy) if username: headers["Proxy-Authorization"] = _basic_auth_str(username, password) return headers
22,220
psf/requests
61c324da43dd8b775d3930d76265538b3ca27bc1
requests/adapters.py
HTTPAdapter.send
( self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None )
return self.build_response(request, resp)
Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request content. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple or urllib3 Timeout object :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: (optional) Any user-provided SSL certificate to be trusted. :param proxies: (optional) The proxies dictionary to apply to the request. :rtype: requests.Response
Sends PreparedRequest object. Returns Response object.
436
584
def send( self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None ): """Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request content. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple or urllib3 Timeout object :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: (optional) Any user-provided SSL certificate to be trusted. :param proxies: (optional) The proxies dictionary to apply to the request. :rtype: requests.Response """ try: conn = self.get_connection(request.url, proxies) except LocationValueError as e: raise InvalidURL(e, request=request) self.cert_verify(conn, request.url, verify, cert) url = self.request_url(request, proxies) self.add_headers( request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies, ) chunked = not (request.body is None or "Content-Length" in request.headers) if isinstance(timeout, tuple): try: connect, read = timeout timeout = TimeoutSauce(connect=connect, read=read) except ValueError: raise ValueError( f"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, " f"or a single float to set both timeouts to the same value." ) elif isinstance(timeout, TimeoutSauce): pass else: timeout = TimeoutSauce(connect=timeout, read=timeout) try: if not chunked: resp = conn.urlopen( method=request.method, url=url, body=request.body, headers=request.headers, redirect=False, assert_same_host=False, preload_content=False, decode_content=False, retries=self.max_retries, timeout=timeout, ) # Send the request. else: if hasattr(conn, "proxy_pool"): conn = conn.proxy_pool low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT) try: skip_host = "Host" in request.headers low_conn.putrequest( request.method, url, skip_accept_encoding=True, skip_host=skip_host, ) for header, value in request.headers.items(): low_conn.putheader(header, value) low_conn.endheaders() for i in request.body: low_conn.send(hex(len(i))[2:].encode("utf-8")) low_conn.send(b"\r\n") low_conn.send(i) low_conn.send(b"\r\n") low_conn.send(b"0\r\n\r\n") # Receive the response from the server r = low_conn.getresponse() resp = HTTPResponse.from_httplib( r, pool=conn, connection=low_conn, preload_content=False, decode_content=False, ) except Exception: # If we hit any problems here, clean up the connection. # Then, raise so that we can handle the actual exception. low_conn.close() raise except (ProtocolError, OSError) as err: raise ConnectionError(err, request=request) except MaxRetryError as e: if isinstance(e.reason, ConnectTimeoutError): # TODO: Remove this in 3.0.0: see #2811 if not isinstance(e.reason, NewConnectionError): raise ConnectTimeout(e, request=request) if isinstance(e.reason, ResponseError): raise RetryError(e, request=request) if isinstance(e.reason, _ProxyError): raise ProxyError(e, request=request) if isinstance(e.reason, _SSLError): # This branch is for urllib3 v1.22 and later. raise SSLError(e, request=request) raise ConnectionError(e, request=request) except ClosedPoolError as e: raise ConnectionError(e, request=request) except _ProxyError as e: raise ProxyError(e) except (_SSLError, _HTTPError) as e: if isinstance(e, _SSLError): # This branch is for urllib3 versions earlier than v1.22 raise SSLError(e, request=request) elif isinstance(e, ReadTimeoutError): raise ReadTimeout(e, request=request) elif isinstance(e, _InvalidHeader): raise InvalidHeader(e, request=request) else: raise return self.build_response(request, resp)
https://github.com/psf/requests/blob/61c324da43dd8b775d3930d76265538b3ca27bc1/project33/requests/adapters.py#L436-L584
33
[ 0, 18, 19, 20, 21, 22, 23, 24, 25, 26, 34, 35, 36, 37, 38, 39, 40, 41, 42, 46, 47, 49, 50, 51, 52, 53, 68, 70, 71, 72, 73, 74, 75, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 109, 110, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 136, 137, 138, 139, 141, 142, 143, 144, 147, 148 ]
57.04698
[ 69, 104, 107, 108, 111, 135, 140, 146 ]
5.369128
false
92.592593
149
24
94.630872
14
def send( self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None ): try: conn = self.get_connection(request.url, proxies) except LocationValueError as e: raise InvalidURL(e, request=request) self.cert_verify(conn, request.url, verify, cert) url = self.request_url(request, proxies) self.add_headers( request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies, ) chunked = not (request.body is None or "Content-Length" in request.headers) if isinstance(timeout, tuple): try: connect, read = timeout timeout = TimeoutSauce(connect=connect, read=read) except ValueError: raise ValueError( f"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, " f"or a single float to set both timeouts to the same value." ) elif isinstance(timeout, TimeoutSauce): pass else: timeout = TimeoutSauce(connect=timeout, read=timeout) try: if not chunked: resp = conn.urlopen( method=request.method, url=url, body=request.body, headers=request.headers, redirect=False, assert_same_host=False, preload_content=False, decode_content=False, retries=self.max_retries, timeout=timeout, ) # Send the request. else: if hasattr(conn, "proxy_pool"): conn = conn.proxy_pool low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT) try: skip_host = "Host" in request.headers low_conn.putrequest( request.method, url, skip_accept_encoding=True, skip_host=skip_host, ) for header, value in request.headers.items(): low_conn.putheader(header, value) low_conn.endheaders() for i in request.body: low_conn.send(hex(len(i))[2:].encode("utf-8")) low_conn.send(b"\r\n") low_conn.send(i) low_conn.send(b"\r\n") low_conn.send(b"0\r\n\r\n") # Receive the response from the server r = low_conn.getresponse() resp = HTTPResponse.from_httplib( r, pool=conn, connection=low_conn, preload_content=False, decode_content=False, ) except Exception: # If we hit any problems here, clean up the connection. # Then, raise so that we can handle the actual exception. low_conn.close() raise except (ProtocolError, OSError) as err: raise ConnectionError(err, request=request) except MaxRetryError as e: if isinstance(e.reason, ConnectTimeoutError): # TODO: Remove this in 3.0.0: see #2811 if not isinstance(e.reason, NewConnectionError): raise ConnectTimeout(e, request=request) if isinstance(e.reason, ResponseError): raise RetryError(e, request=request) if isinstance(e.reason, _ProxyError): raise ProxyError(e, request=request) if isinstance(e.reason, _SSLError): # This branch is for urllib3 v1.22 and later. raise SSLError(e, request=request) raise ConnectionError(e, request=request) except ClosedPoolError as e: raise ConnectionError(e, request=request) except _ProxyError as e: raise ProxyError(e) except (_SSLError, _HTTPError) as e: if isinstance(e, _SSLError): # This branch is for urllib3 versions earlier than v1.22 raise SSLError(e, request=request) elif isinstance(e, ReadTimeoutError): raise ReadTimeout(e, request=request) elif isinstance(e, _InvalidHeader): raise InvalidHeader(e, request=request) else: raise return self.build_response(request, resp)
22,221
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/_utilities.py
hashable_identity
(obj)
103
111
def hashable_identity(obj): if hasattr(obj, '__func__'): return (id(obj.__func__), id(obj.__self__)) elif hasattr(obj, 'im_func'): return (id(obj.im_func), id(obj.im_self)) elif isinstance(obj, text): return obj else: return id(obj)
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/_utilities.py#L103-L111
35
[ 0, 1, 2, 3, 5, 6, 8 ]
77.777778
[ 4 ]
11.111111
false
58.695652
9
4
88.888889
0
def hashable_identity(obj): if hasattr(obj, '__func__'): return (id(obj.__func__), id(obj.__self__)) elif hasattr(obj, 'im_func'): return (id(obj.im_func), id(obj.im_self)) elif isinstance(obj, text): return obj else: return id(obj)
22,259
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/_utilities.py
reference
(object, callback=None, **annotations)
return weak
Return an annotated weak ref.
Return an annotated weak ref.
121
129
def reference(object, callback=None, **annotations): """Return an annotated weak ref.""" if callable(object): weak = callable_reference(object, callback) else: weak = annotatable_weakref(object, callback) for key, value in annotations.items(): setattr(weak, key, value) return weak
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/_utilities.py#L121-L129
35
[ 0, 1, 2, 3, 4, 5, 6, 8 ]
88.888889
[ 7 ]
11.111111
false
58.695652
9
3
88.888889
1
def reference(object, callback=None, **annotations): if callable(object): weak = callable_reference(object, callback) else: weak = annotatable_weakref(object, callback) for key, value in annotations.items(): setattr(weak, key, value) return weak
22,260
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/_utilities.py
callable_reference
(object, callback=None)
return annotatable_weakref(object, callback)
Return an annotated weak ref, supporting bound instance methods.
Return an annotated weak ref, supporting bound instance methods.
132
138
def callable_reference(object, callback=None): """Return an annotated weak ref, supporting bound instance methods.""" if hasattr(object, 'im_self') and object.im_self is not None: return BoundMethodWeakref(target=object, on_delete=callback) elif hasattr(object, '__self__') and object.__self__ is not None: return BoundMethodWeakref(target=object, on_delete=callback) return annotatable_weakref(object, callback)
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/_utilities.py#L132-L138
35
[ 0, 1, 2, 4, 5, 6 ]
85.714286
[ 3 ]
14.285714
false
58.695652
7
5
85.714286
1
def callable_reference(object, callback=None): if hasattr(object, 'im_self') and object.im_self is not None: return BoundMethodWeakref(target=object, on_delete=callback) elif hasattr(object, '__self__') and object.__self__ is not None: return BoundMethodWeakref(target=object, on_delete=callback) return annotatable_weakref(object, callback)
22,261
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/_utilities.py
_symbol.__init__
(self, name)
Construct a new named symbol.
Construct a new named symbol.
62
64
def __init__(self, name): """Construct a new named symbol.""" self.__name__ = self.name = name
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/_utilities.py#L62-L64
35
[ 0, 1, 2 ]
100
[]
0
true
58.695652
3
1
100
1
def __init__(self, name): self.__name__ = self.name = name
22,262
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/_utilities.py
_symbol.__reduce__
(self)
return symbol, (self.name,)
66
67
def __reduce__(self): return symbol, (self.name,)
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/_utilities.py#L66-L67
35
[ 0, 1 ]
100
[]
0
true
58.695652
2
1
100
0
def __reduce__(self): return symbol, (self.name,)
22,263
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/_utilities.py
_symbol.__repr__
(self)
return self.name
69
70
def __repr__(self): return self.name
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/_utilities.py#L69-L70
35
[ 0, 1 ]
100
[]
0
true
58.695652
2
1
100
0
def __repr__(self): return self.name
22,264
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/_utilities.py
symbol.__new__
(cls, name)
90
94
def __new__(cls, name): try: return cls.symbols[name] except KeyError: return cls.symbols.setdefault(name, _symbol(name))
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/_utilities.py#L90-L94
35
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
58.695652
5
2
100
0
def __new__(cls, name): try: return cls.symbols[name] except KeyError: return cls.symbols.setdefault(name, _symbol(name))
22,265
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/_utilities.py
lazy_property.__init__
(self, deferred)
144
146
def __init__(self, deferred): self._deferred = deferred self.__doc__ = deferred.__doc__
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/_utilities.py#L144-L146
35
[ 0, 1, 2 ]
100
[]
0
true
58.695652
3
1
100
0
def __init__(self, deferred): self._deferred = deferred self.__doc__ = deferred.__doc__
22,266
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/_utilities.py
lazy_property.__get__
(self, obj, cls)
return value
148
153
def __get__(self, obj, cls): if obj is None: return self value = self._deferred(obj) setattr(obj, self._deferred.__name__, value) return value
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/_utilities.py#L148-L153
35
[ 0, 1, 3, 4, 5 ]
83.333333
[ 2 ]
16.666667
false
58.695652
6
2
83.333333
0
def __get__(self, obj, cls): if obj is None: return self value = self._deferred(obj) setattr(obj, self._deferred.__name__, value) return value
22,267
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/_saferef.py
safe_ref
(target, on_delete=None)
Return a *safe* weak reference to a callable target. - ``target``: The object to be weakly referenced, if it's a bound method reference, will create a BoundMethodWeakref, otherwise creates a simple weakref. - ``on_delete``: If provided, will have a hard reference stored to the callable to be called after the safe reference goes out of scope with the reference object, (either a weakref or a BoundMethodWeakref) as argument.
Return a *safe* weak reference to a callable target.
58
85
def safe_ref(target, on_delete=None): """Return a *safe* weak reference to a callable target. - ``target``: The object to be weakly referenced, if it's a bound method reference, will create a BoundMethodWeakref, otherwise creates a simple weakref. - ``on_delete``: If provided, will have a hard reference stored to the callable to be called after the safe reference goes out of scope with the reference object, (either a weakref or a BoundMethodWeakref) as argument. """ try: im_self = get_self(target) except AttributeError: if callable(on_delete): return weakref.ref(target, on_delete) else: return weakref.ref(target) else: if im_self is not None: # Turn a bound method into a BoundMethodWeakref instance. # Keep track of these instances for lookup by disconnect(). assert hasattr(target, 'im_func') or hasattr(target, '__func__'), ( "safe_ref target %r has im_self, but no im_func, " "don't know how to create reference" % target) reference = BoundMethodWeakref(target=target, on_delete=on_delete) return reference
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/_saferef.py#L58-L85
35
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 ]
100
[]
0
true
77.108434
28
6
100
10
def safe_ref(target, on_delete=None): try: im_self = get_self(target) except AttributeError: if callable(on_delete): return weakref.ref(target, on_delete) else: return weakref.ref(target) else: if im_self is not None: # Turn a bound method into a BoundMethodWeakref instance. # Keep track of these instances for lookup by disconnect(). assert hasattr(target, 'im_func') or hasattr(target, '__func__'), ( "safe_ref target %r has im_self, but no im_func, " "don't know how to create reference" % target) reference = BoundMethodWeakref(target=target, on_delete=on_delete) return reference
22,268
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/_saferef.py
BoundMethodWeakref.__new__
(cls, target, on_delete=None, *arguments, **named)
Create new instance or return current instance. Basically this method of construction allows us to short-circuit creation of references to already- referenced instance methods. The key corresponding to the target is calculated, and if there is already an existing reference, that is returned, with its deletion_methods attribute updated. Otherwise the new instance is created and registered in the table of already-referenced methods.
Create new instance or return current instance.
124
144
def __new__(cls, target, on_delete=None, *arguments, **named): """Create new instance or return current instance. Basically this method of construction allows us to short-circuit creation of references to already- referenced instance methods. The key corresponding to the target is calculated, and if there is already an existing reference, that is returned, with its deletion_methods attribute updated. Otherwise the new instance is created and registered in the table of already-referenced methods. """ key = cls.calculate_key(target) current = cls._all_instances.get(key) if current is not None: current.deletion_methods.append(on_delete) return current else: base = super(BoundMethodWeakref, cls).__new__(cls) cls._all_instances[key] = base base.__init__(target, on_delete, *arguments, **named) return base
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/_saferef.py#L124-L144
35
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]
100
[]
0
true
77.108434
21
2
100
9
def __new__(cls, target, on_delete=None, *arguments, **named): key = cls.calculate_key(target) current = cls._all_instances.get(key) if current is not None: current.deletion_methods.append(on_delete) return current else: base = super(BoundMethodWeakref, cls).__new__(cls) cls._all_instances[key] = base base.__init__(target, on_delete, *arguments, **named) return base
22,269
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/_saferef.py
BoundMethodWeakref.__init__
(self, target, on_delete=None)
Return a weak-reference-like instance for a bound method. - ``target``: The instance-method target for the weak reference, must have im_self and im_func attributes and be reconstructable via the following, which is true of built-in instance methods:: target.im_func.__get__( target.im_self ) - ``on_delete``: Optional callback which will be called when this weak reference ceases to be valid (i.e. either the object or the function is garbage collected). Should take a single argument, which will be passed a pointer to this object.
Return a weak-reference-like instance for a bound method.
146
188
def __init__(self, target, on_delete=None): """Return a weak-reference-like instance for a bound method. - ``target``: The instance-method target for the weak reference, must have im_self and im_func attributes and be reconstructable via the following, which is true of built-in instance methods:: target.im_func.__get__( target.im_self ) - ``on_delete``: Optional callback which will be called when this weak reference ceases to be valid (i.e. either the object or the function is garbage collected). Should take a single argument, which will be passed a pointer to this object. """ def remove(weak, self=self): """Set self.isDead to True when method or instance is destroyed.""" methods = self.deletion_methods[:] del self.deletion_methods[:] try: del self.__class__._all_instances[self.key] except KeyError: pass for function in methods: try: if callable(function): function(self) except Exception: try: traceback.print_exc() except AttributeError: e = sys.exc_info()[1] print ('Exception during saferef %s ' 'cleanup function %s: %s' % (self, function, e)) self.deletion_methods = [on_delete] self.key = self.calculate_key(target) im_self = get_self(target) im_func = get_func(target) self.weak_self = weakref.ref(im_self, remove) self.weak_func = weakref.ref(im_func, remove) self.self_name = str(im_self) self.func_name = str(im_func.__name__)
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/_saferef.py#L146-L188
35
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 24, 25, 26, 27, 34, 35, 36, 37, 38, 39, 40, 41, 42 ]
81.395349
[ 22, 23, 28, 29, 30, 31, 32, 33 ]
18.604651
false
77.108434
43
7
81.395349
14
def __init__(self, target, on_delete=None): def remove(weak, self=self): methods = self.deletion_methods[:] del self.deletion_methods[:] try: del self.__class__._all_instances[self.key] except KeyError: pass for function in methods: try: if callable(function): function(self) except Exception: try: traceback.print_exc() except AttributeError: e = sys.exc_info()[1] print ('Exception during saferef %s ' 'cleanup function %s: %s' % (self, function, e)) self.deletion_methods = [on_delete] self.key = self.calculate_key(target) im_self = get_self(target) im_func = get_func(target) self.weak_self = weakref.ref(im_self, remove) self.weak_func = weakref.ref(im_func, remove) self.self_name = str(im_self) self.func_name = str(im_func.__name__)
22,270
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/_saferef.py
BoundMethodWeakref.calculate_key
(cls, target)
return (id(get_self(target)), id(get_func(target)))
Calculate the reference key for this reference. Currently this is a two-tuple of the id()'s of the target object and the target function respectively.
Calculate the reference key for this reference.
190
196
def calculate_key(cls, target): """Calculate the reference key for this reference. Currently this is a two-tuple of the id()'s of the target object and the target function respectively. """ return (id(get_self(target)), id(get_func(target)))
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/_saferef.py#L190-L196
35
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
77.108434
7
1
100
4
def calculate_key(cls, target): return (id(get_self(target)), id(get_func(target)))
22,271
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/_saferef.py
BoundMethodWeakref.__str__
(self)
return "{}({}.{})".format( self.__class__.__name__, self.self_name, self.func_name, )
Give a friendly representation of the object.
Give a friendly representation of the object.
199
205
def __str__(self): """Give a friendly representation of the object.""" return "{}({}.{})".format( self.__class__.__name__, self.self_name, self.func_name, )
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/_saferef.py#L199-L205
35
[ 0, 1 ]
28.571429
[ 2 ]
14.285714
false
77.108434
7
1
85.714286
1
def __str__(self): return "{}({}.{})".format( self.__class__.__name__, self.self_name, self.func_name, )
22,272
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/_saferef.py
BoundMethodWeakref.__nonzero__
(self)
return self() is not None
Whether we are still a valid reference.
Whether we are still a valid reference.
209
211
def __nonzero__(self): """Whether we are still a valid reference.""" return self() is not None
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/_saferef.py#L209-L211
35
[ 0, 1 ]
66.666667
[ 2 ]
33.333333
false
77.108434
3
1
66.666667
1
def __nonzero__(self): return self() is not None
22,273
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/_saferef.py
BoundMethodWeakref.__cmp__
(self, other)
return cmp(self.key, other.key)
Compare with another reference.
Compare with another reference.
213
217
def __cmp__(self, other): """Compare with another reference.""" if not isinstance(other, self.__class__): return cmp(self.__class__, type(other)) return cmp(self.key, other.key)
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/_saferef.py#L213-L217
35
[ 0, 1 ]
40
[ 2, 3, 4 ]
60
false
77.108434
5
2
40
1
def __cmp__(self, other): if not isinstance(other, self.__class__): return cmp(self.__class__, type(other)) return cmp(self.key, other.key)
22,274
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/_saferef.py
BoundMethodWeakref.__call__
(self)
return None
Return a strong reference to the bound method. If the target cannot be retrieved, then will return None, otherwise returns a bound instance method for our object and function. Note: You may call this method any number of times, as it does not invalidate the reference.
Return a strong reference to the bound method.
219
234
def __call__(self): """Return a strong reference to the bound method. If the target cannot be retrieved, then will return None, otherwise returns a bound instance method for our object and function. Note: You may call this method any number of times, as it does not invalidate the reference. """ target = self.weak_self() if target is not None: function = self.weak_func() if function is not None: return function.__get__(target) return None
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/_saferef.py#L219-L234
35
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
93.75
[ 15 ]
6.25
false
77.108434
16
3
93.75
8
def __call__(self): target = self.weak_self() if target is not None: function = self.weak_func() if function is not None: return function.__get__(target) return None
22,275
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/base.py
Signal.receiver_connected
(self)
return Signal(doc="Emitted after a receiver connects.")
Emitted after each :meth:`connect`. The signal sender is the signal instance, and the :meth:`connect` arguments are passed through: *receiver*, *sender*, and *weak*. .. versionadded:: 1.2
Emitted after each :meth:`connect`.
38
47
def receiver_connected(self): """Emitted after each :meth:`connect`. The signal sender is the signal instance, and the :meth:`connect` arguments are passed through: *receiver*, *sender*, and *weak*. .. versionadded:: 1.2 """ return Signal(doc="Emitted after a receiver connects.")
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/base.py#L38-L47
35
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
93.939394
10
1
100
6
def receiver_connected(self): return Signal(doc="Emitted after a receiver connects.")
22,276
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/base.py
Signal.receiver_disconnected
(self)
return Signal(doc="Emitted after a receiver disconnects.")
Emitted after :meth:`disconnect`. The sender is the signal instance, and the :meth:`disconnect` arguments are passed through: *receiver* and *sender*. Note, this signal is emitted **only** when :meth:`disconnect` is called explicitly. The disconnect signal can not be emitted by an automatic disconnect (due to a weakly referenced receiver or sender going out of scope), as the receiver and/or sender instances are no longer available for use at the time this signal would be emitted. An alternative approach is available by subscribing to :attr:`receiver_connected` and setting up a custom weakref cleanup callback on weak receivers and senders. .. versionadded:: 1.2
Emitted after :meth:`disconnect`.
50
71
def receiver_disconnected(self): """Emitted after :meth:`disconnect`. The sender is the signal instance, and the :meth:`disconnect` arguments are passed through: *receiver* and *sender*. Note, this signal is emitted **only** when :meth:`disconnect` is called explicitly. The disconnect signal can not be emitted by an automatic disconnect (due to a weakly referenced receiver or sender going out of scope), as the receiver and/or sender instances are no longer available for use at the time this signal would be emitted. An alternative approach is available by subscribing to :attr:`receiver_connected` and setting up a custom weakref cleanup callback on weak receivers and senders. .. versionadded:: 1.2 """ return Signal(doc="Emitted after a receiver disconnects.")
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/base.py#L50-L71
35
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 ]
100
[]
0
true
93.939394
22
1
100
18
def receiver_disconnected(self): return Signal(doc="Emitted after a receiver disconnects.")
22,277
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/base.py
Signal.__init__
(self, doc=None)
:param doc: optional. If provided, will be assigned to the signal's __doc__ attribute.
:param doc: optional. If provided, will be assigned to the signal's __doc__ attribute.
73
90
def __init__(self, doc=None): """ :param doc: optional. If provided, will be assigned to the signal's __doc__ attribute. """ if doc: self.__doc__ = doc #: A mapping of connected receivers. #: #: The values of this mapping are not meaningful outside of the #: internal :class:`Signal` implementation, however the boolean value #: of the mapping is useful as an extremely efficient check to see if #: any receivers are connected to the signal. self.receivers = {} self._by_receiver = defaultdict(set) self._by_sender = defaultdict(set) self._weak_senders = {}
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/base.py#L73-L90
35
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]
100
[]
0
true
93.939394
18
2
100
2
def __init__(self, doc=None): if doc: self.__doc__ = doc #: A mapping of connected receivers. #: #: The values of this mapping are not meaningful outside of the #: internal :class:`Signal` implementation, however the boolean value #: of the mapping is useful as an extremely efficient check to see if #: any receivers are connected to the signal. self.receivers = {} self._by_receiver = defaultdict(set) self._by_sender = defaultdict(set) self._weak_senders = {}
22,278
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/base.py
Signal.connect
(self, receiver, sender=ANY, weak=True)
return receiver
Connect *receiver* to signal events sent by *sender*. :param receiver: A callable. Will be invoked by :meth:`send` with `sender=` as a single positional argument and any ``kwargs`` that were provided to a call to :meth:`send`. :param sender: Any object or :obj:`ANY`, defaults to ``ANY``. Restricts notifications delivered to *receiver* to only those :meth:`send` emissions sent by *sender*. If ``ANY``, the receiver will always be notified. A *receiver* may be connected to multiple *sender* values on the same Signal through multiple calls to :meth:`connect`. :param weak: If true, the Signal will hold a weakref to *receiver* and automatically disconnect when *receiver* goes out of scope or is garbage collected. Defaults to True.
Connect *receiver* to signal events sent by *sender*.
92
158
def connect(self, receiver, sender=ANY, weak=True): """Connect *receiver* to signal events sent by *sender*. :param receiver: A callable. Will be invoked by :meth:`send` with `sender=` as a single positional argument and any ``kwargs`` that were provided to a call to :meth:`send`. :param sender: Any object or :obj:`ANY`, defaults to ``ANY``. Restricts notifications delivered to *receiver* to only those :meth:`send` emissions sent by *sender*. If ``ANY``, the receiver will always be notified. A *receiver* may be connected to multiple *sender* values on the same Signal through multiple calls to :meth:`connect`. :param weak: If true, the Signal will hold a weakref to *receiver* and automatically disconnect when *receiver* goes out of scope or is garbage collected. Defaults to True. """ receiver_id = hashable_identity(receiver) if weak: receiver_ref = reference(receiver, self._cleanup_receiver) receiver_ref.receiver_id = receiver_id else: receiver_ref = receiver if sender is ANY: sender_id = ANY_ID else: sender_id = hashable_identity(sender) self.receivers.setdefault(receiver_id, receiver_ref) self._by_sender[sender_id].add(receiver_id) self._by_receiver[receiver_id].add(sender_id) del receiver_ref if sender is not ANY and sender_id not in self._weak_senders: # wire together a cleanup for weakref-able senders try: sender_ref = reference(sender, self._cleanup_sender) sender_ref.sender_id = sender_id except TypeError: pass else: self._weak_senders.setdefault(sender_id, sender_ref) del sender_ref # broadcast this connection. if receivers raise, disconnect. if ('receiver_connected' in self.__dict__ and self.receiver_connected.receivers): try: self.receiver_connected.send(self, receiver=receiver, sender=sender, weak=weak) except: self.disconnect(receiver, sender) raise if receiver_connected.receivers and self is not receiver_connected: try: receiver_connected.send(self, receiver_arg=receiver, sender_arg=sender, weak_arg=weak) except: self.disconnect(receiver, sender) raise return receiver
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/base.py#L92-L158
35
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66 ]
95.522388
[ 54, 55, 56 ]
4.477612
false
93.939394
67
12
95.522388
16
def connect(self, receiver, sender=ANY, weak=True): receiver_id = hashable_identity(receiver) if weak: receiver_ref = reference(receiver, self._cleanup_receiver) receiver_ref.receiver_id = receiver_id else: receiver_ref = receiver if sender is ANY: sender_id = ANY_ID else: sender_id = hashable_identity(sender) self.receivers.setdefault(receiver_id, receiver_ref) self._by_sender[sender_id].add(receiver_id) self._by_receiver[receiver_id].add(sender_id) del receiver_ref if sender is not ANY and sender_id not in self._weak_senders: # wire together a cleanup for weakref-able senders try: sender_ref = reference(sender, self._cleanup_sender) sender_ref.sender_id = sender_id except TypeError: pass else: self._weak_senders.setdefault(sender_id, sender_ref) del sender_ref # broadcast this connection. if receivers raise, disconnect. if ('receiver_connected' in self.__dict__ and self.receiver_connected.receivers): try: self.receiver_connected.send(self, receiver=receiver, sender=sender, weak=weak) except: self.disconnect(receiver, sender) raise if receiver_connected.receivers and self is not receiver_connected: try: receiver_connected.send(self, receiver_arg=receiver, sender_arg=sender, weak_arg=weak) except: self.disconnect(receiver, sender) raise return receiver
22,279
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/base.py
Signal.connect_via
(self, sender, weak=False)
return decorator
Connect the decorated function as a receiver for *sender*. :param sender: Any object or :obj:`ANY`. The decorated function will only receive :meth:`send` emissions sent by *sender*. If ``ANY``, the receiver will always be notified. A function may be decorated multiple times with differing *sender* values. :param weak: If true, the Signal will hold a weakref to the decorated function and automatically disconnect when *receiver* goes out of scope or is garbage collected. Unlike :meth:`connect`, this defaults to False. The decorated function will be invoked by :meth:`send` with `sender=` as a single positional argument and any ``kwargs`` that were provided to the call to :meth:`send`. .. versionadded:: 1.1
Connect the decorated function as a receiver for *sender*.
160
184
def connect_via(self, sender, weak=False): """Connect the decorated function as a receiver for *sender*. :param sender: Any object or :obj:`ANY`. The decorated function will only receive :meth:`send` emissions sent by *sender*. If ``ANY``, the receiver will always be notified. A function may be decorated multiple times with differing *sender* values. :param weak: If true, the Signal will hold a weakref to the decorated function and automatically disconnect when *receiver* goes out of scope or is garbage collected. Unlike :meth:`connect`, this defaults to False. The decorated function will be invoked by :meth:`send` with `sender=` as a single positional argument and any ``kwargs`` that were provided to the call to :meth:`send`. .. versionadded:: 1.1 """ def decorator(fn): self.connect(fn, sender, weak) return fn return decorator
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/base.py#L160-L184
35
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 ]
100
[]
0
true
93.939394
25
2
100
18
def connect_via(self, sender, weak=False): def decorator(fn): self.connect(fn, sender, weak) return fn return decorator
22,280
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/base.py
Signal.connected_to
(self, receiver, sender=ANY)
Execute a block with the signal temporarily connected to *receiver*. :param receiver: a receiver callable :param sender: optional, a sender to filter on This is a context manager for use in the ``with`` statement. It can be useful in unit tests. *receiver* is connected to the signal for the duration of the ``with`` block, and will be disconnected automatically when exiting the block: .. code-block:: python with on_ready.connected_to(receiver): # do stuff on_ready.send(123) .. versionadded:: 1.1
Execute a block with the signal temporarily connected to *receiver*.
187
214
def connected_to(self, receiver, sender=ANY): """Execute a block with the signal temporarily connected to *receiver*. :param receiver: a receiver callable :param sender: optional, a sender to filter on This is a context manager for use in the ``with`` statement. It can be useful in unit tests. *receiver* is connected to the signal for the duration of the ``with`` block, and will be disconnected automatically when exiting the block: .. code-block:: python with on_ready.connected_to(receiver): # do stuff on_ready.send(123) .. versionadded:: 1.1 """ self.connect(receiver, sender=sender, weak=False) try: yield None except: self.disconnect(receiver) raise else: self.disconnect(receiver)
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/base.py#L187-L214
35
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 ]
100
[]
0
true
93.939394
28
2
100
17
def connected_to(self, receiver, sender=ANY): self.connect(receiver, sender=sender, weak=False) try: yield None except: self.disconnect(receiver) raise else: self.disconnect(receiver)
22,281
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/base.py
Signal.temporarily_connected_to
(self, receiver, sender=ANY)
return self.connected_to(receiver, sender)
An alias for :meth:`connected_to`. :param receiver: a receiver callable :param sender: optional, a sender to filter on .. versionadded:: 0.9 .. versionchanged:: 1.1 Renamed to :meth:`connected_to`. ``temporarily_connected_to`` was deprecated in 1.2 and will be removed in a subsequent version.
An alias for :meth:`connected_to`.
216
232
def temporarily_connected_to(self, receiver, sender=ANY): """An alias for :meth:`connected_to`. :param receiver: a receiver callable :param sender: optional, a sender to filter on .. versionadded:: 0.9 .. versionchanged:: 1.1 Renamed to :meth:`connected_to`. ``temporarily_connected_to`` was deprecated in 1.2 and will be removed in a subsequent version. """ warn("temporarily_connected_to is deprecated; " "use connected_to instead.", DeprecationWarning) return self.connected_to(receiver, sender)
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/base.py#L216-L232
35
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
76.470588
[ 13, 16 ]
11.764706
false
93.939394
17
1
88.235294
10
def temporarily_connected_to(self, receiver, sender=ANY): warn("temporarily_connected_to is deprecated; " "use connected_to instead.", DeprecationWarning) return self.connected_to(receiver, sender)
22,282
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/base.py
Signal.send
(self, *sender, **kwargs)
return [(receiver, receiver(sender, **kwargs)) for receiver in self.receivers_for(sender)]
Emit this signal on behalf of *sender*, passing on ``kwargs``. Returns a list of 2-tuples, pairing receivers with their return value. The ordering of receiver notification is undefined. :param sender: Any object or ``None``. If omitted, synonymous with ``None``. Only accepts one positional argument. :param kwargs: Data to be sent to receivers.
Emit this signal on behalf of *sender*, passing on ``kwargs``.
234
264
def send(self, *sender, **kwargs): """Emit this signal on behalf of *sender*, passing on ``kwargs``. Returns a list of 2-tuples, pairing receivers with their return value. The ordering of receiver notification is undefined. :param sender: Any object or ``None``. If omitted, synonymous with ``None``. Only accepts one positional argument. :param kwargs: Data to be sent to receivers. """ if not self.receivers: # Ensure correct signature even on no-op sends, disable with -O # for lowest possible cost. if __debug__ and sender and len(sender) > 1: raise TypeError('send() accepts only one positional ' 'argument, %s given' % len(sender)) return [] # Using '*sender' rather than 'sender=None' allows 'sender' to be # used as a keyword argument- i.e. it's an invisible name in the # function signature. if len(sender) == 0: sender = None elif len(sender) > 1: raise TypeError('send() accepts only one positional argument, ' '%s given' % len(sender)) else: sender = sender[0] return [(receiver, receiver(sender, **kwargs)) for receiver in self.receivers_for(sender)]
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/base.py#L234-L264
35
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 27, 28, 29, 30 ]
90.322581
[ 15, 25 ]
6.451613
false
93.939394
31
8
93.548387
9
def send(self, *sender, **kwargs): if not self.receivers: # Ensure correct signature even on no-op sends, disable with -O # for lowest possible cost. if __debug__ and sender and len(sender) > 1: raise TypeError('send() accepts only one positional ' 'argument, %s given' % len(sender)) return [] # Using '*sender' rather than 'sender=None' allows 'sender' to be # used as a keyword argument- i.e. it's an invisible name in the # function signature. if len(sender) == 0: sender = None elif len(sender) > 1: raise TypeError('send() accepts only one positional argument, ' '%s given' % len(sender)) else: sender = sender[0] return [(receiver, receiver(sender, **kwargs)) for receiver in self.receivers_for(sender)]
22,283
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/base.py
Signal.has_receivers_for
(self, sender)
return hashable_identity(sender) in self._by_sender
True if there is probably a receiver for *sender*. Performs an optimistic check only. Does not guarantee that all weakly referenced receivers are still alive. See :meth:`receivers_for` for a stronger search.
True if there is probably a receiver for *sender*.
266
280
def has_receivers_for(self, sender): """True if there is probably a receiver for *sender*. Performs an optimistic check only. Does not guarantee that all weakly referenced receivers are still alive. See :meth:`receivers_for` for a stronger search. """ if not self.receivers: return False if self._by_sender[ANY_ID]: return True if sender is ANY: return False return hashable_identity(sender) in self._by_sender
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/base.py#L266-L280
35
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
100
[]
0
true
93.939394
15
4
100
5
def has_receivers_for(self, sender): if not self.receivers: return False if self._by_sender[ANY_ID]: return True if sender is ANY: return False return hashable_identity(sender) in self._by_sender
22,284
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/base.py
Signal.receivers_for
(self, sender)
Iterate all live receivers listening for *sender*.
Iterate all live receivers listening for *sender*.
282
302
def receivers_for(self, sender): """Iterate all live receivers listening for *sender*.""" # TODO: test receivers_for(ANY) if self.receivers: sender_id = hashable_identity(sender) if sender_id in self._by_sender: ids = (self._by_sender[ANY_ID] | self._by_sender[sender_id]) else: ids = self._by_sender[ANY_ID].copy() for receiver_id in ids: receiver = self.receivers.get(receiver_id) if receiver is None: continue if isinstance(receiver, WeakTypes): strong = receiver() if strong is None: self._disconnect(receiver_id, ANY_ID) continue receiver = strong yield receiver
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/base.py#L282-L302
35
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 19, 20 ]
85.714286
[ 13, 17, 18 ]
14.285714
false
93.939394
21
7
85.714286
1
def receivers_for(self, sender): # TODO: test receivers_for(ANY) if self.receivers: sender_id = hashable_identity(sender) if sender_id in self._by_sender: ids = (self._by_sender[ANY_ID] | self._by_sender[sender_id]) else: ids = self._by_sender[ANY_ID].copy() for receiver_id in ids: receiver = self.receivers.get(receiver_id) if receiver is None: continue if isinstance(receiver, WeakTypes): strong = receiver() if strong is None: self._disconnect(receiver_id, ANY_ID) continue receiver = strong yield receiver
22,285
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/base.py
Signal.disconnect
(self, receiver, sender=ANY)
Disconnect *receiver* from this signal's events. :param receiver: a previously :meth:`connected<connect>` callable :param sender: a specific sender to disconnect from, or :obj:`ANY` to disconnect from all senders. Defaults to ``ANY``.
Disconnect *receiver* from this signal's events.
304
324
def disconnect(self, receiver, sender=ANY): """Disconnect *receiver* from this signal's events. :param receiver: a previously :meth:`connected<connect>` callable :param sender: a specific sender to disconnect from, or :obj:`ANY` to disconnect from all senders. Defaults to ``ANY``. """ if sender is ANY: sender_id = ANY_ID else: sender_id = hashable_identity(sender) receiver_id = hashable_identity(receiver) self._disconnect(receiver_id, sender_id) if ('receiver_disconnected' in self.__dict__ and self.receiver_disconnected.receivers): self.receiver_disconnected.send(self, receiver=receiver, sender=sender)
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/base.py#L304-L324
35
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]
100
[]
0
true
93.939394
21
4
100
6
def disconnect(self, receiver, sender=ANY): if sender is ANY: sender_id = ANY_ID else: sender_id = hashable_identity(sender) receiver_id = hashable_identity(receiver) self._disconnect(receiver_id, sender_id) if ('receiver_disconnected' in self.__dict__ and self.receiver_disconnected.receivers): self.receiver_disconnected.send(self, receiver=receiver, sender=sender)
22,286
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/base.py
Signal._disconnect
(self, receiver_id, sender_id)
326
334
def _disconnect(self, receiver_id, sender_id): if sender_id == ANY_ID: if self._by_receiver.pop(receiver_id, False): for bucket in self._by_sender.values(): bucket.discard(receiver_id) self.receivers.pop(receiver_id, None) else: self._by_sender[sender_id].discard(receiver_id) self._by_receiver[receiver_id].discard(sender_id)
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/base.py#L326-L334
35
[ 0, 1, 2, 3, 4, 5, 7, 8 ]
88.888889
[]
0
false
93.939394
9
4
100
0
def _disconnect(self, receiver_id, sender_id): if sender_id == ANY_ID: if self._by_receiver.pop(receiver_id, False): for bucket in self._by_sender.values(): bucket.discard(receiver_id) self.receivers.pop(receiver_id, None) else: self._by_sender[sender_id].discard(receiver_id) self._by_receiver[receiver_id].discard(sender_id)
22,287
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/base.py
Signal._cleanup_receiver
(self, receiver_ref)
Disconnect a receiver from all senders.
Disconnect a receiver from all senders.
336
338
def _cleanup_receiver(self, receiver_ref): """Disconnect a receiver from all senders.""" self._disconnect(receiver_ref.receiver_id, ANY_ID)
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/base.py#L336-L338
35
[ 0, 1, 2 ]
100
[]
0
true
93.939394
3
1
100
1
def _cleanup_receiver(self, receiver_ref): self._disconnect(receiver_ref.receiver_id, ANY_ID)
22,288
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/base.py
Signal._cleanup_sender
(self, sender_ref)
Disconnect all receivers from a sender.
Disconnect all receivers from a sender.
340
346
def _cleanup_sender(self, sender_ref): """Disconnect all receivers from a sender.""" sender_id = sender_ref.sender_id assert sender_id != ANY_ID self._weak_senders.pop(sender_id, None) for receiver_id in self._by_sender.pop(sender_id, ()): self._by_receiver[receiver_id].discard(sender_id)
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/base.py#L340-L346
35
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
93.939394
7
3
100
1
def _cleanup_sender(self, sender_ref): sender_id = sender_ref.sender_id assert sender_id != ANY_ID self._weak_senders.pop(sender_id, None) for receiver_id in self._by_sender.pop(sender_id, ()): self._by_receiver[receiver_id].discard(sender_id)
22,289
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/base.py
Signal._cleanup_bookkeeping
(self)
Prune unused sender/receiver bookkeeping. Not threadsafe. Connecting & disconnecting leave behind a small amount of bookkeeping for the receiver and sender values. Typical workloads using Blinker, for example in most web apps, Flask, CLI scripts, etc., are not adversely affected by this bookkeeping. With a long-running Python process performing dynamic signal routing with high volume- e.g. connecting to function closures, "senders" are all unique object instances, and doing all of this over and over- you may see memory usage will grow due to extraneous bookkeeping. (An empty set() for each stale sender/receiver pair.) This method will prune that bookkeeping away, with the caveat that such pruning is not threadsafe. The risk is that cleanup of a fully disconnected receiver/sender pair occurs while another thread is connecting that same pair. If you are in the highly dynamic, unique receiver/sender situation that has lead you to this method, that failure mode is perhaps not a big deal for you.
Prune unused sender/receiver bookkeeping. Not threadsafe.
348
372
def _cleanup_bookkeeping(self): """Prune unused sender/receiver bookkeeping. Not threadsafe. Connecting & disconnecting leave behind a small amount of bookkeeping for the receiver and sender values. Typical workloads using Blinker, for example in most web apps, Flask, CLI scripts, etc., are not adversely affected by this bookkeeping. With a long-running Python process performing dynamic signal routing with high volume- e.g. connecting to function closures, "senders" are all unique object instances, and doing all of this over and over- you may see memory usage will grow due to extraneous bookkeeping. (An empty set() for each stale sender/receiver pair.) This method will prune that bookkeeping away, with the caveat that such pruning is not threadsafe. The risk is that cleanup of a fully disconnected receiver/sender pair occurs while another thread is connecting that same pair. If you are in the highly dynamic, unique receiver/sender situation that has lead you to this method, that failure mode is perhaps not a big deal for you. """ for mapping in (self._by_sender, self._by_receiver): for _id, bucket in list(mapping.items()): if not bucket: mapping.pop(_id, None)
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/base.py#L348-L372
35
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 ]
100
[]
0
true
93.939394
25
4
100
19
def _cleanup_bookkeeping(self): for mapping in (self._by_sender, self._by_receiver): for _id, bucket in list(mapping.items()): if not bucket: mapping.pop(_id, None)
22,290
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/base.py
Signal._clear_state
(self)
Throw away all signal state. Useful for unit tests.
Throw away all signal state. Useful for unit tests.
374
379
def _clear_state(self): """Throw away all signal state. Useful for unit tests.""" self._weak_senders.clear() self.receivers.clear() self._by_sender.clear() self._by_receiver.clear()
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/base.py#L374-L379
35
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
93.939394
6
1
100
1
def _clear_state(self): self._weak_senders.clear() self.receivers.clear() self._by_sender.clear() self._by_receiver.clear()
22,291
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/base.py
NamedSignal.__init__
(self, name, doc=None)
403
407
def __init__(self, name, doc=None): Signal.__init__(self, doc) #: The name of this signal. self.name = name
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/base.py#L403-L407
35
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
93.939394
5
1
100
0
def __init__(self, name, doc=None): Signal.__init__(self, doc) #: The name of this signal. self.name = name
22,292
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/base.py
NamedSignal.__repr__
(self)
return "{}; {!r}>".format(base[:-1], self.name)
409
411
def __repr__(self): base = Signal.__repr__(self) return "{}; {!r}>".format(base[:-1], self.name)
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/base.py#L409-L411
35
[ 0, 1, 2 ]
100
[]
0
true
93.939394
3
1
100
0
def __repr__(self): base = Signal.__repr__(self) return "{}; {!r}>".format(base[:-1], self.name)
22,293
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/base.py
Namespace.signal
(self, name, doc=None)
Return the :class:`NamedSignal` *name*, creating it if required. Repeated calls to this function will return the same signal object.
Return the :class:`NamedSignal` *name*, creating it if required.
417
426
def signal(self, name, doc=None): """Return the :class:`NamedSignal` *name*, creating it if required. Repeated calls to this function will return the same signal object. """ try: return self[name] except KeyError: return self.setdefault(name, NamedSignal(name, doc))
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/base.py#L417-L426
35
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
93.939394
10
2
100
3
def signal(self, name, doc=None): try: return self[name] except KeyError: return self.setdefault(name, NamedSignal(name, doc))
22,294
pallets-eco/blinker
c074cdd06328b724bbe95c060373a57ff2e86b1f
blinker/base.py
WeakNamespace.signal
(self, name, doc=None)
Return the :class:`NamedSignal` *name*, creating it if required. Repeated calls to this function will return the same signal object.
Return the :class:`NamedSignal` *name*, creating it if required.
440
449
def signal(self, name, doc=None): """Return the :class:`NamedSignal` *name*, creating it if required. Repeated calls to this function will return the same signal object. """ try: return self[name] except KeyError: return self.setdefault(name, NamedSignal(name, doc))
https://github.com/pallets-eco/blinker/blob/c074cdd06328b724bbe95c060373a57ff2e86b1f/project35/blinker/base.py#L440-L449
35
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
93.939394
10
2
100
3
def signal(self, name, doc=None): try: return self[name] except KeyError: return self.setdefault(name, NamedSignal(name, doc))
22,295
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/patterns.py
ReqRep.process_call
(self, context, channel, req_event, functor)
28
34
def process_call(self, context, channel, req_event, functor): context.hook_server_before_exec(req_event) result = functor(*req_event.args) rep_event = channel.new_event(u'OK', (result,), context.hook_get_task_context()) context.hook_server_after_exec(req_event, rep_event) channel.emit_event(rep_event)
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/patterns.py#L28-L34
36
[ 0, 1, 2, 3, 5, 6 ]
85.714286
[]
0
false
100
7
1
100
0
def process_call(self, context, channel, req_event, functor): context.hook_server_before_exec(req_event) result = functor(*req_event.args) rep_event = channel.new_event(u'OK', (result,), context.hook_get_task_context()) context.hook_server_after_exec(req_event, rep_event) channel.emit_event(rep_event)
22,479
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/patterns.py
ReqRep.accept_answer
(self, event)
return event.name in (u'OK', u'ERR')
36
37
def accept_answer(self, event): return event.name in (u'OK', u'ERR')
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/patterns.py#L36-L37
36
[ 0, 1 ]
100
[]
0
true
100
2
1
100
0
def accept_answer(self, event): return event.name in (u'OK', u'ERR')
22,480
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/patterns.py
ReqRep.process_answer
(self, context, channel, req_event, rep_event, handle_remote_error)
39
49
def process_answer(self, context, channel, req_event, rep_event, handle_remote_error): try: if rep_event.name == u'ERR': exception = handle_remote_error(rep_event) context.hook_client_after_request(req_event, rep_event, exception) raise exception context.hook_client_after_request(req_event, rep_event) return rep_event.args[0] finally: channel.close()
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/patterns.py#L39-L49
36
[ 0, 2, 3, 4, 5, 6, 7, 8, 10 ]
81.818182
[]
0
false
100
11
2
100
0
def process_answer(self, context, channel, req_event, rep_event, handle_remote_error): try: if rep_event.name == u'ERR': exception = handle_remote_error(rep_event) context.hook_client_after_request(req_event, rep_event, exception) raise exception context.hook_client_after_request(req_event, rep_event) return rep_event.args[0] finally: channel.close()
22,481
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/patterns.py
ReqStream.process_call
(self, context, channel, req_event, functor)
54
65
def process_call(self, context, channel, req_event, functor): context.hook_server_before_exec(req_event) xheader = context.hook_get_task_context() for result in iter(functor(*req_event.args)): channel.emit(u'STREAM', result, xheader) done_event = channel.new_event(u'STREAM_DONE', None, xheader) # NOTE: "We" made the choice to call the hook once the stream is done, # the other choice was to call it at each iteration. I donu't think that # one choice is better than the other, so Iu'm fine with changing this # or adding the server_after_iteration and client_after_iteration hooks. context.hook_server_after_exec(req_event, done_event) channel.emit_event(done_event)
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/patterns.py#L54-L65
36
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
100
[]
0
true
100
12
2
100
0
def process_call(self, context, channel, req_event, functor): context.hook_server_before_exec(req_event) xheader = context.hook_get_task_context() for result in iter(functor(*req_event.args)): channel.emit(u'STREAM', result, xheader) done_event = channel.new_event(u'STREAM_DONE', None, xheader) # NOTE: "We" made the choice to call the hook once the stream is done, # the other choice was to call it at each iteration. I donu't think that # one choice is better than the other, so Iu'm fine with changing this # or adding the server_after_iteration and client_after_iteration hooks. context.hook_server_after_exec(req_event, done_event) channel.emit_event(done_event)
22,482
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/patterns.py
ReqStream.accept_answer
(self, event)
return event.name in (u'STREAM', u'STREAM_DONE')
67
68
def accept_answer(self, event): return event.name in (u'STREAM', u'STREAM_DONE')
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/patterns.py#L67-L68
36
[ 0, 1 ]
100
[]
0
true
100
2
1
100
0
def accept_answer(self, event): return event.name in (u'STREAM', u'STREAM_DONE')
22,483
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/patterns.py
ReqStream.process_answer
(self, context, channel, req_event, rep_event, handle_remote_error)
return iterator(req_event, rep_event)
70
92
def process_answer(self, context, channel, req_event, rep_event, handle_remote_error): def is_stream_done(rep_event): return rep_event.name == u'STREAM_DONE' channel.on_close_if = is_stream_done def iterator(req_event, rep_event): try: while rep_event.name == u'STREAM': # Like in process_call, we made the choice to call the # after_exec hook only when the stream is done. yield rep_event.args rep_event = channel.recv() if rep_event.name == u'ERR': exception = handle_remote_error(rep_event) context.hook_client_after_request(req_event, rep_event, exception) raise exception context.hook_client_after_request(req_event, rep_event) finally: channel.close() return iterator(req_event, rep_event)
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/patterns.py#L70-L92
36
[ 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22 ]
91.304348
[]
0
false
100
23
5
100
0
def process_answer(self, context, channel, req_event, rep_event, handle_remote_error): def is_stream_done(rep_event): return rep_event.name == u'STREAM_DONE' channel.on_close_if = is_stream_done def iterator(req_event, rep_event): try: while rep_event.name == u'STREAM': # Like in process_call, we made the choice to call the # after_exec hook only when the stream is done. yield rep_event.args rep_event = channel.recv() if rep_event.name == u'ERR': exception = handle_remote_error(rep_event) context.hook_client_after_request(req_event, rep_event, exception) raise exception context.hook_client_after_request(req_event, rep_event) finally: channel.close() return iterator(req_event, rep_event)
22,484
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/heartbeat.py
HeartBeatOnChannel.__init__
(self, channel, freq=5, passive=False)
39
51
def __init__(self, channel, freq=5, passive=False): self._closed = False self._channel = channel self._heartbeat_freq = freq self._input_queue = gevent.queue.Channel() self._remote_last_hb = None self._lost_remote = False self._recv_task = gevent.spawn(self._recver) self._heartbeat_task = None self._parent_coroutine = gevent.getcurrent() self._compat_v2 = None if not passive: self._start_heartbeat()
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/heartbeat.py#L39-L51
36
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
90.909091
13
2
100
0
def __init__(self, channel, freq=5, passive=False): self._closed = False self._channel = channel self._heartbeat_freq = freq self._input_queue = gevent.queue.Channel() self._remote_last_hb = None self._lost_remote = False self._recv_task = gevent.spawn(self._recver) self._heartbeat_task = None self._parent_coroutine = gevent.getcurrent() self._compat_v2 = None if not passive: self._start_heartbeat()
22,485
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/heartbeat.py
HeartBeatOnChannel.recv_is_supported
(self)
return self._channel.recv_is_supported
54
55
def recv_is_supported(self): return self._channel.recv_is_supported
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/heartbeat.py#L54-L55
36
[ 0 ]
50
[ 1 ]
50
false
90.909091
2
1
50
0
def recv_is_supported(self): return self._channel.recv_is_supported
22,486
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/heartbeat.py
HeartBeatOnChannel.emit_is_supported
(self)
return self._channel.emit_is_supported
58
59
def emit_is_supported(self): return self._channel.emit_is_supported
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/heartbeat.py#L58-L59
36
[ 0 ]
50
[ 1 ]
50
false
90.909091
2
1
50
0
def emit_is_supported(self): return self._channel.emit_is_supported
22,487
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/heartbeat.py
HeartBeatOnChannel.close
(self)
61
71
def close(self): self._closed = True if self._heartbeat_task is not None: self._heartbeat_task.kill() self._heartbeat_task = None if self._recv_task is not None: self._recv_task.kill() self._recv_task = None if self._channel is not None: self._channel.close() self._channel = None
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/heartbeat.py#L61-L71
36
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
100
[]
0
true
90.909091
11
4
100
0
def close(self): self._closed = True if self._heartbeat_task is not None: self._heartbeat_task.kill() self._heartbeat_task = None if self._recv_task is not None: self._recv_task.kill() self._recv_task = None if self._channel is not None: self._channel.close() self._channel = None
22,488
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/heartbeat.py
HeartBeatOnChannel._heartbeat
(self)
73
84
def _heartbeat(self): while True: gevent.sleep(self._heartbeat_freq) if self._remote_last_hb is None: self._remote_last_hb = time.time() if time.time() > self._remote_last_hb + self._heartbeat_freq * 2: self._lost_remote = True if not self._closed: gevent.kill(self._parent_coroutine, self._lost_remote_exception()) break self._channel.emit(u'_zpc_hb', (0,))
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/heartbeat.py#L73-L84
36
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11 ]
91.666667
[]
0
false
90.909091
12
5
100
0
def _heartbeat(self): while True: gevent.sleep(self._heartbeat_freq) if self._remote_last_hb is None: self._remote_last_hb = time.time() if time.time() > self._remote_last_hb + self._heartbeat_freq * 2: self._lost_remote = True if not self._closed: gevent.kill(self._parent_coroutine, self._lost_remote_exception()) break self._channel.emit(u'_zpc_hb', (0,))
22,489
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/heartbeat.py
HeartBeatOnChannel._start_heartbeat
(self)
86
88
def _start_heartbeat(self): if self._heartbeat_task is None and self._heartbeat_freq is not None and not self._closed: self._heartbeat_task = gevent.spawn(self._heartbeat)
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/heartbeat.py#L86-L88
36
[ 0, 1, 2 ]
100
[]
0
true
90.909091
3
4
100
0
def _start_heartbeat(self): if self._heartbeat_task is None and self._heartbeat_freq is not None and not self._closed: self._heartbeat_task = gevent.spawn(self._heartbeat)
22,490
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/heartbeat.py
HeartBeatOnChannel._recver
(self)
90
102
def _recver(self): while True: event = self._channel.recv() if self._compat_v2 is None: self._compat_v2 = event.header.get(u'v', 0) < 3 if event.name == u'_zpc_hb': self._remote_last_hb = time.time() self._start_heartbeat() if self._compat_v2: event.name = u'_zpc_more' self._input_queue.put(event) else: self._input_queue.put(event)
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/heartbeat.py#L90-L102
36
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
90.909091
13
5
100
0
def _recver(self): while True: event = self._channel.recv() if self._compat_v2 is None: self._compat_v2 = event.header.get(u'v', 0) < 3 if event.name == u'_zpc_hb': self._remote_last_hb = time.time() self._start_heartbeat() if self._compat_v2: event.name = u'_zpc_more' self._input_queue.put(event) else: self._input_queue.put(event)
22,491
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/heartbeat.py
HeartBeatOnChannel._lost_remote_exception
(self)
return LostRemote('Lost remote after {0}s heartbeat'.format( self._heartbeat_freq * 2))
104
106
def _lost_remote_exception(self): return LostRemote('Lost remote after {0}s heartbeat'.format( self._heartbeat_freq * 2))
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/heartbeat.py#L104-L106
36
[ 0, 1 ]
66.666667
[]
0
false
90.909091
3
1
100
0
def _lost_remote_exception(self): return LostRemote('Lost remote after {0}s heartbeat'.format( self._heartbeat_freq * 2))
22,492
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/heartbeat.py
HeartBeatOnChannel.new_event
(self, name, args, header=None)
return self._channel.new_event(name, args, header)
108
111
def new_event(self, name, args, header=None): if self._compat_v2 and name == u'_zpc_more': name = u'_zpc_hb' return self._channel.new_event(name, args, header)
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/heartbeat.py#L108-L111
36
[ 0, 1, 3 ]
75
[ 2 ]
25
false
90.909091
4
3
75
0
def new_event(self, name, args, header=None): if self._compat_v2 and name == u'_zpc_more': name = u'_zpc_hb' return self._channel.new_event(name, args, header)
22,493
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/heartbeat.py
HeartBeatOnChannel.emit_event
(self, event, timeout=None)
113
116
def emit_event(self, event, timeout=None): if self._lost_remote: raise self._lost_remote_exception() self._channel.emit_event(event, timeout)
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/heartbeat.py#L113-L116
36
[ 0, 1, 3 ]
75
[ 2 ]
25
false
90.909091
4
2
75
0
def emit_event(self, event, timeout=None): if self._lost_remote: raise self._lost_remote_exception() self._channel.emit_event(event, timeout)
22,494
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/heartbeat.py
HeartBeatOnChannel.recv
(self, timeout=None)
118
124
def recv(self, timeout=None): if self._lost_remote: raise self._lost_remote_exception() try: return self._input_queue.get(timeout=timeout) except gevent.queue.Empty: raise TimeoutExpired(timeout)
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/heartbeat.py#L118-L124
36
[ 0, 1, 3, 4 ]
57.142857
[ 2, 5, 6 ]
42.857143
false
90.909091
7
3
57.142857
0
def recv(self, timeout=None): if self._lost_remote: raise self._lost_remote_exception() try: return self._input_queue.get(timeout=timeout) except gevent.queue.Empty: raise TimeoutExpired(timeout)
22,495
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/heartbeat.py
HeartBeatOnChannel.channel
(self)
return self._channel
127
128
def channel(self): return self._channel
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/heartbeat.py#L127-L128
36
[ 0 ]
50
[ 1 ]
50
false
90.909091
2
1
50
0
def channel(self): return self._channel
22,496
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/heartbeat.py
HeartBeatOnChannel.context
(self)
return self._channel.context
131
132
def context(self): return self._channel.context
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/heartbeat.py#L131-L132
36
[ 0, 1 ]
100
[]
0
true
90.909091
2
1
100
0
def context(self): return self._channel.context
22,497
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/exceptions.py
TimeoutExpired.__init__
(self, timeout_s, when=None)
32
36
def __init__(self, timeout_s, when=None): msg = 'timeout after {0}s'.format(timeout_s) if when: msg = '{0}, when {1}'.format(msg, when) super(TimeoutExpired, self).__init__(msg)
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/exceptions.py#L32-L36
36
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
94.117647
5
2
100
0
def __init__(self, timeout_s, when=None): msg = 'timeout after {0}s'.format(timeout_s) if when: msg = '{0}, when {1}'.format(msg, when) super(TimeoutExpired, self).__init__(msg)
22,498
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/exceptions.py
RemoteError.__init__
(self, name, human_msg, human_traceback)
41
44
def __init__(self, name, human_msg, human_traceback): self.name = name self.msg = human_msg self.traceback = human_traceback
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/exceptions.py#L41-L44
36
[ 0, 1, 2, 3 ]
100
[]
0
true
94.117647
4
1
100
0
def __init__(self, name, human_msg, human_traceback): self.name = name self.msg = human_msg self.traceback = human_traceback
22,499
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/exceptions.py
RemoteError.__str__
(self)
return '{0}: {1}'.format(self.name, self.msg)
46
49
def __str__(self): if self.traceback is not None: return self.traceback return '{0}: {1}'.format(self.name, self.msg)
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/exceptions.py#L46-L49
36
[ 0, 1, 2 ]
75
[ 3 ]
25
false
94.117647
4
2
75
0
def __str__(self): if self.traceback is not None: return self.traceback return '{0}: {1}'.format(self.name, self.msg)
22,500
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/decorators.py
DecoratorBase.__init__
(self, functor)
33
36
def __init__(self, functor): self._functor = functor self.__doc__ = functor.__doc__ self.__name__ = getattr(functor, "__name__", str(functor))
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/decorators.py#L33-L36
36
[ 0, 1, 2, 3 ]
100
[]
0
true
55.882353
4
1
100
0
def __init__(self, functor): self._functor = functor self.__doc__ = functor.__doc__ self.__name__ = getattr(functor, "__name__", str(functor))
22,501
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/decorators.py
DecoratorBase.__get__
(self, instance, type_instance=None)
return self.__class__(self._functor.__get__(instance, type_instance))
38
41
def __get__(self, instance, type_instance=None): if instance is None: return self return self.__class__(self._functor.__get__(instance, type_instance))
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/decorators.py#L38-L41
36
[ 0, 1, 3 ]
75
[ 2 ]
25
false
55.882353
4
2
75
0
def __get__(self, instance, type_instance=None): if instance is None: return self return self.__class__(self._functor.__get__(instance, type_instance))
22,502
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/decorators.py
DecoratorBase.__call__
(self, *args, **kargs)
return self._functor(*args, **kargs)
43
44
def __call__(self, *args, **kargs): return self._functor(*args, **kargs)
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/decorators.py#L43-L44
36
[ 0, 1 ]
100
[]
0
true
55.882353
2
1
100
0
def __call__(self, *args, **kargs): return self._functor(*args, **kargs)
22,503
0rpc/zerorpc-python
99ee6e47c8baf909b97eec94f184a19405f392a2
zerorpc/decorators.py
DecoratorBase._zerorpc_doc
(self)
return inspect.cleandoc(self.__doc__)
46
49
def _zerorpc_doc(self): if self.__doc__ is None: return None return inspect.cleandoc(self.__doc__)
https://github.com/0rpc/zerorpc-python/blob/99ee6e47c8baf909b97eec94f184a19405f392a2/project36/zerorpc/decorators.py#L46-L49
36
[ 0 ]
25
[ 1, 2, 3 ]
75
false
55.882353
4
2
25
0
def _zerorpc_doc(self): if self.__doc__ is None: return None return inspect.cleandoc(self.__doc__)
22,504